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
jhclark/bigfatlm
src/bigfat/step4/UninterpolatedInfo.java
// Path: src/bigfat/util/SerializationPrecision.java // public class SerializationPrecision { // public static boolean DOUBLE_PRECISION = false; // // public static void writeReal(DataOutput out, double prob) throws IOException { // if(DOUBLE_PRECISION) { // out.writeDouble(prob); // } else { // out.writeFloat((float)prob); // } // } // // public static double readReal(DataInput in) throws IOException { // if(DOUBLE_PRECISION) { // return in.readDouble(); // } else { // return in.readFloat(); // } // } // // public static void writeRealArray(DataOutput out, double[] arr) throws IOException { // WritableUtils.writeVInt(out, arr.length); // for(int i=0; i<arr.length; i++) { // writeReal(out, arr[i]); // } // } // // public static double[] readRealArray(DataInput in, double[] arr) throws IOException { // int len = WritableUtils.readVInt(in); // double[] result; // if(arr == null || len != arr.length) { // result = new double[len]; // } else { // result = arr; // } // for(int i=0; i<len; i++) { // result[i] = readReal(in); // } // return result; // } // }
import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableUtils; import bigfat.util.SerializationPrecision;
package bigfat.step4; /** * Stores a word w (as in P(w|h), it's interpolation weight, and its * uninterpolated probability. * * @author jhclark * */ public class UninterpolatedInfo implements Writable { private int wordId; private double prob; private double interpWeight; public double getUninterpolatedProb() { return prob; } public double getInterpolationWeight() { return interpWeight; } public int getWord() { return wordId; } public void setValues(int wordId, double p, double bo) { this.prob = p; this.interpWeight = bo; this.wordId = wordId; } @Override public void write(DataOutput out) throws IOException { WritableUtils.writeVInt(out, wordId);
// Path: src/bigfat/util/SerializationPrecision.java // public class SerializationPrecision { // public static boolean DOUBLE_PRECISION = false; // // public static void writeReal(DataOutput out, double prob) throws IOException { // if(DOUBLE_PRECISION) { // out.writeDouble(prob); // } else { // out.writeFloat((float)prob); // } // } // // public static double readReal(DataInput in) throws IOException { // if(DOUBLE_PRECISION) { // return in.readDouble(); // } else { // return in.readFloat(); // } // } // // public static void writeRealArray(DataOutput out, double[] arr) throws IOException { // WritableUtils.writeVInt(out, arr.length); // for(int i=0; i<arr.length; i++) { // writeReal(out, arr[i]); // } // } // // public static double[] readRealArray(DataInput in, double[] arr) throws IOException { // int len = WritableUtils.readVInt(in); // double[] result; // if(arr == null || len != arr.length) { // result = new double[len]; // } else { // result = arr; // } // for(int i=0; i<len; i++) { // result[i] = readReal(in); // } // return result; // } // } // Path: src/bigfat/step4/UninterpolatedInfo.java import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableUtils; import bigfat.util.SerializationPrecision; package bigfat.step4; /** * Stores a word w (as in P(w|h), it's interpolation weight, and its * uninterpolated probability. * * @author jhclark * */ public class UninterpolatedInfo implements Writable { private int wordId; private double prob; private double interpWeight; public double getUninterpolatedProb() { return prob; } public double getInterpolationWeight() { return interpWeight; } public int getWord() { return wordId; } public void setValues(int wordId, double p, double bo) { this.prob = p; this.interpWeight = bo; this.wordId = wordId; } @Override public void write(DataOutput out) throws IOException { WritableUtils.writeVInt(out, wordId);
SerializationPrecision.writeReal(out, prob);
Abiy/distGatling
gatling-rest/src/main/java/com/alh/gatling/config/WebSecurityConfig.java
// Path: gatling-rest/src/main/java/com/alh/gatling/security/rest/RestAuthenticationAccessDeniedHandler.java // public class RestAuthenticationAccessDeniedHandler implements AccessDeniedHandler { // // @Override // public void handle(HttpServletRequest request, HttpServletResponse response, // AccessDeniedException ex) throws IOException, ServletException { // response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); // } // } // // Path: gatling-rest/src/main/java/com/alh/gatling/security/rest/RestAuthenticationEntryPoint.java // public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint { // // @Override // public void commence(HttpServletRequest req, HttpServletResponse res, // AuthenticationException ex) throws IOException, ServletException { // res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); // } // // } // // Path: gatling-rest/src/main/java/com/alh/gatling/service/SimpleCORSFilter.java // @Component // public class SimpleCORSFilter implements Filter { // // private final Logger log = LoggerFactory.getLogger(SimpleCORSFilter.class); // // public SimpleCORSFilter() { // log.info("SimpleCORSFilter init"); // } // // @Override // public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { // // HttpServletRequest request = (HttpServletRequest) req; // HttpServletResponse response = (HttpServletResponse) res; // // // replace with "*" for testing, and request.getHeader("Origin") for production // response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); // response.setHeader("Access-Control-Allow-Credentials", "true"); // response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); // response.setHeader("Access-Control-Max-Age", "3600"); // response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept, X-Requested-With, remember-me, Cache-Control"); // // // Just REPLY OK if request method is OPTIONS for CORS (pre-flight) // if ( request.getMethod().equals("OPTIONS") ) { // response.setStatus(HttpServletResponse.SC_OK); // return; // } // // chain.doFilter(req, res); // } // // @Override // public void init(FilterConfig filterConfig) { // } // // @Override // public void destroy() { // } // // }
import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; 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.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.web.access.channel.ChannelProcessingFilter; import com.alh.gatling.security.rest.RestAuthenticationAccessDeniedHandler; import com.alh.gatling.security.rest.RestAuthenticationEntryPoint; import com.alh.gatling.service.SimpleCORSFilter;
package com.alh.gatling.config; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Value("${security.username}") private String USERNAME; @Value("${security.password}") private String PASSWORD; @Override public void configure(WebSecurity web) throws Exception { // Filters will not get executed for the resources web.ignoring().antMatchers("/", "/resources/**", "/static/**", "/public/**", "/webui/**", "/h2-console/**" , "/gatling/lib/**", "/configuration/**", "/swagger-ui/**", "/swagger-resources/**", "/api-docs", "/api-docs/**", "/v2/api-docs/**" , "/*.html", "/**/*.html" ,"/**/*.css","/**/*.js","/**/*.png","/**/*.jpg", "/**/*.gif", "/**/*.svg", "/**/*.ico", "/**/*.ttf","/**/*.woff","/**/*.otf"); } @Override public void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser(USERNAME) .password(PASSWORD) .roles("USER", "ACTUATOR"); } @Override protected void configure(HttpSecurity http) throws Exception { http .antMatcher("/**").csrf().disable() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .exceptionHandling()
// Path: gatling-rest/src/main/java/com/alh/gatling/security/rest/RestAuthenticationAccessDeniedHandler.java // public class RestAuthenticationAccessDeniedHandler implements AccessDeniedHandler { // // @Override // public void handle(HttpServletRequest request, HttpServletResponse response, // AccessDeniedException ex) throws IOException, ServletException { // response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); // } // } // // Path: gatling-rest/src/main/java/com/alh/gatling/security/rest/RestAuthenticationEntryPoint.java // public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint { // // @Override // public void commence(HttpServletRequest req, HttpServletResponse res, // AuthenticationException ex) throws IOException, ServletException { // res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); // } // // } // // Path: gatling-rest/src/main/java/com/alh/gatling/service/SimpleCORSFilter.java // @Component // public class SimpleCORSFilter implements Filter { // // private final Logger log = LoggerFactory.getLogger(SimpleCORSFilter.class); // // public SimpleCORSFilter() { // log.info("SimpleCORSFilter init"); // } // // @Override // public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { // // HttpServletRequest request = (HttpServletRequest) req; // HttpServletResponse response = (HttpServletResponse) res; // // // replace with "*" for testing, and request.getHeader("Origin") for production // response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); // response.setHeader("Access-Control-Allow-Credentials", "true"); // response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); // response.setHeader("Access-Control-Max-Age", "3600"); // response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept, X-Requested-With, remember-me, Cache-Control"); // // // Just REPLY OK if request method is OPTIONS for CORS (pre-flight) // if ( request.getMethod().equals("OPTIONS") ) { // response.setStatus(HttpServletResponse.SC_OK); // return; // } // // chain.doFilter(req, res); // } // // @Override // public void init(FilterConfig filterConfig) { // } // // @Override // public void destroy() { // } // // } // Path: gatling-rest/src/main/java/com/alh/gatling/config/WebSecurityConfig.java import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; 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.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.web.access.channel.ChannelProcessingFilter; import com.alh.gatling.security.rest.RestAuthenticationAccessDeniedHandler; import com.alh.gatling.security.rest.RestAuthenticationEntryPoint; import com.alh.gatling.service.SimpleCORSFilter; package com.alh.gatling.config; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Value("${security.username}") private String USERNAME; @Value("${security.password}") private String PASSWORD; @Override public void configure(WebSecurity web) throws Exception { // Filters will not get executed for the resources web.ignoring().antMatchers("/", "/resources/**", "/static/**", "/public/**", "/webui/**", "/h2-console/**" , "/gatling/lib/**", "/configuration/**", "/swagger-ui/**", "/swagger-resources/**", "/api-docs", "/api-docs/**", "/v2/api-docs/**" , "/*.html", "/**/*.html" ,"/**/*.css","/**/*.js","/**/*.png","/**/*.jpg", "/**/*.gif", "/**/*.svg", "/**/*.ico", "/**/*.ttf","/**/*.woff","/**/*.otf"); } @Override public void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser(USERNAME) .password(PASSWORD) .roles("USER", "ACTUATOR"); } @Override protected void configure(HttpSecurity http) throws Exception { http .antMatcher("/**").csrf().disable() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .exceptionHandling()
.authenticationEntryPoint(new RestAuthenticationEntryPoint())
Abiy/distGatling
gatling-rest/src/main/java/com/alh/gatling/config/WebSecurityConfig.java
// Path: gatling-rest/src/main/java/com/alh/gatling/security/rest/RestAuthenticationAccessDeniedHandler.java // public class RestAuthenticationAccessDeniedHandler implements AccessDeniedHandler { // // @Override // public void handle(HttpServletRequest request, HttpServletResponse response, // AccessDeniedException ex) throws IOException, ServletException { // response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); // } // } // // Path: gatling-rest/src/main/java/com/alh/gatling/security/rest/RestAuthenticationEntryPoint.java // public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint { // // @Override // public void commence(HttpServletRequest req, HttpServletResponse res, // AuthenticationException ex) throws IOException, ServletException { // res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); // } // // } // // Path: gatling-rest/src/main/java/com/alh/gatling/service/SimpleCORSFilter.java // @Component // public class SimpleCORSFilter implements Filter { // // private final Logger log = LoggerFactory.getLogger(SimpleCORSFilter.class); // // public SimpleCORSFilter() { // log.info("SimpleCORSFilter init"); // } // // @Override // public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { // // HttpServletRequest request = (HttpServletRequest) req; // HttpServletResponse response = (HttpServletResponse) res; // // // replace with "*" for testing, and request.getHeader("Origin") for production // response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); // response.setHeader("Access-Control-Allow-Credentials", "true"); // response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); // response.setHeader("Access-Control-Max-Age", "3600"); // response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept, X-Requested-With, remember-me, Cache-Control"); // // // Just REPLY OK if request method is OPTIONS for CORS (pre-flight) // if ( request.getMethod().equals("OPTIONS") ) { // response.setStatus(HttpServletResponse.SC_OK); // return; // } // // chain.doFilter(req, res); // } // // @Override // public void init(FilterConfig filterConfig) { // } // // @Override // public void destroy() { // } // // }
import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; 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.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.web.access.channel.ChannelProcessingFilter; import com.alh.gatling.security.rest.RestAuthenticationAccessDeniedHandler; import com.alh.gatling.security.rest.RestAuthenticationEntryPoint; import com.alh.gatling.service.SimpleCORSFilter;
package com.alh.gatling.config; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Value("${security.username}") private String USERNAME; @Value("${security.password}") private String PASSWORD; @Override public void configure(WebSecurity web) throws Exception { // Filters will not get executed for the resources web.ignoring().antMatchers("/", "/resources/**", "/static/**", "/public/**", "/webui/**", "/h2-console/**" , "/gatling/lib/**", "/configuration/**", "/swagger-ui/**", "/swagger-resources/**", "/api-docs", "/api-docs/**", "/v2/api-docs/**" , "/*.html", "/**/*.html" ,"/**/*.css","/**/*.js","/**/*.png","/**/*.jpg", "/**/*.gif", "/**/*.svg", "/**/*.ico", "/**/*.ttf","/**/*.woff","/**/*.otf"); } @Override public void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser(USERNAME) .password(PASSWORD) .roles("USER", "ACTUATOR"); } @Override protected void configure(HttpSecurity http) throws Exception { http .antMatcher("/**").csrf().disable() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .exceptionHandling() .authenticationEntryPoint(new RestAuthenticationEntryPoint())
// Path: gatling-rest/src/main/java/com/alh/gatling/security/rest/RestAuthenticationAccessDeniedHandler.java // public class RestAuthenticationAccessDeniedHandler implements AccessDeniedHandler { // // @Override // public void handle(HttpServletRequest request, HttpServletResponse response, // AccessDeniedException ex) throws IOException, ServletException { // response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); // } // } // // Path: gatling-rest/src/main/java/com/alh/gatling/security/rest/RestAuthenticationEntryPoint.java // public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint { // // @Override // public void commence(HttpServletRequest req, HttpServletResponse res, // AuthenticationException ex) throws IOException, ServletException { // res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); // } // // } // // Path: gatling-rest/src/main/java/com/alh/gatling/service/SimpleCORSFilter.java // @Component // public class SimpleCORSFilter implements Filter { // // private final Logger log = LoggerFactory.getLogger(SimpleCORSFilter.class); // // public SimpleCORSFilter() { // log.info("SimpleCORSFilter init"); // } // // @Override // public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { // // HttpServletRequest request = (HttpServletRequest) req; // HttpServletResponse response = (HttpServletResponse) res; // // // replace with "*" for testing, and request.getHeader("Origin") for production // response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); // response.setHeader("Access-Control-Allow-Credentials", "true"); // response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); // response.setHeader("Access-Control-Max-Age", "3600"); // response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept, X-Requested-With, remember-me, Cache-Control"); // // // Just REPLY OK if request method is OPTIONS for CORS (pre-flight) // if ( request.getMethod().equals("OPTIONS") ) { // response.setStatus(HttpServletResponse.SC_OK); // return; // } // // chain.doFilter(req, res); // } // // @Override // public void init(FilterConfig filterConfig) { // } // // @Override // public void destroy() { // } // // } // Path: gatling-rest/src/main/java/com/alh/gatling/config/WebSecurityConfig.java import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; 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.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.web.access.channel.ChannelProcessingFilter; import com.alh.gatling.security.rest.RestAuthenticationAccessDeniedHandler; import com.alh.gatling.security.rest.RestAuthenticationEntryPoint; import com.alh.gatling.service.SimpleCORSFilter; package com.alh.gatling.config; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Value("${security.username}") private String USERNAME; @Value("${security.password}") private String PASSWORD; @Override public void configure(WebSecurity web) throws Exception { // Filters will not get executed for the resources web.ignoring().antMatchers("/", "/resources/**", "/static/**", "/public/**", "/webui/**", "/h2-console/**" , "/gatling/lib/**", "/configuration/**", "/swagger-ui/**", "/swagger-resources/**", "/api-docs", "/api-docs/**", "/v2/api-docs/**" , "/*.html", "/**/*.html" ,"/**/*.css","/**/*.js","/**/*.png","/**/*.jpg", "/**/*.gif", "/**/*.svg", "/**/*.ico", "/**/*.ttf","/**/*.woff","/**/*.otf"); } @Override public void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser(USERNAME) .password(PASSWORD) .roles("USER", "ACTUATOR"); } @Override protected void configure(HttpSecurity http) throws Exception { http .antMatcher("/**").csrf().disable() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .exceptionHandling() .authenticationEntryPoint(new RestAuthenticationEntryPoint())
.accessDeniedHandler(new RestAuthenticationAccessDeniedHandler())
Abiy/distGatling
gatling-rest/src/main/java/com/alh/gatling/config/WebSecurityConfig.java
// Path: gatling-rest/src/main/java/com/alh/gatling/security/rest/RestAuthenticationAccessDeniedHandler.java // public class RestAuthenticationAccessDeniedHandler implements AccessDeniedHandler { // // @Override // public void handle(HttpServletRequest request, HttpServletResponse response, // AccessDeniedException ex) throws IOException, ServletException { // response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); // } // } // // Path: gatling-rest/src/main/java/com/alh/gatling/security/rest/RestAuthenticationEntryPoint.java // public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint { // // @Override // public void commence(HttpServletRequest req, HttpServletResponse res, // AuthenticationException ex) throws IOException, ServletException { // res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); // } // // } // // Path: gatling-rest/src/main/java/com/alh/gatling/service/SimpleCORSFilter.java // @Component // public class SimpleCORSFilter implements Filter { // // private final Logger log = LoggerFactory.getLogger(SimpleCORSFilter.class); // // public SimpleCORSFilter() { // log.info("SimpleCORSFilter init"); // } // // @Override // public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { // // HttpServletRequest request = (HttpServletRequest) req; // HttpServletResponse response = (HttpServletResponse) res; // // // replace with "*" for testing, and request.getHeader("Origin") for production // response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); // response.setHeader("Access-Control-Allow-Credentials", "true"); // response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); // response.setHeader("Access-Control-Max-Age", "3600"); // response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept, X-Requested-With, remember-me, Cache-Control"); // // // Just REPLY OK if request method is OPTIONS for CORS (pre-flight) // if ( request.getMethod().equals("OPTIONS") ) { // response.setStatus(HttpServletResponse.SC_OK); // return; // } // // chain.doFilter(req, res); // } // // @Override // public void init(FilterConfig filterConfig) { // } // // @Override // public void destroy() { // } // // }
import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; 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.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.web.access.channel.ChannelProcessingFilter; import com.alh.gatling.security.rest.RestAuthenticationAccessDeniedHandler; import com.alh.gatling.security.rest.RestAuthenticationEntryPoint; import com.alh.gatling.service.SimpleCORSFilter;
@Value("${security.password}") private String PASSWORD; @Override public void configure(WebSecurity web) throws Exception { // Filters will not get executed for the resources web.ignoring().antMatchers("/", "/resources/**", "/static/**", "/public/**", "/webui/**", "/h2-console/**" , "/gatling/lib/**", "/configuration/**", "/swagger-ui/**", "/swagger-resources/**", "/api-docs", "/api-docs/**", "/v2/api-docs/**" , "/*.html", "/**/*.html" ,"/**/*.css","/**/*.js","/**/*.png","/**/*.jpg", "/**/*.gif", "/**/*.svg", "/**/*.ico", "/**/*.ttf","/**/*.woff","/**/*.otf"); } @Override public void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser(USERNAME) .password(PASSWORD) .roles("USER", "ACTUATOR"); } @Override protected void configure(HttpSecurity http) throws Exception { http .antMatcher("/**").csrf().disable() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .exceptionHandling() .authenticationEntryPoint(new RestAuthenticationEntryPoint()) .accessDeniedHandler(new RestAuthenticationAccessDeniedHandler()) .and() .authorizeRequests() .antMatchers("/gatling/server/abort**", "/gatling/server/getlog/**").permitAll() .anyRequest().hasRole("USER") .and()
// Path: gatling-rest/src/main/java/com/alh/gatling/security/rest/RestAuthenticationAccessDeniedHandler.java // public class RestAuthenticationAccessDeniedHandler implements AccessDeniedHandler { // // @Override // public void handle(HttpServletRequest request, HttpServletResponse response, // AccessDeniedException ex) throws IOException, ServletException { // response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); // } // } // // Path: gatling-rest/src/main/java/com/alh/gatling/security/rest/RestAuthenticationEntryPoint.java // public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint { // // @Override // public void commence(HttpServletRequest req, HttpServletResponse res, // AuthenticationException ex) throws IOException, ServletException { // res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); // } // // } // // Path: gatling-rest/src/main/java/com/alh/gatling/service/SimpleCORSFilter.java // @Component // public class SimpleCORSFilter implements Filter { // // private final Logger log = LoggerFactory.getLogger(SimpleCORSFilter.class); // // public SimpleCORSFilter() { // log.info("SimpleCORSFilter init"); // } // // @Override // public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { // // HttpServletRequest request = (HttpServletRequest) req; // HttpServletResponse response = (HttpServletResponse) res; // // // replace with "*" for testing, and request.getHeader("Origin") for production // response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); // response.setHeader("Access-Control-Allow-Credentials", "true"); // response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); // response.setHeader("Access-Control-Max-Age", "3600"); // response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept, X-Requested-With, remember-me, Cache-Control"); // // // Just REPLY OK if request method is OPTIONS for CORS (pre-flight) // if ( request.getMethod().equals("OPTIONS") ) { // response.setStatus(HttpServletResponse.SC_OK); // return; // } // // chain.doFilter(req, res); // } // // @Override // public void init(FilterConfig filterConfig) { // } // // @Override // public void destroy() { // } // // } // Path: gatling-rest/src/main/java/com/alh/gatling/config/WebSecurityConfig.java import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; 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.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.web.access.channel.ChannelProcessingFilter; import com.alh.gatling.security.rest.RestAuthenticationAccessDeniedHandler; import com.alh.gatling.security.rest.RestAuthenticationEntryPoint; import com.alh.gatling.service.SimpleCORSFilter; @Value("${security.password}") private String PASSWORD; @Override public void configure(WebSecurity web) throws Exception { // Filters will not get executed for the resources web.ignoring().antMatchers("/", "/resources/**", "/static/**", "/public/**", "/webui/**", "/h2-console/**" , "/gatling/lib/**", "/configuration/**", "/swagger-ui/**", "/swagger-resources/**", "/api-docs", "/api-docs/**", "/v2/api-docs/**" , "/*.html", "/**/*.html" ,"/**/*.css","/**/*.js","/**/*.png","/**/*.jpg", "/**/*.gif", "/**/*.svg", "/**/*.ico", "/**/*.ttf","/**/*.woff","/**/*.otf"); } @Override public void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser(USERNAME) .password(PASSWORD) .roles("USER", "ACTUATOR"); } @Override protected void configure(HttpSecurity http) throws Exception { http .antMatcher("/**").csrf().disable() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .exceptionHandling() .authenticationEntryPoint(new RestAuthenticationEntryPoint()) .accessDeniedHandler(new RestAuthenticationAccessDeniedHandler()) .and() .authorizeRequests() .antMatchers("/gatling/server/abort**", "/gatling/server/getlog/**").permitAll() .anyRequest().hasRole("USER") .and()
.addFilterBefore(new SimpleCORSFilter(), ChannelProcessingFilter.class)
Abiy/distGatling
gatling-client/src/main/java/com/alh/gatling/client/UploadUtils.java
// Path: gatling-commons/src/main/java/com/alh/gatling/commons/HostUtils.java // public class HostUtils { // // public static String lookupHost() { // InetAddress ip; // String hostname; // try { // ip = InetAddress.getLocalHost(); // hostname = ip.getHostName(); // return hostname; // } catch (UnknownHostException e) { // e.printStackTrace(); // } // return "UNKNOWN"; // } // // public static String lookupIp() { // String ipAddress; // ipAddress = System.getProperty("bind.ip.address",getLocalAddress()); // return ipAddress; // } // // private static String getLocalAddress(){ // try { // Enumeration<NetworkInterface> b = NetworkInterface.getNetworkInterfaces(); // while( b.hasMoreElements()){ // for ( InterfaceAddress f : b.nextElement().getInterfaceAddresses()) // if ( f.getAddress().isSiteLocalAddress()) // return f.getAddress().getHostAddress(); // } // } catch (SocketException e) { // e.printStackTrace(); // } // // try { // return InetAddress.getLocalHost().getHostAddress(); // } catch (UnknownHostException e) { // e.printStackTrace(); // } // return "UNKNOWN"; // } // }
import java.io.File; import java.io.IOException; import com.alh.gatling.commons.HostUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder;
/* * * Copyright 2016 alh Technology * * 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.alh.gatling.client; /** * on 5/16/17. */ public class UploadUtils { protected static final Log logger = LogFactory.getLog(UploadUtils.class); public static String uploadFile(String server, String path,String basicToken) throws IOException { CloseableHttpClient client = HttpClientBuilder.create() .build(); HttpPost post = new HttpPost( server + "/uploadFile"); post.setHeader("Authorization",basicToken); //File jarFile = new File(jarFilePath); File dataFeedFile = new File(path);
// Path: gatling-commons/src/main/java/com/alh/gatling/commons/HostUtils.java // public class HostUtils { // // public static String lookupHost() { // InetAddress ip; // String hostname; // try { // ip = InetAddress.getLocalHost(); // hostname = ip.getHostName(); // return hostname; // } catch (UnknownHostException e) { // e.printStackTrace(); // } // return "UNKNOWN"; // } // // public static String lookupIp() { // String ipAddress; // ipAddress = System.getProperty("bind.ip.address",getLocalAddress()); // return ipAddress; // } // // private static String getLocalAddress(){ // try { // Enumeration<NetworkInterface> b = NetworkInterface.getNetworkInterfaces(); // while( b.hasMoreElements()){ // for ( InterfaceAddress f : b.nextElement().getInterfaceAddresses()) // if ( f.getAddress().isSiteLocalAddress()) // return f.getAddress().getHostAddress(); // } // } catch (SocketException e) { // e.printStackTrace(); // } // // try { // return InetAddress.getLocalHost().getHostAddress(); // } catch (UnknownHostException e) { // e.printStackTrace(); // } // return "UNKNOWN"; // } // } // Path: gatling-client/src/main/java/com/alh/gatling/client/UploadUtils.java import java.io.File; import java.io.IOException; import com.alh.gatling.commons.HostUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; /* * * Copyright 2016 alh Technology * * 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.alh.gatling.client; /** * on 5/16/17. */ public class UploadUtils { protected static final Log logger = LogFactory.getLog(UploadUtils.class); public static String uploadFile(String server, String path,String basicToken) throws IOException { CloseableHttpClient client = HttpClientBuilder.create() .build(); HttpPost post = new HttpPost( server + "/uploadFile"); post.setHeader("Authorization",basicToken); //File jarFile = new File(jarFilePath); File dataFeedFile = new File(path);
String message = HostUtils.lookupIp();
Abiy/distGatling
gatling-agent/src/main/java/com/alh/gatling/MonitoringConfiguration.java
// Path: gatling-commons/src/main/java/com/alh/gatling/commons/HostUtils.java // public class HostUtils { // // public static String lookupHost() { // InetAddress ip; // String hostname; // try { // ip = InetAddress.getLocalHost(); // hostname = ip.getHostName(); // return hostname; // } catch (UnknownHostException e) { // e.printStackTrace(); // } // return "UNKNOWN"; // } // // public static String lookupIp() { // String ipAddress; // ipAddress = System.getProperty("bind.ip.address",getLocalAddress()); // return ipAddress; // } // // private static String getLocalAddress(){ // try { // Enumeration<NetworkInterface> b = NetworkInterface.getNetworkInterfaces(); // while( b.hasMoreElements()){ // for ( InterfaceAddress f : b.nextElement().getInterfaceAddresses()) // if ( f.getAddress().isSiteLocalAddress()) // return f.getAddress().getHostAddress(); // } // } catch (SocketException e) { // e.printStackTrace(); // } // // try { // return InetAddress.getLocalHost().getHostAddress(); // } catch (UnknownHostException e) { // e.printStackTrace(); // } // return "UNKNOWN"; // } // }
import java.net.InetSocketAddress; import java.util.concurrent.TimeUnit; import com.codahale.metrics.ConsoleReporter; import com.codahale.metrics.MetricFilter; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.graphite.Graphite; import com.codahale.metrics.graphite.GraphiteReporter; import com.codahale.metrics.jvm.MemoryUsageGaugeSet; import com.codahale.metrics.jvm.ThreadStatesGaugeSet; import com.alh.gatling.commons.HostUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
/* * * Copyright 2016 alh Technology * * 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.alh.gatling; /** * Created alh */ @Configuration public class MonitoringConfiguration { @Bean public Graphite graphite(@Value("${graphite.host}") String graphiteHost, @Value("${graphite.port}") int graphitePort) { return new Graphite( new InetSocketAddress(graphiteHost, graphitePort)); } //@Bean public GraphiteReporter graphiteReporter(Graphite graphite, MetricRegistry registry, @Value("${graphite.prefix}") String prefix,@Value("${graphite.frequency-in-seconds}") long frequencyInSeconds) { GraphiteReporter reporter = GraphiteReporter.forRegistry(registry)
// Path: gatling-commons/src/main/java/com/alh/gatling/commons/HostUtils.java // public class HostUtils { // // public static String lookupHost() { // InetAddress ip; // String hostname; // try { // ip = InetAddress.getLocalHost(); // hostname = ip.getHostName(); // return hostname; // } catch (UnknownHostException e) { // e.printStackTrace(); // } // return "UNKNOWN"; // } // // public static String lookupIp() { // String ipAddress; // ipAddress = System.getProperty("bind.ip.address",getLocalAddress()); // return ipAddress; // } // // private static String getLocalAddress(){ // try { // Enumeration<NetworkInterface> b = NetworkInterface.getNetworkInterfaces(); // while( b.hasMoreElements()){ // for ( InterfaceAddress f : b.nextElement().getInterfaceAddresses()) // if ( f.getAddress().isSiteLocalAddress()) // return f.getAddress().getHostAddress(); // } // } catch (SocketException e) { // e.printStackTrace(); // } // // try { // return InetAddress.getLocalHost().getHostAddress(); // } catch (UnknownHostException e) { // e.printStackTrace(); // } // return "UNKNOWN"; // } // } // Path: gatling-agent/src/main/java/com/alh/gatling/MonitoringConfiguration.java import java.net.InetSocketAddress; import java.util.concurrent.TimeUnit; import com.codahale.metrics.ConsoleReporter; import com.codahale.metrics.MetricFilter; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.graphite.Graphite; import com.codahale.metrics.graphite.GraphiteReporter; import com.codahale.metrics.jvm.MemoryUsageGaugeSet; import com.codahale.metrics.jvm.ThreadStatesGaugeSet; import com.alh.gatling.commons.HostUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /* * * Copyright 2016 alh Technology * * 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.alh.gatling; /** * Created alh */ @Configuration public class MonitoringConfiguration { @Bean public Graphite graphite(@Value("${graphite.host}") String graphiteHost, @Value("${graphite.port}") int graphitePort) { return new Graphite( new InetSocketAddress(graphiteHost, graphitePort)); } //@Bean public GraphiteReporter graphiteReporter(Graphite graphite, MetricRegistry registry, @Value("${graphite.prefix}") String prefix,@Value("${graphite.frequency-in-seconds}") long frequencyInSeconds) { GraphiteReporter reporter = GraphiteReporter.forRegistry(registry)
.prefixedWith(prefix + "." + HostUtils.lookupHost())
Abiy/distGatling
gatling-rest/src/main/java/com/alh/gatling/config/MonitoringConfig.java
// Path: gatling-commons/src/main/java/com/alh/gatling/commons/HostUtils.java // public class HostUtils { // // public static String lookupHost() { // InetAddress ip; // String hostname; // try { // ip = InetAddress.getLocalHost(); // hostname = ip.getHostName(); // return hostname; // } catch (UnknownHostException e) { // e.printStackTrace(); // } // return "UNKNOWN"; // } // // public static String lookupIp() { // String ipAddress; // ipAddress = System.getProperty("bind.ip.address",getLocalAddress()); // return ipAddress; // } // // private static String getLocalAddress(){ // try { // Enumeration<NetworkInterface> b = NetworkInterface.getNetworkInterfaces(); // while( b.hasMoreElements()){ // for ( InterfaceAddress f : b.nextElement().getInterfaceAddresses()) // if ( f.getAddress().isSiteLocalAddress()) // return f.getAddress().getHostAddress(); // } // } catch (SocketException e) { // e.printStackTrace(); // } // // try { // return InetAddress.getLocalHost().getHostAddress(); // } catch (UnknownHostException e) { // e.printStackTrace(); // } // return "UNKNOWN"; // } // }
import java.net.InetSocketAddress; import java.util.concurrent.TimeUnit; import com.codahale.metrics.ConsoleReporter; import com.codahale.metrics.MetricFilter; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.graphite.Graphite; import com.codahale.metrics.graphite.GraphiteReporter; import com.codahale.metrics.jvm.MemoryUsageGaugeSet; import com.codahale.metrics.jvm.ThreadStatesGaugeSet; import com.alh.gatling.commons.HostUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
/* * * Copyright 2016 alh Technology * * 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.alh.gatling.config; /** * Configured the metrics for collection and for reporting */ @Configuration public class MonitoringConfig { @Bean public Graphite graphite(@Value("${graphite.host}") String graphiteHost, @Value("${graphite.port}") int graphitePort) { return new Graphite( new InetSocketAddress(graphiteHost, graphitePort)); } //@Bean public GraphiteReporter graphiteReporter(Graphite graphite, MetricRegistry registry, @Value("${graphite.prefix}") String prefix,@Value("${graphite.frequency-in-seconds}") long frequencyInSeconds) { GraphiteReporter reporter = GraphiteReporter.forRegistry(registry)
// Path: gatling-commons/src/main/java/com/alh/gatling/commons/HostUtils.java // public class HostUtils { // // public static String lookupHost() { // InetAddress ip; // String hostname; // try { // ip = InetAddress.getLocalHost(); // hostname = ip.getHostName(); // return hostname; // } catch (UnknownHostException e) { // e.printStackTrace(); // } // return "UNKNOWN"; // } // // public static String lookupIp() { // String ipAddress; // ipAddress = System.getProperty("bind.ip.address",getLocalAddress()); // return ipAddress; // } // // private static String getLocalAddress(){ // try { // Enumeration<NetworkInterface> b = NetworkInterface.getNetworkInterfaces(); // while( b.hasMoreElements()){ // for ( InterfaceAddress f : b.nextElement().getInterfaceAddresses()) // if ( f.getAddress().isSiteLocalAddress()) // return f.getAddress().getHostAddress(); // } // } catch (SocketException e) { // e.printStackTrace(); // } // // try { // return InetAddress.getLocalHost().getHostAddress(); // } catch (UnknownHostException e) { // e.printStackTrace(); // } // return "UNKNOWN"; // } // } // Path: gatling-rest/src/main/java/com/alh/gatling/config/MonitoringConfig.java import java.net.InetSocketAddress; import java.util.concurrent.TimeUnit; import com.codahale.metrics.ConsoleReporter; import com.codahale.metrics.MetricFilter; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.graphite.Graphite; import com.codahale.metrics.graphite.GraphiteReporter; import com.codahale.metrics.jvm.MemoryUsageGaugeSet; import com.codahale.metrics.jvm.ThreadStatesGaugeSet; import com.alh.gatling.commons.HostUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /* * * Copyright 2016 alh Technology * * 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.alh.gatling.config; /** * Configured the metrics for collection and for reporting */ @Configuration public class MonitoringConfig { @Bean public Graphite graphite(@Value("${graphite.host}") String graphiteHost, @Value("${graphite.port}") int graphitePort) { return new Graphite( new InetSocketAddress(graphiteHost, graphitePort)); } //@Bean public GraphiteReporter graphiteReporter(Graphite graphite, MetricRegistry registry, @Value("${graphite.prefix}") String prefix,@Value("${graphite.frequency-in-seconds}") long frequencyInSeconds) { GraphiteReporter reporter = GraphiteReporter.forRegistry(registry)
.prefixedWith(prefix + "." + HostUtils.lookupHost())
Abiy/distGatling
gatling-client/src/main/java/com/alh/gatling/Client.java
// Path: gatling-client/src/main/java/com/alh/gatling/client/StartupRunner.java // public class StartupRunner implements CommandLineRunner { // protected final Log logger = LogFactory.getLog(getClass()); // // @Override // public void run(String... args) throws Exception { // //logger.info("CommandClientActor Initializing..."); // //run basic check to make sure the app is starting in a healthy state // } // }
import com.alh.gatling.client.StartupRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean;
/* * * Copyright 2016 alh Technology * * 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.alh.gatling; @SpringBootApplication public class Client { public static void main(String[] args) throws Exception { //new JHades().overlappingJarsReport(); SpringApplication.run(Client.class, args); } @Bean
// Path: gatling-client/src/main/java/com/alh/gatling/client/StartupRunner.java // public class StartupRunner implements CommandLineRunner { // protected final Log logger = LogFactory.getLog(getClass()); // // @Override // public void run(String... args) throws Exception { // //logger.info("CommandClientActor Initializing..."); // //run basic check to make sure the app is starting in a healthy state // } // } // Path: gatling-client/src/main/java/com/alh/gatling/Client.java import com.alh.gatling.client.StartupRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; /* * * Copyright 2016 alh Technology * * 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.alh.gatling; @SpringBootApplication public class Client { public static void main(String[] args) throws Exception { //new JHades().overlappingJarsReport(); SpringApplication.run(Client.class, args); } @Bean
public StartupRunner schedulerRunner() {
Abiy/distGatling
gatling-rest/src/test/java/com/alh/gatling/endpoint/v1/RestControllerIntTest.java
// Path: gatling-agent/src/test/java/com/alh/gatling/AbstractRestIntTest.java // @RunWith(SpringJUnit4ClassRunner.class) // @SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) // @TestPropertySource(locations = "classpath:application.yml") // @ActiveProfiles({"testing"}) // public abstract class AbstractRestIntTest { // // private static final Logger logger = LoggerFactory.getLogger(AbstractRestIntTest.class); // @Autowired // protected TestRestTemplate template ; // protected final String rootUrl = "/api/v1"; // // @Autowired // protected ObjectMapper mapper; // // // protected String toJson(Object obj) { // try { // return mapper.writeValueAsString(obj); // } catch (JsonProcessingException e) { // e.printStackTrace(); // throw new RuntimeException("Error marshalling object '" + obj + "' to json string.", e); // } // } // // } // // Path: gatling-rest/src/main/java/com/alh/gatling/domain/WorkerModel.java // @Data // @XmlRootElement // public class WorkerModel { // private String status; // private String host; // private String actor; // private String workerId; // private String role; // // public WorkerModel(String status, String actor, String workerId) { // this.status = status; // try { // this.actor = java.net.URLDecoder.decode(actor, "UTF-8"); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // this.workerId = workerId; // this.host = this.actor.split("@")[1].split(":")[0]; // this.role = this.actor.split("/")[4].split("#")[0].replaceAll("[0-9]",""); // } // }
import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.client.support.BasicAuthorizationInterceptor; import com.alh.gatling.AbstractRestIntTest; import com.alh.gatling.domain.WorkerModel;
/* * * Copyright 2016 alh Technology * * 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.alh.gatling.endpoint.v1; /** * Trivial integration test class that exercises the Junit spring runner and in container testing. * * @author * */ public class RestControllerIntTest extends AbstractRestIntTest { private final Logger log = LoggerFactory.getLogger(RestControllerIntTest.class); @Value("${security.username}") private String USERNAME; @Value("${security.password}") private String PASSWORD; @Before public void setup() { BasicAuthorizationInterceptor bai = new BasicAuthorizationInterceptor(USERNAME, PASSWORD); template.getRestTemplate().getInterceptors().add(bai); } @Test public void test(){
// Path: gatling-agent/src/test/java/com/alh/gatling/AbstractRestIntTest.java // @RunWith(SpringJUnit4ClassRunner.class) // @SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) // @TestPropertySource(locations = "classpath:application.yml") // @ActiveProfiles({"testing"}) // public abstract class AbstractRestIntTest { // // private static final Logger logger = LoggerFactory.getLogger(AbstractRestIntTest.class); // @Autowired // protected TestRestTemplate template ; // protected final String rootUrl = "/api/v1"; // // @Autowired // protected ObjectMapper mapper; // // // protected String toJson(Object obj) { // try { // return mapper.writeValueAsString(obj); // } catch (JsonProcessingException e) { // e.printStackTrace(); // throw new RuntimeException("Error marshalling object '" + obj + "' to json string.", e); // } // } // // } // // Path: gatling-rest/src/main/java/com/alh/gatling/domain/WorkerModel.java // @Data // @XmlRootElement // public class WorkerModel { // private String status; // private String host; // private String actor; // private String workerId; // private String role; // // public WorkerModel(String status, String actor, String workerId) { // this.status = status; // try { // this.actor = java.net.URLDecoder.decode(actor, "UTF-8"); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // this.workerId = workerId; // this.host = this.actor.split("@")[1].split(":")[0]; // this.role = this.actor.split("/")[4].split("#")[0].replaceAll("[0-9]",""); // } // } // Path: gatling-rest/src/test/java/com/alh/gatling/endpoint/v1/RestControllerIntTest.java import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.client.support.BasicAuthorizationInterceptor; import com.alh.gatling.AbstractRestIntTest; import com.alh.gatling.domain.WorkerModel; /* * * Copyright 2016 alh Technology * * 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.alh.gatling.endpoint.v1; /** * Trivial integration test class that exercises the Junit spring runner and in container testing. * * @author * */ public class RestControllerIntTest extends AbstractRestIntTest { private final Logger log = LoggerFactory.getLogger(RestControllerIntTest.class); @Value("${security.username}") private String USERNAME; @Value("${security.password}") private String PASSWORD; @Before public void setup() { BasicAuthorizationInterceptor bai = new BasicAuthorizationInterceptor(USERNAME, PASSWORD); template.getRestTemplate().getInterceptors().add(bai); } @Test public void test(){
WorkerModel[] info = template.getForObject(rootUrl+ "/server/info", WorkerModel[].class);
Abiy/distGatling
gatling-commons/src/main/java/com/alh/gatling/commons/Worker.java
// Path: gatling-commons/src/main/java/com/alh/gatling/commons/Master.java // public static final class Ack implements Serializable { // final String workId; // // public Ack(String workId) { // this.workId = workId; // } // // public String getWorkId() { // return workId; // } // // @Override // public String toString() { // return "Ack{" + "jobId='" + workId + '\'' + '}'; // } // } // // Path: gatling-commons/src/main/java/com/alh/gatling/commons/Master.java // public static final class Job implements Serializable { // public final Object taskEvent;//task // public final String jobId; // public final String roleId; // public final String trackingId; // public final boolean isJarSimulation; // public String abortUrl; // public String jobFileUrl; // public String resourcesFileUrl; // // public Job(String roleId, Object job, String trackingId, String abortUrl, String jobFileUrl, String resourcesFileUrl, boolean isJarSimulation) { // this.jobId = UUID.randomUUID().toString(); // this.roleId = roleId; // this.taskEvent = job; // this.trackingId = trackingId; // this.abortUrl = abortUrl; // this.jobFileUrl = jobFileUrl; // this.resourcesFileUrl = resourcesFileUrl; // this.isJarSimulation = isJarSimulation; // } // // @Override // public String toString() { // return "Job{" + // "taskEvent=" + taskEvent + // ", jobId='" + jobId + '\'' + // ", roleId='" + roleId + '\'' + // ", trackingId='" + trackingId + '\'' + // ", isJarSimulation=" + isJarSimulation + // ", abortUrl='" + abortUrl + '\'' + // ", jobFileUrl='" + jobFileUrl + '\'' + // ", resourcesFileUrl='" + resourcesFileUrl + '\'' + // '}'; // } // }
import akka.actor.AbstractActor; import akka.actor.ActorInitializationException; import akka.actor.ActorRef; import akka.actor.Cancellable; import akka.actor.DeathPactException; import akka.actor.OneForOneStrategy; import akka.actor.Props; import akka.actor.ReceiveTimeout; import akka.actor.SupervisorStrategy; import akka.actor.Terminated; import akka.cluster.client.ClusterClient; import akka.event.Logging; import akka.event.LoggingAdapter; import akka.japi.Procedure; import com.alh.gatling.commons.Master.Ack; import com.alh.gatling.commons.Master.Job; import scala.concurrent.duration.Duration; import scala.concurrent.duration.FiniteDuration; import java.io.Serializable; import java.util.UUID; import static akka.actor.SupervisorStrategy.*;
//log.info("Work is complete. Result {}.", result); sendToMaster(new MasterWorkerProtocol.WorkIsDone(workerId, jobId(), result)); getContext().setReceiveTimeout(Duration.create(5, "seconds")); Procedure<Object> waitForWorkIsDoneAck = waitForWorkIsDoneAck(result); getContext().become(receiveBuilder() .matchAny(p -> waitForWorkIsDoneAck.apply(p)) .build()); } else if (message instanceof Worker.FileUploadComplete){ sendToMaster(message); getContext().become(receiveBuilder() .matchAny(p->idle.apply(p)) .build()); } else if (message instanceof WorkFailed) { Object result = ((WorkFailed) message).result; log.info("Work is failed. Result {}.", result); sendToMaster(new MasterWorkerProtocol.WorkFailed(workerId, jobId(),result)); getContext().become(receiveBuilder() .matchAny(p->idle.apply(p)) .build()); //getContext().setReceiveTimeout(Duration.create(5, "seconds")); ///Procedure<Object> waitForWorkIsDoneAck = waitForWorkIsDoneAck(result); //getContext().become(waitForWorkIsDoneAck); } else if(message==KeepAliveTick){ log.info("Job is in progress. {}.", jobId()); if (currentJobId!=null){ sendToMaster(new MasterWorkerProtocol.WorkInProgress(workerId, jobId())); }
// Path: gatling-commons/src/main/java/com/alh/gatling/commons/Master.java // public static final class Ack implements Serializable { // final String workId; // // public Ack(String workId) { // this.workId = workId; // } // // public String getWorkId() { // return workId; // } // // @Override // public String toString() { // return "Ack{" + "jobId='" + workId + '\'' + '}'; // } // } // // Path: gatling-commons/src/main/java/com/alh/gatling/commons/Master.java // public static final class Job implements Serializable { // public final Object taskEvent;//task // public final String jobId; // public final String roleId; // public final String trackingId; // public final boolean isJarSimulation; // public String abortUrl; // public String jobFileUrl; // public String resourcesFileUrl; // // public Job(String roleId, Object job, String trackingId, String abortUrl, String jobFileUrl, String resourcesFileUrl, boolean isJarSimulation) { // this.jobId = UUID.randomUUID().toString(); // this.roleId = roleId; // this.taskEvent = job; // this.trackingId = trackingId; // this.abortUrl = abortUrl; // this.jobFileUrl = jobFileUrl; // this.resourcesFileUrl = resourcesFileUrl; // this.isJarSimulation = isJarSimulation; // } // // @Override // public String toString() { // return "Job{" + // "taskEvent=" + taskEvent + // ", jobId='" + jobId + '\'' + // ", roleId='" + roleId + '\'' + // ", trackingId='" + trackingId + '\'' + // ", isJarSimulation=" + isJarSimulation + // ", abortUrl='" + abortUrl + '\'' + // ", jobFileUrl='" + jobFileUrl + '\'' + // ", resourcesFileUrl='" + resourcesFileUrl + '\'' + // '}'; // } // } // Path: gatling-commons/src/main/java/com/alh/gatling/commons/Worker.java import akka.actor.AbstractActor; import akka.actor.ActorInitializationException; import akka.actor.ActorRef; import akka.actor.Cancellable; import akka.actor.DeathPactException; import akka.actor.OneForOneStrategy; import akka.actor.Props; import akka.actor.ReceiveTimeout; import akka.actor.SupervisorStrategy; import akka.actor.Terminated; import akka.cluster.client.ClusterClient; import akka.event.Logging; import akka.event.LoggingAdapter; import akka.japi.Procedure; import com.alh.gatling.commons.Master.Ack; import com.alh.gatling.commons.Master.Job; import scala.concurrent.duration.Duration; import scala.concurrent.duration.FiniteDuration; import java.io.Serializable; import java.util.UUID; import static akka.actor.SupervisorStrategy.*; //log.info("Work is complete. Result {}.", result); sendToMaster(new MasterWorkerProtocol.WorkIsDone(workerId, jobId(), result)); getContext().setReceiveTimeout(Duration.create(5, "seconds")); Procedure<Object> waitForWorkIsDoneAck = waitForWorkIsDoneAck(result); getContext().become(receiveBuilder() .matchAny(p -> waitForWorkIsDoneAck.apply(p)) .build()); } else if (message instanceof Worker.FileUploadComplete){ sendToMaster(message); getContext().become(receiveBuilder() .matchAny(p->idle.apply(p)) .build()); } else if (message instanceof WorkFailed) { Object result = ((WorkFailed) message).result; log.info("Work is failed. Result {}.", result); sendToMaster(new MasterWorkerProtocol.WorkFailed(workerId, jobId(),result)); getContext().become(receiveBuilder() .matchAny(p->idle.apply(p)) .build()); //getContext().setReceiveTimeout(Duration.create(5, "seconds")); ///Procedure<Object> waitForWorkIsDoneAck = waitForWorkIsDoneAck(result); //getContext().become(waitForWorkIsDoneAck); } else if(message==KeepAliveTick){ log.info("Job is in progress. {}.", jobId()); if (currentJobId!=null){ sendToMaster(new MasterWorkerProtocol.WorkInProgress(workerId, jobId())); }
}else if (message instanceof Job) {
Abiy/distGatling
gatling-commons/src/main/java/com/alh/gatling/commons/Worker.java
// Path: gatling-commons/src/main/java/com/alh/gatling/commons/Master.java // public static final class Ack implements Serializable { // final String workId; // // public Ack(String workId) { // this.workId = workId; // } // // public String getWorkId() { // return workId; // } // // @Override // public String toString() { // return "Ack{" + "jobId='" + workId + '\'' + '}'; // } // } // // Path: gatling-commons/src/main/java/com/alh/gatling/commons/Master.java // public static final class Job implements Serializable { // public final Object taskEvent;//task // public final String jobId; // public final String roleId; // public final String trackingId; // public final boolean isJarSimulation; // public String abortUrl; // public String jobFileUrl; // public String resourcesFileUrl; // // public Job(String roleId, Object job, String trackingId, String abortUrl, String jobFileUrl, String resourcesFileUrl, boolean isJarSimulation) { // this.jobId = UUID.randomUUID().toString(); // this.roleId = roleId; // this.taskEvent = job; // this.trackingId = trackingId; // this.abortUrl = abortUrl; // this.jobFileUrl = jobFileUrl; // this.resourcesFileUrl = resourcesFileUrl; // this.isJarSimulation = isJarSimulation; // } // // @Override // public String toString() { // return "Job{" + // "taskEvent=" + taskEvent + // ", jobId='" + jobId + '\'' + // ", roleId='" + roleId + '\'' + // ", trackingId='" + trackingId + '\'' + // ", isJarSimulation=" + isJarSimulation + // ", abortUrl='" + abortUrl + '\'' + // ", jobFileUrl='" + jobFileUrl + '\'' + // ", resourcesFileUrl='" + resourcesFileUrl + '\'' + // '}'; // } // }
import akka.actor.AbstractActor; import akka.actor.ActorInitializationException; import akka.actor.ActorRef; import akka.actor.Cancellable; import akka.actor.DeathPactException; import akka.actor.OneForOneStrategy; import akka.actor.Props; import akka.actor.ReceiveTimeout; import akka.actor.SupervisorStrategy; import akka.actor.Terminated; import akka.cluster.client.ClusterClient; import akka.event.Logging; import akka.event.LoggingAdapter; import akka.japi.Procedure; import com.alh.gatling.commons.Master.Ack; import com.alh.gatling.commons.Master.Job; import scala.concurrent.duration.Duration; import scala.concurrent.duration.FiniteDuration; import java.io.Serializable; import java.util.UUID; import static akka.actor.SupervisorStrategy.*;
.matchAny(p->idle.apply(p)) .build()); return restart(); } else { log.info("Throwable, Work is failed for "+ t); return escalate(); } } ); } @Override public void postStop() { registerTask.cancel(); keepAliveTask.cancel(); } @Override public Receive createReceive() { return receiveBuilder() .build(); } public void onReceive(Object message) { unhandled(message); } private Procedure<Object> waitForWorkIsDoneAck(final Object result) { return message -> {
// Path: gatling-commons/src/main/java/com/alh/gatling/commons/Master.java // public static final class Ack implements Serializable { // final String workId; // // public Ack(String workId) { // this.workId = workId; // } // // public String getWorkId() { // return workId; // } // // @Override // public String toString() { // return "Ack{" + "jobId='" + workId + '\'' + '}'; // } // } // // Path: gatling-commons/src/main/java/com/alh/gatling/commons/Master.java // public static final class Job implements Serializable { // public final Object taskEvent;//task // public final String jobId; // public final String roleId; // public final String trackingId; // public final boolean isJarSimulation; // public String abortUrl; // public String jobFileUrl; // public String resourcesFileUrl; // // public Job(String roleId, Object job, String trackingId, String abortUrl, String jobFileUrl, String resourcesFileUrl, boolean isJarSimulation) { // this.jobId = UUID.randomUUID().toString(); // this.roleId = roleId; // this.taskEvent = job; // this.trackingId = trackingId; // this.abortUrl = abortUrl; // this.jobFileUrl = jobFileUrl; // this.resourcesFileUrl = resourcesFileUrl; // this.isJarSimulation = isJarSimulation; // } // // @Override // public String toString() { // return "Job{" + // "taskEvent=" + taskEvent + // ", jobId='" + jobId + '\'' + // ", roleId='" + roleId + '\'' + // ", trackingId='" + trackingId + '\'' + // ", isJarSimulation=" + isJarSimulation + // ", abortUrl='" + abortUrl + '\'' + // ", jobFileUrl='" + jobFileUrl + '\'' + // ", resourcesFileUrl='" + resourcesFileUrl + '\'' + // '}'; // } // } // Path: gatling-commons/src/main/java/com/alh/gatling/commons/Worker.java import akka.actor.AbstractActor; import akka.actor.ActorInitializationException; import akka.actor.ActorRef; import akka.actor.Cancellable; import akka.actor.DeathPactException; import akka.actor.OneForOneStrategy; import akka.actor.Props; import akka.actor.ReceiveTimeout; import akka.actor.SupervisorStrategy; import akka.actor.Terminated; import akka.cluster.client.ClusterClient; import akka.event.Logging; import akka.event.LoggingAdapter; import akka.japi.Procedure; import com.alh.gatling.commons.Master.Ack; import com.alh.gatling.commons.Master.Job; import scala.concurrent.duration.Duration; import scala.concurrent.duration.FiniteDuration; import java.io.Serializable; import java.util.UUID; import static akka.actor.SupervisorStrategy.*; .matchAny(p->idle.apply(p)) .build()); return restart(); } else { log.info("Throwable, Work is failed for "+ t); return escalate(); } } ); } @Override public void postStop() { registerTask.cancel(); keepAliveTask.cancel(); } @Override public Receive createReceive() { return receiveBuilder() .build(); } public void onReceive(Object message) { unhandled(message); } private Procedure<Object> waitForWorkIsDoneAck(final Object result) { return message -> {
if (message instanceof Ack && ((Ack) message).workId.equals(jobId())) {
Abiy/distGatling
gatling-rest/src/main/java/com/alh/gatling/Application.java
// Path: gatling-rest/src/main/java/com/alh/gatling/init/StartupRunner.java // public class StartupRunner implements CommandLineRunner { // protected final Log logger = LogFactory.getLog(getClass()); // // @Override // public void run(String... args) throws Exception { // logger.info("Application Initializing..."); // //com.romix.akka.serialization.kryo.KryoSerializer serializer = new KryoSerializer() // //run basic check to make sure the app is starting in a healthy state // // } // }
import com.alh.gatling.init.StartupRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean;
/* * * Copyright 2016 alh Technology * * 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.alh.gatling; @SpringBootApplication public class Application { public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } @Bean
// Path: gatling-rest/src/main/java/com/alh/gatling/init/StartupRunner.java // public class StartupRunner implements CommandLineRunner { // protected final Log logger = LogFactory.getLog(getClass()); // // @Override // public void run(String... args) throws Exception { // logger.info("Application Initializing..."); // //com.romix.akka.serialization.kryo.KryoSerializer serializer = new KryoSerializer() // //run basic check to make sure the app is starting in a healthy state // // } // } // Path: gatling-rest/src/main/java/com/alh/gatling/Application.java import com.alh.gatling.init.StartupRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; /* * * Copyright 2016 alh Technology * * 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.alh.gatling; @SpringBootApplication public class Application { public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } @Bean
public StartupRunner schedulerRunner() {
Abiy/distGatling
gatling-rest/src/test/java/com/alh/gatling/repository/ValuePairTest.java
// Path: gatling-rest/src/main/java/com/alh/gatling/domain/WorkerModel.java // @Data // @XmlRootElement // public class WorkerModel { // private String status; // private String host; // private String actor; // private String workerId; // private String role; // // public WorkerModel(String status, String actor, String workerId) { // this.status = status; // try { // this.actor = java.net.URLDecoder.decode(actor, "UTF-8"); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // this.workerId = workerId; // this.host = this.actor.split("@")[1].split(":")[0]; // this.role = this.actor.split("/")[4].split("#")[0].replaceAll("[0-9]",""); // } // }
import com.alh.gatling.domain.WorkerModel; import org.junit.Test; import static org.junit.Assert.*;
/* * * Copyright 2016 alh Technology * * 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.alh.gatling.repository; /** * on 5/3/17. */ public class ValuePairTest { @Test public void testRoleExtractor(){ String path = "akka.tcp://PerformanceSystem@10.165.150.120:2555/user/script4#-1964952736";
// Path: gatling-rest/src/main/java/com/alh/gatling/domain/WorkerModel.java // @Data // @XmlRootElement // public class WorkerModel { // private String status; // private String host; // private String actor; // private String workerId; // private String role; // // public WorkerModel(String status, String actor, String workerId) { // this.status = status; // try { // this.actor = java.net.URLDecoder.decode(actor, "UTF-8"); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // this.workerId = workerId; // this.host = this.actor.split("@")[1].split(":")[0]; // this.role = this.actor.split("/")[4].split("#")[0].replaceAll("[0-9]",""); // } // } // Path: gatling-rest/src/test/java/com/alh/gatling/repository/ValuePairTest.java import com.alh.gatling.domain.WorkerModel; import org.junit.Test; import static org.junit.Assert.*; /* * * Copyright 2016 alh Technology * * 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.alh.gatling.repository; /** * on 5/3/17. */ public class ValuePairTest { @Test public void testRoleExtractor(){ String path = "akka.tcp://PerformanceSystem@10.165.150.120:2555/user/script4#-1964952736";
WorkerModel pair = new WorkerModel("Idle",path,"workerId");
googleapis/google-oauth-java-client
google-oauth-client-servlet/src/main/java/com/google/api/client/extensions/servlet/auth/AbstractCallbackServlet.java
// Path: google-oauth-client-servlet/src/main/java/com/google/api/client/extensions/auth/helpers/Credential.java // @Beta // @Deprecated // public interface Credential // extends HttpRequestInitializer, HttpExecuteInterceptor, HttpUnsuccessfulResponseHandler { // // /** // * Determine if the Credential is no longer valid, after being revoked for example. // * // * @since 1.5 // */ // boolean isInvalid(); // } // // Path: google-oauth-client-servlet/src/main/java/com/google/api/client/extensions/auth/helpers/ThreeLeggedFlow.java // @Beta // @Deprecated // public interface ThreeLeggedFlow { // // /** // * After the object is created, the developer should use this method to interrogate it for the // * authorization URL to which the user should be redirected to obtain permission. // * // * @return URL to which the user should be directed // */ // String getAuthorizationUrl(); // // /** Set {@link HttpTransport} instance for this three legged flow. */ // void setHttpTransport(HttpTransport transport); // // /** Set {@link JsonFactory} instance for this three legged flow. */ // void setJsonFactory(JsonFactory jsonFactory); // // /** // * Convenience function that will load a credential based on the userId for which this flow was // * instantiated. // * // * @param pm {@link PersistenceManager} instance which this flow should use to interact with the // * data store. The caller must remember to call {@link PersistenceManager#close()} after this // * method returns. // * @return Fully initialized {@link Credential} object or {@code null} if none exists. // */ // Credential loadCredential(PersistenceManager pm); // // /** // * After the user has authorized the request, the token or code obtained should be passed to this // * complete function to allow us to exchange the code with the authentication server for a {@link // * Credential}. // * // * @param authorizationCode Code or token obtained after the user grants permission // * @return {@link Credential} object that is obtained from token server // */ // Credential complete(String authorizationCode) throws IOException; // }
import com.google.api.client.extensions.auth.helpers.Credential; import com.google.api.client.extensions.auth.helpers.ThreeLeggedFlow; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.util.Beta; import java.io.IOException; import java.util.logging.Logger; import javax.jdo.JDOObjectNotFoundException; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
/* * Copyright (c) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.extensions.servlet.auth; /** * {@link Beta} <br> * Callback that will retrieve and complete a {@link ThreeLeggedFlow} when redirected to by a token * server or service provider. Developer should subclass to provide the necessary information * tailored to their specific use case. * * <p>Warning: starting with version 1.7, usage of this for OAuth 2.0 is deprecated. Instead use * {@link * com.google.api.client.extensions.servlet.auth.oauth2.AbstractAuthorizationCodeCallbackServlet}. * * @author moshenko@google.com (Jacob Moshenko) * @since 1.4 * @deprecated Use {@link * com.google.api.client.extensions.servlet.auth.oauth2.AbstractAuthorizationCodeCallbackServlet}. */ @Beta @Deprecated public abstract class AbstractCallbackServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final Logger LOG = Logger.getLogger(AbstractCallbackServlet.class.getName()); private static final String ERROR_PARAM = "error"; private PersistenceManagerFactory pmf;
// Path: google-oauth-client-servlet/src/main/java/com/google/api/client/extensions/auth/helpers/Credential.java // @Beta // @Deprecated // public interface Credential // extends HttpRequestInitializer, HttpExecuteInterceptor, HttpUnsuccessfulResponseHandler { // // /** // * Determine if the Credential is no longer valid, after being revoked for example. // * // * @since 1.5 // */ // boolean isInvalid(); // } // // Path: google-oauth-client-servlet/src/main/java/com/google/api/client/extensions/auth/helpers/ThreeLeggedFlow.java // @Beta // @Deprecated // public interface ThreeLeggedFlow { // // /** // * After the object is created, the developer should use this method to interrogate it for the // * authorization URL to which the user should be redirected to obtain permission. // * // * @return URL to which the user should be directed // */ // String getAuthorizationUrl(); // // /** Set {@link HttpTransport} instance for this three legged flow. */ // void setHttpTransport(HttpTransport transport); // // /** Set {@link JsonFactory} instance for this three legged flow. */ // void setJsonFactory(JsonFactory jsonFactory); // // /** // * Convenience function that will load a credential based on the userId for which this flow was // * instantiated. // * // * @param pm {@link PersistenceManager} instance which this flow should use to interact with the // * data store. The caller must remember to call {@link PersistenceManager#close()} after this // * method returns. // * @return Fully initialized {@link Credential} object or {@code null} if none exists. // */ // Credential loadCredential(PersistenceManager pm); // // /** // * After the user has authorized the request, the token or code obtained should be passed to this // * complete function to allow us to exchange the code with the authentication server for a {@link // * Credential}. // * // * @param authorizationCode Code or token obtained after the user grants permission // * @return {@link Credential} object that is obtained from token server // */ // Credential complete(String authorizationCode) throws IOException; // } // Path: google-oauth-client-servlet/src/main/java/com/google/api/client/extensions/servlet/auth/AbstractCallbackServlet.java import com.google.api.client.extensions.auth.helpers.Credential; import com.google.api.client.extensions.auth.helpers.ThreeLeggedFlow; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.util.Beta; import java.io.IOException; import java.util.logging.Logger; import javax.jdo.JDOObjectNotFoundException; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /* * Copyright (c) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.extensions.servlet.auth; /** * {@link Beta} <br> * Callback that will retrieve and complete a {@link ThreeLeggedFlow} when redirected to by a token * server or service provider. Developer should subclass to provide the necessary information * tailored to their specific use case. * * <p>Warning: starting with version 1.7, usage of this for OAuth 2.0 is deprecated. Instead use * {@link * com.google.api.client.extensions.servlet.auth.oauth2.AbstractAuthorizationCodeCallbackServlet}. * * @author moshenko@google.com (Jacob Moshenko) * @since 1.4 * @deprecated Use {@link * com.google.api.client.extensions.servlet.auth.oauth2.AbstractAuthorizationCodeCallbackServlet}. */ @Beta @Deprecated public abstract class AbstractCallbackServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final Logger LOG = Logger.getLogger(AbstractCallbackServlet.class.getName()); private static final String ERROR_PARAM = "error"; private PersistenceManagerFactory pmf;
private Class<? extends ThreeLeggedFlow> flowType;
googleapis/google-oauth-java-client
google-oauth-client-servlet/src/main/java/com/google/api/client/extensions/servlet/auth/AbstractCallbackServlet.java
// Path: google-oauth-client-servlet/src/main/java/com/google/api/client/extensions/auth/helpers/Credential.java // @Beta // @Deprecated // public interface Credential // extends HttpRequestInitializer, HttpExecuteInterceptor, HttpUnsuccessfulResponseHandler { // // /** // * Determine if the Credential is no longer valid, after being revoked for example. // * // * @since 1.5 // */ // boolean isInvalid(); // } // // Path: google-oauth-client-servlet/src/main/java/com/google/api/client/extensions/auth/helpers/ThreeLeggedFlow.java // @Beta // @Deprecated // public interface ThreeLeggedFlow { // // /** // * After the object is created, the developer should use this method to interrogate it for the // * authorization URL to which the user should be redirected to obtain permission. // * // * @return URL to which the user should be directed // */ // String getAuthorizationUrl(); // // /** Set {@link HttpTransport} instance for this three legged flow. */ // void setHttpTransport(HttpTransport transport); // // /** Set {@link JsonFactory} instance for this three legged flow. */ // void setJsonFactory(JsonFactory jsonFactory); // // /** // * Convenience function that will load a credential based on the userId for which this flow was // * instantiated. // * // * @param pm {@link PersistenceManager} instance which this flow should use to interact with the // * data store. The caller must remember to call {@link PersistenceManager#close()} after this // * method returns. // * @return Fully initialized {@link Credential} object or {@code null} if none exists. // */ // Credential loadCredential(PersistenceManager pm); // // /** // * After the user has authorized the request, the token or code obtained should be passed to this // * complete function to allow us to exchange the code with the authentication server for a {@link // * Credential}. // * // * @param authorizationCode Code or token obtained after the user grants permission // * @return {@link Credential} object that is obtained from token server // */ // Credential complete(String authorizationCode) throws IOException; // }
import com.google.api.client.extensions.auth.helpers.Credential; import com.google.api.client.extensions.auth.helpers.ThreeLeggedFlow; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.util.Beta; import java.io.IOException; import java.util.logging.Logger; import javax.jdo.JDOObjectNotFoundException; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
if ((completionCode == null || "".equals(completionCode)) && (errorCode == null || "".equals(errorCode))) { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); resp.getWriter().print("Must have a query parameter: " + completionCodeQueryParam); return; } else if (errorCode != null && !"".equals(errorCode)) { resp.sendRedirect(deniedRedirectUrl); return; } // Get a key for the logged in user to retrieve the flow String userId = getUserId(); // Get flow from the data store PersistenceManager manager = pmf.getPersistenceManager(); try { ThreeLeggedFlow flow = null; try { flow = manager.getObjectById(flowType, userId); } catch (JDOObjectNotFoundException e) { LOG.severe("Unable to locate flow by user: " + userId); resp.setStatus(HttpServletResponse.SC_NOT_FOUND); resp.getWriter().print("Unable to find flow for user: " + userId); return; } flow.setHttpTransport(getHttpTransport()); flow.setJsonFactory(getJsonFactory()); // Complete the flow object with the token we got in our query parameters
// Path: google-oauth-client-servlet/src/main/java/com/google/api/client/extensions/auth/helpers/Credential.java // @Beta // @Deprecated // public interface Credential // extends HttpRequestInitializer, HttpExecuteInterceptor, HttpUnsuccessfulResponseHandler { // // /** // * Determine if the Credential is no longer valid, after being revoked for example. // * // * @since 1.5 // */ // boolean isInvalid(); // } // // Path: google-oauth-client-servlet/src/main/java/com/google/api/client/extensions/auth/helpers/ThreeLeggedFlow.java // @Beta // @Deprecated // public interface ThreeLeggedFlow { // // /** // * After the object is created, the developer should use this method to interrogate it for the // * authorization URL to which the user should be redirected to obtain permission. // * // * @return URL to which the user should be directed // */ // String getAuthorizationUrl(); // // /** Set {@link HttpTransport} instance for this three legged flow. */ // void setHttpTransport(HttpTransport transport); // // /** Set {@link JsonFactory} instance for this three legged flow. */ // void setJsonFactory(JsonFactory jsonFactory); // // /** // * Convenience function that will load a credential based on the userId for which this flow was // * instantiated. // * // * @param pm {@link PersistenceManager} instance which this flow should use to interact with the // * data store. The caller must remember to call {@link PersistenceManager#close()} after this // * method returns. // * @return Fully initialized {@link Credential} object or {@code null} if none exists. // */ // Credential loadCredential(PersistenceManager pm); // // /** // * After the user has authorized the request, the token or code obtained should be passed to this // * complete function to allow us to exchange the code with the authentication server for a {@link // * Credential}. // * // * @param authorizationCode Code or token obtained after the user grants permission // * @return {@link Credential} object that is obtained from token server // */ // Credential complete(String authorizationCode) throws IOException; // } // Path: google-oauth-client-servlet/src/main/java/com/google/api/client/extensions/servlet/auth/AbstractCallbackServlet.java import com.google.api.client.extensions.auth.helpers.Credential; import com.google.api.client.extensions.auth.helpers.ThreeLeggedFlow; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.util.Beta; import java.io.IOException; import java.util.logging.Logger; import javax.jdo.JDOObjectNotFoundException; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; if ((completionCode == null || "".equals(completionCode)) && (errorCode == null || "".equals(errorCode))) { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); resp.getWriter().print("Must have a query parameter: " + completionCodeQueryParam); return; } else if (errorCode != null && !"".equals(errorCode)) { resp.sendRedirect(deniedRedirectUrl); return; } // Get a key for the logged in user to retrieve the flow String userId = getUserId(); // Get flow from the data store PersistenceManager manager = pmf.getPersistenceManager(); try { ThreeLeggedFlow flow = null; try { flow = manager.getObjectById(flowType, userId); } catch (JDOObjectNotFoundException e) { LOG.severe("Unable to locate flow by user: " + userId); resp.setStatus(HttpServletResponse.SC_NOT_FOUND); resp.getWriter().print("Unable to find flow for user: " + userId); return; } flow.setHttpTransport(getHttpTransport()); flow.setJsonFactory(getJsonFactory()); // Complete the flow object with the token we got in our query parameters
Credential c = flow.complete(completionCode);
googleapis/google-oauth-java-client
google-oauth-client/src/test/java/com/google/api/client/auth/oauth2/ClientCredentialsTokenRequestTest.java
// Path: google-oauth-client/src/main/java/com/google/api/client/auth/openidconnect/IdTokenResponse.java // @Beta // public class IdTokenResponse extends TokenResponse { // // /** ID token. */ // @Key("id_token") // private String idToken; // // /** Returns the ID token. */ // public final String getIdToken() { // return idToken; // } // // /** // * Sets the ID token. // * // * <p>Overriding is only supported for the purpose of calling the super implementation and // * changing the return type, but nothing else. // */ // public IdTokenResponse setIdToken(String idToken) { // this.idToken = Preconditions.checkNotNull(idToken); // return this; // } // // @Override // public IdTokenResponse setAccessToken(String accessToken) { // super.setAccessToken(accessToken); // return this; // } // // @Override // public IdTokenResponse setTokenType(String tokenType) { // super.setTokenType(tokenType); // return this; // } // // @Override // public IdTokenResponse setExpiresInSeconds(Long expiresIn) { // super.setExpiresInSeconds(expiresIn); // return this; // } // // @Override // public IdTokenResponse setRefreshToken(String refreshToken) { // super.setRefreshToken(refreshToken); // return this; // } // // @Override // public IdTokenResponse setScope(String scope) { // super.setScope(scope); // return this; // } // // /** // * Parses using {@link JsonWebSignature#parse(JsonFactory, String)} based on the {@link // * #getFactory() JSON factory} and {@link #getIdToken() ID token}. // */ // @SuppressWarnings("javadoc") // public IdToken parseIdToken() throws IOException { // return IdToken.parse(getFactory(), idToken); // } // // /** // * Executes the given ID token request, and returns the parsed ID token response. // * // * @param tokenRequest token request // * @return parsed successful ID token response // * @throws TokenResponseException for an error response // */ // public static IdTokenResponse execute(TokenRequest tokenRequest) throws IOException { // return tokenRequest.executeUnparsed().parseAs(IdTokenResponse.class); // } // // @Override // public IdTokenResponse set(String fieldName, Object value) { // return (IdTokenResponse) super.set(fieldName, value); // } // // @Override // public IdTokenResponse clone() { // return (IdTokenResponse) super.clone(); // } // }
import com.google.api.client.auth.openidconnect.IdTokenResponse; import junit.framework.TestCase;
/* * Copyright (c) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.auth.oauth2; /** * Tests {@link ClientCredentialsTokenRequest}. * * @author Yaniv Inbar */ public class ClientCredentialsTokenRequestTest extends TestCase { public void testConstructor() { check( new ClientCredentialsTokenRequest( TokenRequestTest.TRANSPORT, TokenRequestTest.JSON_FACTORY, TokenRequestTest.AUTHORIZATION_SERVER_URL)); } private void check(ClientCredentialsTokenRequest request) { TokenRequestTest.check(request, "client_credentials"); } public void testSetResponseClass() { ClientCredentialsTokenRequest request = new ClientCredentialsTokenRequest( TokenRequestTest.TRANSPORT, TokenRequestTest.JSON_FACTORY, TokenRequestTest.AUTHORIZATION_SERVER_URL)
// Path: google-oauth-client/src/main/java/com/google/api/client/auth/openidconnect/IdTokenResponse.java // @Beta // public class IdTokenResponse extends TokenResponse { // // /** ID token. */ // @Key("id_token") // private String idToken; // // /** Returns the ID token. */ // public final String getIdToken() { // return idToken; // } // // /** // * Sets the ID token. // * // * <p>Overriding is only supported for the purpose of calling the super implementation and // * changing the return type, but nothing else. // */ // public IdTokenResponse setIdToken(String idToken) { // this.idToken = Preconditions.checkNotNull(idToken); // return this; // } // // @Override // public IdTokenResponse setAccessToken(String accessToken) { // super.setAccessToken(accessToken); // return this; // } // // @Override // public IdTokenResponse setTokenType(String tokenType) { // super.setTokenType(tokenType); // return this; // } // // @Override // public IdTokenResponse setExpiresInSeconds(Long expiresIn) { // super.setExpiresInSeconds(expiresIn); // return this; // } // // @Override // public IdTokenResponse setRefreshToken(String refreshToken) { // super.setRefreshToken(refreshToken); // return this; // } // // @Override // public IdTokenResponse setScope(String scope) { // super.setScope(scope); // return this; // } // // /** // * Parses using {@link JsonWebSignature#parse(JsonFactory, String)} based on the {@link // * #getFactory() JSON factory} and {@link #getIdToken() ID token}. // */ // @SuppressWarnings("javadoc") // public IdToken parseIdToken() throws IOException { // return IdToken.parse(getFactory(), idToken); // } // // /** // * Executes the given ID token request, and returns the parsed ID token response. // * // * @param tokenRequest token request // * @return parsed successful ID token response // * @throws TokenResponseException for an error response // */ // public static IdTokenResponse execute(TokenRequest tokenRequest) throws IOException { // return tokenRequest.executeUnparsed().parseAs(IdTokenResponse.class); // } // // @Override // public IdTokenResponse set(String fieldName, Object value) { // return (IdTokenResponse) super.set(fieldName, value); // } // // @Override // public IdTokenResponse clone() { // return (IdTokenResponse) super.clone(); // } // } // Path: google-oauth-client/src/test/java/com/google/api/client/auth/oauth2/ClientCredentialsTokenRequestTest.java import com.google.api.client.auth.openidconnect.IdTokenResponse; import junit.framework.TestCase; /* * Copyright (c) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.auth.oauth2; /** * Tests {@link ClientCredentialsTokenRequest}. * * @author Yaniv Inbar */ public class ClientCredentialsTokenRequestTest extends TestCase { public void testConstructor() { check( new ClientCredentialsTokenRequest( TokenRequestTest.TRANSPORT, TokenRequestTest.JSON_FACTORY, TokenRequestTest.AUTHORIZATION_SERVER_URL)); } private void check(ClientCredentialsTokenRequest request) { TokenRequestTest.check(request, "client_credentials"); } public void testSetResponseClass() { ClientCredentialsTokenRequest request = new ClientCredentialsTokenRequest( TokenRequestTest.TRANSPORT, TokenRequestTest.JSON_FACTORY, TokenRequestTest.AUTHORIZATION_SERVER_URL)
.setResponseClass(IdTokenResponse.class);
googleapis/google-oauth-java-client
google-oauth-client-servlet/src/main/java/com/google/api/client/extensions/servlet/auth/AbstractFlowUserServlet.java
// Path: google-oauth-client-servlet/src/main/java/com/google/api/client/extensions/auth/helpers/Credential.java // @Beta // @Deprecated // public interface Credential // extends HttpRequestInitializer, HttpExecuteInterceptor, HttpUnsuccessfulResponseHandler { // // /** // * Determine if the Credential is no longer valid, after being revoked for example. // * // * @since 1.5 // */ // boolean isInvalid(); // } // // Path: google-oauth-client-servlet/src/main/java/com/google/api/client/extensions/auth/helpers/ThreeLeggedFlow.java // @Beta // @Deprecated // public interface ThreeLeggedFlow { // // /** // * After the object is created, the developer should use this method to interrogate it for the // * authorization URL to which the user should be redirected to obtain permission. // * // * @return URL to which the user should be directed // */ // String getAuthorizationUrl(); // // /** Set {@link HttpTransport} instance for this three legged flow. */ // void setHttpTransport(HttpTransport transport); // // /** Set {@link JsonFactory} instance for this three legged flow. */ // void setJsonFactory(JsonFactory jsonFactory); // // /** // * Convenience function that will load a credential based on the userId for which this flow was // * instantiated. // * // * @param pm {@link PersistenceManager} instance which this flow should use to interact with the // * data store. The caller must remember to call {@link PersistenceManager#close()} after this // * method returns. // * @return Fully initialized {@link Credential} object or {@code null} if none exists. // */ // Credential loadCredential(PersistenceManager pm); // // /** // * After the user has authorized the request, the token or code obtained should be passed to this // * complete function to allow us to exchange the code with the authentication server for a {@link // * Credential}. // * // * @param authorizationCode Code or token obtained after the user grants permission // * @return {@link Credential} object that is obtained from token server // */ // Credential complete(String authorizationCode) throws IOException; // }
import com.google.api.client.extensions.auth.helpers.Credential; import com.google.api.client.extensions.auth.helpers.ThreeLeggedFlow; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.util.Beta; import java.io.IOException; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
/* * Copyright (c) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.extensions.servlet.auth; /** * {@link Beta} <br> * Servlet that can be used to invoke and manage a {@link ThreeLeggedFlow} object in the App Engine * container. Developers should subclass this to provide the necessary information for their * specific use case. * * <p>Warning: starting with version 1.7, usage of this for OAuth 2.0 is deprecated. Instead use * {@link com.google.api.client.extensions.servlet.auth.oauth2.AbstractAuthorizationCodeServlet}. * * @author moshenko@google.com (Jacob Moshenko) * @since 1.4 * @deprecated Use {@link * com.google.api.client.extensions.servlet.auth.oauth2.AbstractAuthorizationCodeServlet}. */ @Beta @Deprecated public abstract class AbstractFlowUserServlet extends HttpServlet { private static final long serialVersionUID = 1L; private final HttpTransport httpTransport; private final JsonFactory jsonFactory; /** * Reserved request context identifier used to store the credential instance in an authorized * servlet. */ private static final String AUTH_CREDENTIAL = "com.google.api.client.extensions.servlet.auth.credential"; public AbstractFlowUserServlet() { httpTransport = newHttpTransportInstance(); jsonFactory = newJsonFactoryInstance(); } @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { PersistenceManager pm = getPersistenceManagerFactory().getPersistenceManager(); String userId = getUserId();
// Path: google-oauth-client-servlet/src/main/java/com/google/api/client/extensions/auth/helpers/Credential.java // @Beta // @Deprecated // public interface Credential // extends HttpRequestInitializer, HttpExecuteInterceptor, HttpUnsuccessfulResponseHandler { // // /** // * Determine if the Credential is no longer valid, after being revoked for example. // * // * @since 1.5 // */ // boolean isInvalid(); // } // // Path: google-oauth-client-servlet/src/main/java/com/google/api/client/extensions/auth/helpers/ThreeLeggedFlow.java // @Beta // @Deprecated // public interface ThreeLeggedFlow { // // /** // * After the object is created, the developer should use this method to interrogate it for the // * authorization URL to which the user should be redirected to obtain permission. // * // * @return URL to which the user should be directed // */ // String getAuthorizationUrl(); // // /** Set {@link HttpTransport} instance for this three legged flow. */ // void setHttpTransport(HttpTransport transport); // // /** Set {@link JsonFactory} instance for this three legged flow. */ // void setJsonFactory(JsonFactory jsonFactory); // // /** // * Convenience function that will load a credential based on the userId for which this flow was // * instantiated. // * // * @param pm {@link PersistenceManager} instance which this flow should use to interact with the // * data store. The caller must remember to call {@link PersistenceManager#close()} after this // * method returns. // * @return Fully initialized {@link Credential} object or {@code null} if none exists. // */ // Credential loadCredential(PersistenceManager pm); // // /** // * After the user has authorized the request, the token or code obtained should be passed to this // * complete function to allow us to exchange the code with the authentication server for a {@link // * Credential}. // * // * @param authorizationCode Code or token obtained after the user grants permission // * @return {@link Credential} object that is obtained from token server // */ // Credential complete(String authorizationCode) throws IOException; // } // Path: google-oauth-client-servlet/src/main/java/com/google/api/client/extensions/servlet/auth/AbstractFlowUserServlet.java import com.google.api.client.extensions.auth.helpers.Credential; import com.google.api.client.extensions.auth.helpers.ThreeLeggedFlow; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.util.Beta; import java.io.IOException; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /* * Copyright (c) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.extensions.servlet.auth; /** * {@link Beta} <br> * Servlet that can be used to invoke and manage a {@link ThreeLeggedFlow} object in the App Engine * container. Developers should subclass this to provide the necessary information for their * specific use case. * * <p>Warning: starting with version 1.7, usage of this for OAuth 2.0 is deprecated. Instead use * {@link com.google.api.client.extensions.servlet.auth.oauth2.AbstractAuthorizationCodeServlet}. * * @author moshenko@google.com (Jacob Moshenko) * @since 1.4 * @deprecated Use {@link * com.google.api.client.extensions.servlet.auth.oauth2.AbstractAuthorizationCodeServlet}. */ @Beta @Deprecated public abstract class AbstractFlowUserServlet extends HttpServlet { private static final long serialVersionUID = 1L; private final HttpTransport httpTransport; private final JsonFactory jsonFactory; /** * Reserved request context identifier used to store the credential instance in an authorized * servlet. */ private static final String AUTH_CREDENTIAL = "com.google.api.client.extensions.servlet.auth.credential"; public AbstractFlowUserServlet() { httpTransport = newHttpTransportInstance(); jsonFactory = newJsonFactoryInstance(); } @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { PersistenceManager pm = getPersistenceManagerFactory().getPersistenceManager(); String userId = getUserId();
ThreeLeggedFlow oauthFlow = newFlow(userId);
googleapis/google-oauth-java-client
google-oauth-client-servlet/src/main/java/com/google/api/client/extensions/servlet/auth/AbstractFlowUserServlet.java
// Path: google-oauth-client-servlet/src/main/java/com/google/api/client/extensions/auth/helpers/Credential.java // @Beta // @Deprecated // public interface Credential // extends HttpRequestInitializer, HttpExecuteInterceptor, HttpUnsuccessfulResponseHandler { // // /** // * Determine if the Credential is no longer valid, after being revoked for example. // * // * @since 1.5 // */ // boolean isInvalid(); // } // // Path: google-oauth-client-servlet/src/main/java/com/google/api/client/extensions/auth/helpers/ThreeLeggedFlow.java // @Beta // @Deprecated // public interface ThreeLeggedFlow { // // /** // * After the object is created, the developer should use this method to interrogate it for the // * authorization URL to which the user should be redirected to obtain permission. // * // * @return URL to which the user should be directed // */ // String getAuthorizationUrl(); // // /** Set {@link HttpTransport} instance for this three legged flow. */ // void setHttpTransport(HttpTransport transport); // // /** Set {@link JsonFactory} instance for this three legged flow. */ // void setJsonFactory(JsonFactory jsonFactory); // // /** // * Convenience function that will load a credential based on the userId for which this flow was // * instantiated. // * // * @param pm {@link PersistenceManager} instance which this flow should use to interact with the // * data store. The caller must remember to call {@link PersistenceManager#close()} after this // * method returns. // * @return Fully initialized {@link Credential} object or {@code null} if none exists. // */ // Credential loadCredential(PersistenceManager pm); // // /** // * After the user has authorized the request, the token or code obtained should be passed to this // * complete function to allow us to exchange the code with the authentication server for a {@link // * Credential}. // * // * @param authorizationCode Code or token obtained after the user grants permission // * @return {@link Credential} object that is obtained from token server // */ // Credential complete(String authorizationCode) throws IOException; // }
import com.google.api.client.extensions.auth.helpers.Credential; import com.google.api.client.extensions.auth.helpers.ThreeLeggedFlow; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.util.Beta; import java.io.IOException; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
/* * Copyright (c) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.extensions.servlet.auth; /** * {@link Beta} <br> * Servlet that can be used to invoke and manage a {@link ThreeLeggedFlow} object in the App Engine * container. Developers should subclass this to provide the necessary information for their * specific use case. * * <p>Warning: starting with version 1.7, usage of this for OAuth 2.0 is deprecated. Instead use * {@link com.google.api.client.extensions.servlet.auth.oauth2.AbstractAuthorizationCodeServlet}. * * @author moshenko@google.com (Jacob Moshenko) * @since 1.4 * @deprecated Use {@link * com.google.api.client.extensions.servlet.auth.oauth2.AbstractAuthorizationCodeServlet}. */ @Beta @Deprecated public abstract class AbstractFlowUserServlet extends HttpServlet { private static final long serialVersionUID = 1L; private final HttpTransport httpTransport; private final JsonFactory jsonFactory; /** * Reserved request context identifier used to store the credential instance in an authorized * servlet. */ private static final String AUTH_CREDENTIAL = "com.google.api.client.extensions.servlet.auth.credential"; public AbstractFlowUserServlet() { httpTransport = newHttpTransportInstance(); jsonFactory = newJsonFactoryInstance(); } @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { PersistenceManager pm = getPersistenceManagerFactory().getPersistenceManager(); String userId = getUserId(); ThreeLeggedFlow oauthFlow = newFlow(userId); oauthFlow.setJsonFactory(getJsonFactory()); oauthFlow.setHttpTransport(getHttpTransport()); try {
// Path: google-oauth-client-servlet/src/main/java/com/google/api/client/extensions/auth/helpers/Credential.java // @Beta // @Deprecated // public interface Credential // extends HttpRequestInitializer, HttpExecuteInterceptor, HttpUnsuccessfulResponseHandler { // // /** // * Determine if the Credential is no longer valid, after being revoked for example. // * // * @since 1.5 // */ // boolean isInvalid(); // } // // Path: google-oauth-client-servlet/src/main/java/com/google/api/client/extensions/auth/helpers/ThreeLeggedFlow.java // @Beta // @Deprecated // public interface ThreeLeggedFlow { // // /** // * After the object is created, the developer should use this method to interrogate it for the // * authorization URL to which the user should be redirected to obtain permission. // * // * @return URL to which the user should be directed // */ // String getAuthorizationUrl(); // // /** Set {@link HttpTransport} instance for this three legged flow. */ // void setHttpTransport(HttpTransport transport); // // /** Set {@link JsonFactory} instance for this three legged flow. */ // void setJsonFactory(JsonFactory jsonFactory); // // /** // * Convenience function that will load a credential based on the userId for which this flow was // * instantiated. // * // * @param pm {@link PersistenceManager} instance which this flow should use to interact with the // * data store. The caller must remember to call {@link PersistenceManager#close()} after this // * method returns. // * @return Fully initialized {@link Credential} object or {@code null} if none exists. // */ // Credential loadCredential(PersistenceManager pm); // // /** // * After the user has authorized the request, the token or code obtained should be passed to this // * complete function to allow us to exchange the code with the authentication server for a {@link // * Credential}. // * // * @param authorizationCode Code or token obtained after the user grants permission // * @return {@link Credential} object that is obtained from token server // */ // Credential complete(String authorizationCode) throws IOException; // } // Path: google-oauth-client-servlet/src/main/java/com/google/api/client/extensions/servlet/auth/AbstractFlowUserServlet.java import com.google.api.client.extensions.auth.helpers.Credential; import com.google.api.client.extensions.auth.helpers.ThreeLeggedFlow; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.util.Beta; import java.io.IOException; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /* * Copyright (c) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.extensions.servlet.auth; /** * {@link Beta} <br> * Servlet that can be used to invoke and manage a {@link ThreeLeggedFlow} object in the App Engine * container. Developers should subclass this to provide the necessary information for their * specific use case. * * <p>Warning: starting with version 1.7, usage of this for OAuth 2.0 is deprecated. Instead use * {@link com.google.api.client.extensions.servlet.auth.oauth2.AbstractAuthorizationCodeServlet}. * * @author moshenko@google.com (Jacob Moshenko) * @since 1.4 * @deprecated Use {@link * com.google.api.client.extensions.servlet.auth.oauth2.AbstractAuthorizationCodeServlet}. */ @Beta @Deprecated public abstract class AbstractFlowUserServlet extends HttpServlet { private static final long serialVersionUID = 1L; private final HttpTransport httpTransport; private final JsonFactory jsonFactory; /** * Reserved request context identifier used to store the credential instance in an authorized * servlet. */ private static final String AUTH_CREDENTIAL = "com.google.api.client.extensions.servlet.auth.credential"; public AbstractFlowUserServlet() { httpTransport = newHttpTransportInstance(); jsonFactory = newJsonFactoryInstance(); } @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { PersistenceManager pm = getPersistenceManagerFactory().getPersistenceManager(); String userId = getUserId(); ThreeLeggedFlow oauthFlow = newFlow(userId); oauthFlow.setJsonFactory(getJsonFactory()); oauthFlow.setHttpTransport(getHttpTransport()); try {
Credential cred = oauthFlow.loadCredential(pm);
googleapis/google-oauth-java-client
google-oauth-client/src/test/java/com/google/api/client/auth/oauth2/RefreshTokenRequestTest.java
// Path: google-oauth-client/src/main/java/com/google/api/client/auth/openidconnect/IdTokenResponse.java // @Beta // public class IdTokenResponse extends TokenResponse { // // /** ID token. */ // @Key("id_token") // private String idToken; // // /** Returns the ID token. */ // public final String getIdToken() { // return idToken; // } // // /** // * Sets the ID token. // * // * <p>Overriding is only supported for the purpose of calling the super implementation and // * changing the return type, but nothing else. // */ // public IdTokenResponse setIdToken(String idToken) { // this.idToken = Preconditions.checkNotNull(idToken); // return this; // } // // @Override // public IdTokenResponse setAccessToken(String accessToken) { // super.setAccessToken(accessToken); // return this; // } // // @Override // public IdTokenResponse setTokenType(String tokenType) { // super.setTokenType(tokenType); // return this; // } // // @Override // public IdTokenResponse setExpiresInSeconds(Long expiresIn) { // super.setExpiresInSeconds(expiresIn); // return this; // } // // @Override // public IdTokenResponse setRefreshToken(String refreshToken) { // super.setRefreshToken(refreshToken); // return this; // } // // @Override // public IdTokenResponse setScope(String scope) { // super.setScope(scope); // return this; // } // // /** // * Parses using {@link JsonWebSignature#parse(JsonFactory, String)} based on the {@link // * #getFactory() JSON factory} and {@link #getIdToken() ID token}. // */ // @SuppressWarnings("javadoc") // public IdToken parseIdToken() throws IOException { // return IdToken.parse(getFactory(), idToken); // } // // /** // * Executes the given ID token request, and returns the parsed ID token response. // * // * @param tokenRequest token request // * @return parsed successful ID token response // * @throws TokenResponseException for an error response // */ // public static IdTokenResponse execute(TokenRequest tokenRequest) throws IOException { // return tokenRequest.executeUnparsed().parseAs(IdTokenResponse.class); // } // // @Override // public IdTokenResponse set(String fieldName, Object value) { // return (IdTokenResponse) super.set(fieldName, value); // } // // @Override // public IdTokenResponse clone() { // return (IdTokenResponse) super.clone(); // } // }
import com.google.api.client.auth.openidconnect.IdTokenResponse; import junit.framework.TestCase;
/* * Copyright (c) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.auth.oauth2; /** * Tests {@link RefreshTokenRequest}. * * @author Yaniv Inbar */ public class RefreshTokenRequestTest extends TestCase { private static final String REFRESH_TOKEN = "tGzv3JOkF0XG5Qx2TlKWIA"; public void testConstructor() { check( new RefreshTokenRequest( TokenRequestTest.TRANSPORT, TokenRequestTest.JSON_FACTORY, TokenRequestTest.AUTHORIZATION_SERVER_URL, REFRESH_TOKEN)); } private void check(RefreshTokenRequest request) { TokenRequestTest.check(request, "refresh_token"); assertEquals(REFRESH_TOKEN, request.getRefreshToken()); } public void testSetResponseClass() { RefreshTokenRequest request = new RefreshTokenRequest( TokenRequestTest.TRANSPORT, TokenRequestTest.JSON_FACTORY, TokenRequestTest.AUTHORIZATION_SERVER_URL, REFRESH_TOKEN)
// Path: google-oauth-client/src/main/java/com/google/api/client/auth/openidconnect/IdTokenResponse.java // @Beta // public class IdTokenResponse extends TokenResponse { // // /** ID token. */ // @Key("id_token") // private String idToken; // // /** Returns the ID token. */ // public final String getIdToken() { // return idToken; // } // // /** // * Sets the ID token. // * // * <p>Overriding is only supported for the purpose of calling the super implementation and // * changing the return type, but nothing else. // */ // public IdTokenResponse setIdToken(String idToken) { // this.idToken = Preconditions.checkNotNull(idToken); // return this; // } // // @Override // public IdTokenResponse setAccessToken(String accessToken) { // super.setAccessToken(accessToken); // return this; // } // // @Override // public IdTokenResponse setTokenType(String tokenType) { // super.setTokenType(tokenType); // return this; // } // // @Override // public IdTokenResponse setExpiresInSeconds(Long expiresIn) { // super.setExpiresInSeconds(expiresIn); // return this; // } // // @Override // public IdTokenResponse setRefreshToken(String refreshToken) { // super.setRefreshToken(refreshToken); // return this; // } // // @Override // public IdTokenResponse setScope(String scope) { // super.setScope(scope); // return this; // } // // /** // * Parses using {@link JsonWebSignature#parse(JsonFactory, String)} based on the {@link // * #getFactory() JSON factory} and {@link #getIdToken() ID token}. // */ // @SuppressWarnings("javadoc") // public IdToken parseIdToken() throws IOException { // return IdToken.parse(getFactory(), idToken); // } // // /** // * Executes the given ID token request, and returns the parsed ID token response. // * // * @param tokenRequest token request // * @return parsed successful ID token response // * @throws TokenResponseException for an error response // */ // public static IdTokenResponse execute(TokenRequest tokenRequest) throws IOException { // return tokenRequest.executeUnparsed().parseAs(IdTokenResponse.class); // } // // @Override // public IdTokenResponse set(String fieldName, Object value) { // return (IdTokenResponse) super.set(fieldName, value); // } // // @Override // public IdTokenResponse clone() { // return (IdTokenResponse) super.clone(); // } // } // Path: google-oauth-client/src/test/java/com/google/api/client/auth/oauth2/RefreshTokenRequestTest.java import com.google.api.client.auth.openidconnect.IdTokenResponse; import junit.framework.TestCase; /* * Copyright (c) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.auth.oauth2; /** * Tests {@link RefreshTokenRequest}. * * @author Yaniv Inbar */ public class RefreshTokenRequestTest extends TestCase { private static final String REFRESH_TOKEN = "tGzv3JOkF0XG5Qx2TlKWIA"; public void testConstructor() { check( new RefreshTokenRequest( TokenRequestTest.TRANSPORT, TokenRequestTest.JSON_FACTORY, TokenRequestTest.AUTHORIZATION_SERVER_URL, REFRESH_TOKEN)); } private void check(RefreshTokenRequest request) { TokenRequestTest.check(request, "refresh_token"); assertEquals(REFRESH_TOKEN, request.getRefreshToken()); } public void testSetResponseClass() { RefreshTokenRequest request = new RefreshTokenRequest( TokenRequestTest.TRANSPORT, TokenRequestTest.JSON_FACTORY, TokenRequestTest.AUTHORIZATION_SERVER_URL, REFRESH_TOKEN)
.setResponseClass(IdTokenResponse.class);
googleapis/google-oauth-java-client
google-oauth-client/src/test/java/com/google/api/client/auth/oauth2/AuthorizationCodeTokenRequestTest.java
// Path: google-oauth-client/src/main/java/com/google/api/client/auth/openidconnect/IdTokenResponse.java // @Beta // public class IdTokenResponse extends TokenResponse { // // /** ID token. */ // @Key("id_token") // private String idToken; // // /** Returns the ID token. */ // public final String getIdToken() { // return idToken; // } // // /** // * Sets the ID token. // * // * <p>Overriding is only supported for the purpose of calling the super implementation and // * changing the return type, but nothing else. // */ // public IdTokenResponse setIdToken(String idToken) { // this.idToken = Preconditions.checkNotNull(idToken); // return this; // } // // @Override // public IdTokenResponse setAccessToken(String accessToken) { // super.setAccessToken(accessToken); // return this; // } // // @Override // public IdTokenResponse setTokenType(String tokenType) { // super.setTokenType(tokenType); // return this; // } // // @Override // public IdTokenResponse setExpiresInSeconds(Long expiresIn) { // super.setExpiresInSeconds(expiresIn); // return this; // } // // @Override // public IdTokenResponse setRefreshToken(String refreshToken) { // super.setRefreshToken(refreshToken); // return this; // } // // @Override // public IdTokenResponse setScope(String scope) { // super.setScope(scope); // return this; // } // // /** // * Parses using {@link JsonWebSignature#parse(JsonFactory, String)} based on the {@link // * #getFactory() JSON factory} and {@link #getIdToken() ID token}. // */ // @SuppressWarnings("javadoc") // public IdToken parseIdToken() throws IOException { // return IdToken.parse(getFactory(), idToken); // } // // /** // * Executes the given ID token request, and returns the parsed ID token response. // * // * @param tokenRequest token request // * @return parsed successful ID token response // * @throws TokenResponseException for an error response // */ // public static IdTokenResponse execute(TokenRequest tokenRequest) throws IOException { // return tokenRequest.executeUnparsed().parseAs(IdTokenResponse.class); // } // // @Override // public IdTokenResponse set(String fieldName, Object value) { // return (IdTokenResponse) super.set(fieldName, value); // } // // @Override // public IdTokenResponse clone() { // return (IdTokenResponse) super.clone(); // } // }
import com.google.api.client.auth.openidconnect.IdTokenResponse; import junit.framework.TestCase;
/* * Copyright (c) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.auth.oauth2; /** * Tests {@link AuthorizationCodeTokenRequest}. * * @author Yaniv Inbar */ public class AuthorizationCodeTokenRequestTest extends TestCase { private static final String CODE = "i1WsRn1uB1"; private static final String REDIRECT_URI = "https://client.example.com/rd"; public void testConstructor() { check( new AuthorizationCodeTokenRequest( TokenRequestTest.TRANSPORT, TokenRequestTest.JSON_FACTORY, TokenRequestTest.AUTHORIZATION_SERVER_URL, CODE) .setRedirectUri(REDIRECT_URI)); } private void check(AuthorizationCodeTokenRequest request) { TokenRequestTest.check(request, "authorization_code"); assertEquals(CODE, request.getCode()); assertEquals(REDIRECT_URI, request.getRedirectUri()); } public void testSetResponseClass() { AuthorizationCodeTokenRequest request = new AuthorizationCodeTokenRequest( TokenRequestTest.TRANSPORT, TokenRequestTest.JSON_FACTORY, TokenRequestTest.AUTHORIZATION_SERVER_URL, CODE)
// Path: google-oauth-client/src/main/java/com/google/api/client/auth/openidconnect/IdTokenResponse.java // @Beta // public class IdTokenResponse extends TokenResponse { // // /** ID token. */ // @Key("id_token") // private String idToken; // // /** Returns the ID token. */ // public final String getIdToken() { // return idToken; // } // // /** // * Sets the ID token. // * // * <p>Overriding is only supported for the purpose of calling the super implementation and // * changing the return type, but nothing else. // */ // public IdTokenResponse setIdToken(String idToken) { // this.idToken = Preconditions.checkNotNull(idToken); // return this; // } // // @Override // public IdTokenResponse setAccessToken(String accessToken) { // super.setAccessToken(accessToken); // return this; // } // // @Override // public IdTokenResponse setTokenType(String tokenType) { // super.setTokenType(tokenType); // return this; // } // // @Override // public IdTokenResponse setExpiresInSeconds(Long expiresIn) { // super.setExpiresInSeconds(expiresIn); // return this; // } // // @Override // public IdTokenResponse setRefreshToken(String refreshToken) { // super.setRefreshToken(refreshToken); // return this; // } // // @Override // public IdTokenResponse setScope(String scope) { // super.setScope(scope); // return this; // } // // /** // * Parses using {@link JsonWebSignature#parse(JsonFactory, String)} based on the {@link // * #getFactory() JSON factory} and {@link #getIdToken() ID token}. // */ // @SuppressWarnings("javadoc") // public IdToken parseIdToken() throws IOException { // return IdToken.parse(getFactory(), idToken); // } // // /** // * Executes the given ID token request, and returns the parsed ID token response. // * // * @param tokenRequest token request // * @return parsed successful ID token response // * @throws TokenResponseException for an error response // */ // public static IdTokenResponse execute(TokenRequest tokenRequest) throws IOException { // return tokenRequest.executeUnparsed().parseAs(IdTokenResponse.class); // } // // @Override // public IdTokenResponse set(String fieldName, Object value) { // return (IdTokenResponse) super.set(fieldName, value); // } // // @Override // public IdTokenResponse clone() { // return (IdTokenResponse) super.clone(); // } // } // Path: google-oauth-client/src/test/java/com/google/api/client/auth/oauth2/AuthorizationCodeTokenRequestTest.java import com.google.api.client.auth.openidconnect.IdTokenResponse; import junit.framework.TestCase; /* * Copyright (c) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.auth.oauth2; /** * Tests {@link AuthorizationCodeTokenRequest}. * * @author Yaniv Inbar */ public class AuthorizationCodeTokenRequestTest extends TestCase { private static final String CODE = "i1WsRn1uB1"; private static final String REDIRECT_URI = "https://client.example.com/rd"; public void testConstructor() { check( new AuthorizationCodeTokenRequest( TokenRequestTest.TRANSPORT, TokenRequestTest.JSON_FACTORY, TokenRequestTest.AUTHORIZATION_SERVER_URL, CODE) .setRedirectUri(REDIRECT_URI)); } private void check(AuthorizationCodeTokenRequest request) { TokenRequestTest.check(request, "authorization_code"); assertEquals(CODE, request.getCode()); assertEquals(REDIRECT_URI, request.getRedirectUri()); } public void testSetResponseClass() { AuthorizationCodeTokenRequest request = new AuthorizationCodeTokenRequest( TokenRequestTest.TRANSPORT, TokenRequestTest.JSON_FACTORY, TokenRequestTest.AUTHORIZATION_SERVER_URL, CODE)
.setResponseClass(IdTokenResponse.class);
googleapis/google-oauth-java-client
google-oauth-client/src/test/java/com/google/api/client/auth/oauth2/PasswordTokenRequestTest.java
// Path: google-oauth-client/src/main/java/com/google/api/client/auth/openidconnect/IdTokenResponse.java // @Beta // public class IdTokenResponse extends TokenResponse { // // /** ID token. */ // @Key("id_token") // private String idToken; // // /** Returns the ID token. */ // public final String getIdToken() { // return idToken; // } // // /** // * Sets the ID token. // * // * <p>Overriding is only supported for the purpose of calling the super implementation and // * changing the return type, but nothing else. // */ // public IdTokenResponse setIdToken(String idToken) { // this.idToken = Preconditions.checkNotNull(idToken); // return this; // } // // @Override // public IdTokenResponse setAccessToken(String accessToken) { // super.setAccessToken(accessToken); // return this; // } // // @Override // public IdTokenResponse setTokenType(String tokenType) { // super.setTokenType(tokenType); // return this; // } // // @Override // public IdTokenResponse setExpiresInSeconds(Long expiresIn) { // super.setExpiresInSeconds(expiresIn); // return this; // } // // @Override // public IdTokenResponse setRefreshToken(String refreshToken) { // super.setRefreshToken(refreshToken); // return this; // } // // @Override // public IdTokenResponse setScope(String scope) { // super.setScope(scope); // return this; // } // // /** // * Parses using {@link JsonWebSignature#parse(JsonFactory, String)} based on the {@link // * #getFactory() JSON factory} and {@link #getIdToken() ID token}. // */ // @SuppressWarnings("javadoc") // public IdToken parseIdToken() throws IOException { // return IdToken.parse(getFactory(), idToken); // } // // /** // * Executes the given ID token request, and returns the parsed ID token response. // * // * @param tokenRequest token request // * @return parsed successful ID token response // * @throws TokenResponseException for an error response // */ // public static IdTokenResponse execute(TokenRequest tokenRequest) throws IOException { // return tokenRequest.executeUnparsed().parseAs(IdTokenResponse.class); // } // // @Override // public IdTokenResponse set(String fieldName, Object value) { // return (IdTokenResponse) super.set(fieldName, value); // } // // @Override // public IdTokenResponse clone() { // return (IdTokenResponse) super.clone(); // } // }
import com.google.api.client.auth.openidconnect.IdTokenResponse; import junit.framework.TestCase;
/* * Copyright (c) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.auth.oauth2; /** * Tests {@link PasswordTokenRequest}. * * @author Yaniv Inbar */ public class PasswordTokenRequestTest extends TestCase { private static final String USERNAME = "johndoe"; private static final String PASSWORD = "A3ddj3w"; public void testConstructor() { check( new PasswordTokenRequest( TokenRequestTest.TRANSPORT, TokenRequestTest.JSON_FACTORY, TokenRequestTest.AUTHORIZATION_SERVER_URL, USERNAME, PASSWORD)); } private void check(PasswordTokenRequest request) { TokenRequestTest.check(request, "password"); assertEquals(USERNAME, request.getUsername()); assertEquals(PASSWORD, request.getPassword()); } public void testSetResponseClass() { PasswordTokenRequest request = new PasswordTokenRequest( TokenRequestTest.TRANSPORT, TokenRequestTest.JSON_FACTORY, TokenRequestTest.AUTHORIZATION_SERVER_URL, USERNAME, PASSWORD)
// Path: google-oauth-client/src/main/java/com/google/api/client/auth/openidconnect/IdTokenResponse.java // @Beta // public class IdTokenResponse extends TokenResponse { // // /** ID token. */ // @Key("id_token") // private String idToken; // // /** Returns the ID token. */ // public final String getIdToken() { // return idToken; // } // // /** // * Sets the ID token. // * // * <p>Overriding is only supported for the purpose of calling the super implementation and // * changing the return type, but nothing else. // */ // public IdTokenResponse setIdToken(String idToken) { // this.idToken = Preconditions.checkNotNull(idToken); // return this; // } // // @Override // public IdTokenResponse setAccessToken(String accessToken) { // super.setAccessToken(accessToken); // return this; // } // // @Override // public IdTokenResponse setTokenType(String tokenType) { // super.setTokenType(tokenType); // return this; // } // // @Override // public IdTokenResponse setExpiresInSeconds(Long expiresIn) { // super.setExpiresInSeconds(expiresIn); // return this; // } // // @Override // public IdTokenResponse setRefreshToken(String refreshToken) { // super.setRefreshToken(refreshToken); // return this; // } // // @Override // public IdTokenResponse setScope(String scope) { // super.setScope(scope); // return this; // } // // /** // * Parses using {@link JsonWebSignature#parse(JsonFactory, String)} based on the {@link // * #getFactory() JSON factory} and {@link #getIdToken() ID token}. // */ // @SuppressWarnings("javadoc") // public IdToken parseIdToken() throws IOException { // return IdToken.parse(getFactory(), idToken); // } // // /** // * Executes the given ID token request, and returns the parsed ID token response. // * // * @param tokenRequest token request // * @return parsed successful ID token response // * @throws TokenResponseException for an error response // */ // public static IdTokenResponse execute(TokenRequest tokenRequest) throws IOException { // return tokenRequest.executeUnparsed().parseAs(IdTokenResponse.class); // } // // @Override // public IdTokenResponse set(String fieldName, Object value) { // return (IdTokenResponse) super.set(fieldName, value); // } // // @Override // public IdTokenResponse clone() { // return (IdTokenResponse) super.clone(); // } // } // Path: google-oauth-client/src/test/java/com/google/api/client/auth/oauth2/PasswordTokenRequestTest.java import com.google.api.client.auth.openidconnect.IdTokenResponse; import junit.framework.TestCase; /* * Copyright (c) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.auth.oauth2; /** * Tests {@link PasswordTokenRequest}. * * @author Yaniv Inbar */ public class PasswordTokenRequestTest extends TestCase { private static final String USERNAME = "johndoe"; private static final String PASSWORD = "A3ddj3w"; public void testConstructor() { check( new PasswordTokenRequest( TokenRequestTest.TRANSPORT, TokenRequestTest.JSON_FACTORY, TokenRequestTest.AUTHORIZATION_SERVER_URL, USERNAME, PASSWORD)); } private void check(PasswordTokenRequest request) { TokenRequestTest.check(request, "password"); assertEquals(USERNAME, request.getUsername()); assertEquals(PASSWORD, request.getPassword()); } public void testSetResponseClass() { PasswordTokenRequest request = new PasswordTokenRequest( TokenRequestTest.TRANSPORT, TokenRequestTest.JSON_FACTORY, TokenRequestTest.AUTHORIZATION_SERVER_URL, USERNAME, PASSWORD)
.setResponseClass(IdTokenResponse.class);
aripollak/PictureMap
libs/src/com/drewChanged/metadata/exif/DataFormat.java
// Path: libs/src/com/drewChanged/metadata/MetadataException.java // public class MetadataException extends CompoundException // { // public MetadataException(String msg) // { // super(msg); // } // // public MetadataException(Throwable exception) // { // super(exception); // } // // public MetadataException(String msg, Throwable innerException) // { // super(msg, innerException); // } // }
import com.drewChanged.metadata.MetadataException;
/* * This is public domain software - that is, you can do whatever you want * with it, and include it software that is licensed under the GNU or the * BSD license, or whatever other licence you choose, including proprietary * closed source licenses. I do ask that you leave this header in tact. * * If you make modifications to this code that you think would benefit the * wider community, please send me a copy and I'll post it on my site. * * If you make use of this code, I'd appreciate hearing about it. * drew@drewnoakes.com * Latest version of this software kept at * http://drewnoakes.com/ */ package com.drewChanged.metadata.exif; /** * An enumeration of data formats used in the TIFF IFDs. */ public class DataFormat { public static final DataFormat BYTE = new DataFormat("BYTE", 1); public static final DataFormat STRING = new DataFormat("STRING", 2); public static final DataFormat USHORT = new DataFormat("USHORT", 3); public static final DataFormat ULONG = new DataFormat("ULONG", 4); public static final DataFormat URATIONAL = new DataFormat("URATIONAL", 5); public static final DataFormat SBYTE = new DataFormat("SBYTE", 6); public static final DataFormat UNDEFINED = new DataFormat("UNDEFINED", 7); public static final DataFormat SSHORT = new DataFormat("SSHORT", 8); public static final DataFormat SLONG = new DataFormat("SLONG", 9); public static final DataFormat SRATIONAL = new DataFormat("SRATIONAL", 10); public static final DataFormat SINGLE = new DataFormat("SINGLE", 11); public static final DataFormat DOUBLE = new DataFormat("DOUBLE", 12); private final String myName; private final int value;
// Path: libs/src/com/drewChanged/metadata/MetadataException.java // public class MetadataException extends CompoundException // { // public MetadataException(String msg) // { // super(msg); // } // // public MetadataException(Throwable exception) // { // super(exception); // } // // public MetadataException(String msg, Throwable innerException) // { // super(msg, innerException); // } // } // Path: libs/src/com/drewChanged/metadata/exif/DataFormat.java import com.drewChanged.metadata.MetadataException; /* * This is public domain software - that is, you can do whatever you want * with it, and include it software that is licensed under the GNU or the * BSD license, or whatever other licence you choose, including proprietary * closed source licenses. I do ask that you leave this header in tact. * * If you make modifications to this code that you think would benefit the * wider community, please send me a copy and I'll post it on my site. * * If you make use of this code, I'd appreciate hearing about it. * drew@drewnoakes.com * Latest version of this software kept at * http://drewnoakes.com/ */ package com.drewChanged.metadata.exif; /** * An enumeration of data formats used in the TIFF IFDs. */ public class DataFormat { public static final DataFormat BYTE = new DataFormat("BYTE", 1); public static final DataFormat STRING = new DataFormat("STRING", 2); public static final DataFormat USHORT = new DataFormat("USHORT", 3); public static final DataFormat ULONG = new DataFormat("ULONG", 4); public static final DataFormat URATIONAL = new DataFormat("URATIONAL", 5); public static final DataFormat SBYTE = new DataFormat("SBYTE", 6); public static final DataFormat UNDEFINED = new DataFormat("UNDEFINED", 7); public static final DataFormat SSHORT = new DataFormat("SSHORT", 8); public static final DataFormat SLONG = new DataFormat("SLONG", 9); public static final DataFormat SRATIONAL = new DataFormat("SRATIONAL", 10); public static final DataFormat SINGLE = new DataFormat("SINGLE", 11); public static final DataFormat DOUBLE = new DataFormat("DOUBLE", 12); private final String myName; private final int value;
public static DataFormat fromValue(int value) throws MetadataException
aripollak/PictureMap
libs/src/com/drewChanged/metadata/jpeg/JpegComponent.java
// Path: libs/src/com/drewChanged/metadata/MetadataException.java // public class MetadataException extends CompoundException // { // public MetadataException(String msg) // { // super(msg); // } // // public MetadataException(Throwable exception) // { // super(exception); // } // // public MetadataException(String msg, Throwable innerException) // { // super(msg, innerException); // } // }
import com.drewChanged.metadata.MetadataException;
/* * This is public domain software - that is, you can do whatever you want * with it, and include it software that is licensed under the GNU or the * BSD license, or whatever other licence you choose, including proprietary * closed source licenses. I do ask that you leave this header in tact. * * If you make modifications to this code that you think would benefit the * wider community, please send me a copy and I'll post it on my site. * * If you make use of this code, I'd appreciate hearing about it. * drew@drewnoakes.com * Latest version of this software kept at * http://drewnoakes.com/ * * Created by dnoakes on Oct 9, 17:04:07 using IntelliJ IDEA. */ package com.drewChanged.metadata.jpeg; /** * Created by IntelliJ IDEA. * User: dnoakes * Date: 09-Oct-2003 * Time: 17:04:07 * To change this template use Options | File Templates. */ public class JpegComponent { private final int _componentId; private final int _samplingFactorByte; private final int _quantizationTableNumber; public JpegComponent(int componentId, int samplingFactorByte, int quantizationTableNumber) { _componentId = componentId; _samplingFactorByte = samplingFactorByte; _quantizationTableNumber = quantizationTableNumber; } public int getComponentId() { return _componentId; }
// Path: libs/src/com/drewChanged/metadata/MetadataException.java // public class MetadataException extends CompoundException // { // public MetadataException(String msg) // { // super(msg); // } // // public MetadataException(Throwable exception) // { // super(exception); // } // // public MetadataException(String msg, Throwable innerException) // { // super(msg, innerException); // } // } // Path: libs/src/com/drewChanged/metadata/jpeg/JpegComponent.java import com.drewChanged.metadata.MetadataException; /* * This is public domain software - that is, you can do whatever you want * with it, and include it software that is licensed under the GNU or the * BSD license, or whatever other licence you choose, including proprietary * closed source licenses. I do ask that you leave this header in tact. * * If you make modifications to this code that you think would benefit the * wider community, please send me a copy and I'll post it on my site. * * If you make use of this code, I'd appreciate hearing about it. * drew@drewnoakes.com * Latest version of this software kept at * http://drewnoakes.com/ * * Created by dnoakes on Oct 9, 17:04:07 using IntelliJ IDEA. */ package com.drewChanged.metadata.jpeg; /** * Created by IntelliJ IDEA. * User: dnoakes * Date: 09-Oct-2003 * Time: 17:04:07 * To change this template use Options | File Templates. */ public class JpegComponent { private final int _componentId; private final int _samplingFactorByte; private final int _quantizationTableNumber; public JpegComponent(int componentId, int samplingFactorByte, int quantizationTableNumber) { _componentId = componentId; _samplingFactorByte = samplingFactorByte; _quantizationTableNumber = quantizationTableNumber; } public int getComponentId() { return _componentId; }
public String getComponentName() throws MetadataException
aripollak/PictureMap
libs/src/com/drewChanged/metadata/jpeg/test/JpegComponentTest.java
// Path: libs/src/com/drewChanged/metadata/jpeg/JpegComponent.java // public class JpegComponent // { // private final int _componentId; // private final int _samplingFactorByte; // private final int _quantizationTableNumber; // // public JpegComponent(int componentId, int samplingFactorByte, int quantizationTableNumber) // { // _componentId = componentId; // _samplingFactorByte = samplingFactorByte; // _quantizationTableNumber = quantizationTableNumber; // } // // public int getComponentId() // { // return _componentId; // } // // public String getComponentName() throws MetadataException // { // switch (_componentId) // { // case 1: // return "Y"; // case 2: // return "Cb"; // case 3: // return "Cr"; // case 4: // return "I"; // case 5: // return "Q"; // } // // throw new MetadataException("Unsupported component id: " + _componentId); // } // // public int getQuantizationTableNumber() // { // return _quantizationTableNumber; // } // // public int getHorizontalSamplingFactor() // { // return _samplingFactorByte & 0x0F; // } // // public int getVerticalSamplingFactor() // { // return (_samplingFactorByte>>4) & 0x0F; // } // }
import com.drewChanged.metadata.jpeg.JpegComponent; import junit.framework.TestCase;
/* * This is public domain software - that is, you can do whatever you want * with it, and include it software that is licensed under the GNU or the * BSD license, or whatever other licence you choose, including proprietary * closed source licenses. I do ask that you leave this header in tact. * * If you make modifications to this code that you think would benefit the * wider community, please send me a copy and I'll post it on my site. * * If you make use of this code, I'd appreciate hearing about it. * drew@drewnoakes.com * Latest version of this software kept at * http://drewnoakes.com/ * * Created by dnoakes on 09-Oct-2003 15:22:23 using IntelliJ IDEA. */ package com.drewChanged.metadata.jpeg.test; /** * */ public class JpegComponentTest extends TestCase { public JpegComponentTest(String s) { super(s); } public void testGetComponentCharacter() throws Exception {
// Path: libs/src/com/drewChanged/metadata/jpeg/JpegComponent.java // public class JpegComponent // { // private final int _componentId; // private final int _samplingFactorByte; // private final int _quantizationTableNumber; // // public JpegComponent(int componentId, int samplingFactorByte, int quantizationTableNumber) // { // _componentId = componentId; // _samplingFactorByte = samplingFactorByte; // _quantizationTableNumber = quantizationTableNumber; // } // // public int getComponentId() // { // return _componentId; // } // // public String getComponentName() throws MetadataException // { // switch (_componentId) // { // case 1: // return "Y"; // case 2: // return "Cb"; // case 3: // return "Cr"; // case 4: // return "I"; // case 5: // return "Q"; // } // // throw new MetadataException("Unsupported component id: " + _componentId); // } // // public int getQuantizationTableNumber() // { // return _quantizationTableNumber; // } // // public int getHorizontalSamplingFactor() // { // return _samplingFactorByte & 0x0F; // } // // public int getVerticalSamplingFactor() // { // return (_samplingFactorByte>>4) & 0x0F; // } // } // Path: libs/src/com/drewChanged/metadata/jpeg/test/JpegComponentTest.java import com.drewChanged.metadata.jpeg.JpegComponent; import junit.framework.TestCase; /* * This is public domain software - that is, you can do whatever you want * with it, and include it software that is licensed under the GNU or the * BSD license, or whatever other licence you choose, including proprietary * closed source licenses. I do ask that you leave this header in tact. * * If you make modifications to this code that you think would benefit the * wider community, please send me a copy and I'll post it on my site. * * If you make use of this code, I'd appreciate hearing about it. * drew@drewnoakes.com * Latest version of this software kept at * http://drewnoakes.com/ * * Created by dnoakes on 09-Oct-2003 15:22:23 using IntelliJ IDEA. */ package com.drewChanged.metadata.jpeg.test; /** * */ public class JpegComponentTest extends TestCase { public JpegComponentTest(String s) { super(s); } public void testGetComponentCharacter() throws Exception {
JpegComponent component;
aripollak/PictureMap
src/com/aripollak/picturemap/PictureCallout.java
// Path: libs/src/com/drewChanged/metadata/Metadata.java // @SuppressWarnings("unchecked") // public final class Metadata // { // /** // * // */ // private final Hashtable directoryMap; // // /** // * List of Directory objects set against this object. Keeping a list handy makes // * creation of an Iterator and counting tags simple. // */ // private final Vector directoryList; // // /** // * Creates a new instance of Metadata. Package private. // */ // public Metadata() // { // directoryMap = new Hashtable(); // directoryList = new Vector(); // } // // // // OTHER METHODS // // /** // * Creates an Iterator over the tag types set against this image, preserving the order // * in which they were set. Should the same tag have been set more than once, it's first // * position is maintained, even though the final value is used. // * @return an Iterator of tag types set for this image // */ // // public Iterator getDirectoryIterator() // // { // // return directoryList.iterator(); // // } // public Vector getDirectoryIterator() // { // return directoryList; // } // // // /** // * Returns a count of unique directories in this metadata collection. // * @return the number of unique directory types set for this metadata collection // */ // public int getDirectoryCount() // { // return directoryList.size(); // } // // /** // * Returns a <code>Directory</code> of specified type. If this <code>Metadata</code> object already contains // * such a directory, it is returned. Otherwise a new instance of this directory will be created and stored within // * this Metadata object. // * @param type the type of the Directory implementation required. // * @return a directory of the specified type. // */ // public Directory getDirectory(Class type) // { // if (!Directory.class.isAssignableFrom(type)) { // throw new RuntimeException("Class type passed to getDirectory must be an implementation of com.drewChanged.metadata.Directory"); // } // // check if we've already issued this type of directory // if (directoryMap.containsKey(type)) { // // System.out.println("obtain dir from directoryMap"); // return (Directory)directoryMap.get(type); // } // Object directory; // try { // directory = type.newInstance(); // } catch (Exception e) { // throw new RuntimeException("Cannot instantiate provided Directory type: " + type.toString()); // } // // store the directory in case it's requested later // // System.out.println("put new dir into directoryMap!"); // directoryMap.put(type, directory); // directoryList.addElement(directory); // return (Directory)directory; // } // // /** // * Indicates whether a given directory type has been created in this metadata // * repository. Directories are created by calling getDirectory(Class). // * @param type the Directory type // * @return true if the metadata directory has been created // */ // public boolean containsDirectory(Class type) // { // return directoryMap.containsKey(type); // } // }
import com.drewChanged.metadata.Metadata; import com.google.android.maps.ItemizedOverlay; import com.google.android.maps.OverlayItem; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.AsyncTask; import android.provider.MediaStore.Images; import android.util.AttributeSet; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TableLayout;
public void onFocusChanged(ItemizedOverlay overlay, OverlayItem item) { // This seems to be required all the time, even when // an image is already focused and we're just switching setVisibility(GONE); mLastItem = item; if (mShowImage != null) { mShowImage.cancel(true); mShowImage = null; } if (item == null) return; mShowImage = new ShowImage(); mShowImage.execute(item.getTitle()); setVisibility(VISIBLE); } /* Re-scales image for use in the popup bubble */ class ShowImage extends AsyncTask<String, Integer, Bitmap>{ @Override protected void onPreExecute() { super.onPreExecute(); mProgressBar.setVisibility(VISIBLE); mImageView.setVisibility(GONE); } @Override protected Bitmap doInBackground(String... locations) {
// Path: libs/src/com/drewChanged/metadata/Metadata.java // @SuppressWarnings("unchecked") // public final class Metadata // { // /** // * // */ // private final Hashtable directoryMap; // // /** // * List of Directory objects set against this object. Keeping a list handy makes // * creation of an Iterator and counting tags simple. // */ // private final Vector directoryList; // // /** // * Creates a new instance of Metadata. Package private. // */ // public Metadata() // { // directoryMap = new Hashtable(); // directoryList = new Vector(); // } // // // // OTHER METHODS // // /** // * Creates an Iterator over the tag types set against this image, preserving the order // * in which they were set. Should the same tag have been set more than once, it's first // * position is maintained, even though the final value is used. // * @return an Iterator of tag types set for this image // */ // // public Iterator getDirectoryIterator() // // { // // return directoryList.iterator(); // // } // public Vector getDirectoryIterator() // { // return directoryList; // } // // // /** // * Returns a count of unique directories in this metadata collection. // * @return the number of unique directory types set for this metadata collection // */ // public int getDirectoryCount() // { // return directoryList.size(); // } // // /** // * Returns a <code>Directory</code> of specified type. If this <code>Metadata</code> object already contains // * such a directory, it is returned. Otherwise a new instance of this directory will be created and stored within // * this Metadata object. // * @param type the type of the Directory implementation required. // * @return a directory of the specified type. // */ // public Directory getDirectory(Class type) // { // if (!Directory.class.isAssignableFrom(type)) { // throw new RuntimeException("Class type passed to getDirectory must be an implementation of com.drewChanged.metadata.Directory"); // } // // check if we've already issued this type of directory // if (directoryMap.containsKey(type)) { // // System.out.println("obtain dir from directoryMap"); // return (Directory)directoryMap.get(type); // } // Object directory; // try { // directory = type.newInstance(); // } catch (Exception e) { // throw new RuntimeException("Cannot instantiate provided Directory type: " + type.toString()); // } // // store the directory in case it's requested later // // System.out.println("put new dir into directoryMap!"); // directoryMap.put(type, directory); // directoryList.addElement(directory); // return (Directory)directory; // } // // /** // * Indicates whether a given directory type has been created in this metadata // * repository. Directories are created by calling getDirectory(Class). // * @param type the Directory type // * @return true if the metadata directory has been created // */ // public boolean containsDirectory(Class type) // { // return directoryMap.containsKey(type); // } // } // Path: src/com/aripollak/picturemap/PictureCallout.java import com.drewChanged.metadata.Metadata; import com.google.android.maps.ItemizedOverlay; import com.google.android.maps.OverlayItem; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.AsyncTask; import android.provider.MediaStore.Images; import android.util.AttributeSet; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TableLayout; public void onFocusChanged(ItemizedOverlay overlay, OverlayItem item) { // This seems to be required all the time, even when // an image is already focused and we're just switching setVisibility(GONE); mLastItem = item; if (mShowImage != null) { mShowImage.cancel(true); mShowImage = null; } if (item == null) return; mShowImage = new ShowImage(); mShowImage.execute(item.getTitle()); setVisibility(VISIBLE); } /* Re-scales image for use in the popup bubble */ class ShowImage extends AsyncTask<String, Integer, Bitmap>{ @Override protected void onPreExecute() { super.onPreExecute(); mProgressBar.setVisibility(VISIBLE); mImageView.setVisibility(GONE); } @Override protected Bitmap doInBackground(String... locations) {
Metadata metadata = ImageUtilities.readMetadata(locations[0]);
jenkinsci/authorize-project-plugin
src/main/java/org/jenkinsci/plugins/authorizeproject/GlobalQueueItemAuthenticator.java
// Path: src/main/java/org/jenkinsci/plugins/authorizeproject/strategy/AnonymousAuthorizationStrategy.java // public class AnonymousAuthorizationStrategy extends AuthorizeProjectStrategy { // /** // * // */ // @DataBoundConstructor // public AnonymousAuthorizationStrategy() { // } // // /** // * Authorize builds as anonymous. // * // * @param project // * @param item // * @return anonymous authorization // * @see org.jenkinsci.plugins.authorizeproject.AuthorizeProjectStrategy#authenticate(hudson.model.Job, hudson.model.Queue.Item) // */ // @Override // public Authentication authenticate(Job<?, ?> project, Queue.Item item) { // return Jenkins.ANONYMOUS; // } // // /** // * // */ // @Extension // public static class DescriptorImpl extends AuthorizeProjectStrategyDescriptor { // /** // * @return the name shown in project configuration pages. // * @see hudson.model.Descriptor#getDisplayName() // */ // @Override // public String getDisplayName() { // return Messages.AnonymousAuthorizationStrategy_DisplayName(); // } // } // }
import hudson.Extension; import hudson.model.Descriptor; import hudson.model.Job; import hudson.model.Queue; import jenkins.security.QueueItemAuthenticator; import jenkins.security.QueueItemAuthenticatorDescriptor; import net.sf.json.JSONObject; import org.acegisecurity.Authentication; import org.jenkinsci.plugins.authorizeproject.strategy.AnonymousAuthorizationStrategy; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import com.google.common.base.Predicate; import com.google.common.collect.Iterables;
} @Extension public static class DescriptorImpl extends QueueItemAuthenticatorDescriptor { /** * {@inheritDoc} */ @Override public String getDisplayName() { return Messages.GlobalQueueItemAuthenticator_DisplayName(); } /** * @return Descriptors for {@link AuthorizeProjectStrategy} applicable to {@link GlobalQueueItemAuthenticator}. */ public Iterable<Descriptor<AuthorizeProjectStrategy>> getStrategyDescriptors() { return Iterables.filter( AuthorizeProjectStrategy.all(), new Predicate<Descriptor<AuthorizeProjectStrategy>>() { public boolean apply(Descriptor<AuthorizeProjectStrategy> d) { if (!(d instanceof AuthorizeProjectStrategyDescriptor)) { return true; } return ((AuthorizeProjectStrategyDescriptor)d).isApplicableToGlobal(); } } ); } public AuthorizeProjectStrategy getDefaultStrategy() {
// Path: src/main/java/org/jenkinsci/plugins/authorizeproject/strategy/AnonymousAuthorizationStrategy.java // public class AnonymousAuthorizationStrategy extends AuthorizeProjectStrategy { // /** // * // */ // @DataBoundConstructor // public AnonymousAuthorizationStrategy() { // } // // /** // * Authorize builds as anonymous. // * // * @param project // * @param item // * @return anonymous authorization // * @see org.jenkinsci.plugins.authorizeproject.AuthorizeProjectStrategy#authenticate(hudson.model.Job, hudson.model.Queue.Item) // */ // @Override // public Authentication authenticate(Job<?, ?> project, Queue.Item item) { // return Jenkins.ANONYMOUS; // } // // /** // * // */ // @Extension // public static class DescriptorImpl extends AuthorizeProjectStrategyDescriptor { // /** // * @return the name shown in project configuration pages. // * @see hudson.model.Descriptor#getDisplayName() // */ // @Override // public String getDisplayName() { // return Messages.AnonymousAuthorizationStrategy_DisplayName(); // } // } // } // Path: src/main/java/org/jenkinsci/plugins/authorizeproject/GlobalQueueItemAuthenticator.java import hudson.Extension; import hudson.model.Descriptor; import hudson.model.Job; import hudson.model.Queue; import jenkins.security.QueueItemAuthenticator; import jenkins.security.QueueItemAuthenticatorDescriptor; import net.sf.json.JSONObject; import org.acegisecurity.Authentication; import org.jenkinsci.plugins.authorizeproject.strategy.AnonymousAuthorizationStrategy; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; } @Extension public static class DescriptorImpl extends QueueItemAuthenticatorDescriptor { /** * {@inheritDoc} */ @Override public String getDisplayName() { return Messages.GlobalQueueItemAuthenticator_DisplayName(); } /** * @return Descriptors for {@link AuthorizeProjectStrategy} applicable to {@link GlobalQueueItemAuthenticator}. */ public Iterable<Descriptor<AuthorizeProjectStrategy>> getStrategyDescriptors() { return Iterables.filter( AuthorizeProjectStrategy.all(), new Predicate<Descriptor<AuthorizeProjectStrategy>>() { public boolean apply(Descriptor<AuthorizeProjectStrategy> d) { if (!(d instanceof AuthorizeProjectStrategyDescriptor)) { return true; } return ((AuthorizeProjectStrategyDescriptor)d).isApplicableToGlobal(); } } ); } public AuthorizeProjectStrategy getDefaultStrategy() {
return new AnonymousAuthorizationStrategy();
cojen/Cojen
src/main/java/org/cojen/classfile/InstructionList.java
// Path: src/main/java/org/cojen/classfile/constant/ConstantClassInfo.java // public class ConstantClassInfo extends ConstantInfo { // private final TypeDesc mType; // private final ConstantUTFInfo mNameConstant; // // public ConstantClassInfo(ConstantUTFInfo nameConstant) { // super(TAG_CLASS); // String name = nameConstant.getValue(); // if (!name.endsWith(";") && !name.startsWith("[")) { // mType = TypeDesc.forClass(name); // } else { // mType = TypeDesc.forDescriptor(name); // } // mNameConstant = nameConstant; // } // // public ConstantClassInfo(ConstantPool cp, String className) { // super(TAG_CLASS); // String desc = className.replace('.', '/'); // mType = TypeDesc.forClass(className); // mNameConstant = cp.addConstantUTF(desc); // } // // /** // * Used to describe an array class. // */ // public ConstantClassInfo(ConstantPool cp, String className, int dim) { // super(TAG_CLASS); // TypeDesc type = TypeDesc.forClass(className); // String desc; // if (dim > 0) { // while (--dim >= 0) { // type = type.toArrayType(); // } // desc = type.getDescriptor(); // } else { // desc = className.replace('.', '/'); // } // mType = type; // mNameConstant = cp.addConstantUTF(desc); // } // // public ConstantClassInfo(ConstantPool cp, TypeDesc type) { // super(TAG_CLASS); // String desc; // if (type.isArray()) { // desc = type.getDescriptor(); // } else { // desc = type.getRootName().replace('.', '/'); // } // mType = type; // mNameConstant = cp.addConstantUTF(desc); // } // // public TypeDesc getType() { // return mType; // } // // public int hashCode() { // return mType.hashCode(); // } // // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj instanceof ConstantClassInfo) { // ConstantClassInfo other = (ConstantClassInfo)obj; // return mType.equals(other.mType); // } // return false; // } // // public void writeTo(DataOutput dout) throws IOException { // super.writeTo(dout); // dout.writeShort(mNameConstant.getIndex()); // } // // public String toString() { // return "CONSTANT_Class_info: ".concat(getType().getFullName()); // } // } // // Path: src/main/java/org/cojen/classfile/constant/ConstantMethodInfo.java // public class ConstantMethodInfo extends ConstantInfo { // private final ConstantClassInfo mParentClass; // private final ConstantNameAndTypeInfo mNameAndType; // // public ConstantMethodInfo(ConstantClassInfo parentClass, // ConstantNameAndTypeInfo nameAndType) { // super(TAG_METHOD); // mParentClass = parentClass; // mNameAndType = nameAndType; // } // // public ConstantClassInfo getParentClass() { // return mParentClass; // } // // public ConstantNameAndTypeInfo getNameAndType() { // return mNameAndType; // } // // public int hashCode() { // return mNameAndType.hashCode(); // } // // public boolean equals(Object obj) { // if (obj instanceof ConstantMethodInfo) { // ConstantMethodInfo other = (ConstantMethodInfo)obj; // return (mParentClass.equals(other.mParentClass) && // mNameAndType.equals(other.mNameAndType)); // } // // return false; // } // // public void writeTo(DataOutput dout) throws IOException { // super.writeTo(dout); // dout.writeShort(mParentClass.getIndex()); // dout.writeShort(mNameAndType.getIndex()); // } // // public String toString() { // StringBuffer buf = new StringBuffer("CONSTANT_Methodref_info: "); // buf.append(getParentClass().getType().getFullName()); // // ConstantNameAndTypeInfo cnati = getNameAndType(); // // buf.append(' '); // buf.append(cnati.getName()); // buf.append(' '); // buf.append(cnati.getType()); // // return buf.toString(); // } // }
import java.util.AbstractCollection; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.cojen.classfile.constant.ConstantClassInfo; import org.cojen.classfile.constant.ConstantMethodInfo;
if (bytes.length < 3) { throw new IllegalArgumentException("Byte for instruction is too small"); } mInfo = info; } @Override public byte[] getBytes() { int index = mInfo.getIndex(); if (index < 0) { throw new IllegalStateException("Constant pool index not resolved"); } mBytes[1] = (byte)(index >> 8); mBytes[2] = (byte)index; return mBytes; } @Override public boolean isResolved() { return mInfo.getIndex() >= 0; } } /** * Defines an instruction which create a new object. */ public class NewObjectInstruction extends ConstantOperandInstruction {
// Path: src/main/java/org/cojen/classfile/constant/ConstantClassInfo.java // public class ConstantClassInfo extends ConstantInfo { // private final TypeDesc mType; // private final ConstantUTFInfo mNameConstant; // // public ConstantClassInfo(ConstantUTFInfo nameConstant) { // super(TAG_CLASS); // String name = nameConstant.getValue(); // if (!name.endsWith(";") && !name.startsWith("[")) { // mType = TypeDesc.forClass(name); // } else { // mType = TypeDesc.forDescriptor(name); // } // mNameConstant = nameConstant; // } // // public ConstantClassInfo(ConstantPool cp, String className) { // super(TAG_CLASS); // String desc = className.replace('.', '/'); // mType = TypeDesc.forClass(className); // mNameConstant = cp.addConstantUTF(desc); // } // // /** // * Used to describe an array class. // */ // public ConstantClassInfo(ConstantPool cp, String className, int dim) { // super(TAG_CLASS); // TypeDesc type = TypeDesc.forClass(className); // String desc; // if (dim > 0) { // while (--dim >= 0) { // type = type.toArrayType(); // } // desc = type.getDescriptor(); // } else { // desc = className.replace('.', '/'); // } // mType = type; // mNameConstant = cp.addConstantUTF(desc); // } // // public ConstantClassInfo(ConstantPool cp, TypeDesc type) { // super(TAG_CLASS); // String desc; // if (type.isArray()) { // desc = type.getDescriptor(); // } else { // desc = type.getRootName().replace('.', '/'); // } // mType = type; // mNameConstant = cp.addConstantUTF(desc); // } // // public TypeDesc getType() { // return mType; // } // // public int hashCode() { // return mType.hashCode(); // } // // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj instanceof ConstantClassInfo) { // ConstantClassInfo other = (ConstantClassInfo)obj; // return mType.equals(other.mType); // } // return false; // } // // public void writeTo(DataOutput dout) throws IOException { // super.writeTo(dout); // dout.writeShort(mNameConstant.getIndex()); // } // // public String toString() { // return "CONSTANT_Class_info: ".concat(getType().getFullName()); // } // } // // Path: src/main/java/org/cojen/classfile/constant/ConstantMethodInfo.java // public class ConstantMethodInfo extends ConstantInfo { // private final ConstantClassInfo mParentClass; // private final ConstantNameAndTypeInfo mNameAndType; // // public ConstantMethodInfo(ConstantClassInfo parentClass, // ConstantNameAndTypeInfo nameAndType) { // super(TAG_METHOD); // mParentClass = parentClass; // mNameAndType = nameAndType; // } // // public ConstantClassInfo getParentClass() { // return mParentClass; // } // // public ConstantNameAndTypeInfo getNameAndType() { // return mNameAndType; // } // // public int hashCode() { // return mNameAndType.hashCode(); // } // // public boolean equals(Object obj) { // if (obj instanceof ConstantMethodInfo) { // ConstantMethodInfo other = (ConstantMethodInfo)obj; // return (mParentClass.equals(other.mParentClass) && // mNameAndType.equals(other.mNameAndType)); // } // // return false; // } // // public void writeTo(DataOutput dout) throws IOException { // super.writeTo(dout); // dout.writeShort(mParentClass.getIndex()); // dout.writeShort(mNameAndType.getIndex()); // } // // public String toString() { // StringBuffer buf = new StringBuffer("CONSTANT_Methodref_info: "); // buf.append(getParentClass().getType().getFullName()); // // ConstantNameAndTypeInfo cnati = getNameAndType(); // // buf.append(' '); // buf.append(cnati.getName()); // buf.append(' '); // buf.append(cnati.getType()); // // return buf.toString(); // } // } // Path: src/main/java/org/cojen/classfile/InstructionList.java import java.util.AbstractCollection; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.cojen.classfile.constant.ConstantClassInfo; import org.cojen.classfile.constant.ConstantMethodInfo; if (bytes.length < 3) { throw new IllegalArgumentException("Byte for instruction is too small"); } mInfo = info; } @Override public byte[] getBytes() { int index = mInfo.getIndex(); if (index < 0) { throw new IllegalStateException("Constant pool index not resolved"); } mBytes[1] = (byte)(index >> 8); mBytes[2] = (byte)index; return mBytes; } @Override public boolean isResolved() { return mInfo.getIndex() >= 0; } } /** * Defines an instruction which create a new object. */ public class NewObjectInstruction extends ConstantOperandInstruction {
public NewObjectInstruction(ConstantClassInfo newType) {
cojen/Cojen
src/main/java/org/cojen/classfile/InstructionList.java
// Path: src/main/java/org/cojen/classfile/constant/ConstantClassInfo.java // public class ConstantClassInfo extends ConstantInfo { // private final TypeDesc mType; // private final ConstantUTFInfo mNameConstant; // // public ConstantClassInfo(ConstantUTFInfo nameConstant) { // super(TAG_CLASS); // String name = nameConstant.getValue(); // if (!name.endsWith(";") && !name.startsWith("[")) { // mType = TypeDesc.forClass(name); // } else { // mType = TypeDesc.forDescriptor(name); // } // mNameConstant = nameConstant; // } // // public ConstantClassInfo(ConstantPool cp, String className) { // super(TAG_CLASS); // String desc = className.replace('.', '/'); // mType = TypeDesc.forClass(className); // mNameConstant = cp.addConstantUTF(desc); // } // // /** // * Used to describe an array class. // */ // public ConstantClassInfo(ConstantPool cp, String className, int dim) { // super(TAG_CLASS); // TypeDesc type = TypeDesc.forClass(className); // String desc; // if (dim > 0) { // while (--dim >= 0) { // type = type.toArrayType(); // } // desc = type.getDescriptor(); // } else { // desc = className.replace('.', '/'); // } // mType = type; // mNameConstant = cp.addConstantUTF(desc); // } // // public ConstantClassInfo(ConstantPool cp, TypeDesc type) { // super(TAG_CLASS); // String desc; // if (type.isArray()) { // desc = type.getDescriptor(); // } else { // desc = type.getRootName().replace('.', '/'); // } // mType = type; // mNameConstant = cp.addConstantUTF(desc); // } // // public TypeDesc getType() { // return mType; // } // // public int hashCode() { // return mType.hashCode(); // } // // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj instanceof ConstantClassInfo) { // ConstantClassInfo other = (ConstantClassInfo)obj; // return mType.equals(other.mType); // } // return false; // } // // public void writeTo(DataOutput dout) throws IOException { // super.writeTo(dout); // dout.writeShort(mNameConstant.getIndex()); // } // // public String toString() { // return "CONSTANT_Class_info: ".concat(getType().getFullName()); // } // } // // Path: src/main/java/org/cojen/classfile/constant/ConstantMethodInfo.java // public class ConstantMethodInfo extends ConstantInfo { // private final ConstantClassInfo mParentClass; // private final ConstantNameAndTypeInfo mNameAndType; // // public ConstantMethodInfo(ConstantClassInfo parentClass, // ConstantNameAndTypeInfo nameAndType) { // super(TAG_METHOD); // mParentClass = parentClass; // mNameAndType = nameAndType; // } // // public ConstantClassInfo getParentClass() { // return mParentClass; // } // // public ConstantNameAndTypeInfo getNameAndType() { // return mNameAndType; // } // // public int hashCode() { // return mNameAndType.hashCode(); // } // // public boolean equals(Object obj) { // if (obj instanceof ConstantMethodInfo) { // ConstantMethodInfo other = (ConstantMethodInfo)obj; // return (mParentClass.equals(other.mParentClass) && // mNameAndType.equals(other.mNameAndType)); // } // // return false; // } // // public void writeTo(DataOutput dout) throws IOException { // super.writeTo(dout); // dout.writeShort(mParentClass.getIndex()); // dout.writeShort(mNameAndType.getIndex()); // } // // public String toString() { // StringBuffer buf = new StringBuffer("CONSTANT_Methodref_info: "); // buf.append(getParentClass().getType().getFullName()); // // ConstantNameAndTypeInfo cnati = getNameAndType(); // // buf.append(' '); // buf.append(cnati.getName()); // buf.append(' '); // buf.append(cnati.getType()); // // return buf.toString(); // } // }
import java.util.AbstractCollection; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.cojen.classfile.constant.ConstantClassInfo; import org.cojen.classfile.constant.ConstantMethodInfo;
bytes = new byte[3]; } bytes[0] = opcode; return bytes; } private static int returnSize(TypeDesc ret) { if (ret == null || ret == TypeDesc.VOID) { return 0; } if (ret.isDoubleWord()) { return 2; } return 1; } private static int argSize(TypeDesc[] params) { int size = 0; if (params != null) { for (int i=0; i<params.length; i++) { size += returnSize(params[i]); } } return size; } /** * Defines an instruction which calls the constructor of a new object. */ public class InvokeConstructorInstruction extends InvokeInstruction {
// Path: src/main/java/org/cojen/classfile/constant/ConstantClassInfo.java // public class ConstantClassInfo extends ConstantInfo { // private final TypeDesc mType; // private final ConstantUTFInfo mNameConstant; // // public ConstantClassInfo(ConstantUTFInfo nameConstant) { // super(TAG_CLASS); // String name = nameConstant.getValue(); // if (!name.endsWith(";") && !name.startsWith("[")) { // mType = TypeDesc.forClass(name); // } else { // mType = TypeDesc.forDescriptor(name); // } // mNameConstant = nameConstant; // } // // public ConstantClassInfo(ConstantPool cp, String className) { // super(TAG_CLASS); // String desc = className.replace('.', '/'); // mType = TypeDesc.forClass(className); // mNameConstant = cp.addConstantUTF(desc); // } // // /** // * Used to describe an array class. // */ // public ConstantClassInfo(ConstantPool cp, String className, int dim) { // super(TAG_CLASS); // TypeDesc type = TypeDesc.forClass(className); // String desc; // if (dim > 0) { // while (--dim >= 0) { // type = type.toArrayType(); // } // desc = type.getDescriptor(); // } else { // desc = className.replace('.', '/'); // } // mType = type; // mNameConstant = cp.addConstantUTF(desc); // } // // public ConstantClassInfo(ConstantPool cp, TypeDesc type) { // super(TAG_CLASS); // String desc; // if (type.isArray()) { // desc = type.getDescriptor(); // } else { // desc = type.getRootName().replace('.', '/'); // } // mType = type; // mNameConstant = cp.addConstantUTF(desc); // } // // public TypeDesc getType() { // return mType; // } // // public int hashCode() { // return mType.hashCode(); // } // // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj instanceof ConstantClassInfo) { // ConstantClassInfo other = (ConstantClassInfo)obj; // return mType.equals(other.mType); // } // return false; // } // // public void writeTo(DataOutput dout) throws IOException { // super.writeTo(dout); // dout.writeShort(mNameConstant.getIndex()); // } // // public String toString() { // return "CONSTANT_Class_info: ".concat(getType().getFullName()); // } // } // // Path: src/main/java/org/cojen/classfile/constant/ConstantMethodInfo.java // public class ConstantMethodInfo extends ConstantInfo { // private final ConstantClassInfo mParentClass; // private final ConstantNameAndTypeInfo mNameAndType; // // public ConstantMethodInfo(ConstantClassInfo parentClass, // ConstantNameAndTypeInfo nameAndType) { // super(TAG_METHOD); // mParentClass = parentClass; // mNameAndType = nameAndType; // } // // public ConstantClassInfo getParentClass() { // return mParentClass; // } // // public ConstantNameAndTypeInfo getNameAndType() { // return mNameAndType; // } // // public int hashCode() { // return mNameAndType.hashCode(); // } // // public boolean equals(Object obj) { // if (obj instanceof ConstantMethodInfo) { // ConstantMethodInfo other = (ConstantMethodInfo)obj; // return (mParentClass.equals(other.mParentClass) && // mNameAndType.equals(other.mNameAndType)); // } // // return false; // } // // public void writeTo(DataOutput dout) throws IOException { // super.writeTo(dout); // dout.writeShort(mParentClass.getIndex()); // dout.writeShort(mNameAndType.getIndex()); // } // // public String toString() { // StringBuffer buf = new StringBuffer("CONSTANT_Methodref_info: "); // buf.append(getParentClass().getType().getFullName()); // // ConstantNameAndTypeInfo cnati = getNameAndType(); // // buf.append(' '); // buf.append(cnati.getName()); // buf.append(' '); // buf.append(cnati.getType()); // // return buf.toString(); // } // } // Path: src/main/java/org/cojen/classfile/InstructionList.java import java.util.AbstractCollection; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.cojen.classfile.constant.ConstantClassInfo; import org.cojen.classfile.constant.ConstantMethodInfo; bytes = new byte[3]; } bytes[0] = opcode; return bytes; } private static int returnSize(TypeDesc ret) { if (ret == null || ret == TypeDesc.VOID) { return 0; } if (ret.isDoubleWord()) { return 2; } return 1; } private static int argSize(TypeDesc[] params) { int size = 0; if (params != null) { for (int i=0; i<params.length; i++) { size += returnSize(params[i]); } } return size; } /** * Defines an instruction which calls the constructor of a new object. */ public class InvokeConstructorInstruction extends InvokeInstruction {
public InvokeConstructorInstruction(ConstantMethodInfo ctor,
cojen/Cojen
src/test/java/org/cojen/test/TestSoftValuedHashMap.java
// Path: src/main/java/org/cojen/util/SoftValuedHashMap.java // public class SoftValuedHashMap<K, V> extends ReferencedValueHashMap<K, V> { // // /** // * Constructs a new, empty map with the specified initial // * capacity and the specified load factor. // * // * @param initialCapacity the initial capacity of the HashMap. // * @param loadFactor the load factor of the HashMap // * @throws IllegalArgumentException if the initial capacity is less // * than zero, or if the load factor is nonpositive. // */ // public SoftValuedHashMap(int initialCapacity, float loadFactor) { // super(initialCapacity, loadFactor); // } // // /** // * Constructs a new, empty map with the specified initial capacity // * and default load factor, which is <tt>0.75</tt>. // * // * @param initialCapacity the initial capacity of the HashMap. // * @throws IllegalArgumentException if the initial capacity is less // * than zero. // */ // public SoftValuedHashMap(int initialCapacity) { // super(initialCapacity); // } // // /** // * Constructs a new, empty map with a default capacity and load // * factor, which is <tt>0.75</tt>. // */ // public SoftValuedHashMap() { // super(); // } // // /** // * Constructs a new map with the same mappings as the given map. The // * map is created with a capacity of twice the number of mappings in // * the given map or 11 (whichever is greater), and a default load factor, // * which is <tt>0.75</tt>. // */ // public SoftValuedHashMap(Map<? extends K, ? extends V> t) { // super(t); // } // // Entry<K, V> newEntry(int hash, K key, V value, Entry<K, V> next) { // return new SoftEntry<K, V>(hash, key, value, next); // } // // static class SoftEntry<K, V> extends ReferencedValueHashMap.Entry<K, V> { // // SoftEntry(int hash, K key, V value, Entry<K, V> next) { // super(hash, key, value, next); // } // // SoftEntry(int hash, K key, Reference<V> value, Entry<K, V> next) { // super(hash, key, value, next); // } // // Entry newEntry(int hash, K key, Reference<V> value, Entry<K, V> next) { // return new SoftEntry<K, V>(hash, key, value, next); // } // // Reference<V> newReference(V value) { // return new SoftReference<V>(value); // } // } // }
import java.util.*; import org.cojen.util.SoftValuedHashMap;
/* * Copyright 2004 Brian S O'Neill * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cojen.test; /** * * * @author Brian S O'Neill */ public class TestSoftValuedHashMap { /** * Test program. */ public static void main(String[] arg) throws Exception {
// Path: src/main/java/org/cojen/util/SoftValuedHashMap.java // public class SoftValuedHashMap<K, V> extends ReferencedValueHashMap<K, V> { // // /** // * Constructs a new, empty map with the specified initial // * capacity and the specified load factor. // * // * @param initialCapacity the initial capacity of the HashMap. // * @param loadFactor the load factor of the HashMap // * @throws IllegalArgumentException if the initial capacity is less // * than zero, or if the load factor is nonpositive. // */ // public SoftValuedHashMap(int initialCapacity, float loadFactor) { // super(initialCapacity, loadFactor); // } // // /** // * Constructs a new, empty map with the specified initial capacity // * and default load factor, which is <tt>0.75</tt>. // * // * @param initialCapacity the initial capacity of the HashMap. // * @throws IllegalArgumentException if the initial capacity is less // * than zero. // */ // public SoftValuedHashMap(int initialCapacity) { // super(initialCapacity); // } // // /** // * Constructs a new, empty map with a default capacity and load // * factor, which is <tt>0.75</tt>. // */ // public SoftValuedHashMap() { // super(); // } // // /** // * Constructs a new map with the same mappings as the given map. The // * map is created with a capacity of twice the number of mappings in // * the given map or 11 (whichever is greater), and a default load factor, // * which is <tt>0.75</tt>. // */ // public SoftValuedHashMap(Map<? extends K, ? extends V> t) { // super(t); // } // // Entry<K, V> newEntry(int hash, K key, V value, Entry<K, V> next) { // return new SoftEntry<K, V>(hash, key, value, next); // } // // static class SoftEntry<K, V> extends ReferencedValueHashMap.Entry<K, V> { // // SoftEntry(int hash, K key, V value, Entry<K, V> next) { // super(hash, key, value, next); // } // // SoftEntry(int hash, K key, Reference<V> value, Entry<K, V> next) { // super(hash, key, value, next); // } // // Entry newEntry(int hash, K key, Reference<V> value, Entry<K, V> next) { // return new SoftEntry<K, V>(hash, key, value, next); // } // // Reference<V> newReference(V value) { // return new SoftReference<V>(value); // } // } // } // Path: src/test/java/org/cojen/test/TestSoftValuedHashMap.java import java.util.*; import org.cojen.util.SoftValuedHashMap; /* * Copyright 2004 Brian S O'Neill * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cojen.test; /** * * * @author Brian S O'Neill */ public class TestSoftValuedHashMap { /** * Test program. */ public static void main(String[] arg) throws Exception {
Map cache = new SoftValuedHashMap();
cojen/Cojen
src/main/java/org/cojen/classfile/ExceptionHandler.java
// Path: src/main/java/org/cojen/classfile/constant/ConstantClassInfo.java // public class ConstantClassInfo extends ConstantInfo { // private final TypeDesc mType; // private final ConstantUTFInfo mNameConstant; // // public ConstantClassInfo(ConstantUTFInfo nameConstant) { // super(TAG_CLASS); // String name = nameConstant.getValue(); // if (!name.endsWith(";") && !name.startsWith("[")) { // mType = TypeDesc.forClass(name); // } else { // mType = TypeDesc.forDescriptor(name); // } // mNameConstant = nameConstant; // } // // public ConstantClassInfo(ConstantPool cp, String className) { // super(TAG_CLASS); // String desc = className.replace('.', '/'); // mType = TypeDesc.forClass(className); // mNameConstant = cp.addConstantUTF(desc); // } // // /** // * Used to describe an array class. // */ // public ConstantClassInfo(ConstantPool cp, String className, int dim) { // super(TAG_CLASS); // TypeDesc type = TypeDesc.forClass(className); // String desc; // if (dim > 0) { // while (--dim >= 0) { // type = type.toArrayType(); // } // desc = type.getDescriptor(); // } else { // desc = className.replace('.', '/'); // } // mType = type; // mNameConstant = cp.addConstantUTF(desc); // } // // public ConstantClassInfo(ConstantPool cp, TypeDesc type) { // super(TAG_CLASS); // String desc; // if (type.isArray()) { // desc = type.getDescriptor(); // } else { // desc = type.getRootName().replace('.', '/'); // } // mType = type; // mNameConstant = cp.addConstantUTF(desc); // } // // public TypeDesc getType() { // return mType; // } // // public int hashCode() { // return mType.hashCode(); // } // // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj instanceof ConstantClassInfo) { // ConstantClassInfo other = (ConstantClassInfo)obj; // return mType.equals(other.mType); // } // return false; // } // // public void writeTo(DataOutput dout) throws IOException { // super.writeTo(dout); // dout.writeShort(mNameConstant.getIndex()); // } // // public String toString() { // return "CONSTANT_Class_info: ".concat(getType().getFullName()); // } // }
import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import org.cojen.classfile.constant.ConstantClassInfo;
/* * Copyright 2004-2010 Brian S O'Neill * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cojen.classfile; /** * This class corresponds to the exception_table structure as defined in <i>The * Java Virtual Machine Specification</i>. * * @author Brian S O'Neill */ public class ExceptionHandler<L extends Location> implements LocationRange<L> { private final L mStart; private final L mEnd; private final L mCatch;
// Path: src/main/java/org/cojen/classfile/constant/ConstantClassInfo.java // public class ConstantClassInfo extends ConstantInfo { // private final TypeDesc mType; // private final ConstantUTFInfo mNameConstant; // // public ConstantClassInfo(ConstantUTFInfo nameConstant) { // super(TAG_CLASS); // String name = nameConstant.getValue(); // if (!name.endsWith(";") && !name.startsWith("[")) { // mType = TypeDesc.forClass(name); // } else { // mType = TypeDesc.forDescriptor(name); // } // mNameConstant = nameConstant; // } // // public ConstantClassInfo(ConstantPool cp, String className) { // super(TAG_CLASS); // String desc = className.replace('.', '/'); // mType = TypeDesc.forClass(className); // mNameConstant = cp.addConstantUTF(desc); // } // // /** // * Used to describe an array class. // */ // public ConstantClassInfo(ConstantPool cp, String className, int dim) { // super(TAG_CLASS); // TypeDesc type = TypeDesc.forClass(className); // String desc; // if (dim > 0) { // while (--dim >= 0) { // type = type.toArrayType(); // } // desc = type.getDescriptor(); // } else { // desc = className.replace('.', '/'); // } // mType = type; // mNameConstant = cp.addConstantUTF(desc); // } // // public ConstantClassInfo(ConstantPool cp, TypeDesc type) { // super(TAG_CLASS); // String desc; // if (type.isArray()) { // desc = type.getDescriptor(); // } else { // desc = type.getRootName().replace('.', '/'); // } // mType = type; // mNameConstant = cp.addConstantUTF(desc); // } // // public TypeDesc getType() { // return mType; // } // // public int hashCode() { // return mType.hashCode(); // } // // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj instanceof ConstantClassInfo) { // ConstantClassInfo other = (ConstantClassInfo)obj; // return mType.equals(other.mType); // } // return false; // } // // public void writeTo(DataOutput dout) throws IOException { // super.writeTo(dout); // dout.writeShort(mNameConstant.getIndex()); // } // // public String toString() { // return "CONSTANT_Class_info: ".concat(getType().getFullName()); // } // } // Path: src/main/java/org/cojen/classfile/ExceptionHandler.java import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import org.cojen.classfile.constant.ConstantClassInfo; /* * Copyright 2004-2010 Brian S O'Neill * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cojen.classfile; /** * This class corresponds to the exception_table structure as defined in <i>The * Java Virtual Machine Specification</i>. * * @author Brian S O'Neill */ public class ExceptionHandler<L extends Location> implements LocationRange<L> { private final L mStart; private final L mEnd; private final L mCatch;
private final ConstantClassInfo mCatchType;
CyberdyneCC/Thermos
src/main/java/thermos/updater/CommandSenderUpdateCallback.java
// Path: src/main/java/thermos/Thermos.java // public class Thermos { // public static final ThreadGroup sThermosThreadGroup = new ThreadGroup("Thermos"); // // private static boolean sManifestParsed = false; // // private static void parseManifest() { // if (sManifestParsed) // return; // sManifestParsed = true; // // try { // Enumeration<URL> resources = Thermos.class.getClassLoader() // .getResources("META-INF/MANIFEST.MF"); // Properties manifest = new Properties(); // while (resources.hasMoreElements()) { // URL url = resources.nextElement(); // manifest.load(url.openStream()); // String version = manifest.getProperty("Thermos-Version"); // if (version != null) { // String path = url.getPath(); // String jarFilePath = path.substring(path.indexOf(":") + 1, // path.indexOf("!")); // jarFilePath = URLDecoder.decode(jarFilePath, "UTF-8"); // sServerLocation = new File(jarFilePath); // // sCurrentVersion = version; // sGroup = manifest.getProperty("Thermos-Group"); // sBranch = manifest.getProperty("Thermos-Branch"); // sChannel = manifest.getProperty("Thermos-Channel"); // sLegacy = Boolean.parseBoolean(manifest.getProperty("Thermos-Legacy")); // sOfficial = Boolean.parseBoolean(manifest.getProperty("Thermos-Official")); // break; // } // manifest.clear(); // } // } catch (Exception e) { // e.printStackTrace(); // } // } // // private static String sCurrentVersion; // // public static String getCurrentVersion() { // parseManifest(); // return sCurrentVersion; // } // // private static File sServerLocation; // // public static File getServerLocation() { // parseManifest(); // return sServerLocation; // } // // private static File sServerHome; // // public static File getServerHome() { // if (sServerHome == null) { // String home = System.getenv("THERMOS_HOME"); // if (home != null) { // sServerHome = new File(home); // } else { // parseManifest(); // sServerHome = sServerLocation.getParentFile(); // } // } // return sServerHome; // } // // private static String sGroup; // // public static String getGroup() { // parseManifest(); // return sGroup; // } // // private static String sBranch; // // public static String getBranch() { // parseManifest(); // return sBranch; // } // // private static String sChannel; // // public static String getChannel() { // parseManifest(); // return sChannel; // } // // private static boolean sLegacy, sOfficial; // // public static boolean isLegacy() { // parseManifest(); // return sLegacy; // } // // public static boolean isOfficial() { // parseManifest(); // return sOfficial; // } // // public static File sNewServerLocation; // public static String sNewServerVersion; // public static boolean sUpdateInProgress; // // public static void restart() { // RestartCommand.restart(true); // } // // private static int sForgeRevision = 0; // // public static int lookupForgeRevision() { // if (sForgeRevision != 0) return sForgeRevision; // int revision = Integer.parseInt(System.getProperty("thermos.forgeRevision", "0")); // if (revision != 0) return sForgeRevision = revision; // try { // Properties p = new Properties(); // p.load(Thermos.class // .getResourceAsStream("/fmlversion.properties")); // revision = Integer.parseInt(String.valueOf(p.getProperty( // "fmlbuild.build.number", "0"))); // } catch (Exception e) { // } // if (revision == 0) { // TLog.get().warning("Thermos: could not parse forge revision, critical error"); // FMLCommonHandler.instance().exitJava(1, false); // } // return sForgeRevision = revision; // } // } // // Path: src/main/java/thermos/updater/TVersionRetriever.java // public interface IVersionCheckCallback { // void upToDate(); // // void newVersion(String newVersion); // // void error(Throwable t); // }
import java.lang.ref.Reference; import java.lang.ref.WeakReference; import thermos.Thermos; import thermos.updater.TVersionRetriever.IVersionCheckCallback; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender;
package thermos.updater; public class CommandSenderUpdateCallback implements IVersionCheckCallback { private Reference<CommandSender> mSender; public CommandSenderUpdateCallback(CommandSender sender) { mSender = new WeakReference<CommandSender>(sender); } protected CommandSender getSender() { return mSender.get(); } @Override public void upToDate() { CommandSender sender = mSender.get(); if (sender != null) {
// Path: src/main/java/thermos/Thermos.java // public class Thermos { // public static final ThreadGroup sThermosThreadGroup = new ThreadGroup("Thermos"); // // private static boolean sManifestParsed = false; // // private static void parseManifest() { // if (sManifestParsed) // return; // sManifestParsed = true; // // try { // Enumeration<URL> resources = Thermos.class.getClassLoader() // .getResources("META-INF/MANIFEST.MF"); // Properties manifest = new Properties(); // while (resources.hasMoreElements()) { // URL url = resources.nextElement(); // manifest.load(url.openStream()); // String version = manifest.getProperty("Thermos-Version"); // if (version != null) { // String path = url.getPath(); // String jarFilePath = path.substring(path.indexOf(":") + 1, // path.indexOf("!")); // jarFilePath = URLDecoder.decode(jarFilePath, "UTF-8"); // sServerLocation = new File(jarFilePath); // // sCurrentVersion = version; // sGroup = manifest.getProperty("Thermos-Group"); // sBranch = manifest.getProperty("Thermos-Branch"); // sChannel = manifest.getProperty("Thermos-Channel"); // sLegacy = Boolean.parseBoolean(manifest.getProperty("Thermos-Legacy")); // sOfficial = Boolean.parseBoolean(manifest.getProperty("Thermos-Official")); // break; // } // manifest.clear(); // } // } catch (Exception e) { // e.printStackTrace(); // } // } // // private static String sCurrentVersion; // // public static String getCurrentVersion() { // parseManifest(); // return sCurrentVersion; // } // // private static File sServerLocation; // // public static File getServerLocation() { // parseManifest(); // return sServerLocation; // } // // private static File sServerHome; // // public static File getServerHome() { // if (sServerHome == null) { // String home = System.getenv("THERMOS_HOME"); // if (home != null) { // sServerHome = new File(home); // } else { // parseManifest(); // sServerHome = sServerLocation.getParentFile(); // } // } // return sServerHome; // } // // private static String sGroup; // // public static String getGroup() { // parseManifest(); // return sGroup; // } // // private static String sBranch; // // public static String getBranch() { // parseManifest(); // return sBranch; // } // // private static String sChannel; // // public static String getChannel() { // parseManifest(); // return sChannel; // } // // private static boolean sLegacy, sOfficial; // // public static boolean isLegacy() { // parseManifest(); // return sLegacy; // } // // public static boolean isOfficial() { // parseManifest(); // return sOfficial; // } // // public static File sNewServerLocation; // public static String sNewServerVersion; // public static boolean sUpdateInProgress; // // public static void restart() { // RestartCommand.restart(true); // } // // private static int sForgeRevision = 0; // // public static int lookupForgeRevision() { // if (sForgeRevision != 0) return sForgeRevision; // int revision = Integer.parseInt(System.getProperty("thermos.forgeRevision", "0")); // if (revision != 0) return sForgeRevision = revision; // try { // Properties p = new Properties(); // p.load(Thermos.class // .getResourceAsStream("/fmlversion.properties")); // revision = Integer.parseInt(String.valueOf(p.getProperty( // "fmlbuild.build.number", "0"))); // } catch (Exception e) { // } // if (revision == 0) { // TLog.get().warning("Thermos: could not parse forge revision, critical error"); // FMLCommonHandler.instance().exitJava(1, false); // } // return sForgeRevision = revision; // } // } // // Path: src/main/java/thermos/updater/TVersionRetriever.java // public interface IVersionCheckCallback { // void upToDate(); // // void newVersion(String newVersion); // // void error(Throwable t); // } // Path: src/main/java/thermos/updater/CommandSenderUpdateCallback.java import java.lang.ref.Reference; import java.lang.ref.WeakReference; import thermos.Thermos; import thermos.updater.TVersionRetriever.IVersionCheckCallback; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; package thermos.updater; public class CommandSenderUpdateCallback implements IVersionCheckCallback { private Reference<CommandSender> mSender; public CommandSenderUpdateCallback(CommandSender sender) { mSender = new WeakReference<CommandSender>(sender); } protected CommandSender getSender() { return mSender.get(); } @Override public void upToDate() { CommandSender sender = mSender.get(); if (sender != null) {
sender.sendMessage(ChatColor.RED + "[Thermos] " + ChatColor.GRAY + "Thermos is up-to-date: " + Thermos.getCurrentVersion());
CyberdyneCC/Thermos
src/main/java/net/md_5/bungee/api/chat/TextComponent.java
// Path: src/main/java/net/md_5/bungee/api/chat/ClickEvent.java // public final class ClickEvent { // private final Action action; // private final String value; // // public Action getAction() { // return this.action; // } // // public String getValue() { // return this.value; // } // // public String toString() { // return "ClickEvent(action=" + (Object)((Object)this.getAction()) + ", value=" + this.getValue() + ")"; // } // // @ConstructorProperties(value={"action", "value"}) // public ClickEvent(Action action, String value) { // this.action = action; // this.value = value; // } // // public static enum Action { // OPEN_URL, // OPEN_FILE, // RUN_COMMAND, // SUGGEST_COMMAND; // // // private Action() { // } // } // // }
import java.beans.ConstructorProperties; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.ClickEvent;
continue block8; } case MAGIC: { component.setObfuscated(true); continue block8; } case RESET: { format = ChatColor.WHITE; } } component = new TextComponent(); component.setColor(format); continue; } int pos = message.indexOf(32, i); if (pos == -1) { pos = message.length(); } if (matcher.region(i, pos).find()) { if (builder.length() > 0) { old = component; component = new TextComponent(old); old.setText(builder.toString()); builder = new StringBuilder(); components.add(old); } old = component; component = new TextComponent(old); String urlString = message.substring(i, pos); component.setText(urlString);
// Path: src/main/java/net/md_5/bungee/api/chat/ClickEvent.java // public final class ClickEvent { // private final Action action; // private final String value; // // public Action getAction() { // return this.action; // } // // public String getValue() { // return this.value; // } // // public String toString() { // return "ClickEvent(action=" + (Object)((Object)this.getAction()) + ", value=" + this.getValue() + ")"; // } // // @ConstructorProperties(value={"action", "value"}) // public ClickEvent(Action action, String value) { // this.action = action; // this.value = value; // } // // public static enum Action { // OPEN_URL, // OPEN_FILE, // RUN_COMMAND, // SUGGEST_COMMAND; // // // private Action() { // } // } // // } // Path: src/main/java/net/md_5/bungee/api/chat/TextComponent.java import java.beans.ConstructorProperties; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.ClickEvent; continue block8; } case MAGIC: { component.setObfuscated(true); continue block8; } case RESET: { format = ChatColor.WHITE; } } component = new TextComponent(); component.setColor(format); continue; } int pos = message.indexOf(32, i); if (pos == -1) { pos = message.length(); } if (matcher.region(i, pos).find()) { if (builder.length() > 0) { old = component; component = new TextComponent(old); old.setText(builder.toString()); builder = new StringBuilder(); components.add(old); } old = component; component = new TextComponent(old); String urlString = message.substring(i, pos); component.setText(urlString);
component.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, urlString.startsWith("http") ? urlString : "http://" + urlString));
CyberdyneCC/Thermos
src/main/java/org/bukkit/craftbukkit/inventory/CraftItemStack.java
// Path: src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java // static final ItemMetaKey ENCHANTMENTS = new ItemMetaKey("ench", "enchants"); // // Path: src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java // @Specific(Specific.To.NBT) // static final ItemMetaKey ENCHANTMENTS_ID = new ItemMetaKey("id"); // // Path: src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java // @Specific(Specific.To.NBT) // static final ItemMetaKey ENCHANTMENTS_LVL = new ItemMetaKey("lvl");
import static org.bukkit.craftbukkit.inventory.CraftMetaItem.ENCHANTMENTS; import static org.bukkit.craftbukkit.inventory.CraftMetaItem.ENCHANTMENTS_ID; import static org.bukkit.craftbukkit.inventory.CraftMetaItem.ENCHANTMENTS_LVL; import java.util.Map; import org.apache.commons.lang.Validate; import org.bukkit.Material; import org.bukkit.configuration.serialization.DelegateDeserialization; import org.bukkit.craftbukkit.util.CraftMagicNumbers; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import com.google.common.collect.ImmutableMap;
// Ignore damage if item is null if (handle != null) { handle.setItemDamage(durability); } } @Override public short getDurability() { if (handle != null) { return (short) handle.getItemDamage(); } else { return -1; } } @Override public int getMaxStackSize() { return (handle == null) ? Material.AIR.getMaxStackSize() : handle.getItem().getItemStackLimit(); } @Override public void addUnsafeEnchantment(Enchantment ench, int level) { Validate.notNull(ench, "Cannot add null enchantment"); if (!makeTag(handle)) { return; } net.minecraft.nbt.NBTTagList list = getEnchantmentList(handle); if (list == null) { list = new net.minecraft.nbt.NBTTagList();
// Path: src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java // static final ItemMetaKey ENCHANTMENTS = new ItemMetaKey("ench", "enchants"); // // Path: src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java // @Specific(Specific.To.NBT) // static final ItemMetaKey ENCHANTMENTS_ID = new ItemMetaKey("id"); // // Path: src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java // @Specific(Specific.To.NBT) // static final ItemMetaKey ENCHANTMENTS_LVL = new ItemMetaKey("lvl"); // Path: src/main/java/org/bukkit/craftbukkit/inventory/CraftItemStack.java import static org.bukkit.craftbukkit.inventory.CraftMetaItem.ENCHANTMENTS; import static org.bukkit.craftbukkit.inventory.CraftMetaItem.ENCHANTMENTS_ID; import static org.bukkit.craftbukkit.inventory.CraftMetaItem.ENCHANTMENTS_LVL; import java.util.Map; import org.apache.commons.lang.Validate; import org.bukkit.Material; import org.bukkit.configuration.serialization.DelegateDeserialization; import org.bukkit.craftbukkit.util.CraftMagicNumbers; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import com.google.common.collect.ImmutableMap; // Ignore damage if item is null if (handle != null) { handle.setItemDamage(durability); } } @Override public short getDurability() { if (handle != null) { return (short) handle.getItemDamage(); } else { return -1; } } @Override public int getMaxStackSize() { return (handle == null) ? Material.AIR.getMaxStackSize() : handle.getItem().getItemStackLimit(); } @Override public void addUnsafeEnchantment(Enchantment ench, int level) { Validate.notNull(ench, "Cannot add null enchantment"); if (!makeTag(handle)) { return; } net.minecraft.nbt.NBTTagList list = getEnchantmentList(handle); if (list == null) { list = new net.minecraft.nbt.NBTTagList();
handle.stackTagCompound.setTag(ENCHANTMENTS.NBT, list);
CyberdyneCC/Thermos
src/main/java/org/bukkit/craftbukkit/inventory/CraftItemStack.java
// Path: src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java // static final ItemMetaKey ENCHANTMENTS = new ItemMetaKey("ench", "enchants"); // // Path: src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java // @Specific(Specific.To.NBT) // static final ItemMetaKey ENCHANTMENTS_ID = new ItemMetaKey("id"); // // Path: src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java // @Specific(Specific.To.NBT) // static final ItemMetaKey ENCHANTMENTS_LVL = new ItemMetaKey("lvl");
import static org.bukkit.craftbukkit.inventory.CraftMetaItem.ENCHANTMENTS; import static org.bukkit.craftbukkit.inventory.CraftMetaItem.ENCHANTMENTS_ID; import static org.bukkit.craftbukkit.inventory.CraftMetaItem.ENCHANTMENTS_LVL; import java.util.Map; import org.apache.commons.lang.Validate; import org.bukkit.Material; import org.bukkit.configuration.serialization.DelegateDeserialization; import org.bukkit.craftbukkit.util.CraftMagicNumbers; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import com.google.common.collect.ImmutableMap;
@Override public short getDurability() { if (handle != null) { return (short) handle.getItemDamage(); } else { return -1; } } @Override public int getMaxStackSize() { return (handle == null) ? Material.AIR.getMaxStackSize() : handle.getItem().getItemStackLimit(); } @Override public void addUnsafeEnchantment(Enchantment ench, int level) { Validate.notNull(ench, "Cannot add null enchantment"); if (!makeTag(handle)) { return; } net.minecraft.nbt.NBTTagList list = getEnchantmentList(handle); if (list == null) { list = new net.minecraft.nbt.NBTTagList(); handle.stackTagCompound.setTag(ENCHANTMENTS.NBT, list); } int size = list.tagCount(); for (int i = 0; i < size; i++) { net.minecraft.nbt.NBTTagCompound tag = (net.minecraft.nbt.NBTTagCompound) list.getCompoundTagAt(i);
// Path: src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java // static final ItemMetaKey ENCHANTMENTS = new ItemMetaKey("ench", "enchants"); // // Path: src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java // @Specific(Specific.To.NBT) // static final ItemMetaKey ENCHANTMENTS_ID = new ItemMetaKey("id"); // // Path: src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java // @Specific(Specific.To.NBT) // static final ItemMetaKey ENCHANTMENTS_LVL = new ItemMetaKey("lvl"); // Path: src/main/java/org/bukkit/craftbukkit/inventory/CraftItemStack.java import static org.bukkit.craftbukkit.inventory.CraftMetaItem.ENCHANTMENTS; import static org.bukkit.craftbukkit.inventory.CraftMetaItem.ENCHANTMENTS_ID; import static org.bukkit.craftbukkit.inventory.CraftMetaItem.ENCHANTMENTS_LVL; import java.util.Map; import org.apache.commons.lang.Validate; import org.bukkit.Material; import org.bukkit.configuration.serialization.DelegateDeserialization; import org.bukkit.craftbukkit.util.CraftMagicNumbers; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import com.google.common.collect.ImmutableMap; @Override public short getDurability() { if (handle != null) { return (short) handle.getItemDamage(); } else { return -1; } } @Override public int getMaxStackSize() { return (handle == null) ? Material.AIR.getMaxStackSize() : handle.getItem().getItemStackLimit(); } @Override public void addUnsafeEnchantment(Enchantment ench, int level) { Validate.notNull(ench, "Cannot add null enchantment"); if (!makeTag(handle)) { return; } net.minecraft.nbt.NBTTagList list = getEnchantmentList(handle); if (list == null) { list = new net.minecraft.nbt.NBTTagList(); handle.stackTagCompound.setTag(ENCHANTMENTS.NBT, list); } int size = list.tagCount(); for (int i = 0; i < size; i++) { net.minecraft.nbt.NBTTagCompound tag = (net.minecraft.nbt.NBTTagCompound) list.getCompoundTagAt(i);
short id = tag.getShort(ENCHANTMENTS_ID.NBT);
CyberdyneCC/Thermos
src/main/java/org/bukkit/craftbukkit/inventory/CraftItemStack.java
// Path: src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java // static final ItemMetaKey ENCHANTMENTS = new ItemMetaKey("ench", "enchants"); // // Path: src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java // @Specific(Specific.To.NBT) // static final ItemMetaKey ENCHANTMENTS_ID = new ItemMetaKey("id"); // // Path: src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java // @Specific(Specific.To.NBT) // static final ItemMetaKey ENCHANTMENTS_LVL = new ItemMetaKey("lvl");
import static org.bukkit.craftbukkit.inventory.CraftMetaItem.ENCHANTMENTS; import static org.bukkit.craftbukkit.inventory.CraftMetaItem.ENCHANTMENTS_ID; import static org.bukkit.craftbukkit.inventory.CraftMetaItem.ENCHANTMENTS_LVL; import java.util.Map; import org.apache.commons.lang.Validate; import org.bukkit.Material; import org.bukkit.configuration.serialization.DelegateDeserialization; import org.bukkit.craftbukkit.util.CraftMagicNumbers; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import com.google.common.collect.ImmutableMap;
if (handle != null) { return (short) handle.getItemDamage(); } else { return -1; } } @Override public int getMaxStackSize() { return (handle == null) ? Material.AIR.getMaxStackSize() : handle.getItem().getItemStackLimit(); } @Override public void addUnsafeEnchantment(Enchantment ench, int level) { Validate.notNull(ench, "Cannot add null enchantment"); if (!makeTag(handle)) { return; } net.minecraft.nbt.NBTTagList list = getEnchantmentList(handle); if (list == null) { list = new net.minecraft.nbt.NBTTagList(); handle.stackTagCompound.setTag(ENCHANTMENTS.NBT, list); } int size = list.tagCount(); for (int i = 0; i < size; i++) { net.minecraft.nbt.NBTTagCompound tag = (net.minecraft.nbt.NBTTagCompound) list.getCompoundTagAt(i); short id = tag.getShort(ENCHANTMENTS_ID.NBT); if (id == ench.getId()) {
// Path: src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java // static final ItemMetaKey ENCHANTMENTS = new ItemMetaKey("ench", "enchants"); // // Path: src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java // @Specific(Specific.To.NBT) // static final ItemMetaKey ENCHANTMENTS_ID = new ItemMetaKey("id"); // // Path: src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java // @Specific(Specific.To.NBT) // static final ItemMetaKey ENCHANTMENTS_LVL = new ItemMetaKey("lvl"); // Path: src/main/java/org/bukkit/craftbukkit/inventory/CraftItemStack.java import static org.bukkit.craftbukkit.inventory.CraftMetaItem.ENCHANTMENTS; import static org.bukkit.craftbukkit.inventory.CraftMetaItem.ENCHANTMENTS_ID; import static org.bukkit.craftbukkit.inventory.CraftMetaItem.ENCHANTMENTS_LVL; import java.util.Map; import org.apache.commons.lang.Validate; import org.bukkit.Material; import org.bukkit.configuration.serialization.DelegateDeserialization; import org.bukkit.craftbukkit.util.CraftMagicNumbers; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import com.google.common.collect.ImmutableMap; if (handle != null) { return (short) handle.getItemDamage(); } else { return -1; } } @Override public int getMaxStackSize() { return (handle == null) ? Material.AIR.getMaxStackSize() : handle.getItem().getItemStackLimit(); } @Override public void addUnsafeEnchantment(Enchantment ench, int level) { Validate.notNull(ench, "Cannot add null enchantment"); if (!makeTag(handle)) { return; } net.minecraft.nbt.NBTTagList list = getEnchantmentList(handle); if (list == null) { list = new net.minecraft.nbt.NBTTagList(); handle.stackTagCompound.setTag(ENCHANTMENTS.NBT, list); } int size = list.tagCount(); for (int i = 0; i < size; i++) { net.minecraft.nbt.NBTTagCompound tag = (net.minecraft.nbt.NBTTagCompound) list.getCompoundTagAt(i); short id = tag.getShort(ENCHANTMENTS_ID.NBT); if (id == ench.getId()) {
tag.setShort(ENCHANTMENTS_LVL.NBT, (short) level);
CyberdyneCC/Thermos
src/main/java/thermos/updater/TVersionRetriever.java
// Path: src/main/java/thermos/Thermos.java // public class Thermos { // public static final ThreadGroup sThermosThreadGroup = new ThreadGroup("Thermos"); // // private static boolean sManifestParsed = false; // // private static void parseManifest() { // if (sManifestParsed) // return; // sManifestParsed = true; // // try { // Enumeration<URL> resources = Thermos.class.getClassLoader() // .getResources("META-INF/MANIFEST.MF"); // Properties manifest = new Properties(); // while (resources.hasMoreElements()) { // URL url = resources.nextElement(); // manifest.load(url.openStream()); // String version = manifest.getProperty("Thermos-Version"); // if (version != null) { // String path = url.getPath(); // String jarFilePath = path.substring(path.indexOf(":") + 1, // path.indexOf("!")); // jarFilePath = URLDecoder.decode(jarFilePath, "UTF-8"); // sServerLocation = new File(jarFilePath); // // sCurrentVersion = version; // sGroup = manifest.getProperty("Thermos-Group"); // sBranch = manifest.getProperty("Thermos-Branch"); // sChannel = manifest.getProperty("Thermos-Channel"); // sLegacy = Boolean.parseBoolean(manifest.getProperty("Thermos-Legacy")); // sOfficial = Boolean.parseBoolean(manifest.getProperty("Thermos-Official")); // break; // } // manifest.clear(); // } // } catch (Exception e) { // e.printStackTrace(); // } // } // // private static String sCurrentVersion; // // public static String getCurrentVersion() { // parseManifest(); // return sCurrentVersion; // } // // private static File sServerLocation; // // public static File getServerLocation() { // parseManifest(); // return sServerLocation; // } // // private static File sServerHome; // // public static File getServerHome() { // if (sServerHome == null) { // String home = System.getenv("THERMOS_HOME"); // if (home != null) { // sServerHome = new File(home); // } else { // parseManifest(); // sServerHome = sServerLocation.getParentFile(); // } // } // return sServerHome; // } // // private static String sGroup; // // public static String getGroup() { // parseManifest(); // return sGroup; // } // // private static String sBranch; // // public static String getBranch() { // parseManifest(); // return sBranch; // } // // private static String sChannel; // // public static String getChannel() { // parseManifest(); // return sChannel; // } // // private static boolean sLegacy, sOfficial; // // public static boolean isLegacy() { // parseManifest(); // return sLegacy; // } // // public static boolean isOfficial() { // parseManifest(); // return sOfficial; // } // // public static File sNewServerLocation; // public static String sNewServerVersion; // public static boolean sUpdateInProgress; // // public static void restart() { // RestartCommand.restart(true); // } // // private static int sForgeRevision = 0; // // public static int lookupForgeRevision() { // if (sForgeRevision != 0) return sForgeRevision; // int revision = Integer.parseInt(System.getProperty("thermos.forgeRevision", "0")); // if (revision != 0) return sForgeRevision = revision; // try { // Properties p = new Properties(); // p.load(Thermos.class // .getResourceAsStream("/fmlversion.properties")); // revision = Integer.parseInt(String.valueOf(p.getProperty( // "fmlbuild.build.number", "0"))); // } catch (Exception e) { // } // if (revision == 0) { // TLog.get().warning("Thermos: could not parse forge revision, critical error"); // FMLCommonHandler.instance().exitJava(1, false); // } // return sForgeRevision = revision; // } // } // // Path: src/main/java/thermos/TLog.java // public class TLog { // private static final TLog DEFAULT_LOGGER = new TLog("Thermos"); // // public static TLog get() { // return DEFAULT_LOGGER; // } // // public static TLog get(String tag) { // return new TLog("Thermos: " + tag); // } // // private final String mTag; // // public TLog(String tag) { // mTag = tag; // } // // public void log(Level level, Throwable throwable, String message, // Object... args) { // Throwable t = null; // if (throwable != null) { // t = new Throwable(); // t.initCause(throwable); // t.fillInStackTrace(); // } // FMLLog.log(mTag, level, t, String.format(message, args)); // } // // public void warning(String message, Object... args) { // log(Level.WARN, null, message, args); // } // // public void warning(Throwable throwable, String message, // Object... args) { // log(Level.WARN, throwable, message, args); // } // // public void info(String message, Object... args) { // log(Level.INFO, null, message, args); // } // // public void info(Throwable throwable, String message, // Object... args) { // log(Level.INFO, throwable, message, args); // } // }
import java.io.InputStreamReader; import java.lang.Thread.UncaughtExceptionHandler; import thermos.Thermos; import thermos.TLog; import net.minecraft.server.MinecraftServer; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.RequestBuilder; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.LaxRedirectStrategy; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser;
package thermos.updater; public class TVersionRetriever implements Runnable, UncaughtExceptionHandler { private static final boolean DEBUG;
// Path: src/main/java/thermos/Thermos.java // public class Thermos { // public static final ThreadGroup sThermosThreadGroup = new ThreadGroup("Thermos"); // // private static boolean sManifestParsed = false; // // private static void parseManifest() { // if (sManifestParsed) // return; // sManifestParsed = true; // // try { // Enumeration<URL> resources = Thermos.class.getClassLoader() // .getResources("META-INF/MANIFEST.MF"); // Properties manifest = new Properties(); // while (resources.hasMoreElements()) { // URL url = resources.nextElement(); // manifest.load(url.openStream()); // String version = manifest.getProperty("Thermos-Version"); // if (version != null) { // String path = url.getPath(); // String jarFilePath = path.substring(path.indexOf(":") + 1, // path.indexOf("!")); // jarFilePath = URLDecoder.decode(jarFilePath, "UTF-8"); // sServerLocation = new File(jarFilePath); // // sCurrentVersion = version; // sGroup = manifest.getProperty("Thermos-Group"); // sBranch = manifest.getProperty("Thermos-Branch"); // sChannel = manifest.getProperty("Thermos-Channel"); // sLegacy = Boolean.parseBoolean(manifest.getProperty("Thermos-Legacy")); // sOfficial = Boolean.parseBoolean(manifest.getProperty("Thermos-Official")); // break; // } // manifest.clear(); // } // } catch (Exception e) { // e.printStackTrace(); // } // } // // private static String sCurrentVersion; // // public static String getCurrentVersion() { // parseManifest(); // return sCurrentVersion; // } // // private static File sServerLocation; // // public static File getServerLocation() { // parseManifest(); // return sServerLocation; // } // // private static File sServerHome; // // public static File getServerHome() { // if (sServerHome == null) { // String home = System.getenv("THERMOS_HOME"); // if (home != null) { // sServerHome = new File(home); // } else { // parseManifest(); // sServerHome = sServerLocation.getParentFile(); // } // } // return sServerHome; // } // // private static String sGroup; // // public static String getGroup() { // parseManifest(); // return sGroup; // } // // private static String sBranch; // // public static String getBranch() { // parseManifest(); // return sBranch; // } // // private static String sChannel; // // public static String getChannel() { // parseManifest(); // return sChannel; // } // // private static boolean sLegacy, sOfficial; // // public static boolean isLegacy() { // parseManifest(); // return sLegacy; // } // // public static boolean isOfficial() { // parseManifest(); // return sOfficial; // } // // public static File sNewServerLocation; // public static String sNewServerVersion; // public static boolean sUpdateInProgress; // // public static void restart() { // RestartCommand.restart(true); // } // // private static int sForgeRevision = 0; // // public static int lookupForgeRevision() { // if (sForgeRevision != 0) return sForgeRevision; // int revision = Integer.parseInt(System.getProperty("thermos.forgeRevision", "0")); // if (revision != 0) return sForgeRevision = revision; // try { // Properties p = new Properties(); // p.load(Thermos.class // .getResourceAsStream("/fmlversion.properties")); // revision = Integer.parseInt(String.valueOf(p.getProperty( // "fmlbuild.build.number", "0"))); // } catch (Exception e) { // } // if (revision == 0) { // TLog.get().warning("Thermos: could not parse forge revision, critical error"); // FMLCommonHandler.instance().exitJava(1, false); // } // return sForgeRevision = revision; // } // } // // Path: src/main/java/thermos/TLog.java // public class TLog { // private static final TLog DEFAULT_LOGGER = new TLog("Thermos"); // // public static TLog get() { // return DEFAULT_LOGGER; // } // // public static TLog get(String tag) { // return new TLog("Thermos: " + tag); // } // // private final String mTag; // // public TLog(String tag) { // mTag = tag; // } // // public void log(Level level, Throwable throwable, String message, // Object... args) { // Throwable t = null; // if (throwable != null) { // t = new Throwable(); // t.initCause(throwable); // t.fillInStackTrace(); // } // FMLLog.log(mTag, level, t, String.format(message, args)); // } // // public void warning(String message, Object... args) { // log(Level.WARN, null, message, args); // } // // public void warning(Throwable throwable, String message, // Object... args) { // log(Level.WARN, throwable, message, args); // } // // public void info(String message, Object... args) { // log(Level.INFO, null, message, args); // } // // public void info(Throwable throwable, String message, // Object... args) { // log(Level.INFO, throwable, message, args); // } // } // Path: src/main/java/thermos/updater/TVersionRetriever.java import java.io.InputStreamReader; import java.lang.Thread.UncaughtExceptionHandler; import thermos.Thermos; import thermos.TLog; import net.minecraft.server.MinecraftServer; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.RequestBuilder; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.LaxRedirectStrategy; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; package thermos.updater; public class TVersionRetriever implements Runnable, UncaughtExceptionHandler { private static final boolean DEBUG;
private static final TLog sLogger;
CyberdyneCC/Thermos
src/main/java/thermos/Thermos.java
// Path: src/main/java/org/spigotmc/RestartCommand.java // public class RestartCommand extends Command // { // // public RestartCommand(String name) // { // super( name ); // this.description = "Restarts the server"; // this.usageMessage = "/restart"; // this.setPermission( "bukkit.command.restart" ); // } // // @Override // public boolean execute(CommandSender sender, String currentAlias, String[] args) // { // if ( testPermission( sender ) ) // { // restart(); // } // return true; // } // // public static void restart() { // restart(false); // } // // public static void restart(boolean forbidShutdown) // { // try // { // final File file = new File( SpigotConfig.restartScript ); // if ( file.isFile() ) // { // System.out.println( "Attempting to restart with " + SpigotConfig.restartScript ); // // // Forbid new logons // net.minecraft.server.dedicated.DedicatedServer.allowPlayerLogins = false; // // // Kick all players // for ( Object p : net.minecraft.server.MinecraftServer.getServer().getConfigurationManager().playerEntityList.toArray() ) // { // if(p instanceof net.minecraft.entity.player.EntityPlayerMP) // { // net.minecraft.entity.player.EntityPlayerMP mp = ( net.minecraft.entity.player.EntityPlayerMP)p; // mp.playerNetServerHandler.kickPlayerFromServer(SpigotConfig.restartMessage); // mp.playerNetServerHandler.netManager.isChannelOpen(); // } // // } // // // Give the socket a chance to send the packets // try // { // Thread.sleep( 100 ); // } catch ( InterruptedException ex ) // { // } // // Close the socket so we can rebind with the new process // net.minecraft.server.MinecraftServer.getServer().func_147137_ag().terminateEndpoints(); // // // Give time for it to kick in // try // { // Thread.sleep( 100 ); // } catch ( InterruptedException ex ) // { // } // // // Actually shutdown // try // { // Bukkit.shutdown(); // } catch ( Throwable t ) // { // } // // // This will be done AFTER the server has completely halted // Thread shutdownHook = new Thread() // { // @Override // public void run() // { // try // { // String os = System.getProperty( "os.name" ).toLowerCase(); // if ( os.contains( "win" ) ) // { // Runtime.getRuntime().exec( "cmd /c start " + file.getPath() ); // } else // { // Runtime.getRuntime().exec( new String[] // { // "/bin/sh", file.getPath() // } ); // } // } catch ( Exception e ) // { // e.printStackTrace(); // } // } // }; // // shutdownHook.setDaemon( true ); // Runtime.getRuntime().addShutdownHook( shutdownHook ); // } else // { // if (forbidShutdown) { // System.out.println("Attempt to restart server without restart script, decline request"); // return; // } // System.out.println( "Startup script '" + SpigotConfig.restartScript + "' does not exist! Stopping server." ); // } // cpw.mods.fml.common.FMLCommonHandler.instance().exitJava(0, false); // } catch ( Exception ex ) // { // ex.printStackTrace(); // } // } // }
import java.io.File; import java.io.InputStream; import java.net.URL; import java.net.URLDecoder; import java.util.Enumeration; import java.util.Properties; import org.spigotmc.RestartCommand; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.FMLLog;
public static String getBranch() { parseManifest(); return sBranch; } private static String sChannel; public static String getChannel() { parseManifest(); return sChannel; } private static boolean sLegacy, sOfficial; public static boolean isLegacy() { parseManifest(); return sLegacy; } public static boolean isOfficial() { parseManifest(); return sOfficial; } public static File sNewServerLocation; public static String sNewServerVersion; public static boolean sUpdateInProgress; public static void restart() {
// Path: src/main/java/org/spigotmc/RestartCommand.java // public class RestartCommand extends Command // { // // public RestartCommand(String name) // { // super( name ); // this.description = "Restarts the server"; // this.usageMessage = "/restart"; // this.setPermission( "bukkit.command.restart" ); // } // // @Override // public boolean execute(CommandSender sender, String currentAlias, String[] args) // { // if ( testPermission( sender ) ) // { // restart(); // } // return true; // } // // public static void restart() { // restart(false); // } // // public static void restart(boolean forbidShutdown) // { // try // { // final File file = new File( SpigotConfig.restartScript ); // if ( file.isFile() ) // { // System.out.println( "Attempting to restart with " + SpigotConfig.restartScript ); // // // Forbid new logons // net.minecraft.server.dedicated.DedicatedServer.allowPlayerLogins = false; // // // Kick all players // for ( Object p : net.minecraft.server.MinecraftServer.getServer().getConfigurationManager().playerEntityList.toArray() ) // { // if(p instanceof net.minecraft.entity.player.EntityPlayerMP) // { // net.minecraft.entity.player.EntityPlayerMP mp = ( net.minecraft.entity.player.EntityPlayerMP)p; // mp.playerNetServerHandler.kickPlayerFromServer(SpigotConfig.restartMessage); // mp.playerNetServerHandler.netManager.isChannelOpen(); // } // // } // // // Give the socket a chance to send the packets // try // { // Thread.sleep( 100 ); // } catch ( InterruptedException ex ) // { // } // // Close the socket so we can rebind with the new process // net.minecraft.server.MinecraftServer.getServer().func_147137_ag().terminateEndpoints(); // // // Give time for it to kick in // try // { // Thread.sleep( 100 ); // } catch ( InterruptedException ex ) // { // } // // // Actually shutdown // try // { // Bukkit.shutdown(); // } catch ( Throwable t ) // { // } // // // This will be done AFTER the server has completely halted // Thread shutdownHook = new Thread() // { // @Override // public void run() // { // try // { // String os = System.getProperty( "os.name" ).toLowerCase(); // if ( os.contains( "win" ) ) // { // Runtime.getRuntime().exec( "cmd /c start " + file.getPath() ); // } else // { // Runtime.getRuntime().exec( new String[] // { // "/bin/sh", file.getPath() // } ); // } // } catch ( Exception e ) // { // e.printStackTrace(); // } // } // }; // // shutdownHook.setDaemon( true ); // Runtime.getRuntime().addShutdownHook( shutdownHook ); // } else // { // if (forbidShutdown) { // System.out.println("Attempt to restart server without restart script, decline request"); // return; // } // System.out.println( "Startup script '" + SpigotConfig.restartScript + "' does not exist! Stopping server." ); // } // cpw.mods.fml.common.FMLCommonHandler.instance().exitJava(0, false); // } catch ( Exception ex ) // { // ex.printStackTrace(); // } // } // } // Path: src/main/java/thermos/Thermos.java import java.io.File; import java.io.InputStream; import java.net.URL; import java.net.URLDecoder; import java.util.Enumeration; import java.util.Properties; import org.spigotmc.RestartCommand; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.FMLLog; public static String getBranch() { parseManifest(); return sBranch; } private static String sChannel; public static String getChannel() { parseManifest(); return sChannel; } private static boolean sLegacy, sOfficial; public static boolean isLegacy() { parseManifest(); return sLegacy; } public static boolean isOfficial() { parseManifest(); return sOfficial; } public static File sNewServerLocation; public static String sNewServerVersion; public static boolean sUpdateInProgress; public static void restart() {
RestartCommand.restart(true);
KKorvin/uPods-android
app/src/main/java/com/chickenkiller/upods2/activity/BasicActivity.java
// Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IContextMenuManager.java // public interface IContextMenuManager { // // /** // * @param view - which shows context menu // * @param type - type of context menu to show // * @param dataToPass - data which will be used for actions inside menu // */ // void openContextMenu(View view, ContextMenuType type, Object dataToPass, IOperationFinishCallback contextItemClicked); // } // // Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IControlStackHistory.java // public interface IControlStackHistory { // boolean shouldBeAddedToStack(); // } // // Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IFragmentsManager.java // public interface IFragmentsManager { // // enum FragmentOpenType {REPLACE, OVERLAY} // // enum FragmentAnimationType {DEFAULT, BOTTOM_TOP} // // // void showFragment(int id, Fragment fragment, String tag, FragmentOpenType openType, FragmentAnimationType animationType); // // void showFragment(int id, Fragment fragment, String tag); // // void hideFragment(Fragment fragment); // // void showDialogFragment(DialogFragment dialogFragment); // // boolean hasFragment(String tag); // // String getLatestFragmentTag(); // } // // Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IOperationFinishCallback.java // public interface IOperationFinishCallback { // // void operationFinished(); // } // // Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IOverlayable.java // public interface IOverlayable { // void toggleOverlay(); // boolean isOverlayShown(); // void setOverlayAlpha(int alphaPercent); // } // // Path: app/src/main/java/com/chickenkiller/upods2/utils/enums/ContextMenuType.java // public enum ContextMenuType { // // CARD_DEFAULT, EPISODE_MIDDLE_SCREEN, PODCAST_MIDDLE_SCREEN, PLAYER_SETTINGS, PROFILE // }
import android.app.Activity; import android.app.DialogFragment; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.pm.PackageManager; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.chickenkiller.upods2.R; import com.chickenkiller.upods2.interfaces.IContextMenuManager; import com.chickenkiller.upods2.interfaces.IControlStackHistory; import com.chickenkiller.upods2.interfaces.IFragmentsManager; import com.chickenkiller.upods2.interfaces.IOperationFinishCallback; import com.chickenkiller.upods2.interfaces.IOverlayable; import com.chickenkiller.upods2.utils.enums.ContextMenuType; import java.util.Calendar;
package com.chickenkiller.upods2.activity; /** * Created by Alon Zilberman on 7/28/15. * Extend this activity to get basic logic for context menu and fragments working */ public class BasicActivity extends Activity implements IFragmentsManager, IContextMenuManager { private final static String DIALOG_TAG_START = "fr_dialog_"; //Permissions public static int WRITE_EXTERNAL_PERMISSIONS_CODE = 785;
// Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IContextMenuManager.java // public interface IContextMenuManager { // // /** // * @param view - which shows context menu // * @param type - type of context menu to show // * @param dataToPass - data which will be used for actions inside menu // */ // void openContextMenu(View view, ContextMenuType type, Object dataToPass, IOperationFinishCallback contextItemClicked); // } // // Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IControlStackHistory.java // public interface IControlStackHistory { // boolean shouldBeAddedToStack(); // } // // Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IFragmentsManager.java // public interface IFragmentsManager { // // enum FragmentOpenType {REPLACE, OVERLAY} // // enum FragmentAnimationType {DEFAULT, BOTTOM_TOP} // // // void showFragment(int id, Fragment fragment, String tag, FragmentOpenType openType, FragmentAnimationType animationType); // // void showFragment(int id, Fragment fragment, String tag); // // void hideFragment(Fragment fragment); // // void showDialogFragment(DialogFragment dialogFragment); // // boolean hasFragment(String tag); // // String getLatestFragmentTag(); // } // // Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IOperationFinishCallback.java // public interface IOperationFinishCallback { // // void operationFinished(); // } // // Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IOverlayable.java // public interface IOverlayable { // void toggleOverlay(); // boolean isOverlayShown(); // void setOverlayAlpha(int alphaPercent); // } // // Path: app/src/main/java/com/chickenkiller/upods2/utils/enums/ContextMenuType.java // public enum ContextMenuType { // // CARD_DEFAULT, EPISODE_MIDDLE_SCREEN, PODCAST_MIDDLE_SCREEN, PLAYER_SETTINGS, PROFILE // } // Path: app/src/main/java/com/chickenkiller/upods2/activity/BasicActivity.java import android.app.Activity; import android.app.DialogFragment; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.pm.PackageManager; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.chickenkiller.upods2.R; import com.chickenkiller.upods2.interfaces.IContextMenuManager; import com.chickenkiller.upods2.interfaces.IControlStackHistory; import com.chickenkiller.upods2.interfaces.IFragmentsManager; import com.chickenkiller.upods2.interfaces.IOperationFinishCallback; import com.chickenkiller.upods2.interfaces.IOverlayable; import com.chickenkiller.upods2.utils.enums.ContextMenuType; import java.util.Calendar; package com.chickenkiller.upods2.activity; /** * Created by Alon Zilberman on 7/28/15. * Extend this activity to get basic logic for context menu and fragments working */ public class BasicActivity extends Activity implements IFragmentsManager, IContextMenuManager { private final static String DIALOG_TAG_START = "fr_dialog_"; //Permissions public static int WRITE_EXTERNAL_PERMISSIONS_CODE = 785;
protected IOperationFinishCallback onPermissionsGranted;
KKorvin/uPods-android
app/src/main/java/com/chickenkiller/upods2/activity/BasicActivity.java
// Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IContextMenuManager.java // public interface IContextMenuManager { // // /** // * @param view - which shows context menu // * @param type - type of context menu to show // * @param dataToPass - data which will be used for actions inside menu // */ // void openContextMenu(View view, ContextMenuType type, Object dataToPass, IOperationFinishCallback contextItemClicked); // } // // Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IControlStackHistory.java // public interface IControlStackHistory { // boolean shouldBeAddedToStack(); // } // // Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IFragmentsManager.java // public interface IFragmentsManager { // // enum FragmentOpenType {REPLACE, OVERLAY} // // enum FragmentAnimationType {DEFAULT, BOTTOM_TOP} // // // void showFragment(int id, Fragment fragment, String tag, FragmentOpenType openType, FragmentAnimationType animationType); // // void showFragment(int id, Fragment fragment, String tag); // // void hideFragment(Fragment fragment); // // void showDialogFragment(DialogFragment dialogFragment); // // boolean hasFragment(String tag); // // String getLatestFragmentTag(); // } // // Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IOperationFinishCallback.java // public interface IOperationFinishCallback { // // void operationFinished(); // } // // Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IOverlayable.java // public interface IOverlayable { // void toggleOverlay(); // boolean isOverlayShown(); // void setOverlayAlpha(int alphaPercent); // } // // Path: app/src/main/java/com/chickenkiller/upods2/utils/enums/ContextMenuType.java // public enum ContextMenuType { // // CARD_DEFAULT, EPISODE_MIDDLE_SCREEN, PODCAST_MIDDLE_SCREEN, PLAYER_SETTINGS, PROFILE // }
import android.app.Activity; import android.app.DialogFragment; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.pm.PackageManager; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.chickenkiller.upods2.R; import com.chickenkiller.upods2.interfaces.IContextMenuManager; import com.chickenkiller.upods2.interfaces.IControlStackHistory; import com.chickenkiller.upods2.interfaces.IFragmentsManager; import com.chickenkiller.upods2.interfaces.IOperationFinishCallback; import com.chickenkiller.upods2.interfaces.IOverlayable; import com.chickenkiller.upods2.utils.enums.ContextMenuType; import java.util.Calendar;
package com.chickenkiller.upods2.activity; /** * Created by Alon Zilberman on 7/28/15. * Extend this activity to get basic logic for context menu and fragments working */ public class BasicActivity extends Activity implements IFragmentsManager, IContextMenuManager { private final static String DIALOG_TAG_START = "fr_dialog_"; //Permissions public static int WRITE_EXTERNAL_PERMISSIONS_CODE = 785; protected IOperationFinishCallback onPermissionsGranted; //For context menus protected Object currentContextMenuData;
// Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IContextMenuManager.java // public interface IContextMenuManager { // // /** // * @param view - which shows context menu // * @param type - type of context menu to show // * @param dataToPass - data which will be used for actions inside menu // */ // void openContextMenu(View view, ContextMenuType type, Object dataToPass, IOperationFinishCallback contextItemClicked); // } // // Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IControlStackHistory.java // public interface IControlStackHistory { // boolean shouldBeAddedToStack(); // } // // Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IFragmentsManager.java // public interface IFragmentsManager { // // enum FragmentOpenType {REPLACE, OVERLAY} // // enum FragmentAnimationType {DEFAULT, BOTTOM_TOP} // // // void showFragment(int id, Fragment fragment, String tag, FragmentOpenType openType, FragmentAnimationType animationType); // // void showFragment(int id, Fragment fragment, String tag); // // void hideFragment(Fragment fragment); // // void showDialogFragment(DialogFragment dialogFragment); // // boolean hasFragment(String tag); // // String getLatestFragmentTag(); // } // // Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IOperationFinishCallback.java // public interface IOperationFinishCallback { // // void operationFinished(); // } // // Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IOverlayable.java // public interface IOverlayable { // void toggleOverlay(); // boolean isOverlayShown(); // void setOverlayAlpha(int alphaPercent); // } // // Path: app/src/main/java/com/chickenkiller/upods2/utils/enums/ContextMenuType.java // public enum ContextMenuType { // // CARD_DEFAULT, EPISODE_MIDDLE_SCREEN, PODCAST_MIDDLE_SCREEN, PLAYER_SETTINGS, PROFILE // } // Path: app/src/main/java/com/chickenkiller/upods2/activity/BasicActivity.java import android.app.Activity; import android.app.DialogFragment; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.pm.PackageManager; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.chickenkiller.upods2.R; import com.chickenkiller.upods2.interfaces.IContextMenuManager; import com.chickenkiller.upods2.interfaces.IControlStackHistory; import com.chickenkiller.upods2.interfaces.IFragmentsManager; import com.chickenkiller.upods2.interfaces.IOperationFinishCallback; import com.chickenkiller.upods2.interfaces.IOverlayable; import com.chickenkiller.upods2.utils.enums.ContextMenuType; import java.util.Calendar; package com.chickenkiller.upods2.activity; /** * Created by Alon Zilberman on 7/28/15. * Extend this activity to get basic logic for context menu and fragments working */ public class BasicActivity extends Activity implements IFragmentsManager, IContextMenuManager { private final static String DIALOG_TAG_START = "fr_dialog_"; //Permissions public static int WRITE_EXTERNAL_PERMISSIONS_CODE = 785; protected IOperationFinishCallback onPermissionsGranted; //For context menus protected Object currentContextMenuData;
protected ContextMenuType contextMenuType;
KKorvin/uPods-android
app/src/main/java/com/chickenkiller/upods2/activity/BasicActivity.java
// Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IContextMenuManager.java // public interface IContextMenuManager { // // /** // * @param view - which shows context menu // * @param type - type of context menu to show // * @param dataToPass - data which will be used for actions inside menu // */ // void openContextMenu(View view, ContextMenuType type, Object dataToPass, IOperationFinishCallback contextItemClicked); // } // // Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IControlStackHistory.java // public interface IControlStackHistory { // boolean shouldBeAddedToStack(); // } // // Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IFragmentsManager.java // public interface IFragmentsManager { // // enum FragmentOpenType {REPLACE, OVERLAY} // // enum FragmentAnimationType {DEFAULT, BOTTOM_TOP} // // // void showFragment(int id, Fragment fragment, String tag, FragmentOpenType openType, FragmentAnimationType animationType); // // void showFragment(int id, Fragment fragment, String tag); // // void hideFragment(Fragment fragment); // // void showDialogFragment(DialogFragment dialogFragment); // // boolean hasFragment(String tag); // // String getLatestFragmentTag(); // } // // Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IOperationFinishCallback.java // public interface IOperationFinishCallback { // // void operationFinished(); // } // // Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IOverlayable.java // public interface IOverlayable { // void toggleOverlay(); // boolean isOverlayShown(); // void setOverlayAlpha(int alphaPercent); // } // // Path: app/src/main/java/com/chickenkiller/upods2/utils/enums/ContextMenuType.java // public enum ContextMenuType { // // CARD_DEFAULT, EPISODE_MIDDLE_SCREEN, PODCAST_MIDDLE_SCREEN, PLAYER_SETTINGS, PROFILE // }
import android.app.Activity; import android.app.DialogFragment; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.pm.PackageManager; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.chickenkiller.upods2.R; import com.chickenkiller.upods2.interfaces.IContextMenuManager; import com.chickenkiller.upods2.interfaces.IControlStackHistory; import com.chickenkiller.upods2.interfaces.IFragmentsManager; import com.chickenkiller.upods2.interfaces.IOperationFinishCallback; import com.chickenkiller.upods2.interfaces.IOverlayable; import com.chickenkiller.upods2.utils.enums.ContextMenuType; import java.util.Calendar;
package com.chickenkiller.upods2.activity; /** * Created by Alon Zilberman on 7/28/15. * Extend this activity to get basic logic for context menu and fragments working */ public class BasicActivity extends Activity implements IFragmentsManager, IContextMenuManager { private final static String DIALOG_TAG_START = "fr_dialog_"; //Permissions public static int WRITE_EXTERNAL_PERMISSIONS_CODE = 785; protected IOperationFinishCallback onPermissionsGranted; //For context menus protected Object currentContextMenuData; protected ContextMenuType contextMenuType; protected IOperationFinishCallback onContextItemSelected; private boolean isContextItemSelected = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void showFragment(int id, Fragment fragment, String tag, IFragmentsManager.FragmentOpenType openType, IFragmentsManager.FragmentAnimationType animationType) { android.app.FragmentManager fm = getFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); if (animationType == IFragmentsManager.FragmentAnimationType.BOTTOM_TOP) { ft.setCustomAnimations(R.animator.animation_fragment_bototm_top, R.animator.animation_fragment_top_bototm, R.animator.animation_fragment_bototm_top, R.animator.animation_fragment_top_bototm); } if (openType == IFragmentsManager.FragmentOpenType.OVERLAY) { ft.add(id, fragment, tag);
// Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IContextMenuManager.java // public interface IContextMenuManager { // // /** // * @param view - which shows context menu // * @param type - type of context menu to show // * @param dataToPass - data which will be used for actions inside menu // */ // void openContextMenu(View view, ContextMenuType type, Object dataToPass, IOperationFinishCallback contextItemClicked); // } // // Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IControlStackHistory.java // public interface IControlStackHistory { // boolean shouldBeAddedToStack(); // } // // Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IFragmentsManager.java // public interface IFragmentsManager { // // enum FragmentOpenType {REPLACE, OVERLAY} // // enum FragmentAnimationType {DEFAULT, BOTTOM_TOP} // // // void showFragment(int id, Fragment fragment, String tag, FragmentOpenType openType, FragmentAnimationType animationType); // // void showFragment(int id, Fragment fragment, String tag); // // void hideFragment(Fragment fragment); // // void showDialogFragment(DialogFragment dialogFragment); // // boolean hasFragment(String tag); // // String getLatestFragmentTag(); // } // // Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IOperationFinishCallback.java // public interface IOperationFinishCallback { // // void operationFinished(); // } // // Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IOverlayable.java // public interface IOverlayable { // void toggleOverlay(); // boolean isOverlayShown(); // void setOverlayAlpha(int alphaPercent); // } // // Path: app/src/main/java/com/chickenkiller/upods2/utils/enums/ContextMenuType.java // public enum ContextMenuType { // // CARD_DEFAULT, EPISODE_MIDDLE_SCREEN, PODCAST_MIDDLE_SCREEN, PLAYER_SETTINGS, PROFILE // } // Path: app/src/main/java/com/chickenkiller/upods2/activity/BasicActivity.java import android.app.Activity; import android.app.DialogFragment; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.pm.PackageManager; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.chickenkiller.upods2.R; import com.chickenkiller.upods2.interfaces.IContextMenuManager; import com.chickenkiller.upods2.interfaces.IControlStackHistory; import com.chickenkiller.upods2.interfaces.IFragmentsManager; import com.chickenkiller.upods2.interfaces.IOperationFinishCallback; import com.chickenkiller.upods2.interfaces.IOverlayable; import com.chickenkiller.upods2.utils.enums.ContextMenuType; import java.util.Calendar; package com.chickenkiller.upods2.activity; /** * Created by Alon Zilberman on 7/28/15. * Extend this activity to get basic logic for context menu and fragments working */ public class BasicActivity extends Activity implements IFragmentsManager, IContextMenuManager { private final static String DIALOG_TAG_START = "fr_dialog_"; //Permissions public static int WRITE_EXTERNAL_PERMISSIONS_CODE = 785; protected IOperationFinishCallback onPermissionsGranted; //For context menus protected Object currentContextMenuData; protected ContextMenuType contextMenuType; protected IOperationFinishCallback onContextItemSelected; private boolean isContextItemSelected = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void showFragment(int id, Fragment fragment, String tag, IFragmentsManager.FragmentOpenType openType, IFragmentsManager.FragmentAnimationType animationType) { android.app.FragmentManager fm = getFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); if (animationType == IFragmentsManager.FragmentAnimationType.BOTTOM_TOP) { ft.setCustomAnimations(R.animator.animation_fragment_bototm_top, R.animator.animation_fragment_top_bototm, R.animator.animation_fragment_bototm_top, R.animator.animation_fragment_top_bototm); } if (openType == IFragmentsManager.FragmentOpenType.OVERLAY) { ft.add(id, fragment, tag);
if (this instanceof IOverlayable) {
KKorvin/uPods-android
app/src/main/java/com/chickenkiller/upods2/activity/BasicActivity.java
// Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IContextMenuManager.java // public interface IContextMenuManager { // // /** // * @param view - which shows context menu // * @param type - type of context menu to show // * @param dataToPass - data which will be used for actions inside menu // */ // void openContextMenu(View view, ContextMenuType type, Object dataToPass, IOperationFinishCallback contextItemClicked); // } // // Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IControlStackHistory.java // public interface IControlStackHistory { // boolean shouldBeAddedToStack(); // } // // Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IFragmentsManager.java // public interface IFragmentsManager { // // enum FragmentOpenType {REPLACE, OVERLAY} // // enum FragmentAnimationType {DEFAULT, BOTTOM_TOP} // // // void showFragment(int id, Fragment fragment, String tag, FragmentOpenType openType, FragmentAnimationType animationType); // // void showFragment(int id, Fragment fragment, String tag); // // void hideFragment(Fragment fragment); // // void showDialogFragment(DialogFragment dialogFragment); // // boolean hasFragment(String tag); // // String getLatestFragmentTag(); // } // // Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IOperationFinishCallback.java // public interface IOperationFinishCallback { // // void operationFinished(); // } // // Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IOverlayable.java // public interface IOverlayable { // void toggleOverlay(); // boolean isOverlayShown(); // void setOverlayAlpha(int alphaPercent); // } // // Path: app/src/main/java/com/chickenkiller/upods2/utils/enums/ContextMenuType.java // public enum ContextMenuType { // // CARD_DEFAULT, EPISODE_MIDDLE_SCREEN, PODCAST_MIDDLE_SCREEN, PLAYER_SETTINGS, PROFILE // }
import android.app.Activity; import android.app.DialogFragment; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.pm.PackageManager; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.chickenkiller.upods2.R; import com.chickenkiller.upods2.interfaces.IContextMenuManager; import com.chickenkiller.upods2.interfaces.IControlStackHistory; import com.chickenkiller.upods2.interfaces.IFragmentsManager; import com.chickenkiller.upods2.interfaces.IOperationFinishCallback; import com.chickenkiller.upods2.interfaces.IOverlayable; import com.chickenkiller.upods2.utils.enums.ContextMenuType; import java.util.Calendar;
package com.chickenkiller.upods2.activity; /** * Created by Alon Zilberman on 7/28/15. * Extend this activity to get basic logic for context menu and fragments working */ public class BasicActivity extends Activity implements IFragmentsManager, IContextMenuManager { private final static String DIALOG_TAG_START = "fr_dialog_"; //Permissions public static int WRITE_EXTERNAL_PERMISSIONS_CODE = 785; protected IOperationFinishCallback onPermissionsGranted; //For context menus protected Object currentContextMenuData; protected ContextMenuType contextMenuType; protected IOperationFinishCallback onContextItemSelected; private boolean isContextItemSelected = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void showFragment(int id, Fragment fragment, String tag, IFragmentsManager.FragmentOpenType openType, IFragmentsManager.FragmentAnimationType animationType) { android.app.FragmentManager fm = getFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); if (animationType == IFragmentsManager.FragmentAnimationType.BOTTOM_TOP) { ft.setCustomAnimations(R.animator.animation_fragment_bototm_top, R.animator.animation_fragment_top_bototm, R.animator.animation_fragment_bototm_top, R.animator.animation_fragment_top_bototm); } if (openType == IFragmentsManager.FragmentOpenType.OVERLAY) { ft.add(id, fragment, tag); if (this instanceof IOverlayable) { ((IOverlayable) this).toggleOverlay(); } } else { ft.replace(id, fragment, tag); } ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
// Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IContextMenuManager.java // public interface IContextMenuManager { // // /** // * @param view - which shows context menu // * @param type - type of context menu to show // * @param dataToPass - data which will be used for actions inside menu // */ // void openContextMenu(View view, ContextMenuType type, Object dataToPass, IOperationFinishCallback contextItemClicked); // } // // Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IControlStackHistory.java // public interface IControlStackHistory { // boolean shouldBeAddedToStack(); // } // // Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IFragmentsManager.java // public interface IFragmentsManager { // // enum FragmentOpenType {REPLACE, OVERLAY} // // enum FragmentAnimationType {DEFAULT, BOTTOM_TOP} // // // void showFragment(int id, Fragment fragment, String tag, FragmentOpenType openType, FragmentAnimationType animationType); // // void showFragment(int id, Fragment fragment, String tag); // // void hideFragment(Fragment fragment); // // void showDialogFragment(DialogFragment dialogFragment); // // boolean hasFragment(String tag); // // String getLatestFragmentTag(); // } // // Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IOperationFinishCallback.java // public interface IOperationFinishCallback { // // void operationFinished(); // } // // Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IOverlayable.java // public interface IOverlayable { // void toggleOverlay(); // boolean isOverlayShown(); // void setOverlayAlpha(int alphaPercent); // } // // Path: app/src/main/java/com/chickenkiller/upods2/utils/enums/ContextMenuType.java // public enum ContextMenuType { // // CARD_DEFAULT, EPISODE_MIDDLE_SCREEN, PODCAST_MIDDLE_SCREEN, PLAYER_SETTINGS, PROFILE // } // Path: app/src/main/java/com/chickenkiller/upods2/activity/BasicActivity.java import android.app.Activity; import android.app.DialogFragment; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.pm.PackageManager; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.chickenkiller.upods2.R; import com.chickenkiller.upods2.interfaces.IContextMenuManager; import com.chickenkiller.upods2.interfaces.IControlStackHistory; import com.chickenkiller.upods2.interfaces.IFragmentsManager; import com.chickenkiller.upods2.interfaces.IOperationFinishCallback; import com.chickenkiller.upods2.interfaces.IOverlayable; import com.chickenkiller.upods2.utils.enums.ContextMenuType; import java.util.Calendar; package com.chickenkiller.upods2.activity; /** * Created by Alon Zilberman on 7/28/15. * Extend this activity to get basic logic for context menu and fragments working */ public class BasicActivity extends Activity implements IFragmentsManager, IContextMenuManager { private final static String DIALOG_TAG_START = "fr_dialog_"; //Permissions public static int WRITE_EXTERNAL_PERMISSIONS_CODE = 785; protected IOperationFinishCallback onPermissionsGranted; //For context menus protected Object currentContextMenuData; protected ContextMenuType contextMenuType; protected IOperationFinishCallback onContextItemSelected; private boolean isContextItemSelected = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void showFragment(int id, Fragment fragment, String tag, IFragmentsManager.FragmentOpenType openType, IFragmentsManager.FragmentAnimationType animationType) { android.app.FragmentManager fm = getFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); if (animationType == IFragmentsManager.FragmentAnimationType.BOTTOM_TOP) { ft.setCustomAnimations(R.animator.animation_fragment_bototm_top, R.animator.animation_fragment_top_bototm, R.animator.animation_fragment_bototm_top, R.animator.animation_fragment_top_bototm); } if (openType == IFragmentsManager.FragmentOpenType.OVERLAY) { ft.add(id, fragment, tag); if (this instanceof IOverlayable) { ((IOverlayable) this).toggleOverlay(); } } else { ft.replace(id, fragment, tag); } ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
if (fragment instanceof IControlStackHistory) {//Decide ether fragment should be added to stack history
KKorvin/uPods-android
app/src/main/java/com/chickenkiller/upods2/models/UserProfile.java
// Path: app/src/main/java/com/chickenkiller/upods2/controllers/app/UpodsApplication.java // public class UpodsApplication extends Application { // // private static final int CHECK_NEW_EPISODS_INTENT_CODE = 2302; // // private static final String TAG = "UpodsApplication"; // private static Context applicationContext; // private static SQLdatabaseManager databaseManager; // private static boolean isLoaded; // // @Override // public void onCreate() { // isLoaded = false; // applicationContext = getApplicationContext(); // YandexMetrica.activate(getApplicationContext(), Config.YANDEX_METRICS_API_KEY); // YandexMetrica.enableActivityAutoTracking(this); // FacebookSdk.sdkInitialize(applicationContext); // LoginMaster.getInstance().init(); // new Prefs.Builder() // .setContext(this) // .setMode(ContextWrapper.MODE_PRIVATE) // .setPrefsName(getPackageName()) // .setUseDefaultSharedPreference(true).build(); // // super.onCreate(); // } // // /** // * All resources which can be loaded not in onCreate(), should be load here, // * this function called while splash screen is active // */ // public static void initAllResources() { // if (!isLoaded) { // databaseManager = new SQLdatabaseManager(applicationContext); // SettingsManager.getInstace().init(); // Category.initPodcastsCatrgories(); // SimpleCacheManager.getInstance().removeExpiredCache(); // runMainService(); // setAlarmManagerTasks(); // isLoaded = true; // } // } // // private static void runMainService() { // applicationContext.startService(new Intent(applicationContext, MainService.class)); // } // // public static void setAlarmManagerTasks() { // setAlarmManagerTasks(applicationContext); // } // // public static void setAlarmManagerTasks(Context context) { // try { // if (ProfileManager.getInstance().getSubscribedPodcasts().size() == 0) { // return; // } // AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // Intent intent = new Intent(context, NetworkTasksService.class); // intent.setAction(NetworkTasksService.ACTION_CHECK_FOR_NEW_EPISODS); // PendingIntent alarmIntent = PendingIntent.getService(context, CHECK_NEW_EPISODS_INTENT_CODE, intent, // PendingIntent.FLAG_UPDATE_CURRENT); // // if (SettingsManager.getInstace().getBooleanSettingsValue(SettingsManager.JS_NOTIFY_EPISODES)) { // long interval = SettingsManager.getInstace().getIntSettingsValue(SettingsManager.JS_PODCASTS_UPDATE_TIME); // //interval = TimeUnit.MINUTES.toMillis(60); // alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, // SystemClock.elapsedRealtime(), // interval, alarmIntent); // Logger.printInfo(TAG, "Alarm managers - Episods check for updates task added"); // } else { // alarmIntent.cancel(); // alarmMgr.cancel(alarmIntent); // Logger.printInfo(TAG, "Alarm managers - Episods check for updates task canceled"); // } // } catch (Exception e) { // Logger.printInfo(TAG, "Alarm managers - can't set alarm manager"); // e.printStackTrace(); // } // } // // @Override // public void onTerminate() { // super.onTerminate(); // } // // public static Context getContext() { // return applicationContext; // } // // public static SQLdatabaseManager getDatabaseManager() { // return databaseManager; // } // }
import com.chickenkiller.upods2.R; import com.chickenkiller.upods2.controllers.app.UpodsApplication;
package com.chickenkiller.upods2.models; /** * Created by Alon Zilberman on 12/11/15. */ public class UserProfile { public static String EMPTY_AVATAR = "https://cdn2.iconfinder.com/data/icons/social-flat-buttons-3/512/anonymous-512.png"; private String name; private String email; private String profileImageUrl; public UserProfile() {
// Path: app/src/main/java/com/chickenkiller/upods2/controllers/app/UpodsApplication.java // public class UpodsApplication extends Application { // // private static final int CHECK_NEW_EPISODS_INTENT_CODE = 2302; // // private static final String TAG = "UpodsApplication"; // private static Context applicationContext; // private static SQLdatabaseManager databaseManager; // private static boolean isLoaded; // // @Override // public void onCreate() { // isLoaded = false; // applicationContext = getApplicationContext(); // YandexMetrica.activate(getApplicationContext(), Config.YANDEX_METRICS_API_KEY); // YandexMetrica.enableActivityAutoTracking(this); // FacebookSdk.sdkInitialize(applicationContext); // LoginMaster.getInstance().init(); // new Prefs.Builder() // .setContext(this) // .setMode(ContextWrapper.MODE_PRIVATE) // .setPrefsName(getPackageName()) // .setUseDefaultSharedPreference(true).build(); // // super.onCreate(); // } // // /** // * All resources which can be loaded not in onCreate(), should be load here, // * this function called while splash screen is active // */ // public static void initAllResources() { // if (!isLoaded) { // databaseManager = new SQLdatabaseManager(applicationContext); // SettingsManager.getInstace().init(); // Category.initPodcastsCatrgories(); // SimpleCacheManager.getInstance().removeExpiredCache(); // runMainService(); // setAlarmManagerTasks(); // isLoaded = true; // } // } // // private static void runMainService() { // applicationContext.startService(new Intent(applicationContext, MainService.class)); // } // // public static void setAlarmManagerTasks() { // setAlarmManagerTasks(applicationContext); // } // // public static void setAlarmManagerTasks(Context context) { // try { // if (ProfileManager.getInstance().getSubscribedPodcasts().size() == 0) { // return; // } // AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // Intent intent = new Intent(context, NetworkTasksService.class); // intent.setAction(NetworkTasksService.ACTION_CHECK_FOR_NEW_EPISODS); // PendingIntent alarmIntent = PendingIntent.getService(context, CHECK_NEW_EPISODS_INTENT_CODE, intent, // PendingIntent.FLAG_UPDATE_CURRENT); // // if (SettingsManager.getInstace().getBooleanSettingsValue(SettingsManager.JS_NOTIFY_EPISODES)) { // long interval = SettingsManager.getInstace().getIntSettingsValue(SettingsManager.JS_PODCASTS_UPDATE_TIME); // //interval = TimeUnit.MINUTES.toMillis(60); // alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, // SystemClock.elapsedRealtime(), // interval, alarmIntent); // Logger.printInfo(TAG, "Alarm managers - Episods check for updates task added"); // } else { // alarmIntent.cancel(); // alarmMgr.cancel(alarmIntent); // Logger.printInfo(TAG, "Alarm managers - Episods check for updates task canceled"); // } // } catch (Exception e) { // Logger.printInfo(TAG, "Alarm managers - can't set alarm manager"); // e.printStackTrace(); // } // } // // @Override // public void onTerminate() { // super.onTerminate(); // } // // public static Context getContext() { // return applicationContext; // } // // public static SQLdatabaseManager getDatabaseManager() { // return databaseManager; // } // } // Path: app/src/main/java/com/chickenkiller/upods2/models/UserProfile.java import com.chickenkiller.upods2.R; import com.chickenkiller.upods2.controllers.app.UpodsApplication; package com.chickenkiller.upods2.models; /** * Created by Alon Zilberman on 12/11/15. */ public class UserProfile { public static String EMPTY_AVATAR = "https://cdn2.iconfinder.com/data/icons/social-flat-buttons-3/512/anonymous-512.png"; private String name; private String email; private String profileImageUrl; public UserProfile() {
this.name = UpodsApplication.getContext().getString(R.string.anonymus);
KKorvin/uPods-android
app/src/main/java/com/chickenkiller/upods2/controllers/adaperts/HelpPagesAdapter.java
// Path: app/src/main/java/com/chickenkiller/upods2/fragments/FragmentHelpItem.java // public class FragmentHelpItem extends Fragment { // // public static final String TAG; // // static { // long time = Calendar.getInstance().get(Calendar.MILLISECOND); // TAG = "f_help_item" + String.valueOf(time); // } // // private ImageView imgHelpTip; // private TextView tvHelpTitle; // private TextView tvHelpText; // private Button btnCloseHelp; // private View.OnClickListener closeClickListener; // // private int index; // // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = inflater.inflate(R.layout.fragment_help_item, container, false); // imgHelpTip = (ImageView) view.findViewById(R.id.imgHelpTip); // tvHelpTitle = (TextView) view.findViewById(R.id.tvHelpTitle); // tvHelpText = (TextView) view.findViewById(R.id.tvHelpText); // btnCloseHelp = (Button) view.findViewById(R.id.btnCloseHelp); // if (closeClickListener != null) { // btnCloseHelp.setVisibility(View.VISIBLE); // btnCloseHelp.setOnClickListener(closeClickListener); // } else { // btnCloseHelp.setVisibility(View.GONE); // } // return view; // } // // @Override // public void onViewCreated(View view, Bundle savedInstanceState) { // super.onViewCreated(view, savedInstanceState); // setCurrentTipImage(); // } // // // private void setCurrentTipImage() { // switch (index) { // case 0: { // imgHelpTip.setImageResource(R.drawable.help_itunes); // tvHelpTitle.setText(getString(R.string.enjoy_free_music)); // tvHelpText.setText(getString(R.string.help_free_music)); // break; // } // case 1: // imgHelpTip.setImageResource(R.drawable.help_tops); // tvHelpTitle.setText(getString(R.string.handmade_tops)); // tvHelpText.setText(getString(R.string.help_handmade_tops)); // break; // case 2: // imgHelpTip.setImageResource(R.drawable.help_ads); // tvHelpTitle.setText(getString(R.string.zero_ads)); // tvHelpText.setText(getString(R.string.help_zero_ads)); // break; // case 3: // imgHelpTip.setImageResource(R.drawable.help_cloud); // tvHelpTitle.setText(getString(R.string.help_cloud_sync_title)); // tvHelpText.setText(getString(R.string.help_cloud_sync)); // break; // } // } // // public void setIndex(int index) { // this.index = index; // } // // public void setCloseClickListener(View.OnClickListener closeClickListener) { // this.closeClickListener = closeClickListener; // } // } // // Path: app/src/main/java/com/chickenkiller/upods2/utils/Logger.java // public class Logger { // // private static boolean isTurnedOn = false; // // public static void printInfo(String tag, String text) { // if (isTurnedOn) { // Log.i(tag, text); // } // } // // public static void printInfo(String tag, int text) { // if (isTurnedOn) { // Log.i(tag, String.valueOf(text)); // } // } // // public static void printInfo(String tag, boolean text) { // if (isTurnedOn) { // Log.i(tag, String.valueOf(text)); // } // } // // // public static void printError(String tag, String text) { // if (isTurnedOn) { // Log.i(tag, text); // } // } // }
import android.app.Fragment; import android.app.FragmentManager; import android.support.v13.app.FragmentStatePagerAdapter; import android.view.View; import com.chickenkiller.upods2.fragments.FragmentHelpItem; import com.chickenkiller.upods2.utils.Logger;
package com.chickenkiller.upods2.controllers.adaperts; /** * Created by Alon Zilberman on 8/14/15. * Use it for simple help viewpager */ public class HelpPagesAdapter extends FragmentStatePagerAdapter { private final int HELP_PAGES_COUNT = 4; private View.OnClickListener closeClickListener; public HelpPagesAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) {
// Path: app/src/main/java/com/chickenkiller/upods2/fragments/FragmentHelpItem.java // public class FragmentHelpItem extends Fragment { // // public static final String TAG; // // static { // long time = Calendar.getInstance().get(Calendar.MILLISECOND); // TAG = "f_help_item" + String.valueOf(time); // } // // private ImageView imgHelpTip; // private TextView tvHelpTitle; // private TextView tvHelpText; // private Button btnCloseHelp; // private View.OnClickListener closeClickListener; // // private int index; // // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = inflater.inflate(R.layout.fragment_help_item, container, false); // imgHelpTip = (ImageView) view.findViewById(R.id.imgHelpTip); // tvHelpTitle = (TextView) view.findViewById(R.id.tvHelpTitle); // tvHelpText = (TextView) view.findViewById(R.id.tvHelpText); // btnCloseHelp = (Button) view.findViewById(R.id.btnCloseHelp); // if (closeClickListener != null) { // btnCloseHelp.setVisibility(View.VISIBLE); // btnCloseHelp.setOnClickListener(closeClickListener); // } else { // btnCloseHelp.setVisibility(View.GONE); // } // return view; // } // // @Override // public void onViewCreated(View view, Bundle savedInstanceState) { // super.onViewCreated(view, savedInstanceState); // setCurrentTipImage(); // } // // // private void setCurrentTipImage() { // switch (index) { // case 0: { // imgHelpTip.setImageResource(R.drawable.help_itunes); // tvHelpTitle.setText(getString(R.string.enjoy_free_music)); // tvHelpText.setText(getString(R.string.help_free_music)); // break; // } // case 1: // imgHelpTip.setImageResource(R.drawable.help_tops); // tvHelpTitle.setText(getString(R.string.handmade_tops)); // tvHelpText.setText(getString(R.string.help_handmade_tops)); // break; // case 2: // imgHelpTip.setImageResource(R.drawable.help_ads); // tvHelpTitle.setText(getString(R.string.zero_ads)); // tvHelpText.setText(getString(R.string.help_zero_ads)); // break; // case 3: // imgHelpTip.setImageResource(R.drawable.help_cloud); // tvHelpTitle.setText(getString(R.string.help_cloud_sync_title)); // tvHelpText.setText(getString(R.string.help_cloud_sync)); // break; // } // } // // public void setIndex(int index) { // this.index = index; // } // // public void setCloseClickListener(View.OnClickListener closeClickListener) { // this.closeClickListener = closeClickListener; // } // } // // Path: app/src/main/java/com/chickenkiller/upods2/utils/Logger.java // public class Logger { // // private static boolean isTurnedOn = false; // // public static void printInfo(String tag, String text) { // if (isTurnedOn) { // Log.i(tag, text); // } // } // // public static void printInfo(String tag, int text) { // if (isTurnedOn) { // Log.i(tag, String.valueOf(text)); // } // } // // public static void printInfo(String tag, boolean text) { // if (isTurnedOn) { // Log.i(tag, String.valueOf(text)); // } // } // // // public static void printError(String tag, String text) { // if (isTurnedOn) { // Log.i(tag, text); // } // } // } // Path: app/src/main/java/com/chickenkiller/upods2/controllers/adaperts/HelpPagesAdapter.java import android.app.Fragment; import android.app.FragmentManager; import android.support.v13.app.FragmentStatePagerAdapter; import android.view.View; import com.chickenkiller.upods2.fragments.FragmentHelpItem; import com.chickenkiller.upods2.utils.Logger; package com.chickenkiller.upods2.controllers.adaperts; /** * Created by Alon Zilberman on 8/14/15. * Use it for simple help viewpager */ public class HelpPagesAdapter extends FragmentStatePagerAdapter { private final int HELP_PAGES_COUNT = 4; private View.OnClickListener closeClickListener; public HelpPagesAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) {
Fragment currentFragment = new FragmentHelpItem();
KKorvin/uPods-android
app/src/main/java/com/chickenkiller/upods2/utils/GlobalUtils.java
// Path: app/src/main/java/com/chickenkiller/upods2/controllers/app/UpodsApplication.java // public class UpodsApplication extends Application { // // private static final int CHECK_NEW_EPISODS_INTENT_CODE = 2302; // // private static final String TAG = "UpodsApplication"; // private static Context applicationContext; // private static SQLdatabaseManager databaseManager; // private static boolean isLoaded; // // @Override // public void onCreate() { // isLoaded = false; // applicationContext = getApplicationContext(); // YandexMetrica.activate(getApplicationContext(), Config.YANDEX_METRICS_API_KEY); // YandexMetrica.enableActivityAutoTracking(this); // FacebookSdk.sdkInitialize(applicationContext); // LoginMaster.getInstance().init(); // new Prefs.Builder() // .setContext(this) // .setMode(ContextWrapper.MODE_PRIVATE) // .setPrefsName(getPackageName()) // .setUseDefaultSharedPreference(true).build(); // // super.onCreate(); // } // // /** // * All resources which can be loaded not in onCreate(), should be load here, // * this function called while splash screen is active // */ // public static void initAllResources() { // if (!isLoaded) { // databaseManager = new SQLdatabaseManager(applicationContext); // SettingsManager.getInstace().init(); // Category.initPodcastsCatrgories(); // SimpleCacheManager.getInstance().removeExpiredCache(); // runMainService(); // setAlarmManagerTasks(); // isLoaded = true; // } // } // // private static void runMainService() { // applicationContext.startService(new Intent(applicationContext, MainService.class)); // } // // public static void setAlarmManagerTasks() { // setAlarmManagerTasks(applicationContext); // } // // public static void setAlarmManagerTasks(Context context) { // try { // if (ProfileManager.getInstance().getSubscribedPodcasts().size() == 0) { // return; // } // AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // Intent intent = new Intent(context, NetworkTasksService.class); // intent.setAction(NetworkTasksService.ACTION_CHECK_FOR_NEW_EPISODS); // PendingIntent alarmIntent = PendingIntent.getService(context, CHECK_NEW_EPISODS_INTENT_CODE, intent, // PendingIntent.FLAG_UPDATE_CURRENT); // // if (SettingsManager.getInstace().getBooleanSettingsValue(SettingsManager.JS_NOTIFY_EPISODES)) { // long interval = SettingsManager.getInstace().getIntSettingsValue(SettingsManager.JS_PODCASTS_UPDATE_TIME); // //interval = TimeUnit.MINUTES.toMillis(60); // alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, // SystemClock.elapsedRealtime(), // interval, alarmIntent); // Logger.printInfo(TAG, "Alarm managers - Episods check for updates task added"); // } else { // alarmIntent.cancel(); // alarmMgr.cancel(alarmIntent); // Logger.printInfo(TAG, "Alarm managers - Episods check for updates task canceled"); // } // } catch (Exception e) { // Logger.printInfo(TAG, "Alarm managers - can't set alarm manager"); // e.printStackTrace(); // } // } // // @Override // public void onTerminate() { // super.onTerminate(); // } // // public static Context getContext() { // return applicationContext; // } // // public static SQLdatabaseManager getDatabaseManager() { // return databaseManager; // } // }
import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.net.ConnectivityManager; import android.net.Uri; import com.chickenkiller.upods2.controllers.app.UpodsApplication; import java.io.File; import java.net.HttpURLConnection; import java.net.URL; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern;
date = dateFormat.format(inputDate); } catch (ParseException e) { e.printStackTrace(); } return date; } public static String getCleanFileName(String str) { str = str.toLowerCase(); return str.replaceAll("[^a-zA-Z0-9]+", "_"); } public static boolean deleteDirectory(File path) { if (path.exists()) { File[] files = path.listFiles(); if (files == null) { return true; } for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { deleteDirectory(files[i]); } else { files[i].delete(); } } } return (path.delete()); } public static boolean isInternetConnected() {
// Path: app/src/main/java/com/chickenkiller/upods2/controllers/app/UpodsApplication.java // public class UpodsApplication extends Application { // // private static final int CHECK_NEW_EPISODS_INTENT_CODE = 2302; // // private static final String TAG = "UpodsApplication"; // private static Context applicationContext; // private static SQLdatabaseManager databaseManager; // private static boolean isLoaded; // // @Override // public void onCreate() { // isLoaded = false; // applicationContext = getApplicationContext(); // YandexMetrica.activate(getApplicationContext(), Config.YANDEX_METRICS_API_KEY); // YandexMetrica.enableActivityAutoTracking(this); // FacebookSdk.sdkInitialize(applicationContext); // LoginMaster.getInstance().init(); // new Prefs.Builder() // .setContext(this) // .setMode(ContextWrapper.MODE_PRIVATE) // .setPrefsName(getPackageName()) // .setUseDefaultSharedPreference(true).build(); // // super.onCreate(); // } // // /** // * All resources which can be loaded not in onCreate(), should be load here, // * this function called while splash screen is active // */ // public static void initAllResources() { // if (!isLoaded) { // databaseManager = new SQLdatabaseManager(applicationContext); // SettingsManager.getInstace().init(); // Category.initPodcastsCatrgories(); // SimpleCacheManager.getInstance().removeExpiredCache(); // runMainService(); // setAlarmManagerTasks(); // isLoaded = true; // } // } // // private static void runMainService() { // applicationContext.startService(new Intent(applicationContext, MainService.class)); // } // // public static void setAlarmManagerTasks() { // setAlarmManagerTasks(applicationContext); // } // // public static void setAlarmManagerTasks(Context context) { // try { // if (ProfileManager.getInstance().getSubscribedPodcasts().size() == 0) { // return; // } // AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // Intent intent = new Intent(context, NetworkTasksService.class); // intent.setAction(NetworkTasksService.ACTION_CHECK_FOR_NEW_EPISODS); // PendingIntent alarmIntent = PendingIntent.getService(context, CHECK_NEW_EPISODS_INTENT_CODE, intent, // PendingIntent.FLAG_UPDATE_CURRENT); // // if (SettingsManager.getInstace().getBooleanSettingsValue(SettingsManager.JS_NOTIFY_EPISODES)) { // long interval = SettingsManager.getInstace().getIntSettingsValue(SettingsManager.JS_PODCASTS_UPDATE_TIME); // //interval = TimeUnit.MINUTES.toMillis(60); // alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, // SystemClock.elapsedRealtime(), // interval, alarmIntent); // Logger.printInfo(TAG, "Alarm managers - Episods check for updates task added"); // } else { // alarmIntent.cancel(); // alarmMgr.cancel(alarmIntent); // Logger.printInfo(TAG, "Alarm managers - Episods check for updates task canceled"); // } // } catch (Exception e) { // Logger.printInfo(TAG, "Alarm managers - can't set alarm manager"); // e.printStackTrace(); // } // } // // @Override // public void onTerminate() { // super.onTerminate(); // } // // public static Context getContext() { // return applicationContext; // } // // public static SQLdatabaseManager getDatabaseManager() { // return databaseManager; // } // } // Path: app/src/main/java/com/chickenkiller/upods2/utils/GlobalUtils.java import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.net.ConnectivityManager; import android.net.Uri; import com.chickenkiller.upods2.controllers.app.UpodsApplication; import java.io.File; import java.net.HttpURLConnection; import java.net.URL; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; date = dateFormat.format(inputDate); } catch (ParseException e) { e.printStackTrace(); } return date; } public static String getCleanFileName(String str) { str = str.toLowerCase(); return str.replaceAll("[^a-zA-Z0-9]+", "_"); } public static boolean deleteDirectory(File path) { if (path.exists()) { File[] files = path.listFiles(); if (files == null) { return true; } for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { deleteDirectory(files[i]); } else { files[i].delete(); } } } return (path.delete()); } public static boolean isInternetConnected() {
ConnectivityManager cm = (ConnectivityManager) UpodsApplication.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
KKorvin/uPods-android
app/src/main/java/com/chickenkiller/upods2/views/DetailsScrollView.java
// Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IMovable.java // public interface IMovable { // // void onMove(MotionEvent event, boolean applyMovement); // }
import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.widget.ScrollView; import com.chickenkiller.upods2.interfaces.IMovable;
package com.chickenkiller.upods2.views; /** * Created by Alon Zilberman on 7/21/15. */ public class DetailsScrollView extends ScrollView { private int isScrollable; //0 - unknown 1-yes 2-no private boolean enabled; private boolean isInTheTop; private boolean isScrollDown;
// Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IMovable.java // public interface IMovable { // // void onMove(MotionEvent event, boolean applyMovement); // } // Path: app/src/main/java/com/chickenkiller/upods2/views/DetailsScrollView.java import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.widget.ScrollView; import com.chickenkiller.upods2.interfaces.IMovable; package com.chickenkiller.upods2.views; /** * Created by Alon Zilberman on 7/21/15. */ public class DetailsScrollView extends ScrollView { private int isScrollable; //0 - unknown 1-yes 2-no private boolean enabled; private boolean isInTheTop; private boolean isScrollDown;
private IMovable iMovable;
KKorvin/uPods-android
app/src/main/java/com/chickenkiller/upods2/views/CircleIndicator.java
// Path: app/src/main/java/com/chickenkiller/upods2/utils/ui/ShapeHolder.java // public class ShapeHolder { // private float x = 0, y = 0;//Ô²µÄx¡¢y×ø±ê // private ShapeDrawable shape; // private int color; // private float alpha = 1f; // private Paint paint; // // public void setPaint(Paint value) { // paint = value; // } // // public Paint getPaint() { // return paint; // } // // public void setX(float value) { // x = value; // } // // public float getX() { // return x; // } // // public void setY(float value) { // y = value; // } // // public float getY() { // return y; // } // // public void setShape(ShapeDrawable value) { // shape = value; // } // // public ShapeDrawable getShape() { // return shape; // } // // public int getColor() { // return color; // } // // public void setColor(int value) { // shape.getPaint().setColor(value); // color = value; // // } // // public void setAlpha(float alpha) { // this.alpha = alpha; // shape.setAlpha((int) ((alpha * 255f) + .5f)); // } // // public float getWidth() { // return shape.getShape().getWidth(); // } // // public void setWidth(float width) { // Shape s = shape.getShape(); // s.resize(width, s.getHeight()); // } // // public float getHeight() { // return shape.getShape().getHeight(); // } // // public void setHeight(float height) { // Shape s = shape.getShape(); // s.resize(s.getWidth(), height); // } // // public void resizeShape(final float width, final float height) { // shape.getShape().resize(width, height); // } // // public ShapeHolder(ShapeDrawable s) { // shape = s; // } // }
import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.OvalShape; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.util.Log; import android.view.View; import com.chickenkiller.upods2.R; import com.chickenkiller.upods2.utils.ui.ShapeHolder; import java.util.ArrayList; import java.util.List;
package com.chickenkiller.upods2.views; /** * From https://github.com/THEONE10211024/CircleIndicator */ public class CircleIndicator extends View { private ViewPager viewPager;
// Path: app/src/main/java/com/chickenkiller/upods2/utils/ui/ShapeHolder.java // public class ShapeHolder { // private float x = 0, y = 0;//Ô²µÄx¡¢y×ø±ê // private ShapeDrawable shape; // private int color; // private float alpha = 1f; // private Paint paint; // // public void setPaint(Paint value) { // paint = value; // } // // public Paint getPaint() { // return paint; // } // // public void setX(float value) { // x = value; // } // // public float getX() { // return x; // } // // public void setY(float value) { // y = value; // } // // public float getY() { // return y; // } // // public void setShape(ShapeDrawable value) { // shape = value; // } // // public ShapeDrawable getShape() { // return shape; // } // // public int getColor() { // return color; // } // // public void setColor(int value) { // shape.getPaint().setColor(value); // color = value; // // } // // public void setAlpha(float alpha) { // this.alpha = alpha; // shape.setAlpha((int) ((alpha * 255f) + .5f)); // } // // public float getWidth() { // return shape.getShape().getWidth(); // } // // public void setWidth(float width) { // Shape s = shape.getShape(); // s.resize(width, s.getHeight()); // } // // public float getHeight() { // return shape.getShape().getHeight(); // } // // public void setHeight(float height) { // Shape s = shape.getShape(); // s.resize(s.getWidth(), height); // } // // public void resizeShape(final float width, final float height) { // shape.getShape().resize(width, height); // } // // public ShapeHolder(ShapeDrawable s) { // shape = s; // } // } // Path: app/src/main/java/com/chickenkiller/upods2/views/CircleIndicator.java import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.OvalShape; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.util.Log; import android.view.View; import com.chickenkiller.upods2.R; import com.chickenkiller.upods2.utils.ui.ShapeHolder; import java.util.ArrayList; import java.util.List; package com.chickenkiller.upods2.views; /** * From https://github.com/THEONE10211024/CircleIndicator */ public class CircleIndicator extends View { private ViewPager viewPager;
private List<ShapeHolder> tabItems;
KKorvin/uPods-android
app/src/main/java/com/chickenkiller/upods2/models/SlidingMenuHeader.java
// Path: app/src/main/java/com/chickenkiller/upods2/controllers/app/UpodsApplication.java // public class UpodsApplication extends Application { // // private static final int CHECK_NEW_EPISODS_INTENT_CODE = 2302; // // private static final String TAG = "UpodsApplication"; // private static Context applicationContext; // private static SQLdatabaseManager databaseManager; // private static boolean isLoaded; // // @Override // public void onCreate() { // isLoaded = false; // applicationContext = getApplicationContext(); // YandexMetrica.activate(getApplicationContext(), Config.YANDEX_METRICS_API_KEY); // YandexMetrica.enableActivityAutoTracking(this); // FacebookSdk.sdkInitialize(applicationContext); // LoginMaster.getInstance().init(); // new Prefs.Builder() // .setContext(this) // .setMode(ContextWrapper.MODE_PRIVATE) // .setPrefsName(getPackageName()) // .setUseDefaultSharedPreference(true).build(); // // super.onCreate(); // } // // /** // * All resources which can be loaded not in onCreate(), should be load here, // * this function called while splash screen is active // */ // public static void initAllResources() { // if (!isLoaded) { // databaseManager = new SQLdatabaseManager(applicationContext); // SettingsManager.getInstace().init(); // Category.initPodcastsCatrgories(); // SimpleCacheManager.getInstance().removeExpiredCache(); // runMainService(); // setAlarmManagerTasks(); // isLoaded = true; // } // } // // private static void runMainService() { // applicationContext.startService(new Intent(applicationContext, MainService.class)); // } // // public static void setAlarmManagerTasks() { // setAlarmManagerTasks(applicationContext); // } // // public static void setAlarmManagerTasks(Context context) { // try { // if (ProfileManager.getInstance().getSubscribedPodcasts().size() == 0) { // return; // } // AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // Intent intent = new Intent(context, NetworkTasksService.class); // intent.setAction(NetworkTasksService.ACTION_CHECK_FOR_NEW_EPISODS); // PendingIntent alarmIntent = PendingIntent.getService(context, CHECK_NEW_EPISODS_INTENT_CODE, intent, // PendingIntent.FLAG_UPDATE_CURRENT); // // if (SettingsManager.getInstace().getBooleanSettingsValue(SettingsManager.JS_NOTIFY_EPISODES)) { // long interval = SettingsManager.getInstace().getIntSettingsValue(SettingsManager.JS_PODCASTS_UPDATE_TIME); // //interval = TimeUnit.MINUTES.toMillis(60); // alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, // SystemClock.elapsedRealtime(), // interval, alarmIntent); // Logger.printInfo(TAG, "Alarm managers - Episods check for updates task added"); // } else { // alarmIntent.cancel(); // alarmMgr.cancel(alarmIntent); // Logger.printInfo(TAG, "Alarm managers - Episods check for updates task canceled"); // } // } catch (Exception e) { // Logger.printInfo(TAG, "Alarm managers - can't set alarm manager"); // e.printStackTrace(); // } // } // // @Override // public void onTerminate() { // super.onTerminate(); // } // // public static Context getContext() { // return applicationContext; // } // // public static SQLdatabaseManager getDatabaseManager() { // return databaseManager; // } // }
import com.chickenkiller.upods2.R; import com.chickenkiller.upods2.controllers.app.UpodsApplication;
package com.chickenkiller.upods2.models; /** * Created by Alon Zilberman on 7/10/15. */ public class SlidingMenuHeader extends SlidingMenuItem { private String name; private String email; private String imgUrl; public SlidingMenuHeader() { super();
// Path: app/src/main/java/com/chickenkiller/upods2/controllers/app/UpodsApplication.java // public class UpodsApplication extends Application { // // private static final int CHECK_NEW_EPISODS_INTENT_CODE = 2302; // // private static final String TAG = "UpodsApplication"; // private static Context applicationContext; // private static SQLdatabaseManager databaseManager; // private static boolean isLoaded; // // @Override // public void onCreate() { // isLoaded = false; // applicationContext = getApplicationContext(); // YandexMetrica.activate(getApplicationContext(), Config.YANDEX_METRICS_API_KEY); // YandexMetrica.enableActivityAutoTracking(this); // FacebookSdk.sdkInitialize(applicationContext); // LoginMaster.getInstance().init(); // new Prefs.Builder() // .setContext(this) // .setMode(ContextWrapper.MODE_PRIVATE) // .setPrefsName(getPackageName()) // .setUseDefaultSharedPreference(true).build(); // // super.onCreate(); // } // // /** // * All resources which can be loaded not in onCreate(), should be load here, // * this function called while splash screen is active // */ // public static void initAllResources() { // if (!isLoaded) { // databaseManager = new SQLdatabaseManager(applicationContext); // SettingsManager.getInstace().init(); // Category.initPodcastsCatrgories(); // SimpleCacheManager.getInstance().removeExpiredCache(); // runMainService(); // setAlarmManagerTasks(); // isLoaded = true; // } // } // // private static void runMainService() { // applicationContext.startService(new Intent(applicationContext, MainService.class)); // } // // public static void setAlarmManagerTasks() { // setAlarmManagerTasks(applicationContext); // } // // public static void setAlarmManagerTasks(Context context) { // try { // if (ProfileManager.getInstance().getSubscribedPodcasts().size() == 0) { // return; // } // AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // Intent intent = new Intent(context, NetworkTasksService.class); // intent.setAction(NetworkTasksService.ACTION_CHECK_FOR_NEW_EPISODS); // PendingIntent alarmIntent = PendingIntent.getService(context, CHECK_NEW_EPISODS_INTENT_CODE, intent, // PendingIntent.FLAG_UPDATE_CURRENT); // // if (SettingsManager.getInstace().getBooleanSettingsValue(SettingsManager.JS_NOTIFY_EPISODES)) { // long interval = SettingsManager.getInstace().getIntSettingsValue(SettingsManager.JS_PODCASTS_UPDATE_TIME); // //interval = TimeUnit.MINUTES.toMillis(60); // alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, // SystemClock.elapsedRealtime(), // interval, alarmIntent); // Logger.printInfo(TAG, "Alarm managers - Episods check for updates task added"); // } else { // alarmIntent.cancel(); // alarmMgr.cancel(alarmIntent); // Logger.printInfo(TAG, "Alarm managers - Episods check for updates task canceled"); // } // } catch (Exception e) { // Logger.printInfo(TAG, "Alarm managers - can't set alarm manager"); // e.printStackTrace(); // } // } // // @Override // public void onTerminate() { // super.onTerminate(); // } // // public static Context getContext() { // return applicationContext; // } // // public static SQLdatabaseManager getDatabaseManager() { // return databaseManager; // } // } // Path: app/src/main/java/com/chickenkiller/upods2/models/SlidingMenuHeader.java import com.chickenkiller.upods2.R; import com.chickenkiller.upods2.controllers.app.UpodsApplication; package com.chickenkiller.upods2.models; /** * Created by Alon Zilberman on 7/10/15. */ public class SlidingMenuHeader extends SlidingMenuItem { private String name; private String email; private String imgUrl; public SlidingMenuHeader() { super();
this.name = UpodsApplication.getContext().getString(R.string.anonymus);
KKorvin/uPods-android
app/src/main/java/com/chickenkiller/upods2/models/SlidingMenuRow.java
// Path: app/src/main/java/com/chickenkiller/upods2/controllers/app/UpodsApplication.java // public class UpodsApplication extends Application { // // private static final int CHECK_NEW_EPISODS_INTENT_CODE = 2302; // // private static final String TAG = "UpodsApplication"; // private static Context applicationContext; // private static SQLdatabaseManager databaseManager; // private static boolean isLoaded; // // @Override // public void onCreate() { // isLoaded = false; // applicationContext = getApplicationContext(); // YandexMetrica.activate(getApplicationContext(), Config.YANDEX_METRICS_API_KEY); // YandexMetrica.enableActivityAutoTracking(this); // FacebookSdk.sdkInitialize(applicationContext); // LoginMaster.getInstance().init(); // new Prefs.Builder() // .setContext(this) // .setMode(ContextWrapper.MODE_PRIVATE) // .setPrefsName(getPackageName()) // .setUseDefaultSharedPreference(true).build(); // // super.onCreate(); // } // // /** // * All resources which can be loaded not in onCreate(), should be load here, // * this function called while splash screen is active // */ // public static void initAllResources() { // if (!isLoaded) { // databaseManager = new SQLdatabaseManager(applicationContext); // SettingsManager.getInstace().init(); // Category.initPodcastsCatrgories(); // SimpleCacheManager.getInstance().removeExpiredCache(); // runMainService(); // setAlarmManagerTasks(); // isLoaded = true; // } // } // // private static void runMainService() { // applicationContext.startService(new Intent(applicationContext, MainService.class)); // } // // public static void setAlarmManagerTasks() { // setAlarmManagerTasks(applicationContext); // } // // public static void setAlarmManagerTasks(Context context) { // try { // if (ProfileManager.getInstance().getSubscribedPodcasts().size() == 0) { // return; // } // AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // Intent intent = new Intent(context, NetworkTasksService.class); // intent.setAction(NetworkTasksService.ACTION_CHECK_FOR_NEW_EPISODS); // PendingIntent alarmIntent = PendingIntent.getService(context, CHECK_NEW_EPISODS_INTENT_CODE, intent, // PendingIntent.FLAG_UPDATE_CURRENT); // // if (SettingsManager.getInstace().getBooleanSettingsValue(SettingsManager.JS_NOTIFY_EPISODES)) { // long interval = SettingsManager.getInstace().getIntSettingsValue(SettingsManager.JS_PODCASTS_UPDATE_TIME); // //interval = TimeUnit.MINUTES.toMillis(60); // alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, // SystemClock.elapsedRealtime(), // interval, alarmIntent); // Logger.printInfo(TAG, "Alarm managers - Episods check for updates task added"); // } else { // alarmIntent.cancel(); // alarmMgr.cancel(alarmIntent); // Logger.printInfo(TAG, "Alarm managers - Episods check for updates task canceled"); // } // } catch (Exception e) { // Logger.printInfo(TAG, "Alarm managers - can't set alarm manager"); // e.printStackTrace(); // } // } // // @Override // public void onTerminate() { // super.onTerminate(); // } // // public static Context getContext() { // return applicationContext; // } // // public static SQLdatabaseManager getDatabaseManager() { // return databaseManager; // } // }
import android.content.Context; import com.chickenkiller.upods2.R; import com.chickenkiller.upods2.controllers.app.UpodsApplication; import java.util.ArrayList; import java.util.List;
package com.chickenkiller.upods2.models; /** * Created by Alon Zilberman on 7/4/15. */ public class SlidingMenuRow extends SlidingMenuItem { private String title; private int mainIconId; private int pressedIconId; public boolean isSelected; public SlidingMenuRow(String title, int mainIconId, int pressedIconId) { super(); this.title = title; this.mainIconId = mainIconId; this.pressedIconId = pressedIconId; } public SlidingMenuRow(String title, int mainIconId, int pressedIconId, boolean hasDevider) { this(title, mainIconId, pressedIconId); this.hasDevider = hasDevider; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getMainIconId() { return mainIconId; } public int getPressedIconId() { return pressedIconId; } public static List<SlidingMenuItem> fromDefaultSlidingMenuSet() {
// Path: app/src/main/java/com/chickenkiller/upods2/controllers/app/UpodsApplication.java // public class UpodsApplication extends Application { // // private static final int CHECK_NEW_EPISODS_INTENT_CODE = 2302; // // private static final String TAG = "UpodsApplication"; // private static Context applicationContext; // private static SQLdatabaseManager databaseManager; // private static boolean isLoaded; // // @Override // public void onCreate() { // isLoaded = false; // applicationContext = getApplicationContext(); // YandexMetrica.activate(getApplicationContext(), Config.YANDEX_METRICS_API_KEY); // YandexMetrica.enableActivityAutoTracking(this); // FacebookSdk.sdkInitialize(applicationContext); // LoginMaster.getInstance().init(); // new Prefs.Builder() // .setContext(this) // .setMode(ContextWrapper.MODE_PRIVATE) // .setPrefsName(getPackageName()) // .setUseDefaultSharedPreference(true).build(); // // super.onCreate(); // } // // /** // * All resources which can be loaded not in onCreate(), should be load here, // * this function called while splash screen is active // */ // public static void initAllResources() { // if (!isLoaded) { // databaseManager = new SQLdatabaseManager(applicationContext); // SettingsManager.getInstace().init(); // Category.initPodcastsCatrgories(); // SimpleCacheManager.getInstance().removeExpiredCache(); // runMainService(); // setAlarmManagerTasks(); // isLoaded = true; // } // } // // private static void runMainService() { // applicationContext.startService(new Intent(applicationContext, MainService.class)); // } // // public static void setAlarmManagerTasks() { // setAlarmManagerTasks(applicationContext); // } // // public static void setAlarmManagerTasks(Context context) { // try { // if (ProfileManager.getInstance().getSubscribedPodcasts().size() == 0) { // return; // } // AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // Intent intent = new Intent(context, NetworkTasksService.class); // intent.setAction(NetworkTasksService.ACTION_CHECK_FOR_NEW_EPISODS); // PendingIntent alarmIntent = PendingIntent.getService(context, CHECK_NEW_EPISODS_INTENT_CODE, intent, // PendingIntent.FLAG_UPDATE_CURRENT); // // if (SettingsManager.getInstace().getBooleanSettingsValue(SettingsManager.JS_NOTIFY_EPISODES)) { // long interval = SettingsManager.getInstace().getIntSettingsValue(SettingsManager.JS_PODCASTS_UPDATE_TIME); // //interval = TimeUnit.MINUTES.toMillis(60); // alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, // SystemClock.elapsedRealtime(), // interval, alarmIntent); // Logger.printInfo(TAG, "Alarm managers - Episods check for updates task added"); // } else { // alarmIntent.cancel(); // alarmMgr.cancel(alarmIntent); // Logger.printInfo(TAG, "Alarm managers - Episods check for updates task canceled"); // } // } catch (Exception e) { // Logger.printInfo(TAG, "Alarm managers - can't set alarm manager"); // e.printStackTrace(); // } // } // // @Override // public void onTerminate() { // super.onTerminate(); // } // // public static Context getContext() { // return applicationContext; // } // // public static SQLdatabaseManager getDatabaseManager() { // return databaseManager; // } // } // Path: app/src/main/java/com/chickenkiller/upods2/models/SlidingMenuRow.java import android.content.Context; import com.chickenkiller.upods2.R; import com.chickenkiller.upods2.controllers.app.UpodsApplication; import java.util.ArrayList; import java.util.List; package com.chickenkiller.upods2.models; /** * Created by Alon Zilberman on 7/4/15. */ public class SlidingMenuRow extends SlidingMenuItem { private String title; private int mainIconId; private int pressedIconId; public boolean isSelected; public SlidingMenuRow(String title, int mainIconId, int pressedIconId) { super(); this.title = title; this.mainIconId = mainIconId; this.pressedIconId = pressedIconId; } public SlidingMenuRow(String title, int mainIconId, int pressedIconId, boolean hasDevider) { this(title, mainIconId, pressedIconId); this.hasDevider = hasDevider; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getMainIconId() { return mainIconId; } public int getPressedIconId() { return pressedIconId; } public static List<SlidingMenuItem> fromDefaultSlidingMenuSet() {
Context mContext = UpodsApplication.getContext();
KKorvin/uPods-android
app/src/main/java/com/chickenkiller/upods2/controllers/app/SettingsManager.java
// Path: app/src/main/java/com/chickenkiller/upods2/models/MediaItem.java // public abstract class MediaItem extends SQLModel implements IMediaItemView { // // /** // * Created by Alon Zilberman on 10/23/15. // * Use it to transfer MediaItems and tracks in one object // */ // public static class MediaItemBucket { // public MediaItem mediaItem; // public Track track; // } // // protected String name; // protected String coverImageUrl; // protected float score; // // // public boolean isSubscribed; // // public MediaItem() { // } // // public String getCoverImageUrl() { // return coverImageUrl; // } // // public String getName() { // return name; // } // // public String getSubHeader() { // return ""; // } // // public String getBottomHeader() { // return ""; // } // // public boolean hasTracks() { // return false; // } // // public String getDescription() { // return ""; // } // // public String getAudeoLink() { // return null; // } // // public String getBitrate() { // return ""; // } // // // public void syncWithDB(){ // // } // // public void syncWithMediaItem(MediaItem updatedMediaItem) { // this.id = updatedMediaItem.id; // this.isSubscribed = updatedMediaItem.isSubscribed; // this.isExistsInDb = updatedMediaItem.isExistsInDb; // } // // public static boolean hasMediaItemWithName(ArrayList<? extends MediaItem> mediaItems, MediaItem mediaItemToCheck) { // for (MediaItem mediaItem : mediaItems) { // if (mediaItem.getName().equals(mediaItemToCheck.getName())) { // return true; // } // } // return false; // } // // public static MediaItem getMediaItemByName(ArrayList<? extends MediaItem> mediaItems, MediaItem mediaItemTarget) { // return getMediaItemByName(mediaItems, mediaItemTarget.getName()); // } // // public static MediaItem getMediaItemByName(ArrayList<? extends MediaItem> mediaItems, String targetName) { // for (MediaItem mediaItem : mediaItems) { // if (GlobalUtils.safeTitleEquals(mediaItem.getName(), targetName)) { // return mediaItem; // } // } // return null; // } // // public static ArrayList<String> getIds(ArrayList<? extends MediaItem> mediaItems) { // ArrayList<String> ids = new ArrayList<>(); // for (MediaItem mediaItem : mediaItems) { // ids.add(String.valueOf(mediaItem.id)); // } // return ids; // } // // public float getScore(){ // return score; // } // } // // Path: app/src/main/java/com/chickenkiller/upods2/utils/Logger.java // public class Logger { // // private static boolean isTurnedOn = false; // // public static void printInfo(String tag, String text) { // if (isTurnedOn) { // Log.i(tag, text); // } // } // // public static void printInfo(String tag, int text) { // if (isTurnedOn) { // Log.i(tag, String.valueOf(text)); // } // } // // public static void printInfo(String tag, boolean text) { // if (isTurnedOn) { // Log.i(tag, String.valueOf(text)); // } // } // // // public static void printError(String tag, String text) { // if (isTurnedOn) { // Log.i(tag, text); // } // } // }
import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Pair; import com.chickenkiller.upods2.models.MediaItem; import com.chickenkiller.upods2.utils.Logger; import com.pixplicity.easyprefs.library.Prefs; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.Locale;
if (settingsManager == null) { settingsManager = new SettingsManager(); } return settingsManager; } public void init() { readSettings(); //Call it here in order to create empty settings if not exist } public void readSettings(JSONObject jsonObject) { Prefs.putString(JS_SETTINGS, jsonObject.toString()); readSettings(); } private JSONObject readSettings() { try { if (Prefs.getString(JS_SETTINGS, null) == null) { JSONObject settingsObject = new JSONObject(); settingsObject.put(JS_START_SCREEN, DEFAULT_START_SCREEN); settingsObject.put(JS_NOTIFY_EPISODES, DEFAULT_NOTIFY_EPISODS); settingsObject.put(JS_PODCASTS_UPDATE_TIME, DEFAULT_PODCAST_UPDATE_TIME); settingsObject.put(JS_STREAM_QUALITY, DEFAULT_STREAM_QUALITY); settingsObject.put(JS_TOPS_LANGUAGE, Locale.getDefault().getLanguage()); Prefs.putString(JS_TOPS_LANGUAGE, Locale.getDefault().getLanguage()); Prefs.putString(JS_SETTINGS, settingsObject.toString()); } return new JSONObject(Prefs.getString(JS_SETTINGS, null)); } catch (JSONException e) {
// Path: app/src/main/java/com/chickenkiller/upods2/models/MediaItem.java // public abstract class MediaItem extends SQLModel implements IMediaItemView { // // /** // * Created by Alon Zilberman on 10/23/15. // * Use it to transfer MediaItems and tracks in one object // */ // public static class MediaItemBucket { // public MediaItem mediaItem; // public Track track; // } // // protected String name; // protected String coverImageUrl; // protected float score; // // // public boolean isSubscribed; // // public MediaItem() { // } // // public String getCoverImageUrl() { // return coverImageUrl; // } // // public String getName() { // return name; // } // // public String getSubHeader() { // return ""; // } // // public String getBottomHeader() { // return ""; // } // // public boolean hasTracks() { // return false; // } // // public String getDescription() { // return ""; // } // // public String getAudeoLink() { // return null; // } // // public String getBitrate() { // return ""; // } // // // public void syncWithDB(){ // // } // // public void syncWithMediaItem(MediaItem updatedMediaItem) { // this.id = updatedMediaItem.id; // this.isSubscribed = updatedMediaItem.isSubscribed; // this.isExistsInDb = updatedMediaItem.isExistsInDb; // } // // public static boolean hasMediaItemWithName(ArrayList<? extends MediaItem> mediaItems, MediaItem mediaItemToCheck) { // for (MediaItem mediaItem : mediaItems) { // if (mediaItem.getName().equals(mediaItemToCheck.getName())) { // return true; // } // } // return false; // } // // public static MediaItem getMediaItemByName(ArrayList<? extends MediaItem> mediaItems, MediaItem mediaItemTarget) { // return getMediaItemByName(mediaItems, mediaItemTarget.getName()); // } // // public static MediaItem getMediaItemByName(ArrayList<? extends MediaItem> mediaItems, String targetName) { // for (MediaItem mediaItem : mediaItems) { // if (GlobalUtils.safeTitleEquals(mediaItem.getName(), targetName)) { // return mediaItem; // } // } // return null; // } // // public static ArrayList<String> getIds(ArrayList<? extends MediaItem> mediaItems) { // ArrayList<String> ids = new ArrayList<>(); // for (MediaItem mediaItem : mediaItems) { // ids.add(String.valueOf(mediaItem.id)); // } // return ids; // } // // public float getScore(){ // return score; // } // } // // Path: app/src/main/java/com/chickenkiller/upods2/utils/Logger.java // public class Logger { // // private static boolean isTurnedOn = false; // // public static void printInfo(String tag, String text) { // if (isTurnedOn) { // Log.i(tag, text); // } // } // // public static void printInfo(String tag, int text) { // if (isTurnedOn) { // Log.i(tag, String.valueOf(text)); // } // } // // public static void printInfo(String tag, boolean text) { // if (isTurnedOn) { // Log.i(tag, String.valueOf(text)); // } // } // // // public static void printError(String tag, String text) { // if (isTurnedOn) { // Log.i(tag, text); // } // } // } // Path: app/src/main/java/com/chickenkiller/upods2/controllers/app/SettingsManager.java import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Pair; import com.chickenkiller.upods2.models.MediaItem; import com.chickenkiller.upods2.utils.Logger; import com.pixplicity.easyprefs.library.Prefs; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.Locale; if (settingsManager == null) { settingsManager = new SettingsManager(); } return settingsManager; } public void init() { readSettings(); //Call it here in order to create empty settings if not exist } public void readSettings(JSONObject jsonObject) { Prefs.putString(JS_SETTINGS, jsonObject.toString()); readSettings(); } private JSONObject readSettings() { try { if (Prefs.getString(JS_SETTINGS, null) == null) { JSONObject settingsObject = new JSONObject(); settingsObject.put(JS_START_SCREEN, DEFAULT_START_SCREEN); settingsObject.put(JS_NOTIFY_EPISODES, DEFAULT_NOTIFY_EPISODS); settingsObject.put(JS_PODCASTS_UPDATE_TIME, DEFAULT_PODCAST_UPDATE_TIME); settingsObject.put(JS_STREAM_QUALITY, DEFAULT_STREAM_QUALITY); settingsObject.put(JS_TOPS_LANGUAGE, Locale.getDefault().getLanguage()); Prefs.putString(JS_TOPS_LANGUAGE, Locale.getDefault().getLanguage()); Prefs.putString(JS_SETTINGS, settingsObject.toString()); } return new JSONObject(Prefs.getString(JS_SETTINGS, null)); } catch (JSONException e) {
Logger.printInfo(TAG, "Can't read settings");
KKorvin/uPods-android
app/src/main/java/com/chickenkiller/upods2/controllers/app/SettingsManager.java
// Path: app/src/main/java/com/chickenkiller/upods2/models/MediaItem.java // public abstract class MediaItem extends SQLModel implements IMediaItemView { // // /** // * Created by Alon Zilberman on 10/23/15. // * Use it to transfer MediaItems and tracks in one object // */ // public static class MediaItemBucket { // public MediaItem mediaItem; // public Track track; // } // // protected String name; // protected String coverImageUrl; // protected float score; // // // public boolean isSubscribed; // // public MediaItem() { // } // // public String getCoverImageUrl() { // return coverImageUrl; // } // // public String getName() { // return name; // } // // public String getSubHeader() { // return ""; // } // // public String getBottomHeader() { // return ""; // } // // public boolean hasTracks() { // return false; // } // // public String getDescription() { // return ""; // } // // public String getAudeoLink() { // return null; // } // // public String getBitrate() { // return ""; // } // // // public void syncWithDB(){ // // } // // public void syncWithMediaItem(MediaItem updatedMediaItem) { // this.id = updatedMediaItem.id; // this.isSubscribed = updatedMediaItem.isSubscribed; // this.isExistsInDb = updatedMediaItem.isExistsInDb; // } // // public static boolean hasMediaItemWithName(ArrayList<? extends MediaItem> mediaItems, MediaItem mediaItemToCheck) { // for (MediaItem mediaItem : mediaItems) { // if (mediaItem.getName().equals(mediaItemToCheck.getName())) { // return true; // } // } // return false; // } // // public static MediaItem getMediaItemByName(ArrayList<? extends MediaItem> mediaItems, MediaItem mediaItemTarget) { // return getMediaItemByName(mediaItems, mediaItemTarget.getName()); // } // // public static MediaItem getMediaItemByName(ArrayList<? extends MediaItem> mediaItems, String targetName) { // for (MediaItem mediaItem : mediaItems) { // if (GlobalUtils.safeTitleEquals(mediaItem.getName(), targetName)) { // return mediaItem; // } // } // return null; // } // // public static ArrayList<String> getIds(ArrayList<? extends MediaItem> mediaItems) { // ArrayList<String> ids = new ArrayList<>(); // for (MediaItem mediaItem : mediaItems) { // ids.add(String.valueOf(mediaItem.id)); // } // return ids; // } // // public float getScore(){ // return score; // } // } // // Path: app/src/main/java/com/chickenkiller/upods2/utils/Logger.java // public class Logger { // // private static boolean isTurnedOn = false; // // public static void printInfo(String tag, String text) { // if (isTurnedOn) { // Log.i(tag, text); // } // } // // public static void printInfo(String tag, int text) { // if (isTurnedOn) { // Log.i(tag, String.valueOf(text)); // } // } // // public static void printInfo(String tag, boolean text) { // if (isTurnedOn) { // Log.i(tag, String.valueOf(text)); // } // } // // // public static void printError(String tag, String text) { // if (isTurnedOn) { // Log.i(tag, text); // } // } // }
import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Pair; import com.chickenkiller.upods2.models.MediaItem; import com.chickenkiller.upods2.utils.Logger; import com.pixplicity.easyprefs.library.Prefs; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.Locale;
public String getStringSettingValue(String key) { try { return readSettings().getString(key); } catch (JSONException e) { Logger.printInfo(TAG, "Can't read value with key: " + key + " from json settings"); e.printStackTrace(); return ""; } } public String getPareSettingValue(String settingsKey, String pareKey) { try { JSONObject rootObject = readSettings(); if (rootObject.has(settingsKey)) { JSONArray streamsArray = readSettings().getJSONArray(settingsKey); for (int i = 0; i < streamsArray.length(); i++) { if (streamsArray.getJSONObject(i).has(pareKey)) { return streamsArray.getJSONObject(i).getString(pareKey); } } } return ""; } catch (JSONException e) { Logger.printInfo(TAG, "Can't read value with key: " + settingsKey + " from json settings"); e.printStackTrace(); return ""; } }
// Path: app/src/main/java/com/chickenkiller/upods2/models/MediaItem.java // public abstract class MediaItem extends SQLModel implements IMediaItemView { // // /** // * Created by Alon Zilberman on 10/23/15. // * Use it to transfer MediaItems and tracks in one object // */ // public static class MediaItemBucket { // public MediaItem mediaItem; // public Track track; // } // // protected String name; // protected String coverImageUrl; // protected float score; // // // public boolean isSubscribed; // // public MediaItem() { // } // // public String getCoverImageUrl() { // return coverImageUrl; // } // // public String getName() { // return name; // } // // public String getSubHeader() { // return ""; // } // // public String getBottomHeader() { // return ""; // } // // public boolean hasTracks() { // return false; // } // // public String getDescription() { // return ""; // } // // public String getAudeoLink() { // return null; // } // // public String getBitrate() { // return ""; // } // // // public void syncWithDB(){ // // } // // public void syncWithMediaItem(MediaItem updatedMediaItem) { // this.id = updatedMediaItem.id; // this.isSubscribed = updatedMediaItem.isSubscribed; // this.isExistsInDb = updatedMediaItem.isExistsInDb; // } // // public static boolean hasMediaItemWithName(ArrayList<? extends MediaItem> mediaItems, MediaItem mediaItemToCheck) { // for (MediaItem mediaItem : mediaItems) { // if (mediaItem.getName().equals(mediaItemToCheck.getName())) { // return true; // } // } // return false; // } // // public static MediaItem getMediaItemByName(ArrayList<? extends MediaItem> mediaItems, MediaItem mediaItemTarget) { // return getMediaItemByName(mediaItems, mediaItemTarget.getName()); // } // // public static MediaItem getMediaItemByName(ArrayList<? extends MediaItem> mediaItems, String targetName) { // for (MediaItem mediaItem : mediaItems) { // if (GlobalUtils.safeTitleEquals(mediaItem.getName(), targetName)) { // return mediaItem; // } // } // return null; // } // // public static ArrayList<String> getIds(ArrayList<? extends MediaItem> mediaItems) { // ArrayList<String> ids = new ArrayList<>(); // for (MediaItem mediaItem : mediaItems) { // ids.add(String.valueOf(mediaItem.id)); // } // return ids; // } // // public float getScore(){ // return score; // } // } // // Path: app/src/main/java/com/chickenkiller/upods2/utils/Logger.java // public class Logger { // // private static boolean isTurnedOn = false; // // public static void printInfo(String tag, String text) { // if (isTurnedOn) { // Log.i(tag, text); // } // } // // public static void printInfo(String tag, int text) { // if (isTurnedOn) { // Log.i(tag, String.valueOf(text)); // } // } // // public static void printInfo(String tag, boolean text) { // if (isTurnedOn) { // Log.i(tag, String.valueOf(text)); // } // } // // // public static void printError(String tag, String text) { // if (isTurnedOn) { // Log.i(tag, text); // } // } // } // Path: app/src/main/java/com/chickenkiller/upods2/controllers/app/SettingsManager.java import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Pair; import com.chickenkiller.upods2.models.MediaItem; import com.chickenkiller.upods2.utils.Logger; import com.pixplicity.easyprefs.library.Prefs; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.Locale; public String getStringSettingValue(String key) { try { return readSettings().getString(key); } catch (JSONException e) { Logger.printInfo(TAG, "Can't read value with key: " + key + " from json settings"); e.printStackTrace(); return ""; } } public String getPareSettingValue(String settingsKey, String pareKey) { try { JSONObject rootObject = readSettings(); if (rootObject.has(settingsKey)) { JSONArray streamsArray = readSettings().getJSONArray(settingsKey); for (int i = 0; i < streamsArray.length(); i++) { if (streamsArray.getJSONObject(i).has(pareKey)) { return streamsArray.getJSONObject(i).getString(pareKey); } } } return ""; } catch (JSONException e) { Logger.printInfo(TAG, "Can't read value with key: " + settingsKey + " from json settings"); e.printStackTrace(); return ""; } }
public void saveStreamQualitySelection(MediaItem mediaItem, String quality) {
KKorvin/uPods-android
app/src/main/java/com/chickenkiller/upods2/fragments/FragmentWellcome.java
// Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IControlStackHistory.java // public interface IControlStackHistory { // boolean shouldBeAddedToStack(); // } // // Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IToolbarHolder.java // public interface IToolbarHolder { // // Toolbar getToolbar(); // // }
import android.app.Fragment; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.chickenkiller.upods2.R; import com.chickenkiller.upods2.interfaces.IControlStackHistory; import com.chickenkiller.upods2.interfaces.IToolbarHolder;
package com.chickenkiller.upods2.fragments; /** * Created by Alon Zilberman on 8/8/15. */ public class FragmentWellcome extends Fragment implements IControlStackHistory { public static final String TAG = "fragment_wellcome"; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_wellcome, container, false);
// Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IControlStackHistory.java // public interface IControlStackHistory { // boolean shouldBeAddedToStack(); // } // // Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IToolbarHolder.java // public interface IToolbarHolder { // // Toolbar getToolbar(); // // } // Path: app/src/main/java/com/chickenkiller/upods2/fragments/FragmentWellcome.java import android.app.Fragment; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.chickenkiller.upods2.R; import com.chickenkiller.upods2.interfaces.IControlStackHistory; import com.chickenkiller.upods2.interfaces.IToolbarHolder; package com.chickenkiller.upods2.fragments; /** * Created by Alon Zilberman on 8/8/15. */ public class FragmentWellcome extends Fragment implements IControlStackHistory { public static final String TAG = "fragment_wellcome"; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_wellcome, container, false);
Toolbar toolbar = ((IToolbarHolder) getActivity()).getToolbar();
KKorvin/uPods-android
app/src/main/java/com/chickenkiller/upods2/utils/ui/UIHelper.java
// Path: app/src/main/java/com/chickenkiller/upods2/controllers/app/UpodsApplication.java // public class UpodsApplication extends Application { // // private static final int CHECK_NEW_EPISODS_INTENT_CODE = 2302; // // private static final String TAG = "UpodsApplication"; // private static Context applicationContext; // private static SQLdatabaseManager databaseManager; // private static boolean isLoaded; // // @Override // public void onCreate() { // isLoaded = false; // applicationContext = getApplicationContext(); // YandexMetrica.activate(getApplicationContext(), Config.YANDEX_METRICS_API_KEY); // YandexMetrica.enableActivityAutoTracking(this); // FacebookSdk.sdkInitialize(applicationContext); // LoginMaster.getInstance().init(); // new Prefs.Builder() // .setContext(this) // .setMode(ContextWrapper.MODE_PRIVATE) // .setPrefsName(getPackageName()) // .setUseDefaultSharedPreference(true).build(); // // super.onCreate(); // } // // /** // * All resources which can be loaded not in onCreate(), should be load here, // * this function called while splash screen is active // */ // public static void initAllResources() { // if (!isLoaded) { // databaseManager = new SQLdatabaseManager(applicationContext); // SettingsManager.getInstace().init(); // Category.initPodcastsCatrgories(); // SimpleCacheManager.getInstance().removeExpiredCache(); // runMainService(); // setAlarmManagerTasks(); // isLoaded = true; // } // } // // private static void runMainService() { // applicationContext.startService(new Intent(applicationContext, MainService.class)); // } // // public static void setAlarmManagerTasks() { // setAlarmManagerTasks(applicationContext); // } // // public static void setAlarmManagerTasks(Context context) { // try { // if (ProfileManager.getInstance().getSubscribedPodcasts().size() == 0) { // return; // } // AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // Intent intent = new Intent(context, NetworkTasksService.class); // intent.setAction(NetworkTasksService.ACTION_CHECK_FOR_NEW_EPISODS); // PendingIntent alarmIntent = PendingIntent.getService(context, CHECK_NEW_EPISODS_INTENT_CODE, intent, // PendingIntent.FLAG_UPDATE_CURRENT); // // if (SettingsManager.getInstace().getBooleanSettingsValue(SettingsManager.JS_NOTIFY_EPISODES)) { // long interval = SettingsManager.getInstace().getIntSettingsValue(SettingsManager.JS_PODCASTS_UPDATE_TIME); // //interval = TimeUnit.MINUTES.toMillis(60); // alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, // SystemClock.elapsedRealtime(), // interval, alarmIntent); // Logger.printInfo(TAG, "Alarm managers - Episods check for updates task added"); // } else { // alarmIntent.cancel(); // alarmMgr.cancel(alarmIntent); // Logger.printInfo(TAG, "Alarm managers - Episods check for updates task canceled"); // } // } catch (Exception e) { // Logger.printInfo(TAG, "Alarm managers - can't set alarm manager"); // e.printStackTrace(); // } // } // // @Override // public void onTerminate() { // super.onTerminate(); // } // // public static Context getContext() { // return applicationContext; // } // // public static SQLdatabaseManager getDatabaseManager() { // return databaseManager; // } // }
import android.content.res.ColorStateList; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.RectF; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.RippleDrawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.StateListDrawable; import android.graphics.drawable.shapes.RoundRectShape; import android.os.Build; import android.support.v7.graphics.Palette; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.TextView; import com.chickenkiller.upods2.R; import com.chickenkiller.upods2.controllers.app.UpodsApplication; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Random;
((TextView) view).setTextColor(color); return; } else if (view instanceof ViewGroup) { ViewGroup viewGroup = (ViewGroup) view; for (int i = 0; i < viewGroup.getChildCount(); i++) { changeSearchViewTextColor(viewGroup.getChildAt(i), color); } } } } public static void setSearchViewStyle(SearchView searchView) { if (searchView.findViewById(android.support.v7.appcompat.R.id.search_plate) != null) { searchView.findViewById(android.support.v7.appcompat.R.id.search_plate).setBackground(null); } if (searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text) != null) { EditText searchPlate = (EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text); searchPlate.setHint(R.string.search_hint); try { Field mCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes"); mCursorDrawableRes.setAccessible(true); mCursorDrawableRes.set(searchPlate, R.drawable.white_cursor); //This sets the cursor resource ID to 0 or @null which will make it visible on white background } catch (Exception e) { } } searchView.setBackgroundColor(Color.TRANSPARENT); } public static int dpToPixels(int value) {
// Path: app/src/main/java/com/chickenkiller/upods2/controllers/app/UpodsApplication.java // public class UpodsApplication extends Application { // // private static final int CHECK_NEW_EPISODS_INTENT_CODE = 2302; // // private static final String TAG = "UpodsApplication"; // private static Context applicationContext; // private static SQLdatabaseManager databaseManager; // private static boolean isLoaded; // // @Override // public void onCreate() { // isLoaded = false; // applicationContext = getApplicationContext(); // YandexMetrica.activate(getApplicationContext(), Config.YANDEX_METRICS_API_KEY); // YandexMetrica.enableActivityAutoTracking(this); // FacebookSdk.sdkInitialize(applicationContext); // LoginMaster.getInstance().init(); // new Prefs.Builder() // .setContext(this) // .setMode(ContextWrapper.MODE_PRIVATE) // .setPrefsName(getPackageName()) // .setUseDefaultSharedPreference(true).build(); // // super.onCreate(); // } // // /** // * All resources which can be loaded not in onCreate(), should be load here, // * this function called while splash screen is active // */ // public static void initAllResources() { // if (!isLoaded) { // databaseManager = new SQLdatabaseManager(applicationContext); // SettingsManager.getInstace().init(); // Category.initPodcastsCatrgories(); // SimpleCacheManager.getInstance().removeExpiredCache(); // runMainService(); // setAlarmManagerTasks(); // isLoaded = true; // } // } // // private static void runMainService() { // applicationContext.startService(new Intent(applicationContext, MainService.class)); // } // // public static void setAlarmManagerTasks() { // setAlarmManagerTasks(applicationContext); // } // // public static void setAlarmManagerTasks(Context context) { // try { // if (ProfileManager.getInstance().getSubscribedPodcasts().size() == 0) { // return; // } // AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // Intent intent = new Intent(context, NetworkTasksService.class); // intent.setAction(NetworkTasksService.ACTION_CHECK_FOR_NEW_EPISODS); // PendingIntent alarmIntent = PendingIntent.getService(context, CHECK_NEW_EPISODS_INTENT_CODE, intent, // PendingIntent.FLAG_UPDATE_CURRENT); // // if (SettingsManager.getInstace().getBooleanSettingsValue(SettingsManager.JS_NOTIFY_EPISODES)) { // long interval = SettingsManager.getInstace().getIntSettingsValue(SettingsManager.JS_PODCASTS_UPDATE_TIME); // //interval = TimeUnit.MINUTES.toMillis(60); // alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, // SystemClock.elapsedRealtime(), // interval, alarmIntent); // Logger.printInfo(TAG, "Alarm managers - Episods check for updates task added"); // } else { // alarmIntent.cancel(); // alarmMgr.cancel(alarmIntent); // Logger.printInfo(TAG, "Alarm managers - Episods check for updates task canceled"); // } // } catch (Exception e) { // Logger.printInfo(TAG, "Alarm managers - can't set alarm manager"); // e.printStackTrace(); // } // } // // @Override // public void onTerminate() { // super.onTerminate(); // } // // public static Context getContext() { // return applicationContext; // } // // public static SQLdatabaseManager getDatabaseManager() { // return databaseManager; // } // } // Path: app/src/main/java/com/chickenkiller/upods2/utils/ui/UIHelper.java import android.content.res.ColorStateList; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.RectF; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.RippleDrawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.StateListDrawable; import android.graphics.drawable.shapes.RoundRectShape; import android.os.Build; import android.support.v7.graphics.Palette; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.TextView; import com.chickenkiller.upods2.R; import com.chickenkiller.upods2.controllers.app.UpodsApplication; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Random; ((TextView) view).setTextColor(color); return; } else if (view instanceof ViewGroup) { ViewGroup viewGroup = (ViewGroup) view; for (int i = 0; i < viewGroup.getChildCount(); i++) { changeSearchViewTextColor(viewGroup.getChildAt(i), color); } } } } public static void setSearchViewStyle(SearchView searchView) { if (searchView.findViewById(android.support.v7.appcompat.R.id.search_plate) != null) { searchView.findViewById(android.support.v7.appcompat.R.id.search_plate).setBackground(null); } if (searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text) != null) { EditText searchPlate = (EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text); searchPlate.setHint(R.string.search_hint); try { Field mCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes"); mCursorDrawableRes.setAccessible(true); mCursorDrawableRes.set(searchPlate, R.drawable.white_cursor); //This sets the cursor resource ID to 0 or @null which will make it visible on white background } catch (Exception e) { } } searchView.setBackgroundColor(Color.TRANSPARENT); } public static int dpToPixels(int value) {
float d = UpodsApplication.getContext().getResources().getDisplayMetrics().density;
KKorvin/uPods-android
app/src/main/java/com/chickenkiller/upods2/models/MediaListItem.java
// Path: app/src/main/java/com/chickenkiller/upods2/controllers/app/UpodsApplication.java // public class UpodsApplication extends Application { // // private static final int CHECK_NEW_EPISODS_INTENT_CODE = 2302; // // private static final String TAG = "UpodsApplication"; // private static Context applicationContext; // private static SQLdatabaseManager databaseManager; // private static boolean isLoaded; // // @Override // public void onCreate() { // isLoaded = false; // applicationContext = getApplicationContext(); // YandexMetrica.activate(getApplicationContext(), Config.YANDEX_METRICS_API_KEY); // YandexMetrica.enableActivityAutoTracking(this); // FacebookSdk.sdkInitialize(applicationContext); // LoginMaster.getInstance().init(); // new Prefs.Builder() // .setContext(this) // .setMode(ContextWrapper.MODE_PRIVATE) // .setPrefsName(getPackageName()) // .setUseDefaultSharedPreference(true).build(); // // super.onCreate(); // } // // /** // * All resources which can be loaded not in onCreate(), should be load here, // * this function called while splash screen is active // */ // public static void initAllResources() { // if (!isLoaded) { // databaseManager = new SQLdatabaseManager(applicationContext); // SettingsManager.getInstace().init(); // Category.initPodcastsCatrgories(); // SimpleCacheManager.getInstance().removeExpiredCache(); // runMainService(); // setAlarmManagerTasks(); // isLoaded = true; // } // } // // private static void runMainService() { // applicationContext.startService(new Intent(applicationContext, MainService.class)); // } // // public static void setAlarmManagerTasks() { // setAlarmManagerTasks(applicationContext); // } // // public static void setAlarmManagerTasks(Context context) { // try { // if (ProfileManager.getInstance().getSubscribedPodcasts().size() == 0) { // return; // } // AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // Intent intent = new Intent(context, NetworkTasksService.class); // intent.setAction(NetworkTasksService.ACTION_CHECK_FOR_NEW_EPISODS); // PendingIntent alarmIntent = PendingIntent.getService(context, CHECK_NEW_EPISODS_INTENT_CODE, intent, // PendingIntent.FLAG_UPDATE_CURRENT); // // if (SettingsManager.getInstace().getBooleanSettingsValue(SettingsManager.JS_NOTIFY_EPISODES)) { // long interval = SettingsManager.getInstace().getIntSettingsValue(SettingsManager.JS_PODCASTS_UPDATE_TIME); // //interval = TimeUnit.MINUTES.toMillis(60); // alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, // SystemClock.elapsedRealtime(), // interval, alarmIntent); // Logger.printInfo(TAG, "Alarm managers - Episods check for updates task added"); // } else { // alarmIntent.cancel(); // alarmMgr.cancel(alarmIntent); // Logger.printInfo(TAG, "Alarm managers - Episods check for updates task canceled"); // } // } catch (Exception e) { // Logger.printInfo(TAG, "Alarm managers - can't set alarm manager"); // e.printStackTrace(); // } // } // // @Override // public void onTerminate() { // super.onTerminate(); // } // // public static Context getContext() { // return applicationContext; // } // // public static SQLdatabaseManager getDatabaseManager() { // return databaseManager; // } // }
import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.chickenkiller.upods2.controllers.app.UpodsApplication; import java.util.ArrayList;
package com.chickenkiller.upods2.models; /** * Created by Alon Zilberman on 17/03/2016. */ public class MediaListItem extends SQLModel { public static final String SUBSCRIBED = "subscribed"; public static final String RECENT = "recent"; public static final String TYPE_PODCAST = "podcast"; public static final String TYPE_RADIO = "radio"; public static final String DOWNLOADED = "downloaded"; public static final String NEW = "new"; public String mediaItemName; public String listType; public MediaListItem() { super(); } public static ArrayList<MediaListItem> withMediaType(String mediaType) { ArrayList<MediaListItem> mediaListItems = new ArrayList<>();
// Path: app/src/main/java/com/chickenkiller/upods2/controllers/app/UpodsApplication.java // public class UpodsApplication extends Application { // // private static final int CHECK_NEW_EPISODS_INTENT_CODE = 2302; // // private static final String TAG = "UpodsApplication"; // private static Context applicationContext; // private static SQLdatabaseManager databaseManager; // private static boolean isLoaded; // // @Override // public void onCreate() { // isLoaded = false; // applicationContext = getApplicationContext(); // YandexMetrica.activate(getApplicationContext(), Config.YANDEX_METRICS_API_KEY); // YandexMetrica.enableActivityAutoTracking(this); // FacebookSdk.sdkInitialize(applicationContext); // LoginMaster.getInstance().init(); // new Prefs.Builder() // .setContext(this) // .setMode(ContextWrapper.MODE_PRIVATE) // .setPrefsName(getPackageName()) // .setUseDefaultSharedPreference(true).build(); // // super.onCreate(); // } // // /** // * All resources which can be loaded not in onCreate(), should be load here, // * this function called while splash screen is active // */ // public static void initAllResources() { // if (!isLoaded) { // databaseManager = new SQLdatabaseManager(applicationContext); // SettingsManager.getInstace().init(); // Category.initPodcastsCatrgories(); // SimpleCacheManager.getInstance().removeExpiredCache(); // runMainService(); // setAlarmManagerTasks(); // isLoaded = true; // } // } // // private static void runMainService() { // applicationContext.startService(new Intent(applicationContext, MainService.class)); // } // // public static void setAlarmManagerTasks() { // setAlarmManagerTasks(applicationContext); // } // // public static void setAlarmManagerTasks(Context context) { // try { // if (ProfileManager.getInstance().getSubscribedPodcasts().size() == 0) { // return; // } // AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // Intent intent = new Intent(context, NetworkTasksService.class); // intent.setAction(NetworkTasksService.ACTION_CHECK_FOR_NEW_EPISODS); // PendingIntent alarmIntent = PendingIntent.getService(context, CHECK_NEW_EPISODS_INTENT_CODE, intent, // PendingIntent.FLAG_UPDATE_CURRENT); // // if (SettingsManager.getInstace().getBooleanSettingsValue(SettingsManager.JS_NOTIFY_EPISODES)) { // long interval = SettingsManager.getInstace().getIntSettingsValue(SettingsManager.JS_PODCASTS_UPDATE_TIME); // //interval = TimeUnit.MINUTES.toMillis(60); // alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, // SystemClock.elapsedRealtime(), // interval, alarmIntent); // Logger.printInfo(TAG, "Alarm managers - Episods check for updates task added"); // } else { // alarmIntent.cancel(); // alarmMgr.cancel(alarmIntent); // Logger.printInfo(TAG, "Alarm managers - Episods check for updates task canceled"); // } // } catch (Exception e) { // Logger.printInfo(TAG, "Alarm managers - can't set alarm manager"); // e.printStackTrace(); // } // } // // @Override // public void onTerminate() { // super.onTerminate(); // } // // public static Context getContext() { // return applicationContext; // } // // public static SQLdatabaseManager getDatabaseManager() { // return databaseManager; // } // } // Path: app/src/main/java/com/chickenkiller/upods2/models/MediaListItem.java import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.chickenkiller.upods2.controllers.app.UpodsApplication; import java.util.ArrayList; package com.chickenkiller.upods2.models; /** * Created by Alon Zilberman on 17/03/2016. */ public class MediaListItem extends SQLModel { public static final String SUBSCRIBED = "subscribed"; public static final String RECENT = "recent"; public static final String TYPE_PODCAST = "podcast"; public static final String TYPE_RADIO = "radio"; public static final String DOWNLOADED = "downloaded"; public static final String NEW = "new"; public String mediaItemName; public String listType; public MediaListItem() { super(); } public static ArrayList<MediaListItem> withMediaType(String mediaType) { ArrayList<MediaListItem> mediaListItems = new ArrayList<>();
SQLiteDatabase database = UpodsApplication.getDatabaseManager().getReadableDatabase();
KKorvin/uPods-android
app/src/main/java/com/chickenkiller/upods2/dialogs/DialogFragmentMessage.java
// Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IOperationFinishCallback.java // public interface IOperationFinishCallback { // // void operationFinished(); // }
import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.os.Bundle; import com.chickenkiller.upods2.R; import com.chickenkiller.upods2.interfaces.IOperationFinishCallback;
package com.chickenkiller.upods2.dialogs; /** * Created by Alon Zilberman on 8/8/15. */ public class DialogFragmentMessage extends DialogFragment { public static final String TAG = "df_simple_message";
// Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IOperationFinishCallback.java // public interface IOperationFinishCallback { // // void operationFinished(); // } // Path: app/src/main/java/com/chickenkiller/upods2/dialogs/DialogFragmentMessage.java import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.os.Bundle; import com.chickenkiller.upods2.R; import com.chickenkiller.upods2.interfaces.IOperationFinishCallback; package com.chickenkiller.upods2.dialogs; /** * Created by Alon Zilberman on 8/8/15. */ public class DialogFragmentMessage extends DialogFragment { public static final String TAG = "df_simple_message";
private IOperationFinishCallback onOkClicked;
KKorvin/uPods-android
app/src/main/java/com/chickenkiller/upods2/controllers/app/SimpleCacheManager.java
// Path: app/src/main/java/com/chickenkiller/upods2/utils/Logger.java // public class Logger { // // private static boolean isTurnedOn = false; // // public static void printInfo(String tag, String text) { // if (isTurnedOn) { // Log.i(tag, text); // } // } // // public static void printInfo(String tag, int text) { // if (isTurnedOn) { // Log.i(tag, String.valueOf(text)); // } // } // // public static void printInfo(String tag, boolean text) { // if (isTurnedOn) { // Log.i(tag, String.valueOf(text)); // } // } // // // public static void printError(String tag, String text) { // if (isTurnedOn) { // Log.i(tag, text); // } // } // }
import com.chickenkiller.upods2.utils.Logger; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException;
package com.chickenkiller.upods2.controllers.app; /** * Created by Alon Zilberman on 10/28/15. */ public class SimpleCacheManager { private static final String LOG_TAG = "SimpleCacheManager"; private static final String CACHE_FOLDER = "/simple_cache/"; private static final String FILE_NAME_SEPARATOR = "_"; private static final String FILE_NAME_SHORTIFY_REGEX = "([^a-z,^A-Z,0-9])|(https)|(http)"; private static final long DEFAULT_CACHE_PERIOD = 900000; //in ms private static SimpleCacheManager cacheManager; private SimpleCacheManager() { File cacheFolder = new File(UpodsApplication.getContext().getFilesDir() + CACHE_FOLDER); try { if (!cacheFolder.exists()) { cacheFolder.mkdirs();
// Path: app/src/main/java/com/chickenkiller/upods2/utils/Logger.java // public class Logger { // // private static boolean isTurnedOn = false; // // public static void printInfo(String tag, String text) { // if (isTurnedOn) { // Log.i(tag, text); // } // } // // public static void printInfo(String tag, int text) { // if (isTurnedOn) { // Log.i(tag, String.valueOf(text)); // } // } // // public static void printInfo(String tag, boolean text) { // if (isTurnedOn) { // Log.i(tag, String.valueOf(text)); // } // } // // // public static void printError(String tag, String text) { // if (isTurnedOn) { // Log.i(tag, text); // } // } // } // Path: app/src/main/java/com/chickenkiller/upods2/controllers/app/SimpleCacheManager.java import com.chickenkiller.upods2.utils.Logger; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; package com.chickenkiller.upods2.controllers.app; /** * Created by Alon Zilberman on 10/28/15. */ public class SimpleCacheManager { private static final String LOG_TAG = "SimpleCacheManager"; private static final String CACHE_FOLDER = "/simple_cache/"; private static final String FILE_NAME_SEPARATOR = "_"; private static final String FILE_NAME_SHORTIFY_REGEX = "([^a-z,^A-Z,0-9])|(https)|(http)"; private static final long DEFAULT_CACHE_PERIOD = 900000; //in ms private static SimpleCacheManager cacheManager; private SimpleCacheManager() { File cacheFolder = new File(UpodsApplication.getContext().getFilesDir() + CACHE_FOLDER); try { if (!cacheFolder.exists()) { cacheFolder.mkdirs();
Logger.printInfo(LOG_TAG, "Cache folder created: " + cacheFolder.getAbsolutePath());
KKorvin/uPods-android
app/src/main/java/com/chickenkiller/upods2/dialogs/DialogFragmentTrackInfo.java
// Path: app/src/main/java/com/chickenkiller/upods2/models/Track.java // public abstract class Track extends SQLModel { // // protected String title; // protected String audeoUrl; // // protected boolean isSelected; // // public Track() { // this.title = ""; // this.audeoUrl = ""; // this.isSelected = false; // } // // public abstract String getDuration(); // // public abstract String getDate(); // // public abstract String getTitle(); // // public abstract String getAudeoUrl(); // // public abstract String getSubTitle(); // // public abstract String getInfo(); // // public void setTitle(String title) { // this.title = title; // } // // public void setAudeoUrl(String audeoUrl) { // this.audeoUrl = audeoUrl; // } // }
import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.os.Environment; import android.view.LayoutInflater; import android.view.View; import android.webkit.WebView; import com.chickenkiller.upods2.R; import com.chickenkiller.upods2.models.Track;
package com.chickenkiller.upods2.dialogs; /** * Created by Alon Zilberman on 8/8/15. */ public class DialogFragmentTrackInfo extends DialogFragment { public static final String TAG = "df_track_info"; public boolean enableStream = true; private View.OnClickListener streamClickListener;
// Path: app/src/main/java/com/chickenkiller/upods2/models/Track.java // public abstract class Track extends SQLModel { // // protected String title; // protected String audeoUrl; // // protected boolean isSelected; // // public Track() { // this.title = ""; // this.audeoUrl = ""; // this.isSelected = false; // } // // public abstract String getDuration(); // // public abstract String getDate(); // // public abstract String getTitle(); // // public abstract String getAudeoUrl(); // // public abstract String getSubTitle(); // // public abstract String getInfo(); // // public void setTitle(String title) { // this.title = title; // } // // public void setAudeoUrl(String audeoUrl) { // this.audeoUrl = audeoUrl; // } // } // Path: app/src/main/java/com/chickenkiller/upods2/dialogs/DialogFragmentTrackInfo.java import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.os.Environment; import android.view.LayoutInflater; import android.view.View; import android.webkit.WebView; import com.chickenkiller.upods2.R; import com.chickenkiller.upods2.models.Track; package com.chickenkiller.upods2.dialogs; /** * Created by Alon Zilberman on 8/8/15. */ public class DialogFragmentTrackInfo extends DialogFragment { public static final String TAG = "df_track_info"; public boolean enableStream = true; private View.OnClickListener streamClickListener;
private Track track;
KKorvin/uPods-android
app/src/main/java/com/chickenkiller/upods2/models/MediaItem.java
// Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IMediaItemView.java // public interface IMediaItemView { // } // // Path: app/src/main/java/com/chickenkiller/upods2/utils/GlobalUtils.java // public class GlobalUtils { // // public static boolean safeTitleEquals(String title1, String title2) { // if (title1 == null || title2 == null) { // return false; // } // //replaceAll("[^a-z,A-Z,0-9,.,+,-, ,!,?,_,:,;,=]", ""); // title1 = title1.trim().replace("'",""); // title2 = title2.trim().replace("'","");; // return title1.equals(title2); // } // // public static String getCurrentDateTimeUS() { // DateFormat df = new SimpleDateFormat("d MMM, HH:mm", Locale.US); // String date = df.format(Calendar.getInstance().getTime()); // Logger.printInfo("Sync date", date); // return date; // } // // public static String parserDateToMonth(String date) { // try { // SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss Z", Locale.US); // Date inputDate = dateFormat.parse(date); // dateFormat = new SimpleDateFormat("MMM\ndd", Locale.US); // date = dateFormat.format(inputDate); // } catch (ParseException e) { // e.printStackTrace(); // } // return date; // } // // public static String getCleanFileName(String str) { // str = str.toLowerCase(); // return str.replaceAll("[^a-zA-Z0-9]+", "_"); // } // // public static boolean deleteDirectory(File path) { // if (path.exists()) { // File[] files = path.listFiles(); // if (files == null) { // return true; // } // for (int i = 0; i < files.length; i++) { // if (files[i].isDirectory()) { // deleteDirectory(files[i]); // } else { // files[i].delete(); // } // } // } // return (path.delete()); // } // // public static boolean isInternetConnected() { // ConnectivityManager cm = (ConnectivityManager) UpodsApplication.getContext().getSystemService(Context.CONNECTIVITY_SERVICE); // return cm.getActiveNetworkInfo() != null; // } // // /** // * Returns a list with all links contained in the input // */ // public static List<String> extractUrls(String text) { // String lines[] = text.split("\\s+"); // List<String> containedUrls = new ArrayList<String>(); // String urlRegex = "((https?|ftp|gopher|telnet|file):((//)|(\\\\))+[\\w\\d:#@%/;$()~_?\\+-=\\\\\\.&]*)"; // Pattern pattern = Pattern.compile(urlRegex, Pattern.CASE_INSENSITIVE); // // for (String line : lines) { // Matcher urlMatcher = pattern.matcher(line); // while (urlMatcher.find()) { // containedUrls.add(line.substring(urlMatcher.start(0), urlMatcher.end(0))); // } // } // return containedUrls; // } // // public static boolean isUrlReachable(String urlToCheck) { // try { // URL url = new URL(urlToCheck); // HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // connection.setConnectTimeout(1000); // int code = connection.getResponseCode(); // if (code == 200) { // return true; // } // } catch (Exception e) { // e.printStackTrace(); // } // return false; // } // // public static void rateApp(Context context) { // Uri uri = Uri.parse("market://details?id=" + context.getPackageName()); // Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri); // // goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_MULTIPLE_TASK); // try { // context.startActivity(goToMarket); // } catch (ActivityNotFoundException e) { // context.startActivity(new Intent(Intent.ACTION_VIEW, // Uri.parse("http://play.google.com/store/apps/details?id=" + context.getPackageName()))); // } // } // // public static boolean isPackageInstalled(String packagename) { // PackageManager pm = UpodsApplication.getContext().getPackageManager(); // try { // pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES); // return true; // } catch (PackageManager.NameNotFoundException e) { // return false; // } // } // // public static String upperCase(String str) { // StringBuilder rackingSystemSb = new StringBuilder(str.toLowerCase()); // rackingSystemSb.setCharAt(0, Character.toUpperCase(rackingSystemSb.charAt(0))); // str = rackingSystemSb.toString(); // return str; // } // // }
import com.chickenkiller.upods2.interfaces.IMediaItemView; import com.chickenkiller.upods2.utils.GlobalUtils; import java.util.ArrayList;
public String getBitrate() { return ""; } public void syncWithDB(){ } public void syncWithMediaItem(MediaItem updatedMediaItem) { this.id = updatedMediaItem.id; this.isSubscribed = updatedMediaItem.isSubscribed; this.isExistsInDb = updatedMediaItem.isExistsInDb; } public static boolean hasMediaItemWithName(ArrayList<? extends MediaItem> mediaItems, MediaItem mediaItemToCheck) { for (MediaItem mediaItem : mediaItems) { if (mediaItem.getName().equals(mediaItemToCheck.getName())) { return true; } } return false; } public static MediaItem getMediaItemByName(ArrayList<? extends MediaItem> mediaItems, MediaItem mediaItemTarget) { return getMediaItemByName(mediaItems, mediaItemTarget.getName()); } public static MediaItem getMediaItemByName(ArrayList<? extends MediaItem> mediaItems, String targetName) { for (MediaItem mediaItem : mediaItems) {
// Path: app/src/main/java/com/chickenkiller/upods2/interfaces/IMediaItemView.java // public interface IMediaItemView { // } // // Path: app/src/main/java/com/chickenkiller/upods2/utils/GlobalUtils.java // public class GlobalUtils { // // public static boolean safeTitleEquals(String title1, String title2) { // if (title1 == null || title2 == null) { // return false; // } // //replaceAll("[^a-z,A-Z,0-9,.,+,-, ,!,?,_,:,;,=]", ""); // title1 = title1.trim().replace("'",""); // title2 = title2.trim().replace("'","");; // return title1.equals(title2); // } // // public static String getCurrentDateTimeUS() { // DateFormat df = new SimpleDateFormat("d MMM, HH:mm", Locale.US); // String date = df.format(Calendar.getInstance().getTime()); // Logger.printInfo("Sync date", date); // return date; // } // // public static String parserDateToMonth(String date) { // try { // SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss Z", Locale.US); // Date inputDate = dateFormat.parse(date); // dateFormat = new SimpleDateFormat("MMM\ndd", Locale.US); // date = dateFormat.format(inputDate); // } catch (ParseException e) { // e.printStackTrace(); // } // return date; // } // // public static String getCleanFileName(String str) { // str = str.toLowerCase(); // return str.replaceAll("[^a-zA-Z0-9]+", "_"); // } // // public static boolean deleteDirectory(File path) { // if (path.exists()) { // File[] files = path.listFiles(); // if (files == null) { // return true; // } // for (int i = 0; i < files.length; i++) { // if (files[i].isDirectory()) { // deleteDirectory(files[i]); // } else { // files[i].delete(); // } // } // } // return (path.delete()); // } // // public static boolean isInternetConnected() { // ConnectivityManager cm = (ConnectivityManager) UpodsApplication.getContext().getSystemService(Context.CONNECTIVITY_SERVICE); // return cm.getActiveNetworkInfo() != null; // } // // /** // * Returns a list with all links contained in the input // */ // public static List<String> extractUrls(String text) { // String lines[] = text.split("\\s+"); // List<String> containedUrls = new ArrayList<String>(); // String urlRegex = "((https?|ftp|gopher|telnet|file):((//)|(\\\\))+[\\w\\d:#@%/;$()~_?\\+-=\\\\\\.&]*)"; // Pattern pattern = Pattern.compile(urlRegex, Pattern.CASE_INSENSITIVE); // // for (String line : lines) { // Matcher urlMatcher = pattern.matcher(line); // while (urlMatcher.find()) { // containedUrls.add(line.substring(urlMatcher.start(0), urlMatcher.end(0))); // } // } // return containedUrls; // } // // public static boolean isUrlReachable(String urlToCheck) { // try { // URL url = new URL(urlToCheck); // HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // connection.setConnectTimeout(1000); // int code = connection.getResponseCode(); // if (code == 200) { // return true; // } // } catch (Exception e) { // e.printStackTrace(); // } // return false; // } // // public static void rateApp(Context context) { // Uri uri = Uri.parse("market://details?id=" + context.getPackageName()); // Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri); // // goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_MULTIPLE_TASK); // try { // context.startActivity(goToMarket); // } catch (ActivityNotFoundException e) { // context.startActivity(new Intent(Intent.ACTION_VIEW, // Uri.parse("http://play.google.com/store/apps/details?id=" + context.getPackageName()))); // } // } // // public static boolean isPackageInstalled(String packagename) { // PackageManager pm = UpodsApplication.getContext().getPackageManager(); // try { // pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES); // return true; // } catch (PackageManager.NameNotFoundException e) { // return false; // } // } // // public static String upperCase(String str) { // StringBuilder rackingSystemSb = new StringBuilder(str.toLowerCase()); // rackingSystemSb.setCharAt(0, Character.toUpperCase(rackingSystemSb.charAt(0))); // str = rackingSystemSb.toString(); // return str; // } // // } // Path: app/src/main/java/com/chickenkiller/upods2/models/MediaItem.java import com.chickenkiller.upods2.interfaces.IMediaItemView; import com.chickenkiller.upods2.utils.GlobalUtils; import java.util.ArrayList; public String getBitrate() { return ""; } public void syncWithDB(){ } public void syncWithMediaItem(MediaItem updatedMediaItem) { this.id = updatedMediaItem.id; this.isSubscribed = updatedMediaItem.isSubscribed; this.isExistsInDb = updatedMediaItem.isExistsInDb; } public static boolean hasMediaItemWithName(ArrayList<? extends MediaItem> mediaItems, MediaItem mediaItemToCheck) { for (MediaItem mediaItem : mediaItems) { if (mediaItem.getName().equals(mediaItemToCheck.getName())) { return true; } } return false; } public static MediaItem getMediaItemByName(ArrayList<? extends MediaItem> mediaItems, MediaItem mediaItemTarget) { return getMediaItemByName(mediaItems, mediaItemTarget.getName()); } public static MediaItem getMediaItemByName(ArrayList<? extends MediaItem> mediaItems, String targetName) { for (MediaItem mediaItem : mediaItems) {
if (GlobalUtils.safeTitleEquals(mediaItem.getName(), targetName)) {
andrey7mel/android-step-by-step
app/src/main/java/com/andrey7mel/stepbystep/presenter/RepoListPresenter.java
// Path: app/src/main/java/com/andrey7mel/stepbystep/other/App.java // public class App extends Application { // // private static AppComponent component; // // public static AppComponent getComponent() { // return component; // } // // @Override // public void onCreate() { // super.onCreate(); // component = buildComponent(); // } // // protected AppComponent buildComponent() { // return DaggerAppComponent.builder() // .build(); // } // // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/mappers/RepoListMapper.java // public class RepoListMapper implements Func1<List<RepositoryDTO>, List<Repository>> { // // @Inject // public RepoListMapper() { // } // // @Override // public List<Repository> call(List<RepositoryDTO> repositoryDTOs) { // if (repositoryDTOs == null) { // return null; // } // List<Repository> repoList = Observable.from(repositoryDTOs) // .map(repoDTO -> new Repository(repoDTO.getName(), repoDTO.getOwner().getLogin())) // .toList() // .toBlocking() // .first(); // return repoList; // } // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/vo/Repository.java // public class Repository implements Serializable { // private String repoName; // private String ownerName; // // public Repository(String repoName, String ownerName) { // this.repoName = repoName; // this.ownerName = ownerName; // } // // public String getRepoName() { // return repoName; // } // // public void setRepoName(String repoName) { // this.repoName = repoName; // } // // public String getOwnerName() { // return ownerName; // } // // public void setOwnerName(String ownerName) { // this.ownerName = ownerName; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Repository that = (Repository) o; // // if (repoName != null ? !repoName.equals(that.repoName) : that.repoName != null) // return false; // return !(ownerName != null ? !ownerName.equals(that.ownerName) : that.ownerName != null); // // } // // @Override // public int hashCode() { // int result = repoName != null ? repoName.hashCode() : 0; // result = 31 * result + (ownerName != null ? ownerName.hashCode() : 0); // return result; // } // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/RepoListView.java // public interface RepoListView extends View { // // void showRepoList(List<Repository> vo); // // void showEmptyList(); // // String getUserName(); // // void startRepoInfoFragment(Repository repository); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/View.java // public interface View { // // void showError(String error); // // void showLoading(); // // void hideLoading(); // }
import android.os.Bundle; import android.text.TextUtils; import com.andrey7mel.stepbystep.other.App; import com.andrey7mel.stepbystep.presenter.mappers.RepoListMapper; import com.andrey7mel.stepbystep.presenter.vo.Repository; import com.andrey7mel.stepbystep.view.fragments.RepoListView; import com.andrey7mel.stepbystep.view.fragments.View; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import rx.Observer; import rx.Subscription;
package com.andrey7mel.stepbystep.presenter; public class RepoListPresenter extends BasePresenter { private static final String BUNDLE_REPO_LIST_KEY = "BUNDLE_REPO_LIST_KEY"; @Inject
// Path: app/src/main/java/com/andrey7mel/stepbystep/other/App.java // public class App extends Application { // // private static AppComponent component; // // public static AppComponent getComponent() { // return component; // } // // @Override // public void onCreate() { // super.onCreate(); // component = buildComponent(); // } // // protected AppComponent buildComponent() { // return DaggerAppComponent.builder() // .build(); // } // // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/mappers/RepoListMapper.java // public class RepoListMapper implements Func1<List<RepositoryDTO>, List<Repository>> { // // @Inject // public RepoListMapper() { // } // // @Override // public List<Repository> call(List<RepositoryDTO> repositoryDTOs) { // if (repositoryDTOs == null) { // return null; // } // List<Repository> repoList = Observable.from(repositoryDTOs) // .map(repoDTO -> new Repository(repoDTO.getName(), repoDTO.getOwner().getLogin())) // .toList() // .toBlocking() // .first(); // return repoList; // } // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/vo/Repository.java // public class Repository implements Serializable { // private String repoName; // private String ownerName; // // public Repository(String repoName, String ownerName) { // this.repoName = repoName; // this.ownerName = ownerName; // } // // public String getRepoName() { // return repoName; // } // // public void setRepoName(String repoName) { // this.repoName = repoName; // } // // public String getOwnerName() { // return ownerName; // } // // public void setOwnerName(String ownerName) { // this.ownerName = ownerName; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Repository that = (Repository) o; // // if (repoName != null ? !repoName.equals(that.repoName) : that.repoName != null) // return false; // return !(ownerName != null ? !ownerName.equals(that.ownerName) : that.ownerName != null); // // } // // @Override // public int hashCode() { // int result = repoName != null ? repoName.hashCode() : 0; // result = 31 * result + (ownerName != null ? ownerName.hashCode() : 0); // return result; // } // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/RepoListView.java // public interface RepoListView extends View { // // void showRepoList(List<Repository> vo); // // void showEmptyList(); // // String getUserName(); // // void startRepoInfoFragment(Repository repository); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/View.java // public interface View { // // void showError(String error); // // void showLoading(); // // void hideLoading(); // } // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/RepoListPresenter.java import android.os.Bundle; import android.text.TextUtils; import com.andrey7mel.stepbystep.other.App; import com.andrey7mel.stepbystep.presenter.mappers.RepoListMapper; import com.andrey7mel.stepbystep.presenter.vo.Repository; import com.andrey7mel.stepbystep.view.fragments.RepoListView; import com.andrey7mel.stepbystep.view.fragments.View; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import rx.Observer; import rx.Subscription; package com.andrey7mel.stepbystep.presenter; public class RepoListPresenter extends BasePresenter { private static final String BUNDLE_REPO_LIST_KEY = "BUNDLE_REPO_LIST_KEY"; @Inject
protected RepoListMapper repoListMapper;
andrey7mel/android-step-by-step
app/src/main/java/com/andrey7mel/stepbystep/presenter/RepoListPresenter.java
// Path: app/src/main/java/com/andrey7mel/stepbystep/other/App.java // public class App extends Application { // // private static AppComponent component; // // public static AppComponent getComponent() { // return component; // } // // @Override // public void onCreate() { // super.onCreate(); // component = buildComponent(); // } // // protected AppComponent buildComponent() { // return DaggerAppComponent.builder() // .build(); // } // // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/mappers/RepoListMapper.java // public class RepoListMapper implements Func1<List<RepositoryDTO>, List<Repository>> { // // @Inject // public RepoListMapper() { // } // // @Override // public List<Repository> call(List<RepositoryDTO> repositoryDTOs) { // if (repositoryDTOs == null) { // return null; // } // List<Repository> repoList = Observable.from(repositoryDTOs) // .map(repoDTO -> new Repository(repoDTO.getName(), repoDTO.getOwner().getLogin())) // .toList() // .toBlocking() // .first(); // return repoList; // } // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/vo/Repository.java // public class Repository implements Serializable { // private String repoName; // private String ownerName; // // public Repository(String repoName, String ownerName) { // this.repoName = repoName; // this.ownerName = ownerName; // } // // public String getRepoName() { // return repoName; // } // // public void setRepoName(String repoName) { // this.repoName = repoName; // } // // public String getOwnerName() { // return ownerName; // } // // public void setOwnerName(String ownerName) { // this.ownerName = ownerName; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Repository that = (Repository) o; // // if (repoName != null ? !repoName.equals(that.repoName) : that.repoName != null) // return false; // return !(ownerName != null ? !ownerName.equals(that.ownerName) : that.ownerName != null); // // } // // @Override // public int hashCode() { // int result = repoName != null ? repoName.hashCode() : 0; // result = 31 * result + (ownerName != null ? ownerName.hashCode() : 0); // return result; // } // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/RepoListView.java // public interface RepoListView extends View { // // void showRepoList(List<Repository> vo); // // void showEmptyList(); // // String getUserName(); // // void startRepoInfoFragment(Repository repository); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/View.java // public interface View { // // void showError(String error); // // void showLoading(); // // void hideLoading(); // }
import android.os.Bundle; import android.text.TextUtils; import com.andrey7mel.stepbystep.other.App; import com.andrey7mel.stepbystep.presenter.mappers.RepoListMapper; import com.andrey7mel.stepbystep.presenter.vo.Repository; import com.andrey7mel.stepbystep.view.fragments.RepoListView; import com.andrey7mel.stepbystep.view.fragments.View; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import rx.Observer; import rx.Subscription;
package com.andrey7mel.stepbystep.presenter; public class RepoListPresenter extends BasePresenter { private static final String BUNDLE_REPO_LIST_KEY = "BUNDLE_REPO_LIST_KEY"; @Inject protected RepoListMapper repoListMapper;
// Path: app/src/main/java/com/andrey7mel/stepbystep/other/App.java // public class App extends Application { // // private static AppComponent component; // // public static AppComponent getComponent() { // return component; // } // // @Override // public void onCreate() { // super.onCreate(); // component = buildComponent(); // } // // protected AppComponent buildComponent() { // return DaggerAppComponent.builder() // .build(); // } // // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/mappers/RepoListMapper.java // public class RepoListMapper implements Func1<List<RepositoryDTO>, List<Repository>> { // // @Inject // public RepoListMapper() { // } // // @Override // public List<Repository> call(List<RepositoryDTO> repositoryDTOs) { // if (repositoryDTOs == null) { // return null; // } // List<Repository> repoList = Observable.from(repositoryDTOs) // .map(repoDTO -> new Repository(repoDTO.getName(), repoDTO.getOwner().getLogin())) // .toList() // .toBlocking() // .first(); // return repoList; // } // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/vo/Repository.java // public class Repository implements Serializable { // private String repoName; // private String ownerName; // // public Repository(String repoName, String ownerName) { // this.repoName = repoName; // this.ownerName = ownerName; // } // // public String getRepoName() { // return repoName; // } // // public void setRepoName(String repoName) { // this.repoName = repoName; // } // // public String getOwnerName() { // return ownerName; // } // // public void setOwnerName(String ownerName) { // this.ownerName = ownerName; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Repository that = (Repository) o; // // if (repoName != null ? !repoName.equals(that.repoName) : that.repoName != null) // return false; // return !(ownerName != null ? !ownerName.equals(that.ownerName) : that.ownerName != null); // // } // // @Override // public int hashCode() { // int result = repoName != null ? repoName.hashCode() : 0; // result = 31 * result + (ownerName != null ? ownerName.hashCode() : 0); // return result; // } // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/RepoListView.java // public interface RepoListView extends View { // // void showRepoList(List<Repository> vo); // // void showEmptyList(); // // String getUserName(); // // void startRepoInfoFragment(Repository repository); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/View.java // public interface View { // // void showError(String error); // // void showLoading(); // // void hideLoading(); // } // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/RepoListPresenter.java import android.os.Bundle; import android.text.TextUtils; import com.andrey7mel.stepbystep.other.App; import com.andrey7mel.stepbystep.presenter.mappers.RepoListMapper; import com.andrey7mel.stepbystep.presenter.vo.Repository; import com.andrey7mel.stepbystep.view.fragments.RepoListView; import com.andrey7mel.stepbystep.view.fragments.View; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import rx.Observer; import rx.Subscription; package com.andrey7mel.stepbystep.presenter; public class RepoListPresenter extends BasePresenter { private static final String BUNDLE_REPO_LIST_KEY = "BUNDLE_REPO_LIST_KEY"; @Inject protected RepoListMapper repoListMapper;
private RepoListView view;
andrey7mel/android-step-by-step
app/src/main/java/com/andrey7mel/stepbystep/presenter/RepoListPresenter.java
// Path: app/src/main/java/com/andrey7mel/stepbystep/other/App.java // public class App extends Application { // // private static AppComponent component; // // public static AppComponent getComponent() { // return component; // } // // @Override // public void onCreate() { // super.onCreate(); // component = buildComponent(); // } // // protected AppComponent buildComponent() { // return DaggerAppComponent.builder() // .build(); // } // // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/mappers/RepoListMapper.java // public class RepoListMapper implements Func1<List<RepositoryDTO>, List<Repository>> { // // @Inject // public RepoListMapper() { // } // // @Override // public List<Repository> call(List<RepositoryDTO> repositoryDTOs) { // if (repositoryDTOs == null) { // return null; // } // List<Repository> repoList = Observable.from(repositoryDTOs) // .map(repoDTO -> new Repository(repoDTO.getName(), repoDTO.getOwner().getLogin())) // .toList() // .toBlocking() // .first(); // return repoList; // } // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/vo/Repository.java // public class Repository implements Serializable { // private String repoName; // private String ownerName; // // public Repository(String repoName, String ownerName) { // this.repoName = repoName; // this.ownerName = ownerName; // } // // public String getRepoName() { // return repoName; // } // // public void setRepoName(String repoName) { // this.repoName = repoName; // } // // public String getOwnerName() { // return ownerName; // } // // public void setOwnerName(String ownerName) { // this.ownerName = ownerName; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Repository that = (Repository) o; // // if (repoName != null ? !repoName.equals(that.repoName) : that.repoName != null) // return false; // return !(ownerName != null ? !ownerName.equals(that.ownerName) : that.ownerName != null); // // } // // @Override // public int hashCode() { // int result = repoName != null ? repoName.hashCode() : 0; // result = 31 * result + (ownerName != null ? ownerName.hashCode() : 0); // return result; // } // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/RepoListView.java // public interface RepoListView extends View { // // void showRepoList(List<Repository> vo); // // void showEmptyList(); // // String getUserName(); // // void startRepoInfoFragment(Repository repository); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/View.java // public interface View { // // void showError(String error); // // void showLoading(); // // void hideLoading(); // }
import android.os.Bundle; import android.text.TextUtils; import com.andrey7mel.stepbystep.other.App; import com.andrey7mel.stepbystep.presenter.mappers.RepoListMapper; import com.andrey7mel.stepbystep.presenter.vo.Repository; import com.andrey7mel.stepbystep.view.fragments.RepoListView; import com.andrey7mel.stepbystep.view.fragments.View; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import rx.Observer; import rx.Subscription;
package com.andrey7mel.stepbystep.presenter; public class RepoListPresenter extends BasePresenter { private static final String BUNDLE_REPO_LIST_KEY = "BUNDLE_REPO_LIST_KEY"; @Inject protected RepoListMapper repoListMapper; private RepoListView view;
// Path: app/src/main/java/com/andrey7mel/stepbystep/other/App.java // public class App extends Application { // // private static AppComponent component; // // public static AppComponent getComponent() { // return component; // } // // @Override // public void onCreate() { // super.onCreate(); // component = buildComponent(); // } // // protected AppComponent buildComponent() { // return DaggerAppComponent.builder() // .build(); // } // // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/mappers/RepoListMapper.java // public class RepoListMapper implements Func1<List<RepositoryDTO>, List<Repository>> { // // @Inject // public RepoListMapper() { // } // // @Override // public List<Repository> call(List<RepositoryDTO> repositoryDTOs) { // if (repositoryDTOs == null) { // return null; // } // List<Repository> repoList = Observable.from(repositoryDTOs) // .map(repoDTO -> new Repository(repoDTO.getName(), repoDTO.getOwner().getLogin())) // .toList() // .toBlocking() // .first(); // return repoList; // } // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/vo/Repository.java // public class Repository implements Serializable { // private String repoName; // private String ownerName; // // public Repository(String repoName, String ownerName) { // this.repoName = repoName; // this.ownerName = ownerName; // } // // public String getRepoName() { // return repoName; // } // // public void setRepoName(String repoName) { // this.repoName = repoName; // } // // public String getOwnerName() { // return ownerName; // } // // public void setOwnerName(String ownerName) { // this.ownerName = ownerName; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Repository that = (Repository) o; // // if (repoName != null ? !repoName.equals(that.repoName) : that.repoName != null) // return false; // return !(ownerName != null ? !ownerName.equals(that.ownerName) : that.ownerName != null); // // } // // @Override // public int hashCode() { // int result = repoName != null ? repoName.hashCode() : 0; // result = 31 * result + (ownerName != null ? ownerName.hashCode() : 0); // return result; // } // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/RepoListView.java // public interface RepoListView extends View { // // void showRepoList(List<Repository> vo); // // void showEmptyList(); // // String getUserName(); // // void startRepoInfoFragment(Repository repository); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/View.java // public interface View { // // void showError(String error); // // void showLoading(); // // void hideLoading(); // } // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/RepoListPresenter.java import android.os.Bundle; import android.text.TextUtils; import com.andrey7mel.stepbystep.other.App; import com.andrey7mel.stepbystep.presenter.mappers.RepoListMapper; import com.andrey7mel.stepbystep.presenter.vo.Repository; import com.andrey7mel.stepbystep.view.fragments.RepoListView; import com.andrey7mel.stepbystep.view.fragments.View; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import rx.Observer; import rx.Subscription; package com.andrey7mel.stepbystep.presenter; public class RepoListPresenter extends BasePresenter { private static final String BUNDLE_REPO_LIST_KEY = "BUNDLE_REPO_LIST_KEY"; @Inject protected RepoListMapper repoListMapper; private RepoListView view;
private List<Repository> repoList;
andrey7mel/android-step-by-step
app/src/main/java/com/andrey7mel/stepbystep/presenter/RepoListPresenter.java
// Path: app/src/main/java/com/andrey7mel/stepbystep/other/App.java // public class App extends Application { // // private static AppComponent component; // // public static AppComponent getComponent() { // return component; // } // // @Override // public void onCreate() { // super.onCreate(); // component = buildComponent(); // } // // protected AppComponent buildComponent() { // return DaggerAppComponent.builder() // .build(); // } // // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/mappers/RepoListMapper.java // public class RepoListMapper implements Func1<List<RepositoryDTO>, List<Repository>> { // // @Inject // public RepoListMapper() { // } // // @Override // public List<Repository> call(List<RepositoryDTO> repositoryDTOs) { // if (repositoryDTOs == null) { // return null; // } // List<Repository> repoList = Observable.from(repositoryDTOs) // .map(repoDTO -> new Repository(repoDTO.getName(), repoDTO.getOwner().getLogin())) // .toList() // .toBlocking() // .first(); // return repoList; // } // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/vo/Repository.java // public class Repository implements Serializable { // private String repoName; // private String ownerName; // // public Repository(String repoName, String ownerName) { // this.repoName = repoName; // this.ownerName = ownerName; // } // // public String getRepoName() { // return repoName; // } // // public void setRepoName(String repoName) { // this.repoName = repoName; // } // // public String getOwnerName() { // return ownerName; // } // // public void setOwnerName(String ownerName) { // this.ownerName = ownerName; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Repository that = (Repository) o; // // if (repoName != null ? !repoName.equals(that.repoName) : that.repoName != null) // return false; // return !(ownerName != null ? !ownerName.equals(that.ownerName) : that.ownerName != null); // // } // // @Override // public int hashCode() { // int result = repoName != null ? repoName.hashCode() : 0; // result = 31 * result + (ownerName != null ? ownerName.hashCode() : 0); // return result; // } // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/RepoListView.java // public interface RepoListView extends View { // // void showRepoList(List<Repository> vo); // // void showEmptyList(); // // String getUserName(); // // void startRepoInfoFragment(Repository repository); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/View.java // public interface View { // // void showError(String error); // // void showLoading(); // // void hideLoading(); // }
import android.os.Bundle; import android.text.TextUtils; import com.andrey7mel.stepbystep.other.App; import com.andrey7mel.stepbystep.presenter.mappers.RepoListMapper; import com.andrey7mel.stepbystep.presenter.vo.Repository; import com.andrey7mel.stepbystep.view.fragments.RepoListView; import com.andrey7mel.stepbystep.view.fragments.View; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import rx.Observer; import rx.Subscription;
package com.andrey7mel.stepbystep.presenter; public class RepoListPresenter extends BasePresenter { private static final String BUNDLE_REPO_LIST_KEY = "BUNDLE_REPO_LIST_KEY"; @Inject protected RepoListMapper repoListMapper; private RepoListView view; private List<Repository> repoList; // for DI @Inject public RepoListPresenter() { } public RepoListPresenter(RepoListView view) {
// Path: app/src/main/java/com/andrey7mel/stepbystep/other/App.java // public class App extends Application { // // private static AppComponent component; // // public static AppComponent getComponent() { // return component; // } // // @Override // public void onCreate() { // super.onCreate(); // component = buildComponent(); // } // // protected AppComponent buildComponent() { // return DaggerAppComponent.builder() // .build(); // } // // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/mappers/RepoListMapper.java // public class RepoListMapper implements Func1<List<RepositoryDTO>, List<Repository>> { // // @Inject // public RepoListMapper() { // } // // @Override // public List<Repository> call(List<RepositoryDTO> repositoryDTOs) { // if (repositoryDTOs == null) { // return null; // } // List<Repository> repoList = Observable.from(repositoryDTOs) // .map(repoDTO -> new Repository(repoDTO.getName(), repoDTO.getOwner().getLogin())) // .toList() // .toBlocking() // .first(); // return repoList; // } // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/vo/Repository.java // public class Repository implements Serializable { // private String repoName; // private String ownerName; // // public Repository(String repoName, String ownerName) { // this.repoName = repoName; // this.ownerName = ownerName; // } // // public String getRepoName() { // return repoName; // } // // public void setRepoName(String repoName) { // this.repoName = repoName; // } // // public String getOwnerName() { // return ownerName; // } // // public void setOwnerName(String ownerName) { // this.ownerName = ownerName; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Repository that = (Repository) o; // // if (repoName != null ? !repoName.equals(that.repoName) : that.repoName != null) // return false; // return !(ownerName != null ? !ownerName.equals(that.ownerName) : that.ownerName != null); // // } // // @Override // public int hashCode() { // int result = repoName != null ? repoName.hashCode() : 0; // result = 31 * result + (ownerName != null ? ownerName.hashCode() : 0); // return result; // } // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/RepoListView.java // public interface RepoListView extends View { // // void showRepoList(List<Repository> vo); // // void showEmptyList(); // // String getUserName(); // // void startRepoInfoFragment(Repository repository); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/View.java // public interface View { // // void showError(String error); // // void showLoading(); // // void hideLoading(); // } // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/RepoListPresenter.java import android.os.Bundle; import android.text.TextUtils; import com.andrey7mel.stepbystep.other.App; import com.andrey7mel.stepbystep.presenter.mappers.RepoListMapper; import com.andrey7mel.stepbystep.presenter.vo.Repository; import com.andrey7mel.stepbystep.view.fragments.RepoListView; import com.andrey7mel.stepbystep.view.fragments.View; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import rx.Observer; import rx.Subscription; package com.andrey7mel.stepbystep.presenter; public class RepoListPresenter extends BasePresenter { private static final String BUNDLE_REPO_LIST_KEY = "BUNDLE_REPO_LIST_KEY"; @Inject protected RepoListMapper repoListMapper; private RepoListView view; private List<Repository> repoList; // for DI @Inject public RepoListPresenter() { } public RepoListPresenter(RepoListView view) {
App.getComponent().inject(this);
andrey7mel/android-step-by-step
app/src/main/java/com/andrey7mel/stepbystep/presenter/RepoListPresenter.java
// Path: app/src/main/java/com/andrey7mel/stepbystep/other/App.java // public class App extends Application { // // private static AppComponent component; // // public static AppComponent getComponent() { // return component; // } // // @Override // public void onCreate() { // super.onCreate(); // component = buildComponent(); // } // // protected AppComponent buildComponent() { // return DaggerAppComponent.builder() // .build(); // } // // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/mappers/RepoListMapper.java // public class RepoListMapper implements Func1<List<RepositoryDTO>, List<Repository>> { // // @Inject // public RepoListMapper() { // } // // @Override // public List<Repository> call(List<RepositoryDTO> repositoryDTOs) { // if (repositoryDTOs == null) { // return null; // } // List<Repository> repoList = Observable.from(repositoryDTOs) // .map(repoDTO -> new Repository(repoDTO.getName(), repoDTO.getOwner().getLogin())) // .toList() // .toBlocking() // .first(); // return repoList; // } // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/vo/Repository.java // public class Repository implements Serializable { // private String repoName; // private String ownerName; // // public Repository(String repoName, String ownerName) { // this.repoName = repoName; // this.ownerName = ownerName; // } // // public String getRepoName() { // return repoName; // } // // public void setRepoName(String repoName) { // this.repoName = repoName; // } // // public String getOwnerName() { // return ownerName; // } // // public void setOwnerName(String ownerName) { // this.ownerName = ownerName; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Repository that = (Repository) o; // // if (repoName != null ? !repoName.equals(that.repoName) : that.repoName != null) // return false; // return !(ownerName != null ? !ownerName.equals(that.ownerName) : that.ownerName != null); // // } // // @Override // public int hashCode() { // int result = repoName != null ? repoName.hashCode() : 0; // result = 31 * result + (ownerName != null ? ownerName.hashCode() : 0); // return result; // } // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/RepoListView.java // public interface RepoListView extends View { // // void showRepoList(List<Repository> vo); // // void showEmptyList(); // // String getUserName(); // // void startRepoInfoFragment(Repository repository); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/View.java // public interface View { // // void showError(String error); // // void showLoading(); // // void hideLoading(); // }
import android.os.Bundle; import android.text.TextUtils; import com.andrey7mel.stepbystep.other.App; import com.andrey7mel.stepbystep.presenter.mappers.RepoListMapper; import com.andrey7mel.stepbystep.presenter.vo.Repository; import com.andrey7mel.stepbystep.view.fragments.RepoListView; import com.andrey7mel.stepbystep.view.fragments.View; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import rx.Observer; import rx.Subscription;
package com.andrey7mel.stepbystep.presenter; public class RepoListPresenter extends BasePresenter { private static final String BUNDLE_REPO_LIST_KEY = "BUNDLE_REPO_LIST_KEY"; @Inject protected RepoListMapper repoListMapper; private RepoListView view; private List<Repository> repoList; // for DI @Inject public RepoListPresenter() { } public RepoListPresenter(RepoListView view) { App.getComponent().inject(this); this.view = view; } @Override
// Path: app/src/main/java/com/andrey7mel/stepbystep/other/App.java // public class App extends Application { // // private static AppComponent component; // // public static AppComponent getComponent() { // return component; // } // // @Override // public void onCreate() { // super.onCreate(); // component = buildComponent(); // } // // protected AppComponent buildComponent() { // return DaggerAppComponent.builder() // .build(); // } // // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/mappers/RepoListMapper.java // public class RepoListMapper implements Func1<List<RepositoryDTO>, List<Repository>> { // // @Inject // public RepoListMapper() { // } // // @Override // public List<Repository> call(List<RepositoryDTO> repositoryDTOs) { // if (repositoryDTOs == null) { // return null; // } // List<Repository> repoList = Observable.from(repositoryDTOs) // .map(repoDTO -> new Repository(repoDTO.getName(), repoDTO.getOwner().getLogin())) // .toList() // .toBlocking() // .first(); // return repoList; // } // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/vo/Repository.java // public class Repository implements Serializable { // private String repoName; // private String ownerName; // // public Repository(String repoName, String ownerName) { // this.repoName = repoName; // this.ownerName = ownerName; // } // // public String getRepoName() { // return repoName; // } // // public void setRepoName(String repoName) { // this.repoName = repoName; // } // // public String getOwnerName() { // return ownerName; // } // // public void setOwnerName(String ownerName) { // this.ownerName = ownerName; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Repository that = (Repository) o; // // if (repoName != null ? !repoName.equals(that.repoName) : that.repoName != null) // return false; // return !(ownerName != null ? !ownerName.equals(that.ownerName) : that.ownerName != null); // // } // // @Override // public int hashCode() { // int result = repoName != null ? repoName.hashCode() : 0; // result = 31 * result + (ownerName != null ? ownerName.hashCode() : 0); // return result; // } // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/RepoListView.java // public interface RepoListView extends View { // // void showRepoList(List<Repository> vo); // // void showEmptyList(); // // String getUserName(); // // void startRepoInfoFragment(Repository repository); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/View.java // public interface View { // // void showError(String error); // // void showLoading(); // // void hideLoading(); // } // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/RepoListPresenter.java import android.os.Bundle; import android.text.TextUtils; import com.andrey7mel.stepbystep.other.App; import com.andrey7mel.stepbystep.presenter.mappers.RepoListMapper; import com.andrey7mel.stepbystep.presenter.vo.Repository; import com.andrey7mel.stepbystep.view.fragments.RepoListView; import com.andrey7mel.stepbystep.view.fragments.View; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import rx.Observer; import rx.Subscription; package com.andrey7mel.stepbystep.presenter; public class RepoListPresenter extends BasePresenter { private static final String BUNDLE_REPO_LIST_KEY = "BUNDLE_REPO_LIST_KEY"; @Inject protected RepoListMapper repoListMapper; private RepoListView view; private List<Repository> repoList; // for DI @Inject public RepoListPresenter() { } public RepoListPresenter(RepoListView view) { App.getComponent().inject(this); this.view = view; } @Override
protected View getView() {
andrey7mel/android-step-by-step
app/src/test/java/com/andrey7mel/stepbystep/integration/other/IntegrationApiModule.java
// Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiInterface.java // public interface ApiInterface { // // @GET("/users/{user}/repos") // Observable<List<RepositoryDTO>> getRepositories(@Path("user") String user); // // @GET("/repos/{owner}/{repo}/contributors") // Observable<List<ContributorDTO>> getContributors(@Path("owner") String owner, @Path("repo") String repo); // // @GET("/repos/{owner}/{repo}/branches") // Observable<List<BranchDTO>> getBranches(@Path("owner") String owner, @Path("repo") String repo); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiModule.java // public final class ApiModule { // // private static final boolean ENABLE_LOG = true; // // private static final boolean ENABLE_AUTH = false; // private static final String AUTH_64 = "***"; // // private ApiModule() { // } // // public static ApiInterface getApiInterface(String url) { // // OkHttpClient httpClient = new OkHttpClient(); // // if (ENABLE_AUTH) { // httpClient.interceptors().add(chain -> { // Request original = chain.request(); // Request request = original.newBuilder() // .header("Authorization", "Basic " + AUTH_64) // .method(original.method(), original.body()) // .build(); // // return chain.proceed(request); // }); // } // // if (ENABLE_LOG) { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // httpClient.interceptors().add(interceptor); // } // // Retrofit.Builder builder = new Retrofit.Builder(). // baseUrl(url) // .addConverterFactory(GsonConverterFactory.create()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()); // // builder.client(httpClient); // // ApiInterface apiInterface = builder.build().create(ApiInterface.class); // return apiInterface; // } // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/TestConst.java // public class TestConst { // public static final String TEST_OWNER = "TEST_OWNER"; // public static final String TEST_REPO = "TEST_REPO"; // public static final String TEST_ERROR = "TEST_ERROR"; // public static final String ERROR_RESPONSE_500 = "HTTP 500 OK"; // public static final String ERROR_RESPONSE_404 = "HTTP 404 OK"; // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/TestUtils.java // public class TestUtils { // // private Gson gson = new GsonBuilder() // .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create(); // // public void log(String log) { // System.out.println(log); // } // // public Gson getGson() { // return gson; // } // // // public <T> T readJson(String fileName, Class<T> inClass) { // return gson.fromJson(readString(fileName), inClass); // } // // public String readString(String fileName) { // InputStream stream = getClass().getClassLoader().getResourceAsStream(fileName); // try { // int size = stream.available(); // byte[] buffer = new byte[size]; // int result = stream.read(buffer); // return new String(buffer, "utf8"); // } catch (IOException e) { // e.printStackTrace(); // return null; // } finally { // try { // if (stream != null) { // stream.close(); // } // } catch (IOException e) { // e.printStackTrace(); // } // } // // } // // }
import com.andrey7mel.stepbystep.model.api.ApiInterface; import com.andrey7mel.stepbystep.model.api.ApiModule; import com.andrey7mel.stepbystep.other.TestConst; import com.andrey7mel.stepbystep.other.TestUtils; import com.squareup.okhttp.HttpUrl; import com.squareup.okhttp.mockwebserver.Dispatcher; import com.squareup.okhttp.mockwebserver.MockResponse; import com.squareup.okhttp.mockwebserver.MockWebServer; import com.squareup.okhttp.mockwebserver.RecordedRequest; import java.io.IOException;
package com.andrey7mel.stepbystep.integration.other; public class IntegrationApiModule { public ApiInterface getApiInterface(MockWebServer mockWebServer) throws IOException { mockWebServer.start();
// Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiInterface.java // public interface ApiInterface { // // @GET("/users/{user}/repos") // Observable<List<RepositoryDTO>> getRepositories(@Path("user") String user); // // @GET("/repos/{owner}/{repo}/contributors") // Observable<List<ContributorDTO>> getContributors(@Path("owner") String owner, @Path("repo") String repo); // // @GET("/repos/{owner}/{repo}/branches") // Observable<List<BranchDTO>> getBranches(@Path("owner") String owner, @Path("repo") String repo); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiModule.java // public final class ApiModule { // // private static final boolean ENABLE_LOG = true; // // private static final boolean ENABLE_AUTH = false; // private static final String AUTH_64 = "***"; // // private ApiModule() { // } // // public static ApiInterface getApiInterface(String url) { // // OkHttpClient httpClient = new OkHttpClient(); // // if (ENABLE_AUTH) { // httpClient.interceptors().add(chain -> { // Request original = chain.request(); // Request request = original.newBuilder() // .header("Authorization", "Basic " + AUTH_64) // .method(original.method(), original.body()) // .build(); // // return chain.proceed(request); // }); // } // // if (ENABLE_LOG) { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // httpClient.interceptors().add(interceptor); // } // // Retrofit.Builder builder = new Retrofit.Builder(). // baseUrl(url) // .addConverterFactory(GsonConverterFactory.create()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()); // // builder.client(httpClient); // // ApiInterface apiInterface = builder.build().create(ApiInterface.class); // return apiInterface; // } // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/TestConst.java // public class TestConst { // public static final String TEST_OWNER = "TEST_OWNER"; // public static final String TEST_REPO = "TEST_REPO"; // public static final String TEST_ERROR = "TEST_ERROR"; // public static final String ERROR_RESPONSE_500 = "HTTP 500 OK"; // public static final String ERROR_RESPONSE_404 = "HTTP 404 OK"; // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/TestUtils.java // public class TestUtils { // // private Gson gson = new GsonBuilder() // .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create(); // // public void log(String log) { // System.out.println(log); // } // // public Gson getGson() { // return gson; // } // // // public <T> T readJson(String fileName, Class<T> inClass) { // return gson.fromJson(readString(fileName), inClass); // } // // public String readString(String fileName) { // InputStream stream = getClass().getClassLoader().getResourceAsStream(fileName); // try { // int size = stream.available(); // byte[] buffer = new byte[size]; // int result = stream.read(buffer); // return new String(buffer, "utf8"); // } catch (IOException e) { // e.printStackTrace(); // return null; // } finally { // try { // if (stream != null) { // stream.close(); // } // } catch (IOException e) { // e.printStackTrace(); // } // } // // } // // } // Path: app/src/test/java/com/andrey7mel/stepbystep/integration/other/IntegrationApiModule.java import com.andrey7mel.stepbystep.model.api.ApiInterface; import com.andrey7mel.stepbystep.model.api.ApiModule; import com.andrey7mel.stepbystep.other.TestConst; import com.andrey7mel.stepbystep.other.TestUtils; import com.squareup.okhttp.HttpUrl; import com.squareup.okhttp.mockwebserver.Dispatcher; import com.squareup.okhttp.mockwebserver.MockResponse; import com.squareup.okhttp.mockwebserver.MockWebServer; import com.squareup.okhttp.mockwebserver.RecordedRequest; import java.io.IOException; package com.andrey7mel.stepbystep.integration.other; public class IntegrationApiModule { public ApiInterface getApiInterface(MockWebServer mockWebServer) throws IOException { mockWebServer.start();
TestUtils testUtils = new TestUtils();
andrey7mel/android-step-by-step
app/src/test/java/com/andrey7mel/stepbystep/integration/other/IntegrationApiModule.java
// Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiInterface.java // public interface ApiInterface { // // @GET("/users/{user}/repos") // Observable<List<RepositoryDTO>> getRepositories(@Path("user") String user); // // @GET("/repos/{owner}/{repo}/contributors") // Observable<List<ContributorDTO>> getContributors(@Path("owner") String owner, @Path("repo") String repo); // // @GET("/repos/{owner}/{repo}/branches") // Observable<List<BranchDTO>> getBranches(@Path("owner") String owner, @Path("repo") String repo); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiModule.java // public final class ApiModule { // // private static final boolean ENABLE_LOG = true; // // private static final boolean ENABLE_AUTH = false; // private static final String AUTH_64 = "***"; // // private ApiModule() { // } // // public static ApiInterface getApiInterface(String url) { // // OkHttpClient httpClient = new OkHttpClient(); // // if (ENABLE_AUTH) { // httpClient.interceptors().add(chain -> { // Request original = chain.request(); // Request request = original.newBuilder() // .header("Authorization", "Basic " + AUTH_64) // .method(original.method(), original.body()) // .build(); // // return chain.proceed(request); // }); // } // // if (ENABLE_LOG) { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // httpClient.interceptors().add(interceptor); // } // // Retrofit.Builder builder = new Retrofit.Builder(). // baseUrl(url) // .addConverterFactory(GsonConverterFactory.create()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()); // // builder.client(httpClient); // // ApiInterface apiInterface = builder.build().create(ApiInterface.class); // return apiInterface; // } // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/TestConst.java // public class TestConst { // public static final String TEST_OWNER = "TEST_OWNER"; // public static final String TEST_REPO = "TEST_REPO"; // public static final String TEST_ERROR = "TEST_ERROR"; // public static final String ERROR_RESPONSE_500 = "HTTP 500 OK"; // public static final String ERROR_RESPONSE_404 = "HTTP 404 OK"; // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/TestUtils.java // public class TestUtils { // // private Gson gson = new GsonBuilder() // .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create(); // // public void log(String log) { // System.out.println(log); // } // // public Gson getGson() { // return gson; // } // // // public <T> T readJson(String fileName, Class<T> inClass) { // return gson.fromJson(readString(fileName), inClass); // } // // public String readString(String fileName) { // InputStream stream = getClass().getClassLoader().getResourceAsStream(fileName); // try { // int size = stream.available(); // byte[] buffer = new byte[size]; // int result = stream.read(buffer); // return new String(buffer, "utf8"); // } catch (IOException e) { // e.printStackTrace(); // return null; // } finally { // try { // if (stream != null) { // stream.close(); // } // } catch (IOException e) { // e.printStackTrace(); // } // } // // } // // }
import com.andrey7mel.stepbystep.model.api.ApiInterface; import com.andrey7mel.stepbystep.model.api.ApiModule; import com.andrey7mel.stepbystep.other.TestConst; import com.andrey7mel.stepbystep.other.TestUtils; import com.squareup.okhttp.HttpUrl; import com.squareup.okhttp.mockwebserver.Dispatcher; import com.squareup.okhttp.mockwebserver.MockResponse; import com.squareup.okhttp.mockwebserver.MockWebServer; import com.squareup.okhttp.mockwebserver.RecordedRequest; import java.io.IOException;
package com.andrey7mel.stepbystep.integration.other; public class IntegrationApiModule { public ApiInterface getApiInterface(MockWebServer mockWebServer) throws IOException { mockWebServer.start(); TestUtils testUtils = new TestUtils(); final Dispatcher dispatcher = new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
// Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiInterface.java // public interface ApiInterface { // // @GET("/users/{user}/repos") // Observable<List<RepositoryDTO>> getRepositories(@Path("user") String user); // // @GET("/repos/{owner}/{repo}/contributors") // Observable<List<ContributorDTO>> getContributors(@Path("owner") String owner, @Path("repo") String repo); // // @GET("/repos/{owner}/{repo}/branches") // Observable<List<BranchDTO>> getBranches(@Path("owner") String owner, @Path("repo") String repo); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiModule.java // public final class ApiModule { // // private static final boolean ENABLE_LOG = true; // // private static final boolean ENABLE_AUTH = false; // private static final String AUTH_64 = "***"; // // private ApiModule() { // } // // public static ApiInterface getApiInterface(String url) { // // OkHttpClient httpClient = new OkHttpClient(); // // if (ENABLE_AUTH) { // httpClient.interceptors().add(chain -> { // Request original = chain.request(); // Request request = original.newBuilder() // .header("Authorization", "Basic " + AUTH_64) // .method(original.method(), original.body()) // .build(); // // return chain.proceed(request); // }); // } // // if (ENABLE_LOG) { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // httpClient.interceptors().add(interceptor); // } // // Retrofit.Builder builder = new Retrofit.Builder(). // baseUrl(url) // .addConverterFactory(GsonConverterFactory.create()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()); // // builder.client(httpClient); // // ApiInterface apiInterface = builder.build().create(ApiInterface.class); // return apiInterface; // } // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/TestConst.java // public class TestConst { // public static final String TEST_OWNER = "TEST_OWNER"; // public static final String TEST_REPO = "TEST_REPO"; // public static final String TEST_ERROR = "TEST_ERROR"; // public static final String ERROR_RESPONSE_500 = "HTTP 500 OK"; // public static final String ERROR_RESPONSE_404 = "HTTP 404 OK"; // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/TestUtils.java // public class TestUtils { // // private Gson gson = new GsonBuilder() // .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create(); // // public void log(String log) { // System.out.println(log); // } // // public Gson getGson() { // return gson; // } // // // public <T> T readJson(String fileName, Class<T> inClass) { // return gson.fromJson(readString(fileName), inClass); // } // // public String readString(String fileName) { // InputStream stream = getClass().getClassLoader().getResourceAsStream(fileName); // try { // int size = stream.available(); // byte[] buffer = new byte[size]; // int result = stream.read(buffer); // return new String(buffer, "utf8"); // } catch (IOException e) { // e.printStackTrace(); // return null; // } finally { // try { // if (stream != null) { // stream.close(); // } // } catch (IOException e) { // e.printStackTrace(); // } // } // // } // // } // Path: app/src/test/java/com/andrey7mel/stepbystep/integration/other/IntegrationApiModule.java import com.andrey7mel.stepbystep.model.api.ApiInterface; import com.andrey7mel.stepbystep.model.api.ApiModule; import com.andrey7mel.stepbystep.other.TestConst; import com.andrey7mel.stepbystep.other.TestUtils; import com.squareup.okhttp.HttpUrl; import com.squareup.okhttp.mockwebserver.Dispatcher; import com.squareup.okhttp.mockwebserver.MockResponse; import com.squareup.okhttp.mockwebserver.MockWebServer; import com.squareup.okhttp.mockwebserver.RecordedRequest; import java.io.IOException; package com.andrey7mel.stepbystep.integration.other; public class IntegrationApiModule { public ApiInterface getApiInterface(MockWebServer mockWebServer) throws IOException { mockWebServer.start(); TestUtils testUtils = new TestUtils(); final Dispatcher dispatcher = new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
if (request.getPath().equals("/users/" + TestConst.TEST_OWNER + "/repos")) {
andrey7mel/android-step-by-step
app/src/test/java/com/andrey7mel/stepbystep/integration/other/IntegrationApiModule.java
// Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiInterface.java // public interface ApiInterface { // // @GET("/users/{user}/repos") // Observable<List<RepositoryDTO>> getRepositories(@Path("user") String user); // // @GET("/repos/{owner}/{repo}/contributors") // Observable<List<ContributorDTO>> getContributors(@Path("owner") String owner, @Path("repo") String repo); // // @GET("/repos/{owner}/{repo}/branches") // Observable<List<BranchDTO>> getBranches(@Path("owner") String owner, @Path("repo") String repo); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiModule.java // public final class ApiModule { // // private static final boolean ENABLE_LOG = true; // // private static final boolean ENABLE_AUTH = false; // private static final String AUTH_64 = "***"; // // private ApiModule() { // } // // public static ApiInterface getApiInterface(String url) { // // OkHttpClient httpClient = new OkHttpClient(); // // if (ENABLE_AUTH) { // httpClient.interceptors().add(chain -> { // Request original = chain.request(); // Request request = original.newBuilder() // .header("Authorization", "Basic " + AUTH_64) // .method(original.method(), original.body()) // .build(); // // return chain.proceed(request); // }); // } // // if (ENABLE_LOG) { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // httpClient.interceptors().add(interceptor); // } // // Retrofit.Builder builder = new Retrofit.Builder(). // baseUrl(url) // .addConverterFactory(GsonConverterFactory.create()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()); // // builder.client(httpClient); // // ApiInterface apiInterface = builder.build().create(ApiInterface.class); // return apiInterface; // } // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/TestConst.java // public class TestConst { // public static final String TEST_OWNER = "TEST_OWNER"; // public static final String TEST_REPO = "TEST_REPO"; // public static final String TEST_ERROR = "TEST_ERROR"; // public static final String ERROR_RESPONSE_500 = "HTTP 500 OK"; // public static final String ERROR_RESPONSE_404 = "HTTP 404 OK"; // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/TestUtils.java // public class TestUtils { // // private Gson gson = new GsonBuilder() // .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create(); // // public void log(String log) { // System.out.println(log); // } // // public Gson getGson() { // return gson; // } // // // public <T> T readJson(String fileName, Class<T> inClass) { // return gson.fromJson(readString(fileName), inClass); // } // // public String readString(String fileName) { // InputStream stream = getClass().getClassLoader().getResourceAsStream(fileName); // try { // int size = stream.available(); // byte[] buffer = new byte[size]; // int result = stream.read(buffer); // return new String(buffer, "utf8"); // } catch (IOException e) { // e.printStackTrace(); // return null; // } finally { // try { // if (stream != null) { // stream.close(); // } // } catch (IOException e) { // e.printStackTrace(); // } // } // // } // // }
import com.andrey7mel.stepbystep.model.api.ApiInterface; import com.andrey7mel.stepbystep.model.api.ApiModule; import com.andrey7mel.stepbystep.other.TestConst; import com.andrey7mel.stepbystep.other.TestUtils; import com.squareup.okhttp.HttpUrl; import com.squareup.okhttp.mockwebserver.Dispatcher; import com.squareup.okhttp.mockwebserver.MockResponse; import com.squareup.okhttp.mockwebserver.MockWebServer; import com.squareup.okhttp.mockwebserver.RecordedRequest; import java.io.IOException;
package com.andrey7mel.stepbystep.integration.other; public class IntegrationApiModule { public ApiInterface getApiInterface(MockWebServer mockWebServer) throws IOException { mockWebServer.start(); TestUtils testUtils = new TestUtils(); final Dispatcher dispatcher = new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException { if (request.getPath().equals("/users/" + TestConst.TEST_OWNER + "/repos")) { return new MockResponse().setResponseCode(200) .setBody(testUtils.readString("json/repos.json")); } else if (request.getPath().equals("/repos/" + TestConst.TEST_OWNER + "/" + TestConst.TEST_REPO + "/branches")) { return new MockResponse().setResponseCode(200) .setBody(testUtils.readString("json/branches.json")); } else if (request.getPath().equals("/repos/" + TestConst.TEST_OWNER + "/" + TestConst.TEST_REPO + "/contributors")) { return new MockResponse().setResponseCode(200) .setBody(testUtils.readString("json/contributors.json")); } return new MockResponse().setResponseCode(404); } }; mockWebServer.setDispatcher(dispatcher); HttpUrl baseUrl = mockWebServer.url("/");
// Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiInterface.java // public interface ApiInterface { // // @GET("/users/{user}/repos") // Observable<List<RepositoryDTO>> getRepositories(@Path("user") String user); // // @GET("/repos/{owner}/{repo}/contributors") // Observable<List<ContributorDTO>> getContributors(@Path("owner") String owner, @Path("repo") String repo); // // @GET("/repos/{owner}/{repo}/branches") // Observable<List<BranchDTO>> getBranches(@Path("owner") String owner, @Path("repo") String repo); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiModule.java // public final class ApiModule { // // private static final boolean ENABLE_LOG = true; // // private static final boolean ENABLE_AUTH = false; // private static final String AUTH_64 = "***"; // // private ApiModule() { // } // // public static ApiInterface getApiInterface(String url) { // // OkHttpClient httpClient = new OkHttpClient(); // // if (ENABLE_AUTH) { // httpClient.interceptors().add(chain -> { // Request original = chain.request(); // Request request = original.newBuilder() // .header("Authorization", "Basic " + AUTH_64) // .method(original.method(), original.body()) // .build(); // // return chain.proceed(request); // }); // } // // if (ENABLE_LOG) { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // httpClient.interceptors().add(interceptor); // } // // Retrofit.Builder builder = new Retrofit.Builder(). // baseUrl(url) // .addConverterFactory(GsonConverterFactory.create()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()); // // builder.client(httpClient); // // ApiInterface apiInterface = builder.build().create(ApiInterface.class); // return apiInterface; // } // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/TestConst.java // public class TestConst { // public static final String TEST_OWNER = "TEST_OWNER"; // public static final String TEST_REPO = "TEST_REPO"; // public static final String TEST_ERROR = "TEST_ERROR"; // public static final String ERROR_RESPONSE_500 = "HTTP 500 OK"; // public static final String ERROR_RESPONSE_404 = "HTTP 404 OK"; // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/TestUtils.java // public class TestUtils { // // private Gson gson = new GsonBuilder() // .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create(); // // public void log(String log) { // System.out.println(log); // } // // public Gson getGson() { // return gson; // } // // // public <T> T readJson(String fileName, Class<T> inClass) { // return gson.fromJson(readString(fileName), inClass); // } // // public String readString(String fileName) { // InputStream stream = getClass().getClassLoader().getResourceAsStream(fileName); // try { // int size = stream.available(); // byte[] buffer = new byte[size]; // int result = stream.read(buffer); // return new String(buffer, "utf8"); // } catch (IOException e) { // e.printStackTrace(); // return null; // } finally { // try { // if (stream != null) { // stream.close(); // } // } catch (IOException e) { // e.printStackTrace(); // } // } // // } // // } // Path: app/src/test/java/com/andrey7mel/stepbystep/integration/other/IntegrationApiModule.java import com.andrey7mel.stepbystep.model.api.ApiInterface; import com.andrey7mel.stepbystep.model.api.ApiModule; import com.andrey7mel.stepbystep.other.TestConst; import com.andrey7mel.stepbystep.other.TestUtils; import com.squareup.okhttp.HttpUrl; import com.squareup.okhttp.mockwebserver.Dispatcher; import com.squareup.okhttp.mockwebserver.MockResponse; import com.squareup.okhttp.mockwebserver.MockWebServer; import com.squareup.okhttp.mockwebserver.RecordedRequest; import java.io.IOException; package com.andrey7mel.stepbystep.integration.other; public class IntegrationApiModule { public ApiInterface getApiInterface(MockWebServer mockWebServer) throws IOException { mockWebServer.start(); TestUtils testUtils = new TestUtils(); final Dispatcher dispatcher = new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException { if (request.getPath().equals("/users/" + TestConst.TEST_OWNER + "/repos")) { return new MockResponse().setResponseCode(200) .setBody(testUtils.readString("json/repos.json")); } else if (request.getPath().equals("/repos/" + TestConst.TEST_OWNER + "/" + TestConst.TEST_REPO + "/branches")) { return new MockResponse().setResponseCode(200) .setBody(testUtils.readString("json/branches.json")); } else if (request.getPath().equals("/repos/" + TestConst.TEST_OWNER + "/" + TestConst.TEST_REPO + "/contributors")) { return new MockResponse().setResponseCode(200) .setBody(testUtils.readString("json/contributors.json")); } return new MockResponse().setResponseCode(404); } }; mockWebServer.setDispatcher(dispatcher); HttpUrl baseUrl = mockWebServer.url("/");
return ApiModule.getApiInterface(baseUrl.toString());
andrey7mel/android-step-by-step
app/src/main/java/com/andrey7mel/stepbystep/other/di/view/ViewComponent.java
// Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/RepoListFragment.java // public class RepoListFragment extends BaseFragment implements RepoListView { // // @Bind(R.id.recycler_view) // protected RecyclerView recyclerView; // // @Bind(R.id.edit_text) // protected EditText editText; // // @Bind(R.id.button_search) // protected Button searchButton; // // @Inject // protected RepoListPresenter presenter; // // private RepoListAdapter adapter; // // private ActivityCallback activityCallback; // // private ViewComponent viewComponent; // // @OnClick(R.id.button_search) // public void onClickSearch(View v) { // if (presenter != null) { // presenter.onSearchButtonClick(); // } // } // // @Override // public void onAttach(Activity activity) { // super.onAttach(activity); // // try { // activityCallback = (ActivityCallback) activity; // } catch (ClassCastException e) { // throw new ClassCastException(activity.toString() // + " must implement activityCallback"); // } // } // // @Override // public void onCreate(@Nullable Bundle savedInstanceState) { // if (viewComponent == null) { // viewComponent = DaggerViewComponent.builder() // .viewDynamicModule(new ViewDynamicModule(this)) // .build(); // } // viewComponent.inject(this); // super.onCreate(savedInstanceState); // } // // public void setViewComponent(ViewComponent viewComponent) { // this.viewComponent = viewComponent; // } // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = inflater.inflate(R.layout.fragment_repo_list, container, false); // ButterKnife.bind(this, view); // // LinearLayoutManager llm = new LinearLayoutManager(getContext()); // recyclerView.setLayoutManager(llm); // adapter = new RepoListAdapter(new ArrayList<>(), presenter); // recyclerView.setAdapter(adapter); // // presenter.onCreateView(savedInstanceState); // // return view; // } // // private void makeToast(String text) { // Snackbar.make(recyclerView, text, Snackbar.LENGTH_LONG).show(); // } // // @Override // protected BasePresenter getPresenter() { // return presenter; // } // // // @Override // public void showError(String error) { // makeToast(error); // } // // @Override // public void showRepoList(List<Repository> repoList) { // adapter.setRepoList(repoList); // } // // @Override // public void showEmptyList() { // makeToast(getActivity().getString(R.string.empty_list)); // } // // @Override // public String getUserName() { // return editText.getText().toString(); // } // // @Override // public void startRepoInfoFragment(Repository repository) { // activityCallback.startRepoInfoFragment(repository); // } // // @Override // public void onSaveInstanceState(Bundle outState) { // super.onSaveInstanceState(outState); // presenter.onSaveInstanceState(outState); // } // // }
import com.andrey7mel.stepbystep.view.fragments.RepoListFragment; import javax.inject.Singleton; import dagger.Component;
package com.andrey7mel.stepbystep.other.di.view; @Singleton @Component(modules = {ViewDynamicModule.class}) public interface ViewComponent {
// Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/RepoListFragment.java // public class RepoListFragment extends BaseFragment implements RepoListView { // // @Bind(R.id.recycler_view) // protected RecyclerView recyclerView; // // @Bind(R.id.edit_text) // protected EditText editText; // // @Bind(R.id.button_search) // protected Button searchButton; // // @Inject // protected RepoListPresenter presenter; // // private RepoListAdapter adapter; // // private ActivityCallback activityCallback; // // private ViewComponent viewComponent; // // @OnClick(R.id.button_search) // public void onClickSearch(View v) { // if (presenter != null) { // presenter.onSearchButtonClick(); // } // } // // @Override // public void onAttach(Activity activity) { // super.onAttach(activity); // // try { // activityCallback = (ActivityCallback) activity; // } catch (ClassCastException e) { // throw new ClassCastException(activity.toString() // + " must implement activityCallback"); // } // } // // @Override // public void onCreate(@Nullable Bundle savedInstanceState) { // if (viewComponent == null) { // viewComponent = DaggerViewComponent.builder() // .viewDynamicModule(new ViewDynamicModule(this)) // .build(); // } // viewComponent.inject(this); // super.onCreate(savedInstanceState); // } // // public void setViewComponent(ViewComponent viewComponent) { // this.viewComponent = viewComponent; // } // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = inflater.inflate(R.layout.fragment_repo_list, container, false); // ButterKnife.bind(this, view); // // LinearLayoutManager llm = new LinearLayoutManager(getContext()); // recyclerView.setLayoutManager(llm); // adapter = new RepoListAdapter(new ArrayList<>(), presenter); // recyclerView.setAdapter(adapter); // // presenter.onCreateView(savedInstanceState); // // return view; // } // // private void makeToast(String text) { // Snackbar.make(recyclerView, text, Snackbar.LENGTH_LONG).show(); // } // // @Override // protected BasePresenter getPresenter() { // return presenter; // } // // // @Override // public void showError(String error) { // makeToast(error); // } // // @Override // public void showRepoList(List<Repository> repoList) { // adapter.setRepoList(repoList); // } // // @Override // public void showEmptyList() { // makeToast(getActivity().getString(R.string.empty_list)); // } // // @Override // public String getUserName() { // return editText.getText().toString(); // } // // @Override // public void startRepoInfoFragment(Repository repository) { // activityCallback.startRepoInfoFragment(repository); // } // // @Override // public void onSaveInstanceState(Bundle outState) { // super.onSaveInstanceState(outState); // presenter.onSaveInstanceState(outState); // } // // } // Path: app/src/main/java/com/andrey7mel/stepbystep/other/di/view/ViewComponent.java import com.andrey7mel.stepbystep.view.fragments.RepoListFragment; import javax.inject.Singleton; import dagger.Component; package com.andrey7mel.stepbystep.other.di.view; @Singleton @Component(modules = {ViewDynamicModule.class}) public interface ViewComponent {
void inject(RepoListFragment repoListFragment);
andrey7mel/android-step-by-step
app/src/test/java/com/andrey7mel/stepbystep/view/fragments/RepoListFragmentTest.java
// Path: app/src/test/java/com/andrey7mel/stepbystep/other/BaseTest.java // @RunWith(RobolectricGradleTestRunner.class) // @Config(application = TestApplication.class, // constants = BuildConfig.class, // sdk = 21) // @Ignore // public class BaseTest { // // public TestComponent component; // public TestUtils testUtils; // // @Before // public void setUp() throws Exception { // component = (TestComponent) App.getComponent(); // testUtils = new TestUtils(); // } // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/di/view/TestViewComponent.java // @Singleton // @Component(modules = {TestViewDynamicModule.class}) // public interface TestViewComponent extends ViewComponent { // // void inject(RepoListFragmentTest in); // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/di/view/TestViewDynamicModule.java // @Module // public class TestViewDynamicModule { // // @Provides // @Singleton // RepoListPresenter provideRepoListPresenter() { // return mock(RepoListPresenter.class); // } // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/RepoListPresenter.java // public class RepoListPresenter extends BasePresenter { // // private static final String BUNDLE_REPO_LIST_KEY = "BUNDLE_REPO_LIST_KEY"; // // @Inject // protected RepoListMapper repoListMapper; // // private RepoListView view; // // private List<Repository> repoList; // // // for DI // @Inject // public RepoListPresenter() { // } // // public RepoListPresenter(RepoListView view) { // App.getComponent().inject(this); // this.view = view; // } // // @Override // protected View getView() { // return view; // } // // public void onSearchButtonClick() { // String name = view.getUserName(); // if (TextUtils.isEmpty(name)) return; // // showLoadingState(); // Subscription subscription = model.getRepoList(name) // .map(repoListMapper) // .subscribe(new Observer<List<Repository>>() { // // @Override // public void onCompleted() { // hideLoadingState(); // } // // @Override // public void onError(Throwable e) { // hideLoadingState(); // showError(e); // } // // @Override // public void onNext(List<Repository> list) { // if (list != null && !list.isEmpty()) { // repoList = list; // view.showRepoList(list); // } else { // view.showEmptyList(); // } // } // }); // addSubscription(subscription); // } // // public void onCreateView(Bundle savedInstanceState) { // if (savedInstanceState != null) { // repoList = (List<Repository>) savedInstanceState.getSerializable(BUNDLE_REPO_LIST_KEY); // } // if (isRepoListNotEmpty()) { // view.showRepoList(repoList); // } // } // // private boolean isRepoListNotEmpty() { // return (repoList != null && !repoList.isEmpty()); // } // // public void onSaveInstanceState(Bundle outState) { // if (isRepoListNotEmpty()) { // outState.putSerializable(BUNDLE_REPO_LIST_KEY, new ArrayList<>(repoList)); // } // } // // public void clickRepo(Repository repository) { // view.startRepoInfoFragment(repository); // } // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/MainActivity.java // public class MainActivity extends AppCompatActivity implements ActivityCallback { // // private static String TAG = "TAG"; // // @Bind(R.id.toolbar) // protected Toolbar toolbar; // // @Bind(R.id.toolbar_progress_bar) // protected ProgressBar progressBar; // // private FragmentManager fragmentManager; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // ButterKnife.bind(this); // setSupportActionBar(toolbar); // fragmentManager = getSupportFragmentManager(); // // Fragment fragment = fragmentManager.findFragmentByTag(TAG); // if (fragment == null) replaceFragment(new RepoListFragment(), false); // } // // private void replaceFragment(Fragment fragment, boolean addBackStack) { // FragmentTransaction transaction = fragmentManager.beginTransaction(); // transaction.replace(R.id.container, fragment, TAG); // if (addBackStack) transaction.addToBackStack(null); // transaction.commit(); // } // // @Override // public void startRepoInfoFragment(Repository repository) { // replaceFragment(RepoInfoFragment.newInstance(repository), true); // } // // @Override // public void showProgressBar() { // progressBar.setVisibility(View.VISIBLE); // } // // @Override // public void hideProgressBar() { // progressBar.setVisibility(View.INVISIBLE); // } // // // }
import android.os.Bundle; import android.view.LayoutInflater; import android.view.ViewGroup; import com.andrey7mel.stepbystep.R; import com.andrey7mel.stepbystep.other.BaseTest; import com.andrey7mel.stepbystep.other.di.view.DaggerTestViewComponent; import com.andrey7mel.stepbystep.other.di.view.TestViewComponent; import com.andrey7mel.stepbystep.other.di.view.TestViewDynamicModule; import com.andrey7mel.stepbystep.presenter.RepoListPresenter; import com.andrey7mel.stepbystep.view.MainActivity; import org.junit.Before; import org.junit.Test; import org.robolectric.Robolectric; import javax.inject.Inject; import static org.mockito.Mockito.verify;
package com.andrey7mel.stepbystep.view.fragments; public class RepoListFragmentTest extends BaseTest { @Inject
// Path: app/src/test/java/com/andrey7mel/stepbystep/other/BaseTest.java // @RunWith(RobolectricGradleTestRunner.class) // @Config(application = TestApplication.class, // constants = BuildConfig.class, // sdk = 21) // @Ignore // public class BaseTest { // // public TestComponent component; // public TestUtils testUtils; // // @Before // public void setUp() throws Exception { // component = (TestComponent) App.getComponent(); // testUtils = new TestUtils(); // } // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/di/view/TestViewComponent.java // @Singleton // @Component(modules = {TestViewDynamicModule.class}) // public interface TestViewComponent extends ViewComponent { // // void inject(RepoListFragmentTest in); // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/di/view/TestViewDynamicModule.java // @Module // public class TestViewDynamicModule { // // @Provides // @Singleton // RepoListPresenter provideRepoListPresenter() { // return mock(RepoListPresenter.class); // } // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/RepoListPresenter.java // public class RepoListPresenter extends BasePresenter { // // private static final String BUNDLE_REPO_LIST_KEY = "BUNDLE_REPO_LIST_KEY"; // // @Inject // protected RepoListMapper repoListMapper; // // private RepoListView view; // // private List<Repository> repoList; // // // for DI // @Inject // public RepoListPresenter() { // } // // public RepoListPresenter(RepoListView view) { // App.getComponent().inject(this); // this.view = view; // } // // @Override // protected View getView() { // return view; // } // // public void onSearchButtonClick() { // String name = view.getUserName(); // if (TextUtils.isEmpty(name)) return; // // showLoadingState(); // Subscription subscription = model.getRepoList(name) // .map(repoListMapper) // .subscribe(new Observer<List<Repository>>() { // // @Override // public void onCompleted() { // hideLoadingState(); // } // // @Override // public void onError(Throwable e) { // hideLoadingState(); // showError(e); // } // // @Override // public void onNext(List<Repository> list) { // if (list != null && !list.isEmpty()) { // repoList = list; // view.showRepoList(list); // } else { // view.showEmptyList(); // } // } // }); // addSubscription(subscription); // } // // public void onCreateView(Bundle savedInstanceState) { // if (savedInstanceState != null) { // repoList = (List<Repository>) savedInstanceState.getSerializable(BUNDLE_REPO_LIST_KEY); // } // if (isRepoListNotEmpty()) { // view.showRepoList(repoList); // } // } // // private boolean isRepoListNotEmpty() { // return (repoList != null && !repoList.isEmpty()); // } // // public void onSaveInstanceState(Bundle outState) { // if (isRepoListNotEmpty()) { // outState.putSerializable(BUNDLE_REPO_LIST_KEY, new ArrayList<>(repoList)); // } // } // // public void clickRepo(Repository repository) { // view.startRepoInfoFragment(repository); // } // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/MainActivity.java // public class MainActivity extends AppCompatActivity implements ActivityCallback { // // private static String TAG = "TAG"; // // @Bind(R.id.toolbar) // protected Toolbar toolbar; // // @Bind(R.id.toolbar_progress_bar) // protected ProgressBar progressBar; // // private FragmentManager fragmentManager; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // ButterKnife.bind(this); // setSupportActionBar(toolbar); // fragmentManager = getSupportFragmentManager(); // // Fragment fragment = fragmentManager.findFragmentByTag(TAG); // if (fragment == null) replaceFragment(new RepoListFragment(), false); // } // // private void replaceFragment(Fragment fragment, boolean addBackStack) { // FragmentTransaction transaction = fragmentManager.beginTransaction(); // transaction.replace(R.id.container, fragment, TAG); // if (addBackStack) transaction.addToBackStack(null); // transaction.commit(); // } // // @Override // public void startRepoInfoFragment(Repository repository) { // replaceFragment(RepoInfoFragment.newInstance(repository), true); // } // // @Override // public void showProgressBar() { // progressBar.setVisibility(View.VISIBLE); // } // // @Override // public void hideProgressBar() { // progressBar.setVisibility(View.INVISIBLE); // } // // // } // Path: app/src/test/java/com/andrey7mel/stepbystep/view/fragments/RepoListFragmentTest.java import android.os.Bundle; import android.view.LayoutInflater; import android.view.ViewGroup; import com.andrey7mel.stepbystep.R; import com.andrey7mel.stepbystep.other.BaseTest; import com.andrey7mel.stepbystep.other.di.view.DaggerTestViewComponent; import com.andrey7mel.stepbystep.other.di.view.TestViewComponent; import com.andrey7mel.stepbystep.other.di.view.TestViewDynamicModule; import com.andrey7mel.stepbystep.presenter.RepoListPresenter; import com.andrey7mel.stepbystep.view.MainActivity; import org.junit.Before; import org.junit.Test; import org.robolectric.Robolectric; import javax.inject.Inject; import static org.mockito.Mockito.verify; package com.andrey7mel.stepbystep.view.fragments; public class RepoListFragmentTest extends BaseTest { @Inject
protected RepoListPresenter repoListPresenter;
andrey7mel/android-step-by-step
app/src/main/java/com/andrey7mel/stepbystep/view/fragments/RepoInfoView.java
// Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/vo/Branch.java // public class Branch implements Serializable { // private String name; // // public Branch(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Branch branch = (Branch) o; // // return !(name != null ? !name.equals(branch.name) : branch.name != null); // // } // // @Override // public int hashCode() { // return name != null ? name.hashCode() : 0; // } // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/vo/Contributor.java // public class Contributor implements Serializable { // private String name; // // public Contributor(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Contributor that = (Contributor) o; // // return !(name != null ? !name.equals(that.name) : that.name != null); // // } // // @Override // public int hashCode() { // return name != null ? name.hashCode() : 0; // } // }
import com.andrey7mel.stepbystep.presenter.vo.Branch; import com.andrey7mel.stepbystep.presenter.vo.Contributor; import java.util.List;
package com.andrey7mel.stepbystep.view.fragments; public interface RepoInfoView extends View { void showContributors(List<Contributor> contributors);
// Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/vo/Branch.java // public class Branch implements Serializable { // private String name; // // public Branch(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Branch branch = (Branch) o; // // return !(name != null ? !name.equals(branch.name) : branch.name != null); // // } // // @Override // public int hashCode() { // return name != null ? name.hashCode() : 0; // } // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/vo/Contributor.java // public class Contributor implements Serializable { // private String name; // // public Contributor(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Contributor that = (Contributor) o; // // return !(name != null ? !name.equals(that.name) : that.name != null); // // } // // @Override // public int hashCode() { // return name != null ? name.hashCode() : 0; // } // } // Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/RepoInfoView.java import com.andrey7mel.stepbystep.presenter.vo.Branch; import com.andrey7mel.stepbystep.presenter.vo.Contributor; import java.util.List; package com.andrey7mel.stepbystep.view.fragments; public interface RepoInfoView extends View { void showContributors(List<Contributor> contributors);
void showBranches(List<Branch> branches);
andrey7mel/android-step-by-step
app/src/test/java/com/andrey7mel/stepbystep/other/di/ViewTestModule.java
// Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/RepoInfoPresenter.java // public class RepoInfoPresenter extends BasePresenter { // // private static final String BUNDLE_BRANCHES_KEY = "BUNDLE_BRANCHES_KEY"; // private static final String BUNDLE_CONTRIBUTORS_KEY = "BUNDLE_CONTRIBUTORS_KEY"; // private static final int COUNT_SUBSCRIPTION = 2; // // @Inject // protected RepoBranchesMapper branchesMapper; // // @Inject // protected RepoContributorsMapper contributorsMapper; // // private int countCompletedSubscription = 0; // // private RepoInfoView view; // // private List<Contributor> contributorList; // private List<Branch> branchList; // // private Repository repository; // // private void loadData() { // String owner = repository.getOwnerName(); // String name = repository.getRepoName(); // // showLoadingState(); // Subscription subscriptionBranches = model.getRepoBranches(owner, name) // .map(branchesMapper) // .subscribe(new Observer<List<Branch>>() { // @Override // public void onCompleted() { // hideInfoLoadingState(); // } // // @Override // public void onError(Throwable e) { // hideInfoLoadingState(); // showError(e); // } // // @Override // public void onNext(List<Branch> list) { // branchList = list; // view.showBranches(list); // } // }); // addSubscription(subscriptionBranches); // // Subscription subscriptionContributors = model.getRepoContributors(owner, name) // .map(contributorsMapper) // .subscribe(new Observer<List<Contributor>>() { // @Override // public void onCompleted() { // hideInfoLoadingState(); // } // // @Override // public void onError(Throwable e) { // hideInfoLoadingState(); // showError(e); // } // // @Override // public void onNext(List<Contributor> list) { // contributorList = list; // view.showContributors(list); // } // }); // // addSubscription(subscriptionContributors); // } // // public void onCreate(RepoInfoView view, Repository repository) { // App.getComponent().inject(this); // this.view = view; // this.repository = repository; // } // // protected void hideInfoLoadingState() { // countCompletedSubscription++; // // if (countCompletedSubscription == COUNT_SUBSCRIPTION) { // hideLoadingState(); // countCompletedSubscription = 0; // } // } // // public void onCreateView(Bundle savedInstanceState) { // // if (savedInstanceState != null) { // contributorList = (List<Contributor>) savedInstanceState.getSerializable(BUNDLE_CONTRIBUTORS_KEY); // branchList = (List<Branch>) savedInstanceState.getSerializable(BUNDLE_BRANCHES_KEY); // } // // if (contributorList == null || branchList == null) { // loadData(); // } else { // view.showBranches(branchList); // view.showContributors(contributorList); // } // // } // // public void onSaveInstanceState(Bundle outState) { // if (contributorList != null) // outState.putSerializable(BUNDLE_CONTRIBUTORS_KEY, new ArrayList<>(contributorList)); // if (branchList != null) // outState.putSerializable(BUNDLE_BRANCHES_KEY, new ArrayList<>(branchList)); // // } // // @Override // protected View getView() { // return view; // } // }
import com.andrey7mel.stepbystep.presenter.RepoInfoPresenter; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import static org.mockito.Mockito.mock;
package com.andrey7mel.stepbystep.other.di; @Module public class ViewTestModule { @Provides @Singleton
// Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/RepoInfoPresenter.java // public class RepoInfoPresenter extends BasePresenter { // // private static final String BUNDLE_BRANCHES_KEY = "BUNDLE_BRANCHES_KEY"; // private static final String BUNDLE_CONTRIBUTORS_KEY = "BUNDLE_CONTRIBUTORS_KEY"; // private static final int COUNT_SUBSCRIPTION = 2; // // @Inject // protected RepoBranchesMapper branchesMapper; // // @Inject // protected RepoContributorsMapper contributorsMapper; // // private int countCompletedSubscription = 0; // // private RepoInfoView view; // // private List<Contributor> contributorList; // private List<Branch> branchList; // // private Repository repository; // // private void loadData() { // String owner = repository.getOwnerName(); // String name = repository.getRepoName(); // // showLoadingState(); // Subscription subscriptionBranches = model.getRepoBranches(owner, name) // .map(branchesMapper) // .subscribe(new Observer<List<Branch>>() { // @Override // public void onCompleted() { // hideInfoLoadingState(); // } // // @Override // public void onError(Throwable e) { // hideInfoLoadingState(); // showError(e); // } // // @Override // public void onNext(List<Branch> list) { // branchList = list; // view.showBranches(list); // } // }); // addSubscription(subscriptionBranches); // // Subscription subscriptionContributors = model.getRepoContributors(owner, name) // .map(contributorsMapper) // .subscribe(new Observer<List<Contributor>>() { // @Override // public void onCompleted() { // hideInfoLoadingState(); // } // // @Override // public void onError(Throwable e) { // hideInfoLoadingState(); // showError(e); // } // // @Override // public void onNext(List<Contributor> list) { // contributorList = list; // view.showContributors(list); // } // }); // // addSubscription(subscriptionContributors); // } // // public void onCreate(RepoInfoView view, Repository repository) { // App.getComponent().inject(this); // this.view = view; // this.repository = repository; // } // // protected void hideInfoLoadingState() { // countCompletedSubscription++; // // if (countCompletedSubscription == COUNT_SUBSCRIPTION) { // hideLoadingState(); // countCompletedSubscription = 0; // } // } // // public void onCreateView(Bundle savedInstanceState) { // // if (savedInstanceState != null) { // contributorList = (List<Contributor>) savedInstanceState.getSerializable(BUNDLE_CONTRIBUTORS_KEY); // branchList = (List<Branch>) savedInstanceState.getSerializable(BUNDLE_BRANCHES_KEY); // } // // if (contributorList == null || branchList == null) { // loadData(); // } else { // view.showBranches(branchList); // view.showContributors(contributorList); // } // // } // // public void onSaveInstanceState(Bundle outState) { // if (contributorList != null) // outState.putSerializable(BUNDLE_CONTRIBUTORS_KEY, new ArrayList<>(contributorList)); // if (branchList != null) // outState.putSerializable(BUNDLE_BRANCHES_KEY, new ArrayList<>(branchList)); // // } // // @Override // protected View getView() { // return view; // } // } // Path: app/src/test/java/com/andrey7mel/stepbystep/other/di/ViewTestModule.java import com.andrey7mel.stepbystep.presenter.RepoInfoPresenter; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import static org.mockito.Mockito.mock; package com.andrey7mel.stepbystep.other.di; @Module public class ViewTestModule { @Provides @Singleton
RepoInfoPresenter provideRepoInfoPresenter() {
andrey7mel/android-step-by-step
app/src/main/java/com/andrey7mel/stepbystep/other/di/ModelModule.java
// Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiInterface.java // public interface ApiInterface { // // @GET("/users/{user}/repos") // Observable<List<RepositoryDTO>> getRepositories(@Path("user") String user); // // @GET("/repos/{owner}/{repo}/contributors") // Observable<List<ContributorDTO>> getContributors(@Path("owner") String owner, @Path("repo") String repo); // // @GET("/repos/{owner}/{repo}/branches") // Observable<List<BranchDTO>> getBranches(@Path("owner") String owner, @Path("repo") String repo); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiModule.java // public final class ApiModule { // // private static final boolean ENABLE_LOG = true; // // private static final boolean ENABLE_AUTH = false; // private static final String AUTH_64 = "***"; // // private ApiModule() { // } // // public static ApiInterface getApiInterface(String url) { // // OkHttpClient httpClient = new OkHttpClient(); // // if (ENABLE_AUTH) { // httpClient.interceptors().add(chain -> { // Request original = chain.request(); // Request request = original.newBuilder() // .header("Authorization", "Basic " + AUTH_64) // .method(original.method(), original.body()) // .build(); // // return chain.proceed(request); // }); // } // // if (ENABLE_LOG) { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // httpClient.interceptors().add(interceptor); // } // // Retrofit.Builder builder = new Retrofit.Builder(). // baseUrl(url) // .addConverterFactory(GsonConverterFactory.create()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()); // // builder.client(httpClient); // // ApiInterface apiInterface = builder.build().create(ApiInterface.class); // return apiInterface; // } // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/other/Const.java // public interface Const { // String UI_THREAD = "UI_THREAD"; // String IO_THREAD = "IO_THREAD"; // // String BASE_URL = "https://api.github.com/"; // // }
import com.andrey7mel.stepbystep.model.api.ApiInterface; import com.andrey7mel.stepbystep.model.api.ApiModule; import com.andrey7mel.stepbystep.other.Const; import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import rx.Scheduler; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers;
package com.andrey7mel.stepbystep.other.di; @Module public class ModelModule { @Provides @Singleton
// Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiInterface.java // public interface ApiInterface { // // @GET("/users/{user}/repos") // Observable<List<RepositoryDTO>> getRepositories(@Path("user") String user); // // @GET("/repos/{owner}/{repo}/contributors") // Observable<List<ContributorDTO>> getContributors(@Path("owner") String owner, @Path("repo") String repo); // // @GET("/repos/{owner}/{repo}/branches") // Observable<List<BranchDTO>> getBranches(@Path("owner") String owner, @Path("repo") String repo); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiModule.java // public final class ApiModule { // // private static final boolean ENABLE_LOG = true; // // private static final boolean ENABLE_AUTH = false; // private static final String AUTH_64 = "***"; // // private ApiModule() { // } // // public static ApiInterface getApiInterface(String url) { // // OkHttpClient httpClient = new OkHttpClient(); // // if (ENABLE_AUTH) { // httpClient.interceptors().add(chain -> { // Request original = chain.request(); // Request request = original.newBuilder() // .header("Authorization", "Basic " + AUTH_64) // .method(original.method(), original.body()) // .build(); // // return chain.proceed(request); // }); // } // // if (ENABLE_LOG) { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // httpClient.interceptors().add(interceptor); // } // // Retrofit.Builder builder = new Retrofit.Builder(). // baseUrl(url) // .addConverterFactory(GsonConverterFactory.create()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()); // // builder.client(httpClient); // // ApiInterface apiInterface = builder.build().create(ApiInterface.class); // return apiInterface; // } // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/other/Const.java // public interface Const { // String UI_THREAD = "UI_THREAD"; // String IO_THREAD = "IO_THREAD"; // // String BASE_URL = "https://api.github.com/"; // // } // Path: app/src/main/java/com/andrey7mel/stepbystep/other/di/ModelModule.java import com.andrey7mel.stepbystep.model.api.ApiInterface; import com.andrey7mel.stepbystep.model.api.ApiModule; import com.andrey7mel.stepbystep.other.Const; import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import rx.Scheduler; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; package com.andrey7mel.stepbystep.other.di; @Module public class ModelModule { @Provides @Singleton
ApiInterface provideApiInterface() {
andrey7mel/android-step-by-step
app/src/main/java/com/andrey7mel/stepbystep/other/di/ModelModule.java
// Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiInterface.java // public interface ApiInterface { // // @GET("/users/{user}/repos") // Observable<List<RepositoryDTO>> getRepositories(@Path("user") String user); // // @GET("/repos/{owner}/{repo}/contributors") // Observable<List<ContributorDTO>> getContributors(@Path("owner") String owner, @Path("repo") String repo); // // @GET("/repos/{owner}/{repo}/branches") // Observable<List<BranchDTO>> getBranches(@Path("owner") String owner, @Path("repo") String repo); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiModule.java // public final class ApiModule { // // private static final boolean ENABLE_LOG = true; // // private static final boolean ENABLE_AUTH = false; // private static final String AUTH_64 = "***"; // // private ApiModule() { // } // // public static ApiInterface getApiInterface(String url) { // // OkHttpClient httpClient = new OkHttpClient(); // // if (ENABLE_AUTH) { // httpClient.interceptors().add(chain -> { // Request original = chain.request(); // Request request = original.newBuilder() // .header("Authorization", "Basic " + AUTH_64) // .method(original.method(), original.body()) // .build(); // // return chain.proceed(request); // }); // } // // if (ENABLE_LOG) { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // httpClient.interceptors().add(interceptor); // } // // Retrofit.Builder builder = new Retrofit.Builder(). // baseUrl(url) // .addConverterFactory(GsonConverterFactory.create()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()); // // builder.client(httpClient); // // ApiInterface apiInterface = builder.build().create(ApiInterface.class); // return apiInterface; // } // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/other/Const.java // public interface Const { // String UI_THREAD = "UI_THREAD"; // String IO_THREAD = "IO_THREAD"; // // String BASE_URL = "https://api.github.com/"; // // }
import com.andrey7mel.stepbystep.model.api.ApiInterface; import com.andrey7mel.stepbystep.model.api.ApiModule; import com.andrey7mel.stepbystep.other.Const; import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import rx.Scheduler; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers;
package com.andrey7mel.stepbystep.other.di; @Module public class ModelModule { @Provides @Singleton ApiInterface provideApiInterface() {
// Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiInterface.java // public interface ApiInterface { // // @GET("/users/{user}/repos") // Observable<List<RepositoryDTO>> getRepositories(@Path("user") String user); // // @GET("/repos/{owner}/{repo}/contributors") // Observable<List<ContributorDTO>> getContributors(@Path("owner") String owner, @Path("repo") String repo); // // @GET("/repos/{owner}/{repo}/branches") // Observable<List<BranchDTO>> getBranches(@Path("owner") String owner, @Path("repo") String repo); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiModule.java // public final class ApiModule { // // private static final boolean ENABLE_LOG = true; // // private static final boolean ENABLE_AUTH = false; // private static final String AUTH_64 = "***"; // // private ApiModule() { // } // // public static ApiInterface getApiInterface(String url) { // // OkHttpClient httpClient = new OkHttpClient(); // // if (ENABLE_AUTH) { // httpClient.interceptors().add(chain -> { // Request original = chain.request(); // Request request = original.newBuilder() // .header("Authorization", "Basic " + AUTH_64) // .method(original.method(), original.body()) // .build(); // // return chain.proceed(request); // }); // } // // if (ENABLE_LOG) { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // httpClient.interceptors().add(interceptor); // } // // Retrofit.Builder builder = new Retrofit.Builder(). // baseUrl(url) // .addConverterFactory(GsonConverterFactory.create()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()); // // builder.client(httpClient); // // ApiInterface apiInterface = builder.build().create(ApiInterface.class); // return apiInterface; // } // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/other/Const.java // public interface Const { // String UI_THREAD = "UI_THREAD"; // String IO_THREAD = "IO_THREAD"; // // String BASE_URL = "https://api.github.com/"; // // } // Path: app/src/main/java/com/andrey7mel/stepbystep/other/di/ModelModule.java import com.andrey7mel.stepbystep.model.api.ApiInterface; import com.andrey7mel.stepbystep.model.api.ApiModule; import com.andrey7mel.stepbystep.other.Const; import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import rx.Scheduler; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; package com.andrey7mel.stepbystep.other.di; @Module public class ModelModule { @Provides @Singleton ApiInterface provideApiInterface() {
return ApiModule.getApiInterface(Const.BASE_URL);
andrey7mel/android-step-by-step
app/src/main/java/com/andrey7mel/stepbystep/other/di/ModelModule.java
// Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiInterface.java // public interface ApiInterface { // // @GET("/users/{user}/repos") // Observable<List<RepositoryDTO>> getRepositories(@Path("user") String user); // // @GET("/repos/{owner}/{repo}/contributors") // Observable<List<ContributorDTO>> getContributors(@Path("owner") String owner, @Path("repo") String repo); // // @GET("/repos/{owner}/{repo}/branches") // Observable<List<BranchDTO>> getBranches(@Path("owner") String owner, @Path("repo") String repo); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiModule.java // public final class ApiModule { // // private static final boolean ENABLE_LOG = true; // // private static final boolean ENABLE_AUTH = false; // private static final String AUTH_64 = "***"; // // private ApiModule() { // } // // public static ApiInterface getApiInterface(String url) { // // OkHttpClient httpClient = new OkHttpClient(); // // if (ENABLE_AUTH) { // httpClient.interceptors().add(chain -> { // Request original = chain.request(); // Request request = original.newBuilder() // .header("Authorization", "Basic " + AUTH_64) // .method(original.method(), original.body()) // .build(); // // return chain.proceed(request); // }); // } // // if (ENABLE_LOG) { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // httpClient.interceptors().add(interceptor); // } // // Retrofit.Builder builder = new Retrofit.Builder(). // baseUrl(url) // .addConverterFactory(GsonConverterFactory.create()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()); // // builder.client(httpClient); // // ApiInterface apiInterface = builder.build().create(ApiInterface.class); // return apiInterface; // } // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/other/Const.java // public interface Const { // String UI_THREAD = "UI_THREAD"; // String IO_THREAD = "IO_THREAD"; // // String BASE_URL = "https://api.github.com/"; // // }
import com.andrey7mel.stepbystep.model.api.ApiInterface; import com.andrey7mel.stepbystep.model.api.ApiModule; import com.andrey7mel.stepbystep.other.Const; import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import rx.Scheduler; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers;
package com.andrey7mel.stepbystep.other.di; @Module public class ModelModule { @Provides @Singleton ApiInterface provideApiInterface() {
// Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiInterface.java // public interface ApiInterface { // // @GET("/users/{user}/repos") // Observable<List<RepositoryDTO>> getRepositories(@Path("user") String user); // // @GET("/repos/{owner}/{repo}/contributors") // Observable<List<ContributorDTO>> getContributors(@Path("owner") String owner, @Path("repo") String repo); // // @GET("/repos/{owner}/{repo}/branches") // Observable<List<BranchDTO>> getBranches(@Path("owner") String owner, @Path("repo") String repo); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiModule.java // public final class ApiModule { // // private static final boolean ENABLE_LOG = true; // // private static final boolean ENABLE_AUTH = false; // private static final String AUTH_64 = "***"; // // private ApiModule() { // } // // public static ApiInterface getApiInterface(String url) { // // OkHttpClient httpClient = new OkHttpClient(); // // if (ENABLE_AUTH) { // httpClient.interceptors().add(chain -> { // Request original = chain.request(); // Request request = original.newBuilder() // .header("Authorization", "Basic " + AUTH_64) // .method(original.method(), original.body()) // .build(); // // return chain.proceed(request); // }); // } // // if (ENABLE_LOG) { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // httpClient.interceptors().add(interceptor); // } // // Retrofit.Builder builder = new Retrofit.Builder(). // baseUrl(url) // .addConverterFactory(GsonConverterFactory.create()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()); // // builder.client(httpClient); // // ApiInterface apiInterface = builder.build().create(ApiInterface.class); // return apiInterface; // } // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/other/Const.java // public interface Const { // String UI_THREAD = "UI_THREAD"; // String IO_THREAD = "IO_THREAD"; // // String BASE_URL = "https://api.github.com/"; // // } // Path: app/src/main/java/com/andrey7mel/stepbystep/other/di/ModelModule.java import com.andrey7mel.stepbystep.model.api.ApiInterface; import com.andrey7mel.stepbystep.model.api.ApiModule; import com.andrey7mel.stepbystep.other.Const; import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import rx.Scheduler; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; package com.andrey7mel.stepbystep.other.di; @Module public class ModelModule { @Provides @Singleton ApiInterface provideApiInterface() {
return ApiModule.getApiInterface(Const.BASE_URL);
andrey7mel/android-step-by-step
app/src/test/java/com/andrey7mel/stepbystep/integration/other/IntegrationTestApp.java
// Path: app/src/main/java/com/andrey7mel/stepbystep/other/App.java // public class App extends Application { // // private static AppComponent component; // // public static AppComponent getComponent() { // return component; // } // // @Override // public void onCreate() { // super.onCreate(); // component = buildComponent(); // } // // protected AppComponent buildComponent() { // return DaggerAppComponent.builder() // .build(); // } // // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/other/di/AppComponent.java // @Singleton // @Component(modules = {ModelModule.class, PresenterModule.class, ViewModule.class}) // public interface AppComponent { // // void inject(ModelImpl dataRepository); // // void inject(BasePresenter basePresenter); // // void inject(RepoListPresenter repoListPresenter); // // void inject(RepoInfoPresenter repoInfoPresenter); // // void inject(RepoInfoFragment repoInfoFragment); // // }
import com.andrey7mel.stepbystep.integration.other.di.DaggerIntegrationTestComponent; import com.andrey7mel.stepbystep.other.App; import com.andrey7mel.stepbystep.other.di.AppComponent;
package com.andrey7mel.stepbystep.integration.other; public class IntegrationTestApp extends App { @Override
// Path: app/src/main/java/com/andrey7mel/stepbystep/other/App.java // public class App extends Application { // // private static AppComponent component; // // public static AppComponent getComponent() { // return component; // } // // @Override // public void onCreate() { // super.onCreate(); // component = buildComponent(); // } // // protected AppComponent buildComponent() { // return DaggerAppComponent.builder() // .build(); // } // // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/other/di/AppComponent.java // @Singleton // @Component(modules = {ModelModule.class, PresenterModule.class, ViewModule.class}) // public interface AppComponent { // // void inject(ModelImpl dataRepository); // // void inject(BasePresenter basePresenter); // // void inject(RepoListPresenter repoListPresenter); // // void inject(RepoInfoPresenter repoInfoPresenter); // // void inject(RepoInfoFragment repoInfoFragment); // // } // Path: app/src/test/java/com/andrey7mel/stepbystep/integration/other/IntegrationTestApp.java import com.andrey7mel.stepbystep.integration.other.di.DaggerIntegrationTestComponent; import com.andrey7mel.stepbystep.other.App; import com.andrey7mel.stepbystep.other.di.AppComponent; package com.andrey7mel.stepbystep.integration.other; public class IntegrationTestApp extends App { @Override
protected AppComponent buildComponent() {
andrey7mel/android-step-by-step
app/src/test/java/com/andrey7mel/stepbystep/other/di/PresenterTestModule.java
// Path: app/src/main/java/com/andrey7mel/stepbystep/model/Model.java // public interface Model { // // Observable<List<RepositoryDTO>> getRepoList(String name); // // Observable<List<BranchDTO>> getRepoBranches(String owner, String name); // // Observable<List<ContributorDTO>> getRepoContributors(String owner, String name); // // }
import com.andrey7mel.stepbystep.model.Model; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import rx.subscriptions.CompositeSubscription; import static org.mockito.Mockito.mock;
package com.andrey7mel.stepbystep.other.di; @Module public class PresenterTestModule { @Provides @Singleton
// Path: app/src/main/java/com/andrey7mel/stepbystep/model/Model.java // public interface Model { // // Observable<List<RepositoryDTO>> getRepoList(String name); // // Observable<List<BranchDTO>> getRepoBranches(String owner, String name); // // Observable<List<ContributorDTO>> getRepoContributors(String owner, String name); // // } // Path: app/src/test/java/com/andrey7mel/stepbystep/other/di/PresenterTestModule.java import com.andrey7mel.stepbystep.model.Model; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import rx.subscriptions.CompositeSubscription; import static org.mockito.Mockito.mock; package com.andrey7mel.stepbystep.other.di; @Module public class PresenterTestModule { @Provides @Singleton
Model provideDataRepository() {
andrey7mel/android-step-by-step
app/src/main/java/com/andrey7mel/stepbystep/other/di/ViewModule.java
// Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/RepoInfoPresenter.java // public class RepoInfoPresenter extends BasePresenter { // // private static final String BUNDLE_BRANCHES_KEY = "BUNDLE_BRANCHES_KEY"; // private static final String BUNDLE_CONTRIBUTORS_KEY = "BUNDLE_CONTRIBUTORS_KEY"; // private static final int COUNT_SUBSCRIPTION = 2; // // @Inject // protected RepoBranchesMapper branchesMapper; // // @Inject // protected RepoContributorsMapper contributorsMapper; // // private int countCompletedSubscription = 0; // // private RepoInfoView view; // // private List<Contributor> contributorList; // private List<Branch> branchList; // // private Repository repository; // // private void loadData() { // String owner = repository.getOwnerName(); // String name = repository.getRepoName(); // // showLoadingState(); // Subscription subscriptionBranches = model.getRepoBranches(owner, name) // .map(branchesMapper) // .subscribe(new Observer<List<Branch>>() { // @Override // public void onCompleted() { // hideInfoLoadingState(); // } // // @Override // public void onError(Throwable e) { // hideInfoLoadingState(); // showError(e); // } // // @Override // public void onNext(List<Branch> list) { // branchList = list; // view.showBranches(list); // } // }); // addSubscription(subscriptionBranches); // // Subscription subscriptionContributors = model.getRepoContributors(owner, name) // .map(contributorsMapper) // .subscribe(new Observer<List<Contributor>>() { // @Override // public void onCompleted() { // hideInfoLoadingState(); // } // // @Override // public void onError(Throwable e) { // hideInfoLoadingState(); // showError(e); // } // // @Override // public void onNext(List<Contributor> list) { // contributorList = list; // view.showContributors(list); // } // }); // // addSubscription(subscriptionContributors); // } // // public void onCreate(RepoInfoView view, Repository repository) { // App.getComponent().inject(this); // this.view = view; // this.repository = repository; // } // // protected void hideInfoLoadingState() { // countCompletedSubscription++; // // if (countCompletedSubscription == COUNT_SUBSCRIPTION) { // hideLoadingState(); // countCompletedSubscription = 0; // } // } // // public void onCreateView(Bundle savedInstanceState) { // // if (savedInstanceState != null) { // contributorList = (List<Contributor>) savedInstanceState.getSerializable(BUNDLE_CONTRIBUTORS_KEY); // branchList = (List<Branch>) savedInstanceState.getSerializable(BUNDLE_BRANCHES_KEY); // } // // if (contributorList == null || branchList == null) { // loadData(); // } else { // view.showBranches(branchList); // view.showContributors(contributorList); // } // // } // // public void onSaveInstanceState(Bundle outState) { // if (contributorList != null) // outState.putSerializable(BUNDLE_CONTRIBUTORS_KEY, new ArrayList<>(contributorList)); // if (branchList != null) // outState.putSerializable(BUNDLE_BRANCHES_KEY, new ArrayList<>(branchList)); // // } // // @Override // protected View getView() { // return view; // } // }
import com.andrey7mel.stepbystep.presenter.RepoInfoPresenter; import dagger.Module; import dagger.Provides;
package com.andrey7mel.stepbystep.other.di; @Module public class ViewModule { @Provides
// Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/RepoInfoPresenter.java // public class RepoInfoPresenter extends BasePresenter { // // private static final String BUNDLE_BRANCHES_KEY = "BUNDLE_BRANCHES_KEY"; // private static final String BUNDLE_CONTRIBUTORS_KEY = "BUNDLE_CONTRIBUTORS_KEY"; // private static final int COUNT_SUBSCRIPTION = 2; // // @Inject // protected RepoBranchesMapper branchesMapper; // // @Inject // protected RepoContributorsMapper contributorsMapper; // // private int countCompletedSubscription = 0; // // private RepoInfoView view; // // private List<Contributor> contributorList; // private List<Branch> branchList; // // private Repository repository; // // private void loadData() { // String owner = repository.getOwnerName(); // String name = repository.getRepoName(); // // showLoadingState(); // Subscription subscriptionBranches = model.getRepoBranches(owner, name) // .map(branchesMapper) // .subscribe(new Observer<List<Branch>>() { // @Override // public void onCompleted() { // hideInfoLoadingState(); // } // // @Override // public void onError(Throwable e) { // hideInfoLoadingState(); // showError(e); // } // // @Override // public void onNext(List<Branch> list) { // branchList = list; // view.showBranches(list); // } // }); // addSubscription(subscriptionBranches); // // Subscription subscriptionContributors = model.getRepoContributors(owner, name) // .map(contributorsMapper) // .subscribe(new Observer<List<Contributor>>() { // @Override // public void onCompleted() { // hideInfoLoadingState(); // } // // @Override // public void onError(Throwable e) { // hideInfoLoadingState(); // showError(e); // } // // @Override // public void onNext(List<Contributor> list) { // contributorList = list; // view.showContributors(list); // } // }); // // addSubscription(subscriptionContributors); // } // // public void onCreate(RepoInfoView view, Repository repository) { // App.getComponent().inject(this); // this.view = view; // this.repository = repository; // } // // protected void hideInfoLoadingState() { // countCompletedSubscription++; // // if (countCompletedSubscription == COUNT_SUBSCRIPTION) { // hideLoadingState(); // countCompletedSubscription = 0; // } // } // // public void onCreateView(Bundle savedInstanceState) { // // if (savedInstanceState != null) { // contributorList = (List<Contributor>) savedInstanceState.getSerializable(BUNDLE_CONTRIBUTORS_KEY); // branchList = (List<Branch>) savedInstanceState.getSerializable(BUNDLE_BRANCHES_KEY); // } // // if (contributorList == null || branchList == null) { // loadData(); // } else { // view.showBranches(branchList); // view.showContributors(contributorList); // } // // } // // public void onSaveInstanceState(Bundle outState) { // if (contributorList != null) // outState.putSerializable(BUNDLE_CONTRIBUTORS_KEY, new ArrayList<>(contributorList)); // if (branchList != null) // outState.putSerializable(BUNDLE_BRANCHES_KEY, new ArrayList<>(branchList)); // // } // // @Override // protected View getView() { // return view; // } // } // Path: app/src/main/java/com/andrey7mel/stepbystep/other/di/ViewModule.java import com.andrey7mel.stepbystep.presenter.RepoInfoPresenter; import dagger.Module; import dagger.Provides; package com.andrey7mel.stepbystep.other.di; @Module public class ViewModule { @Provides
RepoInfoPresenter provideRepoInfoPresenter() {
andrey7mel/android-step-by-step
app/src/test/java/com/andrey7mel/stepbystep/other/TestApplication.java
// Path: app/src/main/java/com/andrey7mel/stepbystep/other/di/AppComponent.java // @Singleton // @Component(modules = {ModelModule.class, PresenterModule.class, ViewModule.class}) // public interface AppComponent { // // void inject(ModelImpl dataRepository); // // void inject(BasePresenter basePresenter); // // void inject(RepoListPresenter repoListPresenter); // // void inject(RepoInfoPresenter repoInfoPresenter); // // void inject(RepoInfoFragment repoInfoFragment); // // }
import com.andrey7mel.stepbystep.other.di.AppComponent; import com.andrey7mel.stepbystep.other.di.DaggerTestComponent;
package com.andrey7mel.stepbystep.other; public class TestApplication extends App { @Override
// Path: app/src/main/java/com/andrey7mel/stepbystep/other/di/AppComponent.java // @Singleton // @Component(modules = {ModelModule.class, PresenterModule.class, ViewModule.class}) // public interface AppComponent { // // void inject(ModelImpl dataRepository); // // void inject(BasePresenter basePresenter); // // void inject(RepoListPresenter repoListPresenter); // // void inject(RepoInfoPresenter repoInfoPresenter); // // void inject(RepoInfoFragment repoInfoFragment); // // } // Path: app/src/test/java/com/andrey7mel/stepbystep/other/TestApplication.java import com.andrey7mel.stepbystep.other.di.AppComponent; import com.andrey7mel.stepbystep.other.di.DaggerTestComponent; package com.andrey7mel.stepbystep.other; public class TestApplication extends App { @Override
protected AppComponent buildComponent() {
andrey7mel/android-step-by-step
app/src/androidTest/java/com/andrey7mel/stepbystep/tools/MockTestRunner.java
// Path: app/src/androidTest/java/com/andrey7mel/stepbystep/di/TestApp.java // public class TestApp extends App { // // @Override // protected TestComponent buildComponent() { // return DaggerTestComponent.builder().build(); // } // }
import android.app.Application; import android.content.Context; import android.support.test.runner.AndroidJUnitRunner; import com.andrey7mel.stepbystep.di.TestApp;
package com.andrey7mel.stepbystep.tools; public class MockTestRunner extends AndroidJUnitRunner { @Override public Application newApplication( ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException { return super.newApplication(
// Path: app/src/androidTest/java/com/andrey7mel/stepbystep/di/TestApp.java // public class TestApp extends App { // // @Override // protected TestComponent buildComponent() { // return DaggerTestComponent.builder().build(); // } // } // Path: app/src/androidTest/java/com/andrey7mel/stepbystep/tools/MockTestRunner.java import android.app.Application; import android.content.Context; import android.support.test.runner.AndroidJUnitRunner; import com.andrey7mel.stepbystep.di.TestApp; package com.andrey7mel.stepbystep.tools; public class MockTestRunner extends AndroidJUnitRunner { @Override public Application newApplication( ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException { return super.newApplication(
cl, TestApp.class.getName(), context);
andrey7mel/android-step-by-step
app/src/main/java/com/andrey7mel/stepbystep/view/fragments/BaseFragment.java
// Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/Presenter.java // public interface Presenter { // // void onStop(); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/ActivityCallback.java // public interface ActivityCallback { // // void startRepoInfoFragment(Repository repository); // // void showProgressBar(); // // void hideProgressBar(); // // }
import android.app.Activity; import android.support.v4.app.Fragment; import com.andrey7mel.stepbystep.presenter.Presenter; import com.andrey7mel.stepbystep.view.ActivityCallback;
package com.andrey7mel.stepbystep.view.fragments; public abstract class BaseFragment extends Fragment implements View { protected ActivityCallback activityCallback;
// Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/Presenter.java // public interface Presenter { // // void onStop(); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/ActivityCallback.java // public interface ActivityCallback { // // void startRepoInfoFragment(Repository repository); // // void showProgressBar(); // // void hideProgressBar(); // // } // Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/BaseFragment.java import android.app.Activity; import android.support.v4.app.Fragment; import com.andrey7mel.stepbystep.presenter.Presenter; import com.andrey7mel.stepbystep.view.ActivityCallback; package com.andrey7mel.stepbystep.view.fragments; public abstract class BaseFragment extends Fragment implements View { protected ActivityCallback activityCallback;
protected abstract Presenter getPresenter();
andrey7mel/android-step-by-step
app/src/test/java/com/andrey7mel/stepbystep/integration/other/di/IntegrationTestModelModule.java
// Path: app/src/test/java/com/andrey7mel/stepbystep/integration/other/IntegrationApiModule.java // public class IntegrationApiModule { // // public ApiInterface getApiInterface(MockWebServer mockWebServer) throws IOException { // mockWebServer.start(); // TestUtils testUtils = new TestUtils(); // final Dispatcher dispatcher = new Dispatcher() { // // @Override // public MockResponse dispatch(RecordedRequest request) throws InterruptedException { // // if (request.getPath().equals("/users/" + TestConst.TEST_OWNER + "/repos")) { // return new MockResponse().setResponseCode(200) // .setBody(testUtils.readString("json/repos.json")); // } else if (request.getPath().equals("/repos/" + TestConst.TEST_OWNER + "/" + TestConst.TEST_REPO + "/branches")) { // return new MockResponse().setResponseCode(200) // .setBody(testUtils.readString("json/branches.json")); // } else if (request.getPath().equals("/repos/" + TestConst.TEST_OWNER + "/" + TestConst.TEST_REPO + "/contributors")) { // return new MockResponse().setResponseCode(200) // .setBody(testUtils.readString("json/contributors.json")); // } // return new MockResponse().setResponseCode(404); // } // }; // // mockWebServer.setDispatcher(dispatcher); // HttpUrl baseUrl = mockWebServer.url("/"); // return ApiModule.getApiInterface(baseUrl.toString()); // } // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiInterface.java // public interface ApiInterface { // // @GET("/users/{user}/repos") // Observable<List<RepositoryDTO>> getRepositories(@Path("user") String user); // // @GET("/repos/{owner}/{repo}/contributors") // Observable<List<ContributorDTO>> getContributors(@Path("owner") String owner, @Path("repo") String repo); // // @GET("/repos/{owner}/{repo}/branches") // Observable<List<BranchDTO>> getBranches(@Path("owner") String owner, @Path("repo") String repo); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/other/Const.java // public interface Const { // String UI_THREAD = "UI_THREAD"; // String IO_THREAD = "IO_THREAD"; // // String BASE_URL = "https://api.github.com/"; // // }
import com.andrey7mel.stepbystep.integration.other.IntegrationApiModule; import com.andrey7mel.stepbystep.model.api.ApiInterface; import com.andrey7mel.stepbystep.other.Const; import com.squareup.okhttp.mockwebserver.MockWebServer; import java.io.IOException; import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import rx.Scheduler; import rx.schedulers.Schedulers;
package com.andrey7mel.stepbystep.integration.other.di; @Module public class IntegrationTestModelModule { @Provides @Singleton
// Path: app/src/test/java/com/andrey7mel/stepbystep/integration/other/IntegrationApiModule.java // public class IntegrationApiModule { // // public ApiInterface getApiInterface(MockWebServer mockWebServer) throws IOException { // mockWebServer.start(); // TestUtils testUtils = new TestUtils(); // final Dispatcher dispatcher = new Dispatcher() { // // @Override // public MockResponse dispatch(RecordedRequest request) throws InterruptedException { // // if (request.getPath().equals("/users/" + TestConst.TEST_OWNER + "/repos")) { // return new MockResponse().setResponseCode(200) // .setBody(testUtils.readString("json/repos.json")); // } else if (request.getPath().equals("/repos/" + TestConst.TEST_OWNER + "/" + TestConst.TEST_REPO + "/branches")) { // return new MockResponse().setResponseCode(200) // .setBody(testUtils.readString("json/branches.json")); // } else if (request.getPath().equals("/repos/" + TestConst.TEST_OWNER + "/" + TestConst.TEST_REPO + "/contributors")) { // return new MockResponse().setResponseCode(200) // .setBody(testUtils.readString("json/contributors.json")); // } // return new MockResponse().setResponseCode(404); // } // }; // // mockWebServer.setDispatcher(dispatcher); // HttpUrl baseUrl = mockWebServer.url("/"); // return ApiModule.getApiInterface(baseUrl.toString()); // } // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiInterface.java // public interface ApiInterface { // // @GET("/users/{user}/repos") // Observable<List<RepositoryDTO>> getRepositories(@Path("user") String user); // // @GET("/repos/{owner}/{repo}/contributors") // Observable<List<ContributorDTO>> getContributors(@Path("owner") String owner, @Path("repo") String repo); // // @GET("/repos/{owner}/{repo}/branches") // Observable<List<BranchDTO>> getBranches(@Path("owner") String owner, @Path("repo") String repo); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/other/Const.java // public interface Const { // String UI_THREAD = "UI_THREAD"; // String IO_THREAD = "IO_THREAD"; // // String BASE_URL = "https://api.github.com/"; // // } // Path: app/src/test/java/com/andrey7mel/stepbystep/integration/other/di/IntegrationTestModelModule.java import com.andrey7mel.stepbystep.integration.other.IntegrationApiModule; import com.andrey7mel.stepbystep.model.api.ApiInterface; import com.andrey7mel.stepbystep.other.Const; import com.squareup.okhttp.mockwebserver.MockWebServer; import java.io.IOException; import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import rx.Scheduler; import rx.schedulers.Schedulers; package com.andrey7mel.stepbystep.integration.other.di; @Module public class IntegrationTestModelModule { @Provides @Singleton
ApiInterface provideApiInterface(MockWebServer mockWebServer) {
andrey7mel/android-step-by-step
app/src/test/java/com/andrey7mel/stepbystep/integration/other/di/IntegrationTestModelModule.java
// Path: app/src/test/java/com/andrey7mel/stepbystep/integration/other/IntegrationApiModule.java // public class IntegrationApiModule { // // public ApiInterface getApiInterface(MockWebServer mockWebServer) throws IOException { // mockWebServer.start(); // TestUtils testUtils = new TestUtils(); // final Dispatcher dispatcher = new Dispatcher() { // // @Override // public MockResponse dispatch(RecordedRequest request) throws InterruptedException { // // if (request.getPath().equals("/users/" + TestConst.TEST_OWNER + "/repos")) { // return new MockResponse().setResponseCode(200) // .setBody(testUtils.readString("json/repos.json")); // } else if (request.getPath().equals("/repos/" + TestConst.TEST_OWNER + "/" + TestConst.TEST_REPO + "/branches")) { // return new MockResponse().setResponseCode(200) // .setBody(testUtils.readString("json/branches.json")); // } else if (request.getPath().equals("/repos/" + TestConst.TEST_OWNER + "/" + TestConst.TEST_REPO + "/contributors")) { // return new MockResponse().setResponseCode(200) // .setBody(testUtils.readString("json/contributors.json")); // } // return new MockResponse().setResponseCode(404); // } // }; // // mockWebServer.setDispatcher(dispatcher); // HttpUrl baseUrl = mockWebServer.url("/"); // return ApiModule.getApiInterface(baseUrl.toString()); // } // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiInterface.java // public interface ApiInterface { // // @GET("/users/{user}/repos") // Observable<List<RepositoryDTO>> getRepositories(@Path("user") String user); // // @GET("/repos/{owner}/{repo}/contributors") // Observable<List<ContributorDTO>> getContributors(@Path("owner") String owner, @Path("repo") String repo); // // @GET("/repos/{owner}/{repo}/branches") // Observable<List<BranchDTO>> getBranches(@Path("owner") String owner, @Path("repo") String repo); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/other/Const.java // public interface Const { // String UI_THREAD = "UI_THREAD"; // String IO_THREAD = "IO_THREAD"; // // String BASE_URL = "https://api.github.com/"; // // }
import com.andrey7mel.stepbystep.integration.other.IntegrationApiModule; import com.andrey7mel.stepbystep.model.api.ApiInterface; import com.andrey7mel.stepbystep.other.Const; import com.squareup.okhttp.mockwebserver.MockWebServer; import java.io.IOException; import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import rx.Scheduler; import rx.schedulers.Schedulers;
package com.andrey7mel.stepbystep.integration.other.di; @Module public class IntegrationTestModelModule { @Provides @Singleton ApiInterface provideApiInterface(MockWebServer mockWebServer) { try {
// Path: app/src/test/java/com/andrey7mel/stepbystep/integration/other/IntegrationApiModule.java // public class IntegrationApiModule { // // public ApiInterface getApiInterface(MockWebServer mockWebServer) throws IOException { // mockWebServer.start(); // TestUtils testUtils = new TestUtils(); // final Dispatcher dispatcher = new Dispatcher() { // // @Override // public MockResponse dispatch(RecordedRequest request) throws InterruptedException { // // if (request.getPath().equals("/users/" + TestConst.TEST_OWNER + "/repos")) { // return new MockResponse().setResponseCode(200) // .setBody(testUtils.readString("json/repos.json")); // } else if (request.getPath().equals("/repos/" + TestConst.TEST_OWNER + "/" + TestConst.TEST_REPO + "/branches")) { // return new MockResponse().setResponseCode(200) // .setBody(testUtils.readString("json/branches.json")); // } else if (request.getPath().equals("/repos/" + TestConst.TEST_OWNER + "/" + TestConst.TEST_REPO + "/contributors")) { // return new MockResponse().setResponseCode(200) // .setBody(testUtils.readString("json/contributors.json")); // } // return new MockResponse().setResponseCode(404); // } // }; // // mockWebServer.setDispatcher(dispatcher); // HttpUrl baseUrl = mockWebServer.url("/"); // return ApiModule.getApiInterface(baseUrl.toString()); // } // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiInterface.java // public interface ApiInterface { // // @GET("/users/{user}/repos") // Observable<List<RepositoryDTO>> getRepositories(@Path("user") String user); // // @GET("/repos/{owner}/{repo}/contributors") // Observable<List<ContributorDTO>> getContributors(@Path("owner") String owner, @Path("repo") String repo); // // @GET("/repos/{owner}/{repo}/branches") // Observable<List<BranchDTO>> getBranches(@Path("owner") String owner, @Path("repo") String repo); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/other/Const.java // public interface Const { // String UI_THREAD = "UI_THREAD"; // String IO_THREAD = "IO_THREAD"; // // String BASE_URL = "https://api.github.com/"; // // } // Path: app/src/test/java/com/andrey7mel/stepbystep/integration/other/di/IntegrationTestModelModule.java import com.andrey7mel.stepbystep.integration.other.IntegrationApiModule; import com.andrey7mel.stepbystep.model.api.ApiInterface; import com.andrey7mel.stepbystep.other.Const; import com.squareup.okhttp.mockwebserver.MockWebServer; import java.io.IOException; import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import rx.Scheduler; import rx.schedulers.Schedulers; package com.andrey7mel.stepbystep.integration.other.di; @Module public class IntegrationTestModelModule { @Provides @Singleton ApiInterface provideApiInterface(MockWebServer mockWebServer) { try {
return new IntegrationApiModule().getApiInterface(mockWebServer);
andrey7mel/android-step-by-step
app/src/test/java/com/andrey7mel/stepbystep/integration/other/di/IntegrationTestModelModule.java
// Path: app/src/test/java/com/andrey7mel/stepbystep/integration/other/IntegrationApiModule.java // public class IntegrationApiModule { // // public ApiInterface getApiInterface(MockWebServer mockWebServer) throws IOException { // mockWebServer.start(); // TestUtils testUtils = new TestUtils(); // final Dispatcher dispatcher = new Dispatcher() { // // @Override // public MockResponse dispatch(RecordedRequest request) throws InterruptedException { // // if (request.getPath().equals("/users/" + TestConst.TEST_OWNER + "/repos")) { // return new MockResponse().setResponseCode(200) // .setBody(testUtils.readString("json/repos.json")); // } else if (request.getPath().equals("/repos/" + TestConst.TEST_OWNER + "/" + TestConst.TEST_REPO + "/branches")) { // return new MockResponse().setResponseCode(200) // .setBody(testUtils.readString("json/branches.json")); // } else if (request.getPath().equals("/repos/" + TestConst.TEST_OWNER + "/" + TestConst.TEST_REPO + "/contributors")) { // return new MockResponse().setResponseCode(200) // .setBody(testUtils.readString("json/contributors.json")); // } // return new MockResponse().setResponseCode(404); // } // }; // // mockWebServer.setDispatcher(dispatcher); // HttpUrl baseUrl = mockWebServer.url("/"); // return ApiModule.getApiInterface(baseUrl.toString()); // } // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiInterface.java // public interface ApiInterface { // // @GET("/users/{user}/repos") // Observable<List<RepositoryDTO>> getRepositories(@Path("user") String user); // // @GET("/repos/{owner}/{repo}/contributors") // Observable<List<ContributorDTO>> getContributors(@Path("owner") String owner, @Path("repo") String repo); // // @GET("/repos/{owner}/{repo}/branches") // Observable<List<BranchDTO>> getBranches(@Path("owner") String owner, @Path("repo") String repo); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/other/Const.java // public interface Const { // String UI_THREAD = "UI_THREAD"; // String IO_THREAD = "IO_THREAD"; // // String BASE_URL = "https://api.github.com/"; // // }
import com.andrey7mel.stepbystep.integration.other.IntegrationApiModule; import com.andrey7mel.stepbystep.model.api.ApiInterface; import com.andrey7mel.stepbystep.other.Const; import com.squareup.okhttp.mockwebserver.MockWebServer; import java.io.IOException; import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import rx.Scheduler; import rx.schedulers.Schedulers;
package com.andrey7mel.stepbystep.integration.other.di; @Module public class IntegrationTestModelModule { @Provides @Singleton ApiInterface provideApiInterface(MockWebServer mockWebServer) { try { return new IntegrationApiModule().getApiInterface(mockWebServer); } catch (IOException e) { throw new RuntimeException("Can't create ApiInterface"); } } @Provides @Singleton MockWebServer provideMockWebServer() { return new MockWebServer(); } @Provides @Singleton
// Path: app/src/test/java/com/andrey7mel/stepbystep/integration/other/IntegrationApiModule.java // public class IntegrationApiModule { // // public ApiInterface getApiInterface(MockWebServer mockWebServer) throws IOException { // mockWebServer.start(); // TestUtils testUtils = new TestUtils(); // final Dispatcher dispatcher = new Dispatcher() { // // @Override // public MockResponse dispatch(RecordedRequest request) throws InterruptedException { // // if (request.getPath().equals("/users/" + TestConst.TEST_OWNER + "/repos")) { // return new MockResponse().setResponseCode(200) // .setBody(testUtils.readString("json/repos.json")); // } else if (request.getPath().equals("/repos/" + TestConst.TEST_OWNER + "/" + TestConst.TEST_REPO + "/branches")) { // return new MockResponse().setResponseCode(200) // .setBody(testUtils.readString("json/branches.json")); // } else if (request.getPath().equals("/repos/" + TestConst.TEST_OWNER + "/" + TestConst.TEST_REPO + "/contributors")) { // return new MockResponse().setResponseCode(200) // .setBody(testUtils.readString("json/contributors.json")); // } // return new MockResponse().setResponseCode(404); // } // }; // // mockWebServer.setDispatcher(dispatcher); // HttpUrl baseUrl = mockWebServer.url("/"); // return ApiModule.getApiInterface(baseUrl.toString()); // } // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiInterface.java // public interface ApiInterface { // // @GET("/users/{user}/repos") // Observable<List<RepositoryDTO>> getRepositories(@Path("user") String user); // // @GET("/repos/{owner}/{repo}/contributors") // Observable<List<ContributorDTO>> getContributors(@Path("owner") String owner, @Path("repo") String repo); // // @GET("/repos/{owner}/{repo}/branches") // Observable<List<BranchDTO>> getBranches(@Path("owner") String owner, @Path("repo") String repo); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/other/Const.java // public interface Const { // String UI_THREAD = "UI_THREAD"; // String IO_THREAD = "IO_THREAD"; // // String BASE_URL = "https://api.github.com/"; // // } // Path: app/src/test/java/com/andrey7mel/stepbystep/integration/other/di/IntegrationTestModelModule.java import com.andrey7mel.stepbystep.integration.other.IntegrationApiModule; import com.andrey7mel.stepbystep.model.api.ApiInterface; import com.andrey7mel.stepbystep.other.Const; import com.squareup.okhttp.mockwebserver.MockWebServer; import java.io.IOException; import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import rx.Scheduler; import rx.schedulers.Schedulers; package com.andrey7mel.stepbystep.integration.other.di; @Module public class IntegrationTestModelModule { @Provides @Singleton ApiInterface provideApiInterface(MockWebServer mockWebServer) { try { return new IntegrationApiModule().getApiInterface(mockWebServer); } catch (IOException e) { throw new RuntimeException("Can't create ApiInterface"); } } @Provides @Singleton MockWebServer provideMockWebServer() { return new MockWebServer(); } @Provides @Singleton
@Named(Const.UI_THREAD)
andrey7mel/android-step-by-step
app/src/test/java/com/andrey7mel/stepbystep/other/BaseTest.java
// Path: app/src/test/java/com/andrey7mel/stepbystep/other/di/TestComponent.java // @Singleton // @Component(modules = {ModelTestModule.class, PresenterTestModule.class, ViewTestModule.class, DataTestModule.class}) // public interface TestComponent extends AppComponent { // // // void inject(ModelImplTest dataRepositoryImplTest); // // void inject(RepoInfoPresenterTest repoInfoPresenterTest); // // void inject(RepoListPresenterTest repoListPresenterTest); // // void inject(RepoBranchesMapperTest repoBranchesMapperTest); // // void inject(RepoContributorsMapperTest repoContributorsMapperTest); // // void inject(RepoListMapperTest userReposMapperTest); // // void inject(RepoInfoFragmentTest repoInfoFragmentTest); // // void inject(RepoListFragmentTest repoListFragmentTest); // // void inject(BaseFragmentTest baseFragmentTest); // }
import com.andrey7mel.stepbystep.BuildConfig; import com.andrey7mel.stepbystep.other.di.TestComponent; import org.junit.Before; import org.junit.Ignore; import org.junit.runner.RunWith; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config;
package com.andrey7mel.stepbystep.other; @RunWith(RobolectricGradleTestRunner.class) @Config(application = TestApplication.class, constants = BuildConfig.class, sdk = 21) @Ignore public class BaseTest {
// Path: app/src/test/java/com/andrey7mel/stepbystep/other/di/TestComponent.java // @Singleton // @Component(modules = {ModelTestModule.class, PresenterTestModule.class, ViewTestModule.class, DataTestModule.class}) // public interface TestComponent extends AppComponent { // // // void inject(ModelImplTest dataRepositoryImplTest); // // void inject(RepoInfoPresenterTest repoInfoPresenterTest); // // void inject(RepoListPresenterTest repoListPresenterTest); // // void inject(RepoBranchesMapperTest repoBranchesMapperTest); // // void inject(RepoContributorsMapperTest repoContributorsMapperTest); // // void inject(RepoListMapperTest userReposMapperTest); // // void inject(RepoInfoFragmentTest repoInfoFragmentTest); // // void inject(RepoListFragmentTest repoListFragmentTest); // // void inject(BaseFragmentTest baseFragmentTest); // } // Path: app/src/test/java/com/andrey7mel/stepbystep/other/BaseTest.java import com.andrey7mel.stepbystep.BuildConfig; import com.andrey7mel.stepbystep.other.di.TestComponent; import org.junit.Before; import org.junit.Ignore; import org.junit.runner.RunWith; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; package com.andrey7mel.stepbystep.other; @RunWith(RobolectricGradleTestRunner.class) @Config(application = TestApplication.class, constants = BuildConfig.class, sdk = 21) @Ignore public class BaseTest {
public TestComponent component;
andrey7mel/android-step-by-step
app/src/main/java/com/andrey7mel/stepbystep/other/di/view/ViewDynamicModule.java
// Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/RepoListPresenter.java // public class RepoListPresenter extends BasePresenter { // // private static final String BUNDLE_REPO_LIST_KEY = "BUNDLE_REPO_LIST_KEY"; // // @Inject // protected RepoListMapper repoListMapper; // // private RepoListView view; // // private List<Repository> repoList; // // // for DI // @Inject // public RepoListPresenter() { // } // // public RepoListPresenter(RepoListView view) { // App.getComponent().inject(this); // this.view = view; // } // // @Override // protected View getView() { // return view; // } // // public void onSearchButtonClick() { // String name = view.getUserName(); // if (TextUtils.isEmpty(name)) return; // // showLoadingState(); // Subscription subscription = model.getRepoList(name) // .map(repoListMapper) // .subscribe(new Observer<List<Repository>>() { // // @Override // public void onCompleted() { // hideLoadingState(); // } // // @Override // public void onError(Throwable e) { // hideLoadingState(); // showError(e); // } // // @Override // public void onNext(List<Repository> list) { // if (list != null && !list.isEmpty()) { // repoList = list; // view.showRepoList(list); // } else { // view.showEmptyList(); // } // } // }); // addSubscription(subscription); // } // // public void onCreateView(Bundle savedInstanceState) { // if (savedInstanceState != null) { // repoList = (List<Repository>) savedInstanceState.getSerializable(BUNDLE_REPO_LIST_KEY); // } // if (isRepoListNotEmpty()) { // view.showRepoList(repoList); // } // } // // private boolean isRepoListNotEmpty() { // return (repoList != null && !repoList.isEmpty()); // } // // public void onSaveInstanceState(Bundle outState) { // if (isRepoListNotEmpty()) { // outState.putSerializable(BUNDLE_REPO_LIST_KEY, new ArrayList<>(repoList)); // } // } // // public void clickRepo(Repository repository) { // view.startRepoInfoFragment(repository); // } // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/RepoListView.java // public interface RepoListView extends View { // // void showRepoList(List<Repository> vo); // // void showEmptyList(); // // String getUserName(); // // void startRepoInfoFragment(Repository repository); // // }
import com.andrey7mel.stepbystep.presenter.RepoListPresenter; import com.andrey7mel.stepbystep.view.fragments.RepoListView; import dagger.Module; import dagger.Provides;
package com.andrey7mel.stepbystep.other.di.view; @Module public class ViewDynamicModule {
// Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/RepoListPresenter.java // public class RepoListPresenter extends BasePresenter { // // private static final String BUNDLE_REPO_LIST_KEY = "BUNDLE_REPO_LIST_KEY"; // // @Inject // protected RepoListMapper repoListMapper; // // private RepoListView view; // // private List<Repository> repoList; // // // for DI // @Inject // public RepoListPresenter() { // } // // public RepoListPresenter(RepoListView view) { // App.getComponent().inject(this); // this.view = view; // } // // @Override // protected View getView() { // return view; // } // // public void onSearchButtonClick() { // String name = view.getUserName(); // if (TextUtils.isEmpty(name)) return; // // showLoadingState(); // Subscription subscription = model.getRepoList(name) // .map(repoListMapper) // .subscribe(new Observer<List<Repository>>() { // // @Override // public void onCompleted() { // hideLoadingState(); // } // // @Override // public void onError(Throwable e) { // hideLoadingState(); // showError(e); // } // // @Override // public void onNext(List<Repository> list) { // if (list != null && !list.isEmpty()) { // repoList = list; // view.showRepoList(list); // } else { // view.showEmptyList(); // } // } // }); // addSubscription(subscription); // } // // public void onCreateView(Bundle savedInstanceState) { // if (savedInstanceState != null) { // repoList = (List<Repository>) savedInstanceState.getSerializable(BUNDLE_REPO_LIST_KEY); // } // if (isRepoListNotEmpty()) { // view.showRepoList(repoList); // } // } // // private boolean isRepoListNotEmpty() { // return (repoList != null && !repoList.isEmpty()); // } // // public void onSaveInstanceState(Bundle outState) { // if (isRepoListNotEmpty()) { // outState.putSerializable(BUNDLE_REPO_LIST_KEY, new ArrayList<>(repoList)); // } // } // // public void clickRepo(Repository repository) { // view.startRepoInfoFragment(repository); // } // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/RepoListView.java // public interface RepoListView extends View { // // void showRepoList(List<Repository> vo); // // void showEmptyList(); // // String getUserName(); // // void startRepoInfoFragment(Repository repository); // // } // Path: app/src/main/java/com/andrey7mel/stepbystep/other/di/view/ViewDynamicModule.java import com.andrey7mel.stepbystep.presenter.RepoListPresenter; import com.andrey7mel.stepbystep.view.fragments.RepoListView; import dagger.Module; import dagger.Provides; package com.andrey7mel.stepbystep.other.di.view; @Module public class ViewDynamicModule {
private RepoListView view;
andrey7mel/android-step-by-step
app/src/main/java/com/andrey7mel/stepbystep/other/di/view/ViewDynamicModule.java
// Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/RepoListPresenter.java // public class RepoListPresenter extends BasePresenter { // // private static final String BUNDLE_REPO_LIST_KEY = "BUNDLE_REPO_LIST_KEY"; // // @Inject // protected RepoListMapper repoListMapper; // // private RepoListView view; // // private List<Repository> repoList; // // // for DI // @Inject // public RepoListPresenter() { // } // // public RepoListPresenter(RepoListView view) { // App.getComponent().inject(this); // this.view = view; // } // // @Override // protected View getView() { // return view; // } // // public void onSearchButtonClick() { // String name = view.getUserName(); // if (TextUtils.isEmpty(name)) return; // // showLoadingState(); // Subscription subscription = model.getRepoList(name) // .map(repoListMapper) // .subscribe(new Observer<List<Repository>>() { // // @Override // public void onCompleted() { // hideLoadingState(); // } // // @Override // public void onError(Throwable e) { // hideLoadingState(); // showError(e); // } // // @Override // public void onNext(List<Repository> list) { // if (list != null && !list.isEmpty()) { // repoList = list; // view.showRepoList(list); // } else { // view.showEmptyList(); // } // } // }); // addSubscription(subscription); // } // // public void onCreateView(Bundle savedInstanceState) { // if (savedInstanceState != null) { // repoList = (List<Repository>) savedInstanceState.getSerializable(BUNDLE_REPO_LIST_KEY); // } // if (isRepoListNotEmpty()) { // view.showRepoList(repoList); // } // } // // private boolean isRepoListNotEmpty() { // return (repoList != null && !repoList.isEmpty()); // } // // public void onSaveInstanceState(Bundle outState) { // if (isRepoListNotEmpty()) { // outState.putSerializable(BUNDLE_REPO_LIST_KEY, new ArrayList<>(repoList)); // } // } // // public void clickRepo(Repository repository) { // view.startRepoInfoFragment(repository); // } // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/RepoListView.java // public interface RepoListView extends View { // // void showRepoList(List<Repository> vo); // // void showEmptyList(); // // String getUserName(); // // void startRepoInfoFragment(Repository repository); // // }
import com.andrey7mel.stepbystep.presenter.RepoListPresenter; import com.andrey7mel.stepbystep.view.fragments.RepoListView; import dagger.Module; import dagger.Provides;
package com.andrey7mel.stepbystep.other.di.view; @Module public class ViewDynamicModule { private RepoListView view; public ViewDynamicModule(RepoListView view) { this.view = view; } @Provides
// Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/RepoListPresenter.java // public class RepoListPresenter extends BasePresenter { // // private static final String BUNDLE_REPO_LIST_KEY = "BUNDLE_REPO_LIST_KEY"; // // @Inject // protected RepoListMapper repoListMapper; // // private RepoListView view; // // private List<Repository> repoList; // // // for DI // @Inject // public RepoListPresenter() { // } // // public RepoListPresenter(RepoListView view) { // App.getComponent().inject(this); // this.view = view; // } // // @Override // protected View getView() { // return view; // } // // public void onSearchButtonClick() { // String name = view.getUserName(); // if (TextUtils.isEmpty(name)) return; // // showLoadingState(); // Subscription subscription = model.getRepoList(name) // .map(repoListMapper) // .subscribe(new Observer<List<Repository>>() { // // @Override // public void onCompleted() { // hideLoadingState(); // } // // @Override // public void onError(Throwable e) { // hideLoadingState(); // showError(e); // } // // @Override // public void onNext(List<Repository> list) { // if (list != null && !list.isEmpty()) { // repoList = list; // view.showRepoList(list); // } else { // view.showEmptyList(); // } // } // }); // addSubscription(subscription); // } // // public void onCreateView(Bundle savedInstanceState) { // if (savedInstanceState != null) { // repoList = (List<Repository>) savedInstanceState.getSerializable(BUNDLE_REPO_LIST_KEY); // } // if (isRepoListNotEmpty()) { // view.showRepoList(repoList); // } // } // // private boolean isRepoListNotEmpty() { // return (repoList != null && !repoList.isEmpty()); // } // // public void onSaveInstanceState(Bundle outState) { // if (isRepoListNotEmpty()) { // outState.putSerializable(BUNDLE_REPO_LIST_KEY, new ArrayList<>(repoList)); // } // } // // public void clickRepo(Repository repository) { // view.startRepoInfoFragment(repository); // } // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/RepoListView.java // public interface RepoListView extends View { // // void showRepoList(List<Repository> vo); // // void showEmptyList(); // // String getUserName(); // // void startRepoInfoFragment(Repository repository); // // } // Path: app/src/main/java/com/andrey7mel/stepbystep/other/di/view/ViewDynamicModule.java import com.andrey7mel.stepbystep.presenter.RepoListPresenter; import com.andrey7mel.stepbystep.view.fragments.RepoListView; import dagger.Module; import dagger.Provides; package com.andrey7mel.stepbystep.other.di.view; @Module public class ViewDynamicModule { private RepoListView view; public ViewDynamicModule(RepoListView view) { this.view = view; } @Provides
RepoListPresenter provideRepoListPresenter() {
andrey7mel/android-step-by-step
app/src/test/java/com/andrey7mel/stepbystep/presenter/mappers/RepoBranchesMapperTest.java
// Path: app/src/main/java/com/andrey7mel/stepbystep/model/dto/BranchDTO.java // public class BranchDTO { // // @SerializedName("name") // @Expose // private String name; // @SerializedName("commit") // @Expose // private CommitDTO commit; // @SerializedName("protection") // @Expose // private ProtectionDTO protection; // // /** // * @return The name // */ // public String getName() { // return name; // } // // /** // * @param name The name // */ // public void setName(String name) { // this.name = name; // } // // /** // * @return The commit // */ // public CommitDTO getCommit() { // return commit; // } // // /** // * @param commit The commit // */ // public void setCommit(CommitDTO commit) { // this.commit = commit; // } // // /** // * @return The protection // */ // public ProtectionDTO getProtection() { // return protection; // } // // /** // * @param protection The protection // */ // public void setProtection(ProtectionDTO protection) { // this.protection = protection; // } // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/BaseTest.java // @RunWith(RobolectricGradleTestRunner.class) // @Config(application = TestApplication.class, // constants = BuildConfig.class, // sdk = 21) // @Ignore // public class BaseTest { // // public TestComponent component; // public TestUtils testUtils; // // @Before // public void setUp() throws Exception { // component = (TestComponent) App.getComponent(); // testUtils = new TestUtils(); // } // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/vo/Branch.java // public class Branch implements Serializable { // private String name; // // public Branch(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Branch branch = (Branch) o; // // return !(name != null ? !name.equals(branch.name) : branch.name != null); // // } // // @Override // public int hashCode() { // return name != null ? name.hashCode() : 0; // } // }
import com.andrey7mel.stepbystep.model.dto.BranchDTO; import com.andrey7mel.stepbystep.other.BaseTest; import com.andrey7mel.stepbystep.presenter.vo.Branch; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import java.util.List; import javax.inject.Inject; import static org.junit.Assert.assertEquals;
package com.andrey7mel.stepbystep.presenter.mappers; public class RepoBranchesMapperTest extends BaseTest { @Inject protected RepoBranchesMapper branchesMapper;
// Path: app/src/main/java/com/andrey7mel/stepbystep/model/dto/BranchDTO.java // public class BranchDTO { // // @SerializedName("name") // @Expose // private String name; // @SerializedName("commit") // @Expose // private CommitDTO commit; // @SerializedName("protection") // @Expose // private ProtectionDTO protection; // // /** // * @return The name // */ // public String getName() { // return name; // } // // /** // * @param name The name // */ // public void setName(String name) { // this.name = name; // } // // /** // * @return The commit // */ // public CommitDTO getCommit() { // return commit; // } // // /** // * @param commit The commit // */ // public void setCommit(CommitDTO commit) { // this.commit = commit; // } // // /** // * @return The protection // */ // public ProtectionDTO getProtection() { // return protection; // } // // /** // * @param protection The protection // */ // public void setProtection(ProtectionDTO protection) { // this.protection = protection; // } // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/BaseTest.java // @RunWith(RobolectricGradleTestRunner.class) // @Config(application = TestApplication.class, // constants = BuildConfig.class, // sdk = 21) // @Ignore // public class BaseTest { // // public TestComponent component; // public TestUtils testUtils; // // @Before // public void setUp() throws Exception { // component = (TestComponent) App.getComponent(); // testUtils = new TestUtils(); // } // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/vo/Branch.java // public class Branch implements Serializable { // private String name; // // public Branch(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Branch branch = (Branch) o; // // return !(name != null ? !name.equals(branch.name) : branch.name != null); // // } // // @Override // public int hashCode() { // return name != null ? name.hashCode() : 0; // } // } // Path: app/src/test/java/com/andrey7mel/stepbystep/presenter/mappers/RepoBranchesMapperTest.java import com.andrey7mel.stepbystep.model.dto.BranchDTO; import com.andrey7mel.stepbystep.other.BaseTest; import com.andrey7mel.stepbystep.presenter.vo.Branch; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import java.util.List; import javax.inject.Inject; import static org.junit.Assert.assertEquals; package com.andrey7mel.stepbystep.presenter.mappers; public class RepoBranchesMapperTest extends BaseTest { @Inject protected RepoBranchesMapper branchesMapper;
private List<BranchDTO> branchDTOs;
andrey7mel/android-step-by-step
app/src/test/java/com/andrey7mel/stepbystep/presenter/mappers/RepoBranchesMapperTest.java
// Path: app/src/main/java/com/andrey7mel/stepbystep/model/dto/BranchDTO.java // public class BranchDTO { // // @SerializedName("name") // @Expose // private String name; // @SerializedName("commit") // @Expose // private CommitDTO commit; // @SerializedName("protection") // @Expose // private ProtectionDTO protection; // // /** // * @return The name // */ // public String getName() { // return name; // } // // /** // * @param name The name // */ // public void setName(String name) { // this.name = name; // } // // /** // * @return The commit // */ // public CommitDTO getCommit() { // return commit; // } // // /** // * @param commit The commit // */ // public void setCommit(CommitDTO commit) { // this.commit = commit; // } // // /** // * @return The protection // */ // public ProtectionDTO getProtection() { // return protection; // } // // /** // * @param protection The protection // */ // public void setProtection(ProtectionDTO protection) { // this.protection = protection; // } // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/BaseTest.java // @RunWith(RobolectricGradleTestRunner.class) // @Config(application = TestApplication.class, // constants = BuildConfig.class, // sdk = 21) // @Ignore // public class BaseTest { // // public TestComponent component; // public TestUtils testUtils; // // @Before // public void setUp() throws Exception { // component = (TestComponent) App.getComponent(); // testUtils = new TestUtils(); // } // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/vo/Branch.java // public class Branch implements Serializable { // private String name; // // public Branch(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Branch branch = (Branch) o; // // return !(name != null ? !name.equals(branch.name) : branch.name != null); // // } // // @Override // public int hashCode() { // return name != null ? name.hashCode() : 0; // } // }
import com.andrey7mel.stepbystep.model.dto.BranchDTO; import com.andrey7mel.stepbystep.other.BaseTest; import com.andrey7mel.stepbystep.presenter.vo.Branch; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import java.util.List; import javax.inject.Inject; import static org.junit.Assert.assertEquals;
package com.andrey7mel.stepbystep.presenter.mappers; public class RepoBranchesMapperTest extends BaseTest { @Inject protected RepoBranchesMapper branchesMapper; private List<BranchDTO> branchDTOs; @Before public void setUp() throws Exception { super.setUp(); component.inject(this); BranchDTO[] branchDTOArray = testUtils.getGson().fromJson(testUtils.readString("json/branches.json"), BranchDTO[].class); branchDTOs = Arrays.asList(branchDTOArray); } @Test public void testCall() throws Exception {
// Path: app/src/main/java/com/andrey7mel/stepbystep/model/dto/BranchDTO.java // public class BranchDTO { // // @SerializedName("name") // @Expose // private String name; // @SerializedName("commit") // @Expose // private CommitDTO commit; // @SerializedName("protection") // @Expose // private ProtectionDTO protection; // // /** // * @return The name // */ // public String getName() { // return name; // } // // /** // * @param name The name // */ // public void setName(String name) { // this.name = name; // } // // /** // * @return The commit // */ // public CommitDTO getCommit() { // return commit; // } // // /** // * @param commit The commit // */ // public void setCommit(CommitDTO commit) { // this.commit = commit; // } // // /** // * @return The protection // */ // public ProtectionDTO getProtection() { // return protection; // } // // /** // * @param protection The protection // */ // public void setProtection(ProtectionDTO protection) { // this.protection = protection; // } // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/BaseTest.java // @RunWith(RobolectricGradleTestRunner.class) // @Config(application = TestApplication.class, // constants = BuildConfig.class, // sdk = 21) // @Ignore // public class BaseTest { // // public TestComponent component; // public TestUtils testUtils; // // @Before // public void setUp() throws Exception { // component = (TestComponent) App.getComponent(); // testUtils = new TestUtils(); // } // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/vo/Branch.java // public class Branch implements Serializable { // private String name; // // public Branch(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Branch branch = (Branch) o; // // return !(name != null ? !name.equals(branch.name) : branch.name != null); // // } // // @Override // public int hashCode() { // return name != null ? name.hashCode() : 0; // } // } // Path: app/src/test/java/com/andrey7mel/stepbystep/presenter/mappers/RepoBranchesMapperTest.java import com.andrey7mel.stepbystep.model.dto.BranchDTO; import com.andrey7mel.stepbystep.other.BaseTest; import com.andrey7mel.stepbystep.presenter.vo.Branch; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import java.util.List; import javax.inject.Inject; import static org.junit.Assert.assertEquals; package com.andrey7mel.stepbystep.presenter.mappers; public class RepoBranchesMapperTest extends BaseTest { @Inject protected RepoBranchesMapper branchesMapper; private List<BranchDTO> branchDTOs; @Before public void setUp() throws Exception { super.setUp(); component.inject(this); BranchDTO[] branchDTOArray = testUtils.getGson().fromJson(testUtils.readString("json/branches.json"), BranchDTO[].class); branchDTOs = Arrays.asList(branchDTOArray); } @Test public void testCall() throws Exception {
List<Branch> branchList = branchesMapper.call(branchDTOs);
andrey7mel/android-step-by-step
app/src/test/java/com/andrey7mel/stepbystep/other/di/ModelTestModule.java
// Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiInterface.java // public interface ApiInterface { // // @GET("/users/{user}/repos") // Observable<List<RepositoryDTO>> getRepositories(@Path("user") String user); // // @GET("/repos/{owner}/{repo}/contributors") // Observable<List<ContributorDTO>> getContributors(@Path("owner") String owner, @Path("repo") String repo); // // @GET("/repos/{owner}/{repo}/branches") // Observable<List<BranchDTO>> getBranches(@Path("owner") String owner, @Path("repo") String repo); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/other/Const.java // public interface Const { // String UI_THREAD = "UI_THREAD"; // String IO_THREAD = "IO_THREAD"; // // String BASE_URL = "https://api.github.com/"; // // }
import com.andrey7mel.stepbystep.model.api.ApiInterface; import com.andrey7mel.stepbystep.other.Const; import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import rx.Scheduler; import rx.schedulers.Schedulers; import static org.mockito.Mockito.mock;
package com.andrey7mel.stepbystep.other.di; @Module public class ModelTestModule { @Provides @Singleton
// Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiInterface.java // public interface ApiInterface { // // @GET("/users/{user}/repos") // Observable<List<RepositoryDTO>> getRepositories(@Path("user") String user); // // @GET("/repos/{owner}/{repo}/contributors") // Observable<List<ContributorDTO>> getContributors(@Path("owner") String owner, @Path("repo") String repo); // // @GET("/repos/{owner}/{repo}/branches") // Observable<List<BranchDTO>> getBranches(@Path("owner") String owner, @Path("repo") String repo); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/other/Const.java // public interface Const { // String UI_THREAD = "UI_THREAD"; // String IO_THREAD = "IO_THREAD"; // // String BASE_URL = "https://api.github.com/"; // // } // Path: app/src/test/java/com/andrey7mel/stepbystep/other/di/ModelTestModule.java import com.andrey7mel.stepbystep.model.api.ApiInterface; import com.andrey7mel.stepbystep.other.Const; import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import rx.Scheduler; import rx.schedulers.Schedulers; import static org.mockito.Mockito.mock; package com.andrey7mel.stepbystep.other.di; @Module public class ModelTestModule { @Provides @Singleton
ApiInterface provideApiInterface() {
andrey7mel/android-step-by-step
app/src/test/java/com/andrey7mel/stepbystep/other/di/ModelTestModule.java
// Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiInterface.java // public interface ApiInterface { // // @GET("/users/{user}/repos") // Observable<List<RepositoryDTO>> getRepositories(@Path("user") String user); // // @GET("/repos/{owner}/{repo}/contributors") // Observable<List<ContributorDTO>> getContributors(@Path("owner") String owner, @Path("repo") String repo); // // @GET("/repos/{owner}/{repo}/branches") // Observable<List<BranchDTO>> getBranches(@Path("owner") String owner, @Path("repo") String repo); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/other/Const.java // public interface Const { // String UI_THREAD = "UI_THREAD"; // String IO_THREAD = "IO_THREAD"; // // String BASE_URL = "https://api.github.com/"; // // }
import com.andrey7mel.stepbystep.model.api.ApiInterface; import com.andrey7mel.stepbystep.other.Const; import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import rx.Scheduler; import rx.schedulers.Schedulers; import static org.mockito.Mockito.mock;
package com.andrey7mel.stepbystep.other.di; @Module public class ModelTestModule { @Provides @Singleton ApiInterface provideApiInterface() { return mock(ApiInterface.class); } @Provides @Singleton
// Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiInterface.java // public interface ApiInterface { // // @GET("/users/{user}/repos") // Observable<List<RepositoryDTO>> getRepositories(@Path("user") String user); // // @GET("/repos/{owner}/{repo}/contributors") // Observable<List<ContributorDTO>> getContributors(@Path("owner") String owner, @Path("repo") String repo); // // @GET("/repos/{owner}/{repo}/branches") // Observable<List<BranchDTO>> getBranches(@Path("owner") String owner, @Path("repo") String repo); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/other/Const.java // public interface Const { // String UI_THREAD = "UI_THREAD"; // String IO_THREAD = "IO_THREAD"; // // String BASE_URL = "https://api.github.com/"; // // } // Path: app/src/test/java/com/andrey7mel/stepbystep/other/di/ModelTestModule.java import com.andrey7mel.stepbystep.model.api.ApiInterface; import com.andrey7mel.stepbystep.other.Const; import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import rx.Scheduler; import rx.schedulers.Schedulers; import static org.mockito.Mockito.mock; package com.andrey7mel.stepbystep.other.di; @Module public class ModelTestModule { @Provides @Singleton ApiInterface provideApiInterface() { return mock(ApiInterface.class); } @Provides @Singleton
@Named(Const.UI_THREAD)
andrey7mel/android-step-by-step
app/src/test/java/com/andrey7mel/stepbystep/integration/other/IntegrationBaseTest.java
// Path: app/src/test/java/com/andrey7mel/stepbystep/integration/other/di/IntegrationTestComponent.java // @Singleton // @Component(modules = {IntegrationTestModelModule.class, PresenterModule.class, ViewModule.class, DataTestModule.class}) // public interface IntegrationTestComponent extends AppComponent { // // void inject(ModelTest modelTest); // // void inject(RepoInfoPresenterTest repoInfoPresenterTest); // // void inject(RepoListPresenterTest repoListPresenterTest); // // void inject(RepoInfoFragmentTest repoInfoFragmentTest); // // void inject(RepoListFragmentTest repoListFragmentTest); // // void inject(IntegrationBaseTest integrationBaseTest); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/other/App.java // public class App extends Application { // // private static AppComponent component; // // public static AppComponent getComponent() { // return component; // } // // @Override // public void onCreate() { // super.onCreate(); // component = buildComponent(); // } // // protected AppComponent buildComponent() { // return DaggerAppComponent.builder() // .build(); // } // // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/TestConst.java // public class TestConst { // public static final String TEST_OWNER = "TEST_OWNER"; // public static final String TEST_REPO = "TEST_REPO"; // public static final String TEST_ERROR = "TEST_ERROR"; // public static final String ERROR_RESPONSE_500 = "HTTP 500 OK"; // public static final String ERROR_RESPONSE_404 = "HTTP 404 OK"; // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/TestUtils.java // public class TestUtils { // // private Gson gson = new GsonBuilder() // .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create(); // // public void log(String log) { // System.out.println(log); // } // // public Gson getGson() { // return gson; // } // // // public <T> T readJson(String fileName, Class<T> inClass) { // return gson.fromJson(readString(fileName), inClass); // } // // public String readString(String fileName) { // InputStream stream = getClass().getClassLoader().getResourceAsStream(fileName); // try { // int size = stream.available(); // byte[] buffer = new byte[size]; // int result = stream.read(buffer); // return new String(buffer, "utf8"); // } catch (IOException e) { // e.printStackTrace(); // return null; // } finally { // try { // if (stream != null) { // stream.close(); // } // } catch (IOException e) { // e.printStackTrace(); // } // } // // } // // }
import com.andrey7mel.stepbystep.BuildConfig; import com.andrey7mel.stepbystep.integration.other.di.IntegrationTestComponent; import com.andrey7mel.stepbystep.other.App; import com.andrey7mel.stepbystep.other.TestConst; import com.andrey7mel.stepbystep.other.TestUtils; import com.squareup.okhttp.mockwebserver.Dispatcher; import com.squareup.okhttp.mockwebserver.MockResponse; import com.squareup.okhttp.mockwebserver.MockWebServer; import com.squareup.okhttp.mockwebserver.RecordedRequest; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.runner.RunWith; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import javax.inject.Inject;
package com.andrey7mel.stepbystep.integration.other; @RunWith(RobolectricGradleTestRunner.class) @Config(application = IntegrationTestApp.class, constants = BuildConfig.class, sdk = 21) @Ignore public class IntegrationBaseTest {
// Path: app/src/test/java/com/andrey7mel/stepbystep/integration/other/di/IntegrationTestComponent.java // @Singleton // @Component(modules = {IntegrationTestModelModule.class, PresenterModule.class, ViewModule.class, DataTestModule.class}) // public interface IntegrationTestComponent extends AppComponent { // // void inject(ModelTest modelTest); // // void inject(RepoInfoPresenterTest repoInfoPresenterTest); // // void inject(RepoListPresenterTest repoListPresenterTest); // // void inject(RepoInfoFragmentTest repoInfoFragmentTest); // // void inject(RepoListFragmentTest repoListFragmentTest); // // void inject(IntegrationBaseTest integrationBaseTest); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/other/App.java // public class App extends Application { // // private static AppComponent component; // // public static AppComponent getComponent() { // return component; // } // // @Override // public void onCreate() { // super.onCreate(); // component = buildComponent(); // } // // protected AppComponent buildComponent() { // return DaggerAppComponent.builder() // .build(); // } // // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/TestConst.java // public class TestConst { // public static final String TEST_OWNER = "TEST_OWNER"; // public static final String TEST_REPO = "TEST_REPO"; // public static final String TEST_ERROR = "TEST_ERROR"; // public static final String ERROR_RESPONSE_500 = "HTTP 500 OK"; // public static final String ERROR_RESPONSE_404 = "HTTP 404 OK"; // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/TestUtils.java // public class TestUtils { // // private Gson gson = new GsonBuilder() // .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create(); // // public void log(String log) { // System.out.println(log); // } // // public Gson getGson() { // return gson; // } // // // public <T> T readJson(String fileName, Class<T> inClass) { // return gson.fromJson(readString(fileName), inClass); // } // // public String readString(String fileName) { // InputStream stream = getClass().getClassLoader().getResourceAsStream(fileName); // try { // int size = stream.available(); // byte[] buffer = new byte[size]; // int result = stream.read(buffer); // return new String(buffer, "utf8"); // } catch (IOException e) { // e.printStackTrace(); // return null; // } finally { // try { // if (stream != null) { // stream.close(); // } // } catch (IOException e) { // e.printStackTrace(); // } // } // // } // // } // Path: app/src/test/java/com/andrey7mel/stepbystep/integration/other/IntegrationBaseTest.java import com.andrey7mel.stepbystep.BuildConfig; import com.andrey7mel.stepbystep.integration.other.di.IntegrationTestComponent; import com.andrey7mel.stepbystep.other.App; import com.andrey7mel.stepbystep.other.TestConst; import com.andrey7mel.stepbystep.other.TestUtils; import com.squareup.okhttp.mockwebserver.Dispatcher; import com.squareup.okhttp.mockwebserver.MockResponse; import com.squareup.okhttp.mockwebserver.MockWebServer; import com.squareup.okhttp.mockwebserver.RecordedRequest; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.runner.RunWith; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import javax.inject.Inject; package com.andrey7mel.stepbystep.integration.other; @RunWith(RobolectricGradleTestRunner.class) @Config(application = IntegrationTestApp.class, constants = BuildConfig.class, sdk = 21) @Ignore public class IntegrationBaseTest {
public IntegrationTestComponent component;
andrey7mel/android-step-by-step
app/src/test/java/com/andrey7mel/stepbystep/integration/other/IntegrationBaseTest.java
// Path: app/src/test/java/com/andrey7mel/stepbystep/integration/other/di/IntegrationTestComponent.java // @Singleton // @Component(modules = {IntegrationTestModelModule.class, PresenterModule.class, ViewModule.class, DataTestModule.class}) // public interface IntegrationTestComponent extends AppComponent { // // void inject(ModelTest modelTest); // // void inject(RepoInfoPresenterTest repoInfoPresenterTest); // // void inject(RepoListPresenterTest repoListPresenterTest); // // void inject(RepoInfoFragmentTest repoInfoFragmentTest); // // void inject(RepoListFragmentTest repoListFragmentTest); // // void inject(IntegrationBaseTest integrationBaseTest); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/other/App.java // public class App extends Application { // // private static AppComponent component; // // public static AppComponent getComponent() { // return component; // } // // @Override // public void onCreate() { // super.onCreate(); // component = buildComponent(); // } // // protected AppComponent buildComponent() { // return DaggerAppComponent.builder() // .build(); // } // // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/TestConst.java // public class TestConst { // public static final String TEST_OWNER = "TEST_OWNER"; // public static final String TEST_REPO = "TEST_REPO"; // public static final String TEST_ERROR = "TEST_ERROR"; // public static final String ERROR_RESPONSE_500 = "HTTP 500 OK"; // public static final String ERROR_RESPONSE_404 = "HTTP 404 OK"; // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/TestUtils.java // public class TestUtils { // // private Gson gson = new GsonBuilder() // .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create(); // // public void log(String log) { // System.out.println(log); // } // // public Gson getGson() { // return gson; // } // // // public <T> T readJson(String fileName, Class<T> inClass) { // return gson.fromJson(readString(fileName), inClass); // } // // public String readString(String fileName) { // InputStream stream = getClass().getClassLoader().getResourceAsStream(fileName); // try { // int size = stream.available(); // byte[] buffer = new byte[size]; // int result = stream.read(buffer); // return new String(buffer, "utf8"); // } catch (IOException e) { // e.printStackTrace(); // return null; // } finally { // try { // if (stream != null) { // stream.close(); // } // } catch (IOException e) { // e.printStackTrace(); // } // } // // } // // }
import com.andrey7mel.stepbystep.BuildConfig; import com.andrey7mel.stepbystep.integration.other.di.IntegrationTestComponent; import com.andrey7mel.stepbystep.other.App; import com.andrey7mel.stepbystep.other.TestConst; import com.andrey7mel.stepbystep.other.TestUtils; import com.squareup.okhttp.mockwebserver.Dispatcher; import com.squareup.okhttp.mockwebserver.MockResponse; import com.squareup.okhttp.mockwebserver.MockWebServer; import com.squareup.okhttp.mockwebserver.RecordedRequest; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.runner.RunWith; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import javax.inject.Inject;
package com.andrey7mel.stepbystep.integration.other; @RunWith(RobolectricGradleTestRunner.class) @Config(application = IntegrationTestApp.class, constants = BuildConfig.class, sdk = 21) @Ignore public class IntegrationBaseTest { public IntegrationTestComponent component;
// Path: app/src/test/java/com/andrey7mel/stepbystep/integration/other/di/IntegrationTestComponent.java // @Singleton // @Component(modules = {IntegrationTestModelModule.class, PresenterModule.class, ViewModule.class, DataTestModule.class}) // public interface IntegrationTestComponent extends AppComponent { // // void inject(ModelTest modelTest); // // void inject(RepoInfoPresenterTest repoInfoPresenterTest); // // void inject(RepoListPresenterTest repoListPresenterTest); // // void inject(RepoInfoFragmentTest repoInfoFragmentTest); // // void inject(RepoListFragmentTest repoListFragmentTest); // // void inject(IntegrationBaseTest integrationBaseTest); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/other/App.java // public class App extends Application { // // private static AppComponent component; // // public static AppComponent getComponent() { // return component; // } // // @Override // public void onCreate() { // super.onCreate(); // component = buildComponent(); // } // // protected AppComponent buildComponent() { // return DaggerAppComponent.builder() // .build(); // } // // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/TestConst.java // public class TestConst { // public static final String TEST_OWNER = "TEST_OWNER"; // public static final String TEST_REPO = "TEST_REPO"; // public static final String TEST_ERROR = "TEST_ERROR"; // public static final String ERROR_RESPONSE_500 = "HTTP 500 OK"; // public static final String ERROR_RESPONSE_404 = "HTTP 404 OK"; // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/TestUtils.java // public class TestUtils { // // private Gson gson = new GsonBuilder() // .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create(); // // public void log(String log) { // System.out.println(log); // } // // public Gson getGson() { // return gson; // } // // // public <T> T readJson(String fileName, Class<T> inClass) { // return gson.fromJson(readString(fileName), inClass); // } // // public String readString(String fileName) { // InputStream stream = getClass().getClassLoader().getResourceAsStream(fileName); // try { // int size = stream.available(); // byte[] buffer = new byte[size]; // int result = stream.read(buffer); // return new String(buffer, "utf8"); // } catch (IOException e) { // e.printStackTrace(); // return null; // } finally { // try { // if (stream != null) { // stream.close(); // } // } catch (IOException e) { // e.printStackTrace(); // } // } // // } // // } // Path: app/src/test/java/com/andrey7mel/stepbystep/integration/other/IntegrationBaseTest.java import com.andrey7mel.stepbystep.BuildConfig; import com.andrey7mel.stepbystep.integration.other.di.IntegrationTestComponent; import com.andrey7mel.stepbystep.other.App; import com.andrey7mel.stepbystep.other.TestConst; import com.andrey7mel.stepbystep.other.TestUtils; import com.squareup.okhttp.mockwebserver.Dispatcher; import com.squareup.okhttp.mockwebserver.MockResponse; import com.squareup.okhttp.mockwebserver.MockWebServer; import com.squareup.okhttp.mockwebserver.RecordedRequest; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.runner.RunWith; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import javax.inject.Inject; package com.andrey7mel.stepbystep.integration.other; @RunWith(RobolectricGradleTestRunner.class) @Config(application = IntegrationTestApp.class, constants = BuildConfig.class, sdk = 21) @Ignore public class IntegrationBaseTest { public IntegrationTestComponent component;
public TestUtils testUtils;
andrey7mel/android-step-by-step
app/src/test/java/com/andrey7mel/stepbystep/integration/other/IntegrationBaseTest.java
// Path: app/src/test/java/com/andrey7mel/stepbystep/integration/other/di/IntegrationTestComponent.java // @Singleton // @Component(modules = {IntegrationTestModelModule.class, PresenterModule.class, ViewModule.class, DataTestModule.class}) // public interface IntegrationTestComponent extends AppComponent { // // void inject(ModelTest modelTest); // // void inject(RepoInfoPresenterTest repoInfoPresenterTest); // // void inject(RepoListPresenterTest repoListPresenterTest); // // void inject(RepoInfoFragmentTest repoInfoFragmentTest); // // void inject(RepoListFragmentTest repoListFragmentTest); // // void inject(IntegrationBaseTest integrationBaseTest); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/other/App.java // public class App extends Application { // // private static AppComponent component; // // public static AppComponent getComponent() { // return component; // } // // @Override // public void onCreate() { // super.onCreate(); // component = buildComponent(); // } // // protected AppComponent buildComponent() { // return DaggerAppComponent.builder() // .build(); // } // // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/TestConst.java // public class TestConst { // public static final String TEST_OWNER = "TEST_OWNER"; // public static final String TEST_REPO = "TEST_REPO"; // public static final String TEST_ERROR = "TEST_ERROR"; // public static final String ERROR_RESPONSE_500 = "HTTP 500 OK"; // public static final String ERROR_RESPONSE_404 = "HTTP 404 OK"; // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/TestUtils.java // public class TestUtils { // // private Gson gson = new GsonBuilder() // .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create(); // // public void log(String log) { // System.out.println(log); // } // // public Gson getGson() { // return gson; // } // // // public <T> T readJson(String fileName, Class<T> inClass) { // return gson.fromJson(readString(fileName), inClass); // } // // public String readString(String fileName) { // InputStream stream = getClass().getClassLoader().getResourceAsStream(fileName); // try { // int size = stream.available(); // byte[] buffer = new byte[size]; // int result = stream.read(buffer); // return new String(buffer, "utf8"); // } catch (IOException e) { // e.printStackTrace(); // return null; // } finally { // try { // if (stream != null) { // stream.close(); // } // } catch (IOException e) { // e.printStackTrace(); // } // } // // } // // }
import com.andrey7mel.stepbystep.BuildConfig; import com.andrey7mel.stepbystep.integration.other.di.IntegrationTestComponent; import com.andrey7mel.stepbystep.other.App; import com.andrey7mel.stepbystep.other.TestConst; import com.andrey7mel.stepbystep.other.TestUtils; import com.squareup.okhttp.mockwebserver.Dispatcher; import com.squareup.okhttp.mockwebserver.MockResponse; import com.squareup.okhttp.mockwebserver.MockWebServer; import com.squareup.okhttp.mockwebserver.RecordedRequest; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.runner.RunWith; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import javax.inject.Inject;
package com.andrey7mel.stepbystep.integration.other; @RunWith(RobolectricGradleTestRunner.class) @Config(application = IntegrationTestApp.class, constants = BuildConfig.class, sdk = 21) @Ignore public class IntegrationBaseTest { public IntegrationTestComponent component; public TestUtils testUtils; @Inject protected MockWebServer mockWebServer; @Before public void setUp() throws Exception {
// Path: app/src/test/java/com/andrey7mel/stepbystep/integration/other/di/IntegrationTestComponent.java // @Singleton // @Component(modules = {IntegrationTestModelModule.class, PresenterModule.class, ViewModule.class, DataTestModule.class}) // public interface IntegrationTestComponent extends AppComponent { // // void inject(ModelTest modelTest); // // void inject(RepoInfoPresenterTest repoInfoPresenterTest); // // void inject(RepoListPresenterTest repoListPresenterTest); // // void inject(RepoInfoFragmentTest repoInfoFragmentTest); // // void inject(RepoListFragmentTest repoListFragmentTest); // // void inject(IntegrationBaseTest integrationBaseTest); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/other/App.java // public class App extends Application { // // private static AppComponent component; // // public static AppComponent getComponent() { // return component; // } // // @Override // public void onCreate() { // super.onCreate(); // component = buildComponent(); // } // // protected AppComponent buildComponent() { // return DaggerAppComponent.builder() // .build(); // } // // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/TestConst.java // public class TestConst { // public static final String TEST_OWNER = "TEST_OWNER"; // public static final String TEST_REPO = "TEST_REPO"; // public static final String TEST_ERROR = "TEST_ERROR"; // public static final String ERROR_RESPONSE_500 = "HTTP 500 OK"; // public static final String ERROR_RESPONSE_404 = "HTTP 404 OK"; // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/TestUtils.java // public class TestUtils { // // private Gson gson = new GsonBuilder() // .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create(); // // public void log(String log) { // System.out.println(log); // } // // public Gson getGson() { // return gson; // } // // // public <T> T readJson(String fileName, Class<T> inClass) { // return gson.fromJson(readString(fileName), inClass); // } // // public String readString(String fileName) { // InputStream stream = getClass().getClassLoader().getResourceAsStream(fileName); // try { // int size = stream.available(); // byte[] buffer = new byte[size]; // int result = stream.read(buffer); // return new String(buffer, "utf8"); // } catch (IOException e) { // e.printStackTrace(); // return null; // } finally { // try { // if (stream != null) { // stream.close(); // } // } catch (IOException e) { // e.printStackTrace(); // } // } // // } // // } // Path: app/src/test/java/com/andrey7mel/stepbystep/integration/other/IntegrationBaseTest.java import com.andrey7mel.stepbystep.BuildConfig; import com.andrey7mel.stepbystep.integration.other.di.IntegrationTestComponent; import com.andrey7mel.stepbystep.other.App; import com.andrey7mel.stepbystep.other.TestConst; import com.andrey7mel.stepbystep.other.TestUtils; import com.squareup.okhttp.mockwebserver.Dispatcher; import com.squareup.okhttp.mockwebserver.MockResponse; import com.squareup.okhttp.mockwebserver.MockWebServer; import com.squareup.okhttp.mockwebserver.RecordedRequest; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.runner.RunWith; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import javax.inject.Inject; package com.andrey7mel.stepbystep.integration.other; @RunWith(RobolectricGradleTestRunner.class) @Config(application = IntegrationTestApp.class, constants = BuildConfig.class, sdk = 21) @Ignore public class IntegrationBaseTest { public IntegrationTestComponent component; public TestUtils testUtils; @Inject protected MockWebServer mockWebServer; @Before public void setUp() throws Exception {
component = (IntegrationTestComponent) App.getComponent();
andrey7mel/android-step-by-step
app/src/test/java/com/andrey7mel/stepbystep/integration/other/IntegrationBaseTest.java
// Path: app/src/test/java/com/andrey7mel/stepbystep/integration/other/di/IntegrationTestComponent.java // @Singleton // @Component(modules = {IntegrationTestModelModule.class, PresenterModule.class, ViewModule.class, DataTestModule.class}) // public interface IntegrationTestComponent extends AppComponent { // // void inject(ModelTest modelTest); // // void inject(RepoInfoPresenterTest repoInfoPresenterTest); // // void inject(RepoListPresenterTest repoListPresenterTest); // // void inject(RepoInfoFragmentTest repoInfoFragmentTest); // // void inject(RepoListFragmentTest repoListFragmentTest); // // void inject(IntegrationBaseTest integrationBaseTest); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/other/App.java // public class App extends Application { // // private static AppComponent component; // // public static AppComponent getComponent() { // return component; // } // // @Override // public void onCreate() { // super.onCreate(); // component = buildComponent(); // } // // protected AppComponent buildComponent() { // return DaggerAppComponent.builder() // .build(); // } // // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/TestConst.java // public class TestConst { // public static final String TEST_OWNER = "TEST_OWNER"; // public static final String TEST_REPO = "TEST_REPO"; // public static final String TEST_ERROR = "TEST_ERROR"; // public static final String ERROR_RESPONSE_500 = "HTTP 500 OK"; // public static final String ERROR_RESPONSE_404 = "HTTP 404 OK"; // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/TestUtils.java // public class TestUtils { // // private Gson gson = new GsonBuilder() // .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create(); // // public void log(String log) { // System.out.println(log); // } // // public Gson getGson() { // return gson; // } // // // public <T> T readJson(String fileName, Class<T> inClass) { // return gson.fromJson(readString(fileName), inClass); // } // // public String readString(String fileName) { // InputStream stream = getClass().getClassLoader().getResourceAsStream(fileName); // try { // int size = stream.available(); // byte[] buffer = new byte[size]; // int result = stream.read(buffer); // return new String(buffer, "utf8"); // } catch (IOException e) { // e.printStackTrace(); // return null; // } finally { // try { // if (stream != null) { // stream.close(); // } // } catch (IOException e) { // e.printStackTrace(); // } // } // // } // // }
import com.andrey7mel.stepbystep.BuildConfig; import com.andrey7mel.stepbystep.integration.other.di.IntegrationTestComponent; import com.andrey7mel.stepbystep.other.App; import com.andrey7mel.stepbystep.other.TestConst; import com.andrey7mel.stepbystep.other.TestUtils; import com.squareup.okhttp.mockwebserver.Dispatcher; import com.squareup.okhttp.mockwebserver.MockResponse; import com.squareup.okhttp.mockwebserver.MockWebServer; import com.squareup.okhttp.mockwebserver.RecordedRequest; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.runner.RunWith; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import javax.inject.Inject;
@Inject protected MockWebServer mockWebServer; @Before public void setUp() throws Exception { component = (IntegrationTestComponent) App.getComponent(); testUtils = new TestUtils(); component.inject(this); } @After public void tearDown() throws Exception { mockWebServer.shutdown(); } protected void setErrorAnswerWebServer() { mockWebServer.setDispatcher(new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException { return new MockResponse().setResponseCode(500); } }); } protected void setCustomAnswer(boolean enableBranches, boolean enableContributors) { mockWebServer.setDispatcher(new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
// Path: app/src/test/java/com/andrey7mel/stepbystep/integration/other/di/IntegrationTestComponent.java // @Singleton // @Component(modules = {IntegrationTestModelModule.class, PresenterModule.class, ViewModule.class, DataTestModule.class}) // public interface IntegrationTestComponent extends AppComponent { // // void inject(ModelTest modelTest); // // void inject(RepoInfoPresenterTest repoInfoPresenterTest); // // void inject(RepoListPresenterTest repoListPresenterTest); // // void inject(RepoInfoFragmentTest repoInfoFragmentTest); // // void inject(RepoListFragmentTest repoListFragmentTest); // // void inject(IntegrationBaseTest integrationBaseTest); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/other/App.java // public class App extends Application { // // private static AppComponent component; // // public static AppComponent getComponent() { // return component; // } // // @Override // public void onCreate() { // super.onCreate(); // component = buildComponent(); // } // // protected AppComponent buildComponent() { // return DaggerAppComponent.builder() // .build(); // } // // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/TestConst.java // public class TestConst { // public static final String TEST_OWNER = "TEST_OWNER"; // public static final String TEST_REPO = "TEST_REPO"; // public static final String TEST_ERROR = "TEST_ERROR"; // public static final String ERROR_RESPONSE_500 = "HTTP 500 OK"; // public static final String ERROR_RESPONSE_404 = "HTTP 404 OK"; // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/TestUtils.java // public class TestUtils { // // private Gson gson = new GsonBuilder() // .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create(); // // public void log(String log) { // System.out.println(log); // } // // public Gson getGson() { // return gson; // } // // // public <T> T readJson(String fileName, Class<T> inClass) { // return gson.fromJson(readString(fileName), inClass); // } // // public String readString(String fileName) { // InputStream stream = getClass().getClassLoader().getResourceAsStream(fileName); // try { // int size = stream.available(); // byte[] buffer = new byte[size]; // int result = stream.read(buffer); // return new String(buffer, "utf8"); // } catch (IOException e) { // e.printStackTrace(); // return null; // } finally { // try { // if (stream != null) { // stream.close(); // } // } catch (IOException e) { // e.printStackTrace(); // } // } // // } // // } // Path: app/src/test/java/com/andrey7mel/stepbystep/integration/other/IntegrationBaseTest.java import com.andrey7mel.stepbystep.BuildConfig; import com.andrey7mel.stepbystep.integration.other.di.IntegrationTestComponent; import com.andrey7mel.stepbystep.other.App; import com.andrey7mel.stepbystep.other.TestConst; import com.andrey7mel.stepbystep.other.TestUtils; import com.squareup.okhttp.mockwebserver.Dispatcher; import com.squareup.okhttp.mockwebserver.MockResponse; import com.squareup.okhttp.mockwebserver.MockWebServer; import com.squareup.okhttp.mockwebserver.RecordedRequest; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.runner.RunWith; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import javax.inject.Inject; @Inject protected MockWebServer mockWebServer; @Before public void setUp() throws Exception { component = (IntegrationTestComponent) App.getComponent(); testUtils = new TestUtils(); component.inject(this); } @After public void tearDown() throws Exception { mockWebServer.shutdown(); } protected void setErrorAnswerWebServer() { mockWebServer.setDispatcher(new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException { return new MockResponse().setResponseCode(500); } }); } protected void setCustomAnswer(boolean enableBranches, boolean enableContributors) { mockWebServer.setDispatcher(new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
if (request.getPath().equals("/users/" + TestConst.TEST_OWNER + "/repos")) {
andrey7mel/android-step-by-step
app/src/main/java/com/andrey7mel/stepbystep/other/di/PresenterModule.java
// Path: app/src/main/java/com/andrey7mel/stepbystep/model/Model.java // public interface Model { // // Observable<List<RepositoryDTO>> getRepoList(String name); // // Observable<List<BranchDTO>> getRepoBranches(String owner, String name); // // Observable<List<ContributorDTO>> getRepoContributors(String owner, String name); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/model/ModelImpl.java // public class ModelImpl implements Model { // // private final Observable.Transformer schedulersTransformer; // // @Inject // protected ApiInterface apiInterface; // // @Inject // @Named(Const.UI_THREAD) // Scheduler uiThread; // // @Inject // @Named(Const.IO_THREAD) // Scheduler ioThread; // // public ModelImpl() { // App.getComponent().inject(this); // schedulersTransformer = o -> ((Observable) o).subscribeOn(ioThread) // .observeOn(uiThread) // .unsubscribeOn(ioThread); // TODO: remove when https://github.com/square/okhttp/issues/1592 is fixed // } // // @Override // public Observable<List<RepositoryDTO>> getRepoList(String name) { // return apiInterface // .getRepositories(name) // .compose(applySchedulers()); // } // // @Override // public Observable<List<BranchDTO>> getRepoBranches(String owner, String name) { // return apiInterface // .getBranches(owner, name) // .compose(applySchedulers()); // } // // @Override // public Observable<List<ContributorDTO>> getRepoContributors(String owner, String name) { // return apiInterface // .getContributors(owner, name) // .compose(applySchedulers()); // } // // @SuppressWarnings("unchecked") // private <T> Observable.Transformer<T, T> applySchedulers() { // return (Observable.Transformer<T, T>) schedulersTransformer; // } // // }
import com.andrey7mel.stepbystep.model.Model; import com.andrey7mel.stepbystep.model.ModelImpl; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import rx.subscriptions.CompositeSubscription;
package com.andrey7mel.stepbystep.other.di; @Module public class PresenterModule { @Provides @Singleton
// Path: app/src/main/java/com/andrey7mel/stepbystep/model/Model.java // public interface Model { // // Observable<List<RepositoryDTO>> getRepoList(String name); // // Observable<List<BranchDTO>> getRepoBranches(String owner, String name); // // Observable<List<ContributorDTO>> getRepoContributors(String owner, String name); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/model/ModelImpl.java // public class ModelImpl implements Model { // // private final Observable.Transformer schedulersTransformer; // // @Inject // protected ApiInterface apiInterface; // // @Inject // @Named(Const.UI_THREAD) // Scheduler uiThread; // // @Inject // @Named(Const.IO_THREAD) // Scheduler ioThread; // // public ModelImpl() { // App.getComponent().inject(this); // schedulersTransformer = o -> ((Observable) o).subscribeOn(ioThread) // .observeOn(uiThread) // .unsubscribeOn(ioThread); // TODO: remove when https://github.com/square/okhttp/issues/1592 is fixed // } // // @Override // public Observable<List<RepositoryDTO>> getRepoList(String name) { // return apiInterface // .getRepositories(name) // .compose(applySchedulers()); // } // // @Override // public Observable<List<BranchDTO>> getRepoBranches(String owner, String name) { // return apiInterface // .getBranches(owner, name) // .compose(applySchedulers()); // } // // @Override // public Observable<List<ContributorDTO>> getRepoContributors(String owner, String name) { // return apiInterface // .getContributors(owner, name) // .compose(applySchedulers()); // } // // @SuppressWarnings("unchecked") // private <T> Observable.Transformer<T, T> applySchedulers() { // return (Observable.Transformer<T, T>) schedulersTransformer; // } // // } // Path: app/src/main/java/com/andrey7mel/stepbystep/other/di/PresenterModule.java import com.andrey7mel.stepbystep.model.Model; import com.andrey7mel.stepbystep.model.ModelImpl; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import rx.subscriptions.CompositeSubscription; package com.andrey7mel.stepbystep.other.di; @Module public class PresenterModule { @Provides @Singleton
Model provideDataRepository() {
andrey7mel/android-step-by-step
app/src/main/java/com/andrey7mel/stepbystep/other/di/PresenterModule.java
// Path: app/src/main/java/com/andrey7mel/stepbystep/model/Model.java // public interface Model { // // Observable<List<RepositoryDTO>> getRepoList(String name); // // Observable<List<BranchDTO>> getRepoBranches(String owner, String name); // // Observable<List<ContributorDTO>> getRepoContributors(String owner, String name); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/model/ModelImpl.java // public class ModelImpl implements Model { // // private final Observable.Transformer schedulersTransformer; // // @Inject // protected ApiInterface apiInterface; // // @Inject // @Named(Const.UI_THREAD) // Scheduler uiThread; // // @Inject // @Named(Const.IO_THREAD) // Scheduler ioThread; // // public ModelImpl() { // App.getComponent().inject(this); // schedulersTransformer = o -> ((Observable) o).subscribeOn(ioThread) // .observeOn(uiThread) // .unsubscribeOn(ioThread); // TODO: remove when https://github.com/square/okhttp/issues/1592 is fixed // } // // @Override // public Observable<List<RepositoryDTO>> getRepoList(String name) { // return apiInterface // .getRepositories(name) // .compose(applySchedulers()); // } // // @Override // public Observable<List<BranchDTO>> getRepoBranches(String owner, String name) { // return apiInterface // .getBranches(owner, name) // .compose(applySchedulers()); // } // // @Override // public Observable<List<ContributorDTO>> getRepoContributors(String owner, String name) { // return apiInterface // .getContributors(owner, name) // .compose(applySchedulers()); // } // // @SuppressWarnings("unchecked") // private <T> Observable.Transformer<T, T> applySchedulers() { // return (Observable.Transformer<T, T>) schedulersTransformer; // } // // }
import com.andrey7mel.stepbystep.model.Model; import com.andrey7mel.stepbystep.model.ModelImpl; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import rx.subscriptions.CompositeSubscription;
package com.andrey7mel.stepbystep.other.di; @Module public class PresenterModule { @Provides @Singleton Model provideDataRepository() {
// Path: app/src/main/java/com/andrey7mel/stepbystep/model/Model.java // public interface Model { // // Observable<List<RepositoryDTO>> getRepoList(String name); // // Observable<List<BranchDTO>> getRepoBranches(String owner, String name); // // Observable<List<ContributorDTO>> getRepoContributors(String owner, String name); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/model/ModelImpl.java // public class ModelImpl implements Model { // // private final Observable.Transformer schedulersTransformer; // // @Inject // protected ApiInterface apiInterface; // // @Inject // @Named(Const.UI_THREAD) // Scheduler uiThread; // // @Inject // @Named(Const.IO_THREAD) // Scheduler ioThread; // // public ModelImpl() { // App.getComponent().inject(this); // schedulersTransformer = o -> ((Observable) o).subscribeOn(ioThread) // .observeOn(uiThread) // .unsubscribeOn(ioThread); // TODO: remove when https://github.com/square/okhttp/issues/1592 is fixed // } // // @Override // public Observable<List<RepositoryDTO>> getRepoList(String name) { // return apiInterface // .getRepositories(name) // .compose(applySchedulers()); // } // // @Override // public Observable<List<BranchDTO>> getRepoBranches(String owner, String name) { // return apiInterface // .getBranches(owner, name) // .compose(applySchedulers()); // } // // @Override // public Observable<List<ContributorDTO>> getRepoContributors(String owner, String name) { // return apiInterface // .getContributors(owner, name) // .compose(applySchedulers()); // } // // @SuppressWarnings("unchecked") // private <T> Observable.Transformer<T, T> applySchedulers() { // return (Observable.Transformer<T, T>) schedulersTransformer; // } // // } // Path: app/src/main/java/com/andrey7mel/stepbystep/other/di/PresenterModule.java import com.andrey7mel.stepbystep.model.Model; import com.andrey7mel.stepbystep.model.ModelImpl; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import rx.subscriptions.CompositeSubscription; package com.andrey7mel.stepbystep.other.di; @Module public class PresenterModule { @Provides @Singleton Model provideDataRepository() {
return new ModelImpl();
andrey7mel/android-step-by-step
app/src/test/java/com/andrey7mel/stepbystep/other/di/view/TestViewComponent.java
// Path: app/src/test/java/com/andrey7mel/stepbystep/view/fragments/RepoListFragmentTest.java // public class RepoListFragmentTest extends BaseTest { // // @Inject // protected RepoListPresenter repoListPresenter; // // private RepoListFragment repoListFragment; // private MainActivity activity; // // private Bundle bundle; // // @Override // @Before // public void setUp() throws Exception { // super.setUp(); // // TestViewComponent testViewComponent = DaggerTestViewComponent.builder() // .testViewDynamicModule(new TestViewDynamicModule()) // .build(); // // testViewComponent.inject(this); // // repoListFragment = new RepoListFragment(); // activity = Robolectric.setupActivity(MainActivity.class); // bundle = Bundle.EMPTY; // // repoListFragment.setViewComponent(testViewComponent); // // repoListFragment.onCreate(null); // need for DI // } // // // @Test // public void testOnCreateView() { // repoListFragment.onCreateView(LayoutInflater.from(activity), (ViewGroup) activity.findViewById(R.id.container), null); // verify(repoListPresenter).onCreateView(null); // } // // @Test // public void testOnCreateViewWithBundle() { // repoListFragment.onCreateView(LayoutInflater.from(activity), (ViewGroup) activity.findViewById(R.id.container), bundle); // verify(repoListPresenter).onCreateView(bundle); // } // // @Test // public void testOnStop() { // repoListFragment.onStop(); // verify(repoListPresenter).onStop(); // } // // @Test // public void testOnSaveInstanceState() { // repoListFragment.onSaveInstanceState(null); // verify(repoListPresenter).onSaveInstanceState(null); // } // // @Test // public void testOnSaveInstanceStateWithBundle() { // repoListFragment.onSaveInstanceState(bundle); // verify(repoListPresenter).onSaveInstanceState(bundle); // } // // // }
import com.andrey7mel.stepbystep.view.fragments.RepoListFragmentTest; import javax.inject.Singleton; import dagger.Component;
package com.andrey7mel.stepbystep.other.di.view; @Singleton @Component(modules = {TestViewDynamicModule.class}) public interface TestViewComponent extends ViewComponent {
// Path: app/src/test/java/com/andrey7mel/stepbystep/view/fragments/RepoListFragmentTest.java // public class RepoListFragmentTest extends BaseTest { // // @Inject // protected RepoListPresenter repoListPresenter; // // private RepoListFragment repoListFragment; // private MainActivity activity; // // private Bundle bundle; // // @Override // @Before // public void setUp() throws Exception { // super.setUp(); // // TestViewComponent testViewComponent = DaggerTestViewComponent.builder() // .testViewDynamicModule(new TestViewDynamicModule()) // .build(); // // testViewComponent.inject(this); // // repoListFragment = new RepoListFragment(); // activity = Robolectric.setupActivity(MainActivity.class); // bundle = Bundle.EMPTY; // // repoListFragment.setViewComponent(testViewComponent); // // repoListFragment.onCreate(null); // need for DI // } // // // @Test // public void testOnCreateView() { // repoListFragment.onCreateView(LayoutInflater.from(activity), (ViewGroup) activity.findViewById(R.id.container), null); // verify(repoListPresenter).onCreateView(null); // } // // @Test // public void testOnCreateViewWithBundle() { // repoListFragment.onCreateView(LayoutInflater.from(activity), (ViewGroup) activity.findViewById(R.id.container), bundle); // verify(repoListPresenter).onCreateView(bundle); // } // // @Test // public void testOnStop() { // repoListFragment.onStop(); // verify(repoListPresenter).onStop(); // } // // @Test // public void testOnSaveInstanceState() { // repoListFragment.onSaveInstanceState(null); // verify(repoListPresenter).onSaveInstanceState(null); // } // // @Test // public void testOnSaveInstanceStateWithBundle() { // repoListFragment.onSaveInstanceState(bundle); // verify(repoListPresenter).onSaveInstanceState(bundle); // } // // // } // Path: app/src/test/java/com/andrey7mel/stepbystep/other/di/view/TestViewComponent.java import com.andrey7mel.stepbystep.view.fragments.RepoListFragmentTest; import javax.inject.Singleton; import dagger.Component; package com.andrey7mel.stepbystep.other.di.view; @Singleton @Component(modules = {TestViewDynamicModule.class}) public interface TestViewComponent extends ViewComponent {
void inject(RepoListFragmentTest in);
andrey7mel/android-step-by-step
app/src/androidTest/java/com/andrey7mel/stepbystep/di/TestModelModule.java
// Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiInterface.java // public interface ApiInterface { // // @GET("/users/{user}/repos") // Observable<List<RepositoryDTO>> getRepositories(@Path("user") String user); // // @GET("/repos/{owner}/{repo}/contributors") // Observable<List<ContributorDTO>> getContributors(@Path("owner") String owner, @Path("repo") String repo); // // @GET("/repos/{owner}/{repo}/branches") // Observable<List<BranchDTO>> getBranches(@Path("owner") String owner, @Path("repo") String repo); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/other/Const.java // public interface Const { // String UI_THREAD = "UI_THREAD"; // String IO_THREAD = "IO_THREAD"; // // String BASE_URL = "https://api.github.com/"; // // }
import com.andrey7mel.stepbystep.model.api.ApiInterface; import com.andrey7mel.stepbystep.other.Const; import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import rx.Scheduler; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import static org.mockito.Mockito.mock;
package com.andrey7mel.stepbystep.di; @Module public class TestModelModule { @Provides @Singleton
// Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiInterface.java // public interface ApiInterface { // // @GET("/users/{user}/repos") // Observable<List<RepositoryDTO>> getRepositories(@Path("user") String user); // // @GET("/repos/{owner}/{repo}/contributors") // Observable<List<ContributorDTO>> getContributors(@Path("owner") String owner, @Path("repo") String repo); // // @GET("/repos/{owner}/{repo}/branches") // Observable<List<BranchDTO>> getBranches(@Path("owner") String owner, @Path("repo") String repo); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/other/Const.java // public interface Const { // String UI_THREAD = "UI_THREAD"; // String IO_THREAD = "IO_THREAD"; // // String BASE_URL = "https://api.github.com/"; // // } // Path: app/src/androidTest/java/com/andrey7mel/stepbystep/di/TestModelModule.java import com.andrey7mel.stepbystep.model.api.ApiInterface; import com.andrey7mel.stepbystep.other.Const; import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import rx.Scheduler; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import static org.mockito.Mockito.mock; package com.andrey7mel.stepbystep.di; @Module public class TestModelModule { @Provides @Singleton
ApiInterface provideApiInterface() {
andrey7mel/android-step-by-step
app/src/androidTest/java/com/andrey7mel/stepbystep/di/TestModelModule.java
// Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiInterface.java // public interface ApiInterface { // // @GET("/users/{user}/repos") // Observable<List<RepositoryDTO>> getRepositories(@Path("user") String user); // // @GET("/repos/{owner}/{repo}/contributors") // Observable<List<ContributorDTO>> getContributors(@Path("owner") String owner, @Path("repo") String repo); // // @GET("/repos/{owner}/{repo}/branches") // Observable<List<BranchDTO>> getBranches(@Path("owner") String owner, @Path("repo") String repo); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/other/Const.java // public interface Const { // String UI_THREAD = "UI_THREAD"; // String IO_THREAD = "IO_THREAD"; // // String BASE_URL = "https://api.github.com/"; // // }
import com.andrey7mel.stepbystep.model.api.ApiInterface; import com.andrey7mel.stepbystep.other.Const; import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import rx.Scheduler; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import static org.mockito.Mockito.mock;
package com.andrey7mel.stepbystep.di; @Module public class TestModelModule { @Provides @Singleton ApiInterface provideApiInterface() { return mock(ApiInterface.class); } @Provides @Singleton
// Path: app/src/main/java/com/andrey7mel/stepbystep/model/api/ApiInterface.java // public interface ApiInterface { // // @GET("/users/{user}/repos") // Observable<List<RepositoryDTO>> getRepositories(@Path("user") String user); // // @GET("/repos/{owner}/{repo}/contributors") // Observable<List<ContributorDTO>> getContributors(@Path("owner") String owner, @Path("repo") String repo); // // @GET("/repos/{owner}/{repo}/branches") // Observable<List<BranchDTO>> getBranches(@Path("owner") String owner, @Path("repo") String repo); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/other/Const.java // public interface Const { // String UI_THREAD = "UI_THREAD"; // String IO_THREAD = "IO_THREAD"; // // String BASE_URL = "https://api.github.com/"; // // } // Path: app/src/androidTest/java/com/andrey7mel/stepbystep/di/TestModelModule.java import com.andrey7mel.stepbystep.model.api.ApiInterface; import com.andrey7mel.stepbystep.other.Const; import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import rx.Scheduler; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import static org.mockito.Mockito.mock; package com.andrey7mel.stepbystep.di; @Module public class TestModelModule { @Provides @Singleton ApiInterface provideApiInterface() { return mock(ApiInterface.class); } @Provides @Singleton
@Named(Const.UI_THREAD)
andrey7mel/android-step-by-step
app/src/test/java/com/andrey7mel/stepbystep/view/fragments/BaseFragmentTest.java
// Path: app/src/test/java/com/andrey7mel/stepbystep/other/BaseTest.java // @RunWith(RobolectricGradleTestRunner.class) // @Config(application = TestApplication.class, // constants = BuildConfig.class, // sdk = 21) // @Ignore // public class BaseTest { // // public TestComponent component; // public TestUtils testUtils; // // @Before // public void setUp() throws Exception { // component = (TestComponent) App.getComponent(); // testUtils = new TestUtils(); // } // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/vo/Repository.java // public class Repository implements Serializable { // private String repoName; // private String ownerName; // // public Repository(String repoName, String ownerName) { // this.repoName = repoName; // this.ownerName = ownerName; // } // // public String getRepoName() { // return repoName; // } // // public void setRepoName(String repoName) { // this.repoName = repoName; // } // // public String getOwnerName() { // return ownerName; // } // // public void setOwnerName(String ownerName) { // this.ownerName = ownerName; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Repository that = (Repository) o; // // if (repoName != null ? !repoName.equals(that.repoName) : that.repoName != null) // return false; // return !(ownerName != null ? !ownerName.equals(that.ownerName) : that.ownerName != null); // // } // // @Override // public int hashCode() { // int result = repoName != null ? repoName.hashCode() : 0; // result = 31 * result + (ownerName != null ? ownerName.hashCode() : 0); // return result; // } // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/MainActivity.java // public class MainActivity extends AppCompatActivity implements ActivityCallback { // // private static String TAG = "TAG"; // // @Bind(R.id.toolbar) // protected Toolbar toolbar; // // @Bind(R.id.toolbar_progress_bar) // protected ProgressBar progressBar; // // private FragmentManager fragmentManager; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // ButterKnife.bind(this); // setSupportActionBar(toolbar); // fragmentManager = getSupportFragmentManager(); // // Fragment fragment = fragmentManager.findFragmentByTag(TAG); // if (fragment == null) replaceFragment(new RepoListFragment(), false); // } // // private void replaceFragment(Fragment fragment, boolean addBackStack) { // FragmentTransaction transaction = fragmentManager.beginTransaction(); // transaction.replace(R.id.container, fragment, TAG); // if (addBackStack) transaction.addToBackStack(null); // transaction.commit(); // } // // @Override // public void startRepoInfoFragment(Repository repository) { // replaceFragment(RepoInfoFragment.newInstance(repository), true); // } // // @Override // public void showProgressBar() { // progressBar.setVisibility(View.VISIBLE); // } // // @Override // public void hideProgressBar() { // progressBar.setVisibility(View.INVISIBLE); // } // // // }
import com.andrey7mel.stepbystep.other.BaseTest; import com.andrey7mel.stepbystep.presenter.BasePresenter; import com.andrey7mel.stepbystep.presenter.vo.Repository; import com.andrey7mel.stepbystep.view.MainActivity; import org.junit.Before; import org.junit.Test; import javax.inject.Inject; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify;
package com.andrey7mel.stepbystep.view.fragments; public class BaseFragmentTest extends BaseTest { @Inject
// Path: app/src/test/java/com/andrey7mel/stepbystep/other/BaseTest.java // @RunWith(RobolectricGradleTestRunner.class) // @Config(application = TestApplication.class, // constants = BuildConfig.class, // sdk = 21) // @Ignore // public class BaseTest { // // public TestComponent component; // public TestUtils testUtils; // // @Before // public void setUp() throws Exception { // component = (TestComponent) App.getComponent(); // testUtils = new TestUtils(); // } // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/vo/Repository.java // public class Repository implements Serializable { // private String repoName; // private String ownerName; // // public Repository(String repoName, String ownerName) { // this.repoName = repoName; // this.ownerName = ownerName; // } // // public String getRepoName() { // return repoName; // } // // public void setRepoName(String repoName) { // this.repoName = repoName; // } // // public String getOwnerName() { // return ownerName; // } // // public void setOwnerName(String ownerName) { // this.ownerName = ownerName; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Repository that = (Repository) o; // // if (repoName != null ? !repoName.equals(that.repoName) : that.repoName != null) // return false; // return !(ownerName != null ? !ownerName.equals(that.ownerName) : that.ownerName != null); // // } // // @Override // public int hashCode() { // int result = repoName != null ? repoName.hashCode() : 0; // result = 31 * result + (ownerName != null ? ownerName.hashCode() : 0); // return result; // } // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/MainActivity.java // public class MainActivity extends AppCompatActivity implements ActivityCallback { // // private static String TAG = "TAG"; // // @Bind(R.id.toolbar) // protected Toolbar toolbar; // // @Bind(R.id.toolbar_progress_bar) // protected ProgressBar progressBar; // // private FragmentManager fragmentManager; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // ButterKnife.bind(this); // setSupportActionBar(toolbar); // fragmentManager = getSupportFragmentManager(); // // Fragment fragment = fragmentManager.findFragmentByTag(TAG); // if (fragment == null) replaceFragment(new RepoListFragment(), false); // } // // private void replaceFragment(Fragment fragment, boolean addBackStack) { // FragmentTransaction transaction = fragmentManager.beginTransaction(); // transaction.replace(R.id.container, fragment, TAG); // if (addBackStack) transaction.addToBackStack(null); // transaction.commit(); // } // // @Override // public void startRepoInfoFragment(Repository repository) { // replaceFragment(RepoInfoFragment.newInstance(repository), true); // } // // @Override // public void showProgressBar() { // progressBar.setVisibility(View.VISIBLE); // } // // @Override // public void hideProgressBar() { // progressBar.setVisibility(View.INVISIBLE); // } // // // } // Path: app/src/test/java/com/andrey7mel/stepbystep/view/fragments/BaseFragmentTest.java import com.andrey7mel.stepbystep.other.BaseTest; import com.andrey7mel.stepbystep.presenter.BasePresenter; import com.andrey7mel.stepbystep.presenter.vo.Repository; import com.andrey7mel.stepbystep.view.MainActivity; import org.junit.Before; import org.junit.Test; import javax.inject.Inject; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; package com.andrey7mel.stepbystep.view.fragments; public class BaseFragmentTest extends BaseTest { @Inject
protected Repository repository;
andrey7mel/android-step-by-step
app/src/test/java/com/andrey7mel/stepbystep/view/fragments/BaseFragmentTest.java
// Path: app/src/test/java/com/andrey7mel/stepbystep/other/BaseTest.java // @RunWith(RobolectricGradleTestRunner.class) // @Config(application = TestApplication.class, // constants = BuildConfig.class, // sdk = 21) // @Ignore // public class BaseTest { // // public TestComponent component; // public TestUtils testUtils; // // @Before // public void setUp() throws Exception { // component = (TestComponent) App.getComponent(); // testUtils = new TestUtils(); // } // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/vo/Repository.java // public class Repository implements Serializable { // private String repoName; // private String ownerName; // // public Repository(String repoName, String ownerName) { // this.repoName = repoName; // this.ownerName = ownerName; // } // // public String getRepoName() { // return repoName; // } // // public void setRepoName(String repoName) { // this.repoName = repoName; // } // // public String getOwnerName() { // return ownerName; // } // // public void setOwnerName(String ownerName) { // this.ownerName = ownerName; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Repository that = (Repository) o; // // if (repoName != null ? !repoName.equals(that.repoName) : that.repoName != null) // return false; // return !(ownerName != null ? !ownerName.equals(that.ownerName) : that.ownerName != null); // // } // // @Override // public int hashCode() { // int result = repoName != null ? repoName.hashCode() : 0; // result = 31 * result + (ownerName != null ? ownerName.hashCode() : 0); // return result; // } // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/MainActivity.java // public class MainActivity extends AppCompatActivity implements ActivityCallback { // // private static String TAG = "TAG"; // // @Bind(R.id.toolbar) // protected Toolbar toolbar; // // @Bind(R.id.toolbar_progress_bar) // protected ProgressBar progressBar; // // private FragmentManager fragmentManager; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // ButterKnife.bind(this); // setSupportActionBar(toolbar); // fragmentManager = getSupportFragmentManager(); // // Fragment fragment = fragmentManager.findFragmentByTag(TAG); // if (fragment == null) replaceFragment(new RepoListFragment(), false); // } // // private void replaceFragment(Fragment fragment, boolean addBackStack) { // FragmentTransaction transaction = fragmentManager.beginTransaction(); // transaction.replace(R.id.container, fragment, TAG); // if (addBackStack) transaction.addToBackStack(null); // transaction.commit(); // } // // @Override // public void startRepoInfoFragment(Repository repository) { // replaceFragment(RepoInfoFragment.newInstance(repository), true); // } // // @Override // public void showProgressBar() { // progressBar.setVisibility(View.VISIBLE); // } // // @Override // public void hideProgressBar() { // progressBar.setVisibility(View.INVISIBLE); // } // // // }
import com.andrey7mel.stepbystep.other.BaseTest; import com.andrey7mel.stepbystep.presenter.BasePresenter; import com.andrey7mel.stepbystep.presenter.vo.Repository; import com.andrey7mel.stepbystep.view.MainActivity; import org.junit.Before; import org.junit.Test; import javax.inject.Inject; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify;
package com.andrey7mel.stepbystep.view.fragments; public class BaseFragmentTest extends BaseTest { @Inject protected Repository repository; private BaseFragment baseFragment;
// Path: app/src/test/java/com/andrey7mel/stepbystep/other/BaseTest.java // @RunWith(RobolectricGradleTestRunner.class) // @Config(application = TestApplication.class, // constants = BuildConfig.class, // sdk = 21) // @Ignore // public class BaseTest { // // public TestComponent component; // public TestUtils testUtils; // // @Before // public void setUp() throws Exception { // component = (TestComponent) App.getComponent(); // testUtils = new TestUtils(); // } // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/vo/Repository.java // public class Repository implements Serializable { // private String repoName; // private String ownerName; // // public Repository(String repoName, String ownerName) { // this.repoName = repoName; // this.ownerName = ownerName; // } // // public String getRepoName() { // return repoName; // } // // public void setRepoName(String repoName) { // this.repoName = repoName; // } // // public String getOwnerName() { // return ownerName; // } // // public void setOwnerName(String ownerName) { // this.ownerName = ownerName; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Repository that = (Repository) o; // // if (repoName != null ? !repoName.equals(that.repoName) : that.repoName != null) // return false; // return !(ownerName != null ? !ownerName.equals(that.ownerName) : that.ownerName != null); // // } // // @Override // public int hashCode() { // int result = repoName != null ? repoName.hashCode() : 0; // result = 31 * result + (ownerName != null ? ownerName.hashCode() : 0); // return result; // } // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/MainActivity.java // public class MainActivity extends AppCompatActivity implements ActivityCallback { // // private static String TAG = "TAG"; // // @Bind(R.id.toolbar) // protected Toolbar toolbar; // // @Bind(R.id.toolbar_progress_bar) // protected ProgressBar progressBar; // // private FragmentManager fragmentManager; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // ButterKnife.bind(this); // setSupportActionBar(toolbar); // fragmentManager = getSupportFragmentManager(); // // Fragment fragment = fragmentManager.findFragmentByTag(TAG); // if (fragment == null) replaceFragment(new RepoListFragment(), false); // } // // private void replaceFragment(Fragment fragment, boolean addBackStack) { // FragmentTransaction transaction = fragmentManager.beginTransaction(); // transaction.replace(R.id.container, fragment, TAG); // if (addBackStack) transaction.addToBackStack(null); // transaction.commit(); // } // // @Override // public void startRepoInfoFragment(Repository repository) { // replaceFragment(RepoInfoFragment.newInstance(repository), true); // } // // @Override // public void showProgressBar() { // progressBar.setVisibility(View.VISIBLE); // } // // @Override // public void hideProgressBar() { // progressBar.setVisibility(View.INVISIBLE); // } // // // } // Path: app/src/test/java/com/andrey7mel/stepbystep/view/fragments/BaseFragmentTest.java import com.andrey7mel.stepbystep.other.BaseTest; import com.andrey7mel.stepbystep.presenter.BasePresenter; import com.andrey7mel.stepbystep.presenter.vo.Repository; import com.andrey7mel.stepbystep.view.MainActivity; import org.junit.Before; import org.junit.Test; import javax.inject.Inject; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; package com.andrey7mel.stepbystep.view.fragments; public class BaseFragmentTest extends BaseTest { @Inject protected Repository repository; private BaseFragment baseFragment;
private MainActivity activity;
andrey7mel/android-step-by-step
app/src/test/java/com/andrey7mel/stepbystep/other/di/view/TestViewDynamicModule.java
// Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/RepoListPresenter.java // public class RepoListPresenter extends BasePresenter { // // private static final String BUNDLE_REPO_LIST_KEY = "BUNDLE_REPO_LIST_KEY"; // // @Inject // protected RepoListMapper repoListMapper; // // private RepoListView view; // // private List<Repository> repoList; // // // for DI // @Inject // public RepoListPresenter() { // } // // public RepoListPresenter(RepoListView view) { // App.getComponent().inject(this); // this.view = view; // } // // @Override // protected View getView() { // return view; // } // // public void onSearchButtonClick() { // String name = view.getUserName(); // if (TextUtils.isEmpty(name)) return; // // showLoadingState(); // Subscription subscription = model.getRepoList(name) // .map(repoListMapper) // .subscribe(new Observer<List<Repository>>() { // // @Override // public void onCompleted() { // hideLoadingState(); // } // // @Override // public void onError(Throwable e) { // hideLoadingState(); // showError(e); // } // // @Override // public void onNext(List<Repository> list) { // if (list != null && !list.isEmpty()) { // repoList = list; // view.showRepoList(list); // } else { // view.showEmptyList(); // } // } // }); // addSubscription(subscription); // } // // public void onCreateView(Bundle savedInstanceState) { // if (savedInstanceState != null) { // repoList = (List<Repository>) savedInstanceState.getSerializable(BUNDLE_REPO_LIST_KEY); // } // if (isRepoListNotEmpty()) { // view.showRepoList(repoList); // } // } // // private boolean isRepoListNotEmpty() { // return (repoList != null && !repoList.isEmpty()); // } // // public void onSaveInstanceState(Bundle outState) { // if (isRepoListNotEmpty()) { // outState.putSerializable(BUNDLE_REPO_LIST_KEY, new ArrayList<>(repoList)); // } // } // // public void clickRepo(Repository repository) { // view.startRepoInfoFragment(repository); // } // // }
import com.andrey7mel.stepbystep.presenter.RepoListPresenter; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import static org.mockito.Mockito.mock;
package com.andrey7mel.stepbystep.other.di.view; @Module public class TestViewDynamicModule { @Provides @Singleton
// Path: app/src/main/java/com/andrey7mel/stepbystep/presenter/RepoListPresenter.java // public class RepoListPresenter extends BasePresenter { // // private static final String BUNDLE_REPO_LIST_KEY = "BUNDLE_REPO_LIST_KEY"; // // @Inject // protected RepoListMapper repoListMapper; // // private RepoListView view; // // private List<Repository> repoList; // // // for DI // @Inject // public RepoListPresenter() { // } // // public RepoListPresenter(RepoListView view) { // App.getComponent().inject(this); // this.view = view; // } // // @Override // protected View getView() { // return view; // } // // public void onSearchButtonClick() { // String name = view.getUserName(); // if (TextUtils.isEmpty(name)) return; // // showLoadingState(); // Subscription subscription = model.getRepoList(name) // .map(repoListMapper) // .subscribe(new Observer<List<Repository>>() { // // @Override // public void onCompleted() { // hideLoadingState(); // } // // @Override // public void onError(Throwable e) { // hideLoadingState(); // showError(e); // } // // @Override // public void onNext(List<Repository> list) { // if (list != null && !list.isEmpty()) { // repoList = list; // view.showRepoList(list); // } else { // view.showEmptyList(); // } // } // }); // addSubscription(subscription); // } // // public void onCreateView(Bundle savedInstanceState) { // if (savedInstanceState != null) { // repoList = (List<Repository>) savedInstanceState.getSerializable(BUNDLE_REPO_LIST_KEY); // } // if (isRepoListNotEmpty()) { // view.showRepoList(repoList); // } // } // // private boolean isRepoListNotEmpty() { // return (repoList != null && !repoList.isEmpty()); // } // // public void onSaveInstanceState(Bundle outState) { // if (isRepoListNotEmpty()) { // outState.putSerializable(BUNDLE_REPO_LIST_KEY, new ArrayList<>(repoList)); // } // } // // public void clickRepo(Repository repository) { // view.startRepoInfoFragment(repository); // } // // } // Path: app/src/test/java/com/andrey7mel/stepbystep/other/di/view/TestViewDynamicModule.java import com.andrey7mel.stepbystep.presenter.RepoListPresenter; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import static org.mockito.Mockito.mock; package com.andrey7mel.stepbystep.other.di.view; @Module public class TestViewDynamicModule { @Provides @Singleton
RepoListPresenter provideRepoListPresenter() {