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
dangdangdotcom/config-toolkit
config-face/src/main/java/com/dangdang/config/face/service/NodeService.java
// Path: config-face/src/main/java/com/dangdang/config/face/entity/PropertyItem.java // public class PropertyItem implements Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // private String name; // private String value; // // public PropertyItem(String name, String value) { // super(); // this.name = name; // this.value = value; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getValue() { // return value; // } // // public void setValue(String value) { // this.value = value; // } // // }
import com.dangdang.config.face.entity.PropertyItem; import com.google.common.base.Charsets; import com.google.common.base.Objects; import com.google.common.base.Strings; import com.google.common.collect.Lists; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.GetChildrenBuilder; import org.apache.curator.framework.api.GetDataBuilder; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.utils.ZKPaths; import org.apache.zookeeper.data.Stat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import java.util.List;
/** * Copyright 1999-2014 dangdang.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dangdang.config.face.service; /** * @author <a href="mailto:[email protected]">Yuxuan Wang</a> * */ @Service public class NodeService implements INodeService { /** * */ private static final long serialVersionUID = 1L; @Value("${zk}") private String zkAddress; private CuratorFramework client; @PostConstruct private void init() { client = CuratorFrameworkFactory.newClient(zkAddress, new ExponentialBackoffRetry(1000, 3)); client.start(); } @PreDestroy private void destroy() { if (client != null) { client.close(); } } private static final Logger LOGGER = LoggerFactory.getLogger(NodeService.class); @Override
// Path: config-face/src/main/java/com/dangdang/config/face/entity/PropertyItem.java // public class PropertyItem implements Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // private String name; // private String value; // // public PropertyItem(String name, String value) { // super(); // this.name = name; // this.value = value; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getValue() { // return value; // } // // public void setValue(String value) { // this.value = value; // } // // } // Path: config-face/src/main/java/com/dangdang/config/face/service/NodeService.java import com.dangdang.config.face.entity.PropertyItem; import com.google.common.base.Charsets; import com.google.common.base.Objects; import com.google.common.base.Strings; import com.google.common.collect.Lists; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.GetChildrenBuilder; import org.apache.curator.framework.api.GetDataBuilder; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.utils.ZKPaths; import org.apache.zookeeper.data.Stat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import java.util.List; /** * Copyright 1999-2014 dangdang.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dangdang.config.face.service; /** * @author <a href="mailto:[email protected]">Yuxuan Wang</a> * */ @Service public class NodeService implements INodeService { /** * */ private static final long serialVersionUID = 1L; @Value("${zk}") private String zkAddress; private CuratorFramework client; @PostConstruct private void init() { client = CuratorFrameworkFactory.newClient(zkAddress, new ExponentialBackoffRetry(1000, 3)); client.start(); } @PreDestroy private void destroy() { if (client != null) { client.close(); } } private static final Logger LOGGER = LoggerFactory.getLogger(NodeService.class); @Override
public List<PropertyItem> findProperties(String node) {
dangdangdotcom/config-toolkit
config-toolkit-demo/src/main/java/com/dangdang/config/service/easyzk/demo/spring/MainEntrance.java
// Path: config-toolkit-demo/src/main/java/com/dangdang/config/service/easyzk/demo/simple/ExampleBeanWithConfigNode.java // @Component // public class ExampleBeanWithConfigNode { // // @Resource // private Map<String, String> propertyGroup1; // // public void someMethod() { // System.out.println(propertyGroup1.get("string_property_key")); // } // // }
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.dangdang.config.service.easyzk.demo.simple.ExampleBeanWithConfigNode;
/** * Copyright 1999-2014 dangdang.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dangdang.config.service.easyzk.demo.spring; /** * Load spring, and validation the property * * @author <a href="mailto:[email protected]">Yuxuan Wang</a> * */ public class MainEntrance { public static void main(String[] args) { ClassPathXmlApplicationContext context = null; try { context = new ClassPathXmlApplicationContext("classpath:config-toolkit-simple.xml"); context.registerShutdownHook(); context.start();
// Path: config-toolkit-demo/src/main/java/com/dangdang/config/service/easyzk/demo/simple/ExampleBeanWithConfigNode.java // @Component // public class ExampleBeanWithConfigNode { // // @Resource // private Map<String, String> propertyGroup1; // // public void someMethod() { // System.out.println(propertyGroup1.get("string_property_key")); // } // // } // Path: config-toolkit-demo/src/main/java/com/dangdang/config/service/easyzk/demo/spring/MainEntrance.java import org.springframework.context.support.ClassPathXmlApplicationContext; import com.dangdang.config.service.easyzk.demo.simple.ExampleBeanWithConfigNode; /** * Copyright 1999-2014 dangdang.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dangdang.config.service.easyzk.demo.spring; /** * Load spring, and validation the property * * @author <a href="mailto:[email protected]">Yuxuan Wang</a> * */ public class MainEntrance { public static void main(String[] args) { ClassPathXmlApplicationContext context = null; try { context = new ClassPathXmlApplicationContext("classpath:config-toolkit-simple.xml"); context.registerShutdownHook(); context.start();
ExampleBeanWithConfigNode bean = context.getBean(ExampleBeanWithConfigNode.class);
dangdangdotcom/config-toolkit
config-toolkit/src/main/java/com/dangdang/config/service/file/contenttype/PropertiesContentType.java
// Path: config-toolkit/src/main/java/com/dangdang/config/service/exception/InvalidPathException.java // public class InvalidPathException extends ConfigToolkitException { // // private static final long serialVersionUID = 1L; // // public InvalidPathException() { // super(); // } // // public InvalidPathException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidPathException(String message) { // super(message); // } // // public InvalidPathException(Throwable cause) { // super(cause); // } // // }
import com.dangdang.config.service.exception.InvalidPathException; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.util.HashMap; import java.util.Map; import java.util.Properties;
package com.dangdang.config.service.file.contenttype; /** * @author <a href="mailto:[email protected]">Yuxuan Wang</a> * */ public class PropertiesContentType implements ContentType { @Override
// Path: config-toolkit/src/main/java/com/dangdang/config/service/exception/InvalidPathException.java // public class InvalidPathException extends ConfigToolkitException { // // private static final long serialVersionUID = 1L; // // public InvalidPathException() { // super(); // } // // public InvalidPathException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidPathException(String message) { // super(message); // } // // public InvalidPathException(Throwable cause) { // super(cause); // } // // } // Path: config-toolkit/src/main/java/com/dangdang/config/service/file/contenttype/PropertiesContentType.java import com.dangdang.config.service.exception.InvalidPathException; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.util.HashMap; import java.util.Map; import java.util.Properties; package com.dangdang.config.service.file.contenttype; /** * @author <a href="mailto:[email protected]">Yuxuan Wang</a> * */ public class PropertiesContentType implements ContentType { @Override
public Map<String, String> resolve(byte[] data, String encoding) throws InvalidPathException {
dangdangdotcom/config-toolkit
config-face/src/main/java/com/dangdang/config/face/config/WebSecurityConfig.java
// Path: config-face/src/main/java/com/dangdang/config/face/service/INodeService.java // public interface INodeService { // // List<PropertyItem> findProperties(String node); // // List<String> listChildren(String node); // // boolean createProperty(String node); // // boolean createProperty(String node, String value); // // boolean updateProperty(String node, String value); // // void deleteProperty(String node); // // String getValue(String node); // }
import com.dangdang.config.face.service.INodeService; import com.google.common.base.Charsets; import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.google.common.hash.Hashing; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.password.PasswordEncoder; import java.util.Objects;
package com.dangdang.config.face.config; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired
// Path: config-face/src/main/java/com/dangdang/config/face/service/INodeService.java // public interface INodeService { // // List<PropertyItem> findProperties(String node); // // List<String> listChildren(String node); // // boolean createProperty(String node); // // boolean createProperty(String node, String value); // // boolean updateProperty(String node, String value); // // void deleteProperty(String node); // // String getValue(String node); // } // Path: config-face/src/main/java/com/dangdang/config/face/config/WebSecurityConfig.java import com.dangdang.config.face.service.INodeService; import com.google.common.base.Charsets; import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.google.common.hash.Hashing; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.password.PasswordEncoder; import java.util.Objects; package com.dangdang.config.face.config; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired
private INodeService nodeService;
dangdangdotcom/config-toolkit
config-toolkit/src/main/java/com/dangdang/config/service/file/protocol/HttpProtocol.java
// Path: config-toolkit/src/main/java/com/dangdang/config/service/exception/InvalidPathException.java // public class InvalidPathException extends ConfigToolkitException { // // private static final long serialVersionUID = 1L; // // public InvalidPathException() { // super(); // } // // public InvalidPathException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidPathException(String message) { // super(message); // } // // public InvalidPathException(Throwable cause) { // super(cause); // } // // } // // Path: config-toolkit/src/main/java/com/dangdang/config/service/file/FileConfigGroup.java // public class FileConfigGroup extends GeneralConfigGroup { // // private static final long serialVersionUID = 1L; // // private FileConfigProfile configProfile; // // private FileLocation location; // // private Protocol protocolBean; // // private static final Logger LOGGER = LoggerFactory.getLogger(FileConfigGroup.class); // // public FileConfigGroup(FileConfigProfile configProfile, String location, boolean enumerable) { // this(configProfile, location); // super.enumerable = enumerable; // } // // public FileConfigGroup(FileConfigProfile configProfile, String location) { // this(null, configProfile, location); // } // // public FileConfigGroup(ConfigGroup internalConfigGroup, FileConfigProfile configProfile, String location) { // super(internalConfigGroup); // // if(location == null) { // throw new IllegalArgumentException("Location cannot be null."); // } // // this.configProfile = configProfile; // this.location = FileLocation.fromLocation(location); // initConfigs(); // try { // protocolBean.watch(this.location, this); // } catch (InvalidPathException e) { // throw new RuntimeException(e); // } // } // // protected void initConfigs() { // LOGGER.debug("Loading file: {}", location); // try { // protocolBean = Protocols.getInstance().get(location.getProtocol()).newInstance(); // // ContentType contentTypeBean = ContentTypes.getInstance().get(configProfile.getContentType()).newInstance(); // cleanAndPutAll(contentTypeBean.resolve(protocolBean.read(location), configProfile.getFileEncoding())); // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // @Override // public void close() throws IOException { // if (protocolBean != null) { // protocolBean.close(); // } // } // // } // // Path: config-toolkit/src/main/java/com/dangdang/config/service/file/FileLocation.java // public class FileLocation { // // private String file; // // private String protocol; // // public FileLocation(String file, String protocol) { // super(); // this.file = file; // this.protocol = protocol; // } // // private static final String COLON = ":"; // // public static FileLocation fromLocation(String location) { // // default as file // if (!location.contains(COLON)) { // return new FileLocation(location, ProtocolNames.FILE); // } // // final int i = location.indexOf(COLON); // final String protocol = location.substring(0, i); // final String file = location.substring(i + 1); // // return new FileLocation(file, protocol.toLowerCase()); // } // // public String getFile() { // return file; // } // // public String getProtocol() { // return protocol; // } // // @Override // public String toString() { // return "FileLocation [file=" + file + ", protocol=" + protocol + "]"; // } // // }
import com.dangdang.config.service.exception.InvalidPathException; import com.dangdang.config.service.file.FileConfigGroup; import com.dangdang.config.service.file.FileLocation; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL;
package com.dangdang.config.service.file.protocol; /** * @author <a href="mailto:[email protected]">Yuxuan Wang</a> * */ public class HttpProtocol implements Protocol { @Override public void close() throws IOException { } @Override
// Path: config-toolkit/src/main/java/com/dangdang/config/service/exception/InvalidPathException.java // public class InvalidPathException extends ConfigToolkitException { // // private static final long serialVersionUID = 1L; // // public InvalidPathException() { // super(); // } // // public InvalidPathException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidPathException(String message) { // super(message); // } // // public InvalidPathException(Throwable cause) { // super(cause); // } // // } // // Path: config-toolkit/src/main/java/com/dangdang/config/service/file/FileConfigGroup.java // public class FileConfigGroup extends GeneralConfigGroup { // // private static final long serialVersionUID = 1L; // // private FileConfigProfile configProfile; // // private FileLocation location; // // private Protocol protocolBean; // // private static final Logger LOGGER = LoggerFactory.getLogger(FileConfigGroup.class); // // public FileConfigGroup(FileConfigProfile configProfile, String location, boolean enumerable) { // this(configProfile, location); // super.enumerable = enumerable; // } // // public FileConfigGroup(FileConfigProfile configProfile, String location) { // this(null, configProfile, location); // } // // public FileConfigGroup(ConfigGroup internalConfigGroup, FileConfigProfile configProfile, String location) { // super(internalConfigGroup); // // if(location == null) { // throw new IllegalArgumentException("Location cannot be null."); // } // // this.configProfile = configProfile; // this.location = FileLocation.fromLocation(location); // initConfigs(); // try { // protocolBean.watch(this.location, this); // } catch (InvalidPathException e) { // throw new RuntimeException(e); // } // } // // protected void initConfigs() { // LOGGER.debug("Loading file: {}", location); // try { // protocolBean = Protocols.getInstance().get(location.getProtocol()).newInstance(); // // ContentType contentTypeBean = ContentTypes.getInstance().get(configProfile.getContentType()).newInstance(); // cleanAndPutAll(contentTypeBean.resolve(protocolBean.read(location), configProfile.getFileEncoding())); // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // @Override // public void close() throws IOException { // if (protocolBean != null) { // protocolBean.close(); // } // } // // } // // Path: config-toolkit/src/main/java/com/dangdang/config/service/file/FileLocation.java // public class FileLocation { // // private String file; // // private String protocol; // // public FileLocation(String file, String protocol) { // super(); // this.file = file; // this.protocol = protocol; // } // // private static final String COLON = ":"; // // public static FileLocation fromLocation(String location) { // // default as file // if (!location.contains(COLON)) { // return new FileLocation(location, ProtocolNames.FILE); // } // // final int i = location.indexOf(COLON); // final String protocol = location.substring(0, i); // final String file = location.substring(i + 1); // // return new FileLocation(file, protocol.toLowerCase()); // } // // public String getFile() { // return file; // } // // public String getProtocol() { // return protocol; // } // // @Override // public String toString() { // return "FileLocation [file=" + file + ", protocol=" + protocol + "]"; // } // // } // Path: config-toolkit/src/main/java/com/dangdang/config/service/file/protocol/HttpProtocol.java import com.dangdang.config.service.exception.InvalidPathException; import com.dangdang.config.service.file.FileConfigGroup; import com.dangdang.config.service.file.FileLocation; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; package com.dangdang.config.service.file.protocol; /** * @author <a href="mailto:[email protected]">Yuxuan Wang</a> * */ public class HttpProtocol implements Protocol { @Override public void close() throws IOException { } @Override
public byte[] read(FileLocation location) throws InvalidPathException {
dangdangdotcom/config-toolkit
config-toolkit/src/main/java/com/dangdang/config/service/file/protocol/HttpProtocol.java
// Path: config-toolkit/src/main/java/com/dangdang/config/service/exception/InvalidPathException.java // public class InvalidPathException extends ConfigToolkitException { // // private static final long serialVersionUID = 1L; // // public InvalidPathException() { // super(); // } // // public InvalidPathException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidPathException(String message) { // super(message); // } // // public InvalidPathException(Throwable cause) { // super(cause); // } // // } // // Path: config-toolkit/src/main/java/com/dangdang/config/service/file/FileConfigGroup.java // public class FileConfigGroup extends GeneralConfigGroup { // // private static final long serialVersionUID = 1L; // // private FileConfigProfile configProfile; // // private FileLocation location; // // private Protocol protocolBean; // // private static final Logger LOGGER = LoggerFactory.getLogger(FileConfigGroup.class); // // public FileConfigGroup(FileConfigProfile configProfile, String location, boolean enumerable) { // this(configProfile, location); // super.enumerable = enumerable; // } // // public FileConfigGroup(FileConfigProfile configProfile, String location) { // this(null, configProfile, location); // } // // public FileConfigGroup(ConfigGroup internalConfigGroup, FileConfigProfile configProfile, String location) { // super(internalConfigGroup); // // if(location == null) { // throw new IllegalArgumentException("Location cannot be null."); // } // // this.configProfile = configProfile; // this.location = FileLocation.fromLocation(location); // initConfigs(); // try { // protocolBean.watch(this.location, this); // } catch (InvalidPathException e) { // throw new RuntimeException(e); // } // } // // protected void initConfigs() { // LOGGER.debug("Loading file: {}", location); // try { // protocolBean = Protocols.getInstance().get(location.getProtocol()).newInstance(); // // ContentType contentTypeBean = ContentTypes.getInstance().get(configProfile.getContentType()).newInstance(); // cleanAndPutAll(contentTypeBean.resolve(protocolBean.read(location), configProfile.getFileEncoding())); // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // @Override // public void close() throws IOException { // if (protocolBean != null) { // protocolBean.close(); // } // } // // } // // Path: config-toolkit/src/main/java/com/dangdang/config/service/file/FileLocation.java // public class FileLocation { // // private String file; // // private String protocol; // // public FileLocation(String file, String protocol) { // super(); // this.file = file; // this.protocol = protocol; // } // // private static final String COLON = ":"; // // public static FileLocation fromLocation(String location) { // // default as file // if (!location.contains(COLON)) { // return new FileLocation(location, ProtocolNames.FILE); // } // // final int i = location.indexOf(COLON); // final String protocol = location.substring(0, i); // final String file = location.substring(i + 1); // // return new FileLocation(file, protocol.toLowerCase()); // } // // public String getFile() { // return file; // } // // public String getProtocol() { // return protocol; // } // // @Override // public String toString() { // return "FileLocation [file=" + file + ", protocol=" + protocol + "]"; // } // // }
import com.dangdang.config.service.exception.InvalidPathException; import com.dangdang.config.service.file.FileConfigGroup; import com.dangdang.config.service.file.FileLocation; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL;
package com.dangdang.config.service.file.protocol; /** * @author <a href="mailto:[email protected]">Yuxuan Wang</a> * */ public class HttpProtocol implements Protocol { @Override public void close() throws IOException { } @Override
// Path: config-toolkit/src/main/java/com/dangdang/config/service/exception/InvalidPathException.java // public class InvalidPathException extends ConfigToolkitException { // // private static final long serialVersionUID = 1L; // // public InvalidPathException() { // super(); // } // // public InvalidPathException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidPathException(String message) { // super(message); // } // // public InvalidPathException(Throwable cause) { // super(cause); // } // // } // // Path: config-toolkit/src/main/java/com/dangdang/config/service/file/FileConfigGroup.java // public class FileConfigGroup extends GeneralConfigGroup { // // private static final long serialVersionUID = 1L; // // private FileConfigProfile configProfile; // // private FileLocation location; // // private Protocol protocolBean; // // private static final Logger LOGGER = LoggerFactory.getLogger(FileConfigGroup.class); // // public FileConfigGroup(FileConfigProfile configProfile, String location, boolean enumerable) { // this(configProfile, location); // super.enumerable = enumerable; // } // // public FileConfigGroup(FileConfigProfile configProfile, String location) { // this(null, configProfile, location); // } // // public FileConfigGroup(ConfigGroup internalConfigGroup, FileConfigProfile configProfile, String location) { // super(internalConfigGroup); // // if(location == null) { // throw new IllegalArgumentException("Location cannot be null."); // } // // this.configProfile = configProfile; // this.location = FileLocation.fromLocation(location); // initConfigs(); // try { // protocolBean.watch(this.location, this); // } catch (InvalidPathException e) { // throw new RuntimeException(e); // } // } // // protected void initConfigs() { // LOGGER.debug("Loading file: {}", location); // try { // protocolBean = Protocols.getInstance().get(location.getProtocol()).newInstance(); // // ContentType contentTypeBean = ContentTypes.getInstance().get(configProfile.getContentType()).newInstance(); // cleanAndPutAll(contentTypeBean.resolve(protocolBean.read(location), configProfile.getFileEncoding())); // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // @Override // public void close() throws IOException { // if (protocolBean != null) { // protocolBean.close(); // } // } // // } // // Path: config-toolkit/src/main/java/com/dangdang/config/service/file/FileLocation.java // public class FileLocation { // // private String file; // // private String protocol; // // public FileLocation(String file, String protocol) { // super(); // this.file = file; // this.protocol = protocol; // } // // private static final String COLON = ":"; // // public static FileLocation fromLocation(String location) { // // default as file // if (!location.contains(COLON)) { // return new FileLocation(location, ProtocolNames.FILE); // } // // final int i = location.indexOf(COLON); // final String protocol = location.substring(0, i); // final String file = location.substring(i + 1); // // return new FileLocation(file, protocol.toLowerCase()); // } // // public String getFile() { // return file; // } // // public String getProtocol() { // return protocol; // } // // @Override // public String toString() { // return "FileLocation [file=" + file + ", protocol=" + protocol + "]"; // } // // } // Path: config-toolkit/src/main/java/com/dangdang/config/service/file/protocol/HttpProtocol.java import com.dangdang.config.service.exception.InvalidPathException; import com.dangdang.config.service.file.FileConfigGroup; import com.dangdang.config.service.file.FileLocation; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; package com.dangdang.config.service.file.protocol; /** * @author <a href="mailto:[email protected]">Yuxuan Wang</a> * */ public class HttpProtocol implements Protocol { @Override public void close() throws IOException { } @Override
public byte[] read(FileLocation location) throws InvalidPathException {
dangdangdotcom/config-toolkit
config-toolkit/src/main/java/com/dangdang/config/service/file/protocol/HttpProtocol.java
// Path: config-toolkit/src/main/java/com/dangdang/config/service/exception/InvalidPathException.java // public class InvalidPathException extends ConfigToolkitException { // // private static final long serialVersionUID = 1L; // // public InvalidPathException() { // super(); // } // // public InvalidPathException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidPathException(String message) { // super(message); // } // // public InvalidPathException(Throwable cause) { // super(cause); // } // // } // // Path: config-toolkit/src/main/java/com/dangdang/config/service/file/FileConfigGroup.java // public class FileConfigGroup extends GeneralConfigGroup { // // private static final long serialVersionUID = 1L; // // private FileConfigProfile configProfile; // // private FileLocation location; // // private Protocol protocolBean; // // private static final Logger LOGGER = LoggerFactory.getLogger(FileConfigGroup.class); // // public FileConfigGroup(FileConfigProfile configProfile, String location, boolean enumerable) { // this(configProfile, location); // super.enumerable = enumerable; // } // // public FileConfigGroup(FileConfigProfile configProfile, String location) { // this(null, configProfile, location); // } // // public FileConfigGroup(ConfigGroup internalConfigGroup, FileConfigProfile configProfile, String location) { // super(internalConfigGroup); // // if(location == null) { // throw new IllegalArgumentException("Location cannot be null."); // } // // this.configProfile = configProfile; // this.location = FileLocation.fromLocation(location); // initConfigs(); // try { // protocolBean.watch(this.location, this); // } catch (InvalidPathException e) { // throw new RuntimeException(e); // } // } // // protected void initConfigs() { // LOGGER.debug("Loading file: {}", location); // try { // protocolBean = Protocols.getInstance().get(location.getProtocol()).newInstance(); // // ContentType contentTypeBean = ContentTypes.getInstance().get(configProfile.getContentType()).newInstance(); // cleanAndPutAll(contentTypeBean.resolve(protocolBean.read(location), configProfile.getFileEncoding())); // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // @Override // public void close() throws IOException { // if (protocolBean != null) { // protocolBean.close(); // } // } // // } // // Path: config-toolkit/src/main/java/com/dangdang/config/service/file/FileLocation.java // public class FileLocation { // // private String file; // // private String protocol; // // public FileLocation(String file, String protocol) { // super(); // this.file = file; // this.protocol = protocol; // } // // private static final String COLON = ":"; // // public static FileLocation fromLocation(String location) { // // default as file // if (!location.contains(COLON)) { // return new FileLocation(location, ProtocolNames.FILE); // } // // final int i = location.indexOf(COLON); // final String protocol = location.substring(0, i); // final String file = location.substring(i + 1); // // return new FileLocation(file, protocol.toLowerCase()); // } // // public String getFile() { // return file; // } // // public String getProtocol() { // return protocol; // } // // @Override // public String toString() { // return "FileLocation [file=" + file + ", protocol=" + protocol + "]"; // } // // }
import com.dangdang.config.service.exception.InvalidPathException; import com.dangdang.config.service.file.FileConfigGroup; import com.dangdang.config.service.file.FileLocation; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL;
package com.dangdang.config.service.file.protocol; /** * @author <a href="mailto:[email protected]">Yuxuan Wang</a> * */ public class HttpProtocol implements Protocol { @Override public void close() throws IOException { } @Override public byte[] read(FileLocation location) throws InvalidPathException { try { URL url = new URL(location.getProtocol() + ":" + location.getFile()); try (InputStream in = url.openStream()) { try(ByteArrayOutputStream buffer = new ByteArrayOutputStream()) { int nRead; byte[] data = new byte[1024]; while ((nRead = in.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); return buffer.toByteArray(); } } } catch (MalformedURLException e) { throw new InvalidPathException(e); } catch (IOException e) { throw new InvalidPathException(e); } } @Override
// Path: config-toolkit/src/main/java/com/dangdang/config/service/exception/InvalidPathException.java // public class InvalidPathException extends ConfigToolkitException { // // private static final long serialVersionUID = 1L; // // public InvalidPathException() { // super(); // } // // public InvalidPathException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidPathException(String message) { // super(message); // } // // public InvalidPathException(Throwable cause) { // super(cause); // } // // } // // Path: config-toolkit/src/main/java/com/dangdang/config/service/file/FileConfigGroup.java // public class FileConfigGroup extends GeneralConfigGroup { // // private static final long serialVersionUID = 1L; // // private FileConfigProfile configProfile; // // private FileLocation location; // // private Protocol protocolBean; // // private static final Logger LOGGER = LoggerFactory.getLogger(FileConfigGroup.class); // // public FileConfigGroup(FileConfigProfile configProfile, String location, boolean enumerable) { // this(configProfile, location); // super.enumerable = enumerable; // } // // public FileConfigGroup(FileConfigProfile configProfile, String location) { // this(null, configProfile, location); // } // // public FileConfigGroup(ConfigGroup internalConfigGroup, FileConfigProfile configProfile, String location) { // super(internalConfigGroup); // // if(location == null) { // throw new IllegalArgumentException("Location cannot be null."); // } // // this.configProfile = configProfile; // this.location = FileLocation.fromLocation(location); // initConfigs(); // try { // protocolBean.watch(this.location, this); // } catch (InvalidPathException e) { // throw new RuntimeException(e); // } // } // // protected void initConfigs() { // LOGGER.debug("Loading file: {}", location); // try { // protocolBean = Protocols.getInstance().get(location.getProtocol()).newInstance(); // // ContentType contentTypeBean = ContentTypes.getInstance().get(configProfile.getContentType()).newInstance(); // cleanAndPutAll(contentTypeBean.resolve(protocolBean.read(location), configProfile.getFileEncoding())); // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // @Override // public void close() throws IOException { // if (protocolBean != null) { // protocolBean.close(); // } // } // // } // // Path: config-toolkit/src/main/java/com/dangdang/config/service/file/FileLocation.java // public class FileLocation { // // private String file; // // private String protocol; // // public FileLocation(String file, String protocol) { // super(); // this.file = file; // this.protocol = protocol; // } // // private static final String COLON = ":"; // // public static FileLocation fromLocation(String location) { // // default as file // if (!location.contains(COLON)) { // return new FileLocation(location, ProtocolNames.FILE); // } // // final int i = location.indexOf(COLON); // final String protocol = location.substring(0, i); // final String file = location.substring(i + 1); // // return new FileLocation(file, protocol.toLowerCase()); // } // // public String getFile() { // return file; // } // // public String getProtocol() { // return protocol; // } // // @Override // public String toString() { // return "FileLocation [file=" + file + ", protocol=" + protocol + "]"; // } // // } // Path: config-toolkit/src/main/java/com/dangdang/config/service/file/protocol/HttpProtocol.java import com.dangdang.config.service.exception.InvalidPathException; import com.dangdang.config.service.file.FileConfigGroup; import com.dangdang.config.service.file.FileLocation; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; package com.dangdang.config.service.file.protocol; /** * @author <a href="mailto:[email protected]">Yuxuan Wang</a> * */ public class HttpProtocol implements Protocol { @Override public void close() throws IOException { } @Override public byte[] read(FileLocation location) throws InvalidPathException { try { URL url = new URL(location.getProtocol() + ":" + location.getFile()); try (InputStream in = url.openStream()) { try(ByteArrayOutputStream buffer = new ByteArrayOutputStream()) { int nRead; byte[] data = new byte[1024]; while ((nRead = in.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); return buffer.toByteArray(); } } } catch (MalformedURLException e) { throw new InvalidPathException(e); } catch (IOException e) { throw new InvalidPathException(e); } } @Override
public void watch(FileLocation location, FileConfigGroup fileConfigGroup) throws InvalidPathException {
dangdangdotcom/config-toolkit
config-toolkit/src/main/java/com/dangdang/config/service/file/protocol/FileProtocol.java
// Path: config-toolkit/src/main/java/com/dangdang/config/service/exception/InvalidPathException.java // public class InvalidPathException extends ConfigToolkitException { // // private static final long serialVersionUID = 1L; // // public InvalidPathException() { // super(); // } // // public InvalidPathException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidPathException(String message) { // super(message); // } // // public InvalidPathException(Throwable cause) { // super(cause); // } // // } // // Path: config-toolkit/src/main/java/com/dangdang/config/service/file/FileLocation.java // public class FileLocation { // // private String file; // // private String protocol; // // public FileLocation(String file, String protocol) { // super(); // this.file = file; // this.protocol = protocol; // } // // private static final String COLON = ":"; // // public static FileLocation fromLocation(String location) { // // default as file // if (!location.contains(COLON)) { // return new FileLocation(location, ProtocolNames.FILE); // } // // final int i = location.indexOf(COLON); // final String protocol = location.substring(0, i); // final String file = location.substring(i + 1); // // return new FileLocation(file, protocol.toLowerCase()); // } // // public String getFile() { // return file; // } // // public String getProtocol() { // return protocol; // } // // @Override // public String toString() { // return "FileLocation [file=" + file + ", protocol=" + protocol + "]"; // } // // }
import java.nio.file.Path; import java.nio.file.Paths; import com.dangdang.config.service.exception.InvalidPathException; import com.dangdang.config.service.file.FileLocation;
package com.dangdang.config.service.file.protocol; /** * @author <a href="mailto:[email protected]">Yuxuan Wang</a> * */ public class FileProtocol extends LocalFileProtocol { @Override
// Path: config-toolkit/src/main/java/com/dangdang/config/service/exception/InvalidPathException.java // public class InvalidPathException extends ConfigToolkitException { // // private static final long serialVersionUID = 1L; // // public InvalidPathException() { // super(); // } // // public InvalidPathException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidPathException(String message) { // super(message); // } // // public InvalidPathException(Throwable cause) { // super(cause); // } // // } // // Path: config-toolkit/src/main/java/com/dangdang/config/service/file/FileLocation.java // public class FileLocation { // // private String file; // // private String protocol; // // public FileLocation(String file, String protocol) { // super(); // this.file = file; // this.protocol = protocol; // } // // private static final String COLON = ":"; // // public static FileLocation fromLocation(String location) { // // default as file // if (!location.contains(COLON)) { // return new FileLocation(location, ProtocolNames.FILE); // } // // final int i = location.indexOf(COLON); // final String protocol = location.substring(0, i); // final String file = location.substring(i + 1); // // return new FileLocation(file, protocol.toLowerCase()); // } // // public String getFile() { // return file; // } // // public String getProtocol() { // return protocol; // } // // @Override // public String toString() { // return "FileLocation [file=" + file + ", protocol=" + protocol + "]"; // } // // } // Path: config-toolkit/src/main/java/com/dangdang/config/service/file/protocol/FileProtocol.java import java.nio.file.Path; import java.nio.file.Paths; import com.dangdang.config.service.exception.InvalidPathException; import com.dangdang.config.service.file.FileLocation; package com.dangdang.config.service.file.protocol; /** * @author <a href="mailto:[email protected]">Yuxuan Wang</a> * */ public class FileProtocol extends LocalFileProtocol { @Override
protected Path getPath(FileLocation location) throws InvalidPathException {
dangdangdotcom/config-toolkit
config-toolkit/src/main/java/com/dangdang/config/service/file/protocol/FileProtocol.java
// Path: config-toolkit/src/main/java/com/dangdang/config/service/exception/InvalidPathException.java // public class InvalidPathException extends ConfigToolkitException { // // private static final long serialVersionUID = 1L; // // public InvalidPathException() { // super(); // } // // public InvalidPathException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidPathException(String message) { // super(message); // } // // public InvalidPathException(Throwable cause) { // super(cause); // } // // } // // Path: config-toolkit/src/main/java/com/dangdang/config/service/file/FileLocation.java // public class FileLocation { // // private String file; // // private String protocol; // // public FileLocation(String file, String protocol) { // super(); // this.file = file; // this.protocol = protocol; // } // // private static final String COLON = ":"; // // public static FileLocation fromLocation(String location) { // // default as file // if (!location.contains(COLON)) { // return new FileLocation(location, ProtocolNames.FILE); // } // // final int i = location.indexOf(COLON); // final String protocol = location.substring(0, i); // final String file = location.substring(i + 1); // // return new FileLocation(file, protocol.toLowerCase()); // } // // public String getFile() { // return file; // } // // public String getProtocol() { // return protocol; // } // // @Override // public String toString() { // return "FileLocation [file=" + file + ", protocol=" + protocol + "]"; // } // // }
import java.nio.file.Path; import java.nio.file.Paths; import com.dangdang.config.service.exception.InvalidPathException; import com.dangdang.config.service.file.FileLocation;
package com.dangdang.config.service.file.protocol; /** * @author <a href="mailto:[email protected]">Yuxuan Wang</a> * */ public class FileProtocol extends LocalFileProtocol { @Override
// Path: config-toolkit/src/main/java/com/dangdang/config/service/exception/InvalidPathException.java // public class InvalidPathException extends ConfigToolkitException { // // private static final long serialVersionUID = 1L; // // public InvalidPathException() { // super(); // } // // public InvalidPathException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidPathException(String message) { // super(message); // } // // public InvalidPathException(Throwable cause) { // super(cause); // } // // } // // Path: config-toolkit/src/main/java/com/dangdang/config/service/file/FileLocation.java // public class FileLocation { // // private String file; // // private String protocol; // // public FileLocation(String file, String protocol) { // super(); // this.file = file; // this.protocol = protocol; // } // // private static final String COLON = ":"; // // public static FileLocation fromLocation(String location) { // // default as file // if (!location.contains(COLON)) { // return new FileLocation(location, ProtocolNames.FILE); // } // // final int i = location.indexOf(COLON); // final String protocol = location.substring(0, i); // final String file = location.substring(i + 1); // // return new FileLocation(file, protocol.toLowerCase()); // } // // public String getFile() { // return file; // } // // public String getProtocol() { // return protocol; // } // // @Override // public String toString() { // return "FileLocation [file=" + file + ", protocol=" + protocol + "]"; // } // // } // Path: config-toolkit/src/main/java/com/dangdang/config/service/file/protocol/FileProtocol.java import java.nio.file.Path; import java.nio.file.Paths; import com.dangdang.config.service.exception.InvalidPathException; import com.dangdang.config.service.file.FileLocation; package com.dangdang.config.service.file.protocol; /** * @author <a href="mailto:[email protected]">Yuxuan Wang</a> * */ public class FileProtocol extends LocalFileProtocol { @Override
protected Path getPath(FileLocation location) throws InvalidPathException {
dangdangdotcom/config-toolkit
config-toolkit/src/main/java/com/dangdang/config/service/file/protocol/ClasspathProtocol.java
// Path: config-toolkit/src/main/java/com/dangdang/config/service/exception/InvalidPathException.java // public class InvalidPathException extends ConfigToolkitException { // // private static final long serialVersionUID = 1L; // // public InvalidPathException() { // super(); // } // // public InvalidPathException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidPathException(String message) { // super(message); // } // // public InvalidPathException(Throwable cause) { // super(cause); // } // // } // // Path: config-toolkit/src/main/java/com/dangdang/config/service/file/FileLocation.java // public class FileLocation { // // private String file; // // private String protocol; // // public FileLocation(String file, String protocol) { // super(); // this.file = file; // this.protocol = protocol; // } // // private static final String COLON = ":"; // // public static FileLocation fromLocation(String location) { // // default as file // if (!location.contains(COLON)) { // return new FileLocation(location, ProtocolNames.FILE); // } // // final int i = location.indexOf(COLON); // final String protocol = location.substring(0, i); // final String file = location.substring(i + 1); // // return new FileLocation(file, protocol.toLowerCase()); // } // // public String getFile() { // return file; // } // // public String getProtocol() { // return protocol; // } // // @Override // public String toString() { // return "FileLocation [file=" + file + ", protocol=" + protocol + "]"; // } // // }
import com.dangdang.config.service.exception.InvalidPathException; import com.dangdang.config.service.file.FileLocation; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map;
package com.dangdang.config.service.file.protocol; /** * @author <a href="mailto:[email protected]">Yuxuan Wang</a> * */ public class ClasspathProtocol extends LocalFileProtocol { private static Map<String, FileSystem> fsMap; static { fsMap = new HashMap<>(); } @Override
// Path: config-toolkit/src/main/java/com/dangdang/config/service/exception/InvalidPathException.java // public class InvalidPathException extends ConfigToolkitException { // // private static final long serialVersionUID = 1L; // // public InvalidPathException() { // super(); // } // // public InvalidPathException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidPathException(String message) { // super(message); // } // // public InvalidPathException(Throwable cause) { // super(cause); // } // // } // // Path: config-toolkit/src/main/java/com/dangdang/config/service/file/FileLocation.java // public class FileLocation { // // private String file; // // private String protocol; // // public FileLocation(String file, String protocol) { // super(); // this.file = file; // this.protocol = protocol; // } // // private static final String COLON = ":"; // // public static FileLocation fromLocation(String location) { // // default as file // if (!location.contains(COLON)) { // return new FileLocation(location, ProtocolNames.FILE); // } // // final int i = location.indexOf(COLON); // final String protocol = location.substring(0, i); // final String file = location.substring(i + 1); // // return new FileLocation(file, protocol.toLowerCase()); // } // // public String getFile() { // return file; // } // // public String getProtocol() { // return protocol; // } // // @Override // public String toString() { // return "FileLocation [file=" + file + ", protocol=" + protocol + "]"; // } // // } // Path: config-toolkit/src/main/java/com/dangdang/config/service/file/protocol/ClasspathProtocol.java import com.dangdang.config.service.exception.InvalidPathException; import com.dangdang.config.service.file.FileLocation; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; package com.dangdang.config.service.file.protocol; /** * @author <a href="mailto:[email protected]">Yuxuan Wang</a> * */ public class ClasspathProtocol extends LocalFileProtocol { private static Map<String, FileSystem> fsMap; static { fsMap = new HashMap<>(); } @Override
protected Path getPath(FileLocation location) throws InvalidPathException {
dangdangdotcom/config-toolkit
config-toolkit/src/main/java/com/dangdang/config/service/file/protocol/ClasspathProtocol.java
// Path: config-toolkit/src/main/java/com/dangdang/config/service/exception/InvalidPathException.java // public class InvalidPathException extends ConfigToolkitException { // // private static final long serialVersionUID = 1L; // // public InvalidPathException() { // super(); // } // // public InvalidPathException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidPathException(String message) { // super(message); // } // // public InvalidPathException(Throwable cause) { // super(cause); // } // // } // // Path: config-toolkit/src/main/java/com/dangdang/config/service/file/FileLocation.java // public class FileLocation { // // private String file; // // private String protocol; // // public FileLocation(String file, String protocol) { // super(); // this.file = file; // this.protocol = protocol; // } // // private static final String COLON = ":"; // // public static FileLocation fromLocation(String location) { // // default as file // if (!location.contains(COLON)) { // return new FileLocation(location, ProtocolNames.FILE); // } // // final int i = location.indexOf(COLON); // final String protocol = location.substring(0, i); // final String file = location.substring(i + 1); // // return new FileLocation(file, protocol.toLowerCase()); // } // // public String getFile() { // return file; // } // // public String getProtocol() { // return protocol; // } // // @Override // public String toString() { // return "FileLocation [file=" + file + ", protocol=" + protocol + "]"; // } // // }
import com.dangdang.config.service.exception.InvalidPathException; import com.dangdang.config.service.file.FileLocation; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map;
package com.dangdang.config.service.file.protocol; /** * @author <a href="mailto:[email protected]">Yuxuan Wang</a> * */ public class ClasspathProtocol extends LocalFileProtocol { private static Map<String, FileSystem> fsMap; static { fsMap = new HashMap<>(); } @Override
// Path: config-toolkit/src/main/java/com/dangdang/config/service/exception/InvalidPathException.java // public class InvalidPathException extends ConfigToolkitException { // // private static final long serialVersionUID = 1L; // // public InvalidPathException() { // super(); // } // // public InvalidPathException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidPathException(String message) { // super(message); // } // // public InvalidPathException(Throwable cause) { // super(cause); // } // // } // // Path: config-toolkit/src/main/java/com/dangdang/config/service/file/FileLocation.java // public class FileLocation { // // private String file; // // private String protocol; // // public FileLocation(String file, String protocol) { // super(); // this.file = file; // this.protocol = protocol; // } // // private static final String COLON = ":"; // // public static FileLocation fromLocation(String location) { // // default as file // if (!location.contains(COLON)) { // return new FileLocation(location, ProtocolNames.FILE); // } // // final int i = location.indexOf(COLON); // final String protocol = location.substring(0, i); // final String file = location.substring(i + 1); // // return new FileLocation(file, protocol.toLowerCase()); // } // // public String getFile() { // return file; // } // // public String getProtocol() { // return protocol; // } // // @Override // public String toString() { // return "FileLocation [file=" + file + ", protocol=" + protocol + "]"; // } // // } // Path: config-toolkit/src/main/java/com/dangdang/config/service/file/protocol/ClasspathProtocol.java import com.dangdang.config.service.exception.InvalidPathException; import com.dangdang.config.service.file.FileLocation; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; package com.dangdang.config.service.file.protocol; /** * @author <a href="mailto:[email protected]">Yuxuan Wang</a> * */ public class ClasspathProtocol extends LocalFileProtocol { private static Map<String, FileSystem> fsMap; static { fsMap = new HashMap<>(); } @Override
protected Path getPath(FileLocation location) throws InvalidPathException {
dangdangdotcom/config-toolkit
config-toolkit/src/main/java/com/dangdang/config/service/support/spring/ZookeeperConfigProfileConfigBean.java
// Path: config-toolkit/src/main/java/com/dangdang/config/service/zookeeper/ZookeeperConfigProfile.java // public class ZookeeperConfigProfile extends ConfigProfile { // // private static final ExponentialBackoffRetry DEFAULT_RETRY_POLICY = new ExponentialBackoffRetry(1000, 3); // // /** // * zookeeper地址 // */ // private final String connectStr; // // /** // * 项目配置根目录 // */ // private final String rootNode; // // /** // * 重试策略 // */ // private final RetryPolicy retryPolicy; // // /** // * 是否开启本地缓存, 基础为当前用户目录下的.config-toolkit // */ // private final boolean openLocalCache; // // public ZookeeperConfigProfile(final String connectStr, final String rootNode, final String version) { // this(connectStr, rootNode, version, false); // } // // public ZookeeperConfigProfile(final String connectStr, final String rootNode, final String version, final boolean openLocalCache) { // this(connectStr, rootNode, version, openLocalCache, DEFAULT_RETRY_POLICY); // } // // public ZookeeperConfigProfile(final String connectStr, final String rootNode, final String version, final boolean openLocalCache, // final RetryPolicy retryPolicy) { // super(version); // // if(connectStr == null || rootNode == null || retryPolicy == null) { // throw new IllegalArgumentException(); // } // // this.connectStr = connectStr; // this.rootNode = rootNode; // this.retryPolicy = retryPolicy; // this.openLocalCache = openLocalCache; // } // // public String getConnectStr() { // return connectStr; // } // // public String getRootNode() { // return rootNode; // } // // public RetryPolicy getRetryPolicy() { // return retryPolicy; // } // // public String getVersionedRootNode() { // if (version == null) { // throw new IllegalArgumentException("Version cannot be null"); // } // return ZKPaths.makePath(rootNode, version); // } // // public boolean isOpenLocalCache() { // return openLocalCache; // } // // @Override // public String toString() { // return "ZookeeperConfigProfile{" + // "connectStr='" + connectStr + '\'' + // ", rootNode='" + rootNode + '\'' + // ", retryPolicy=" + retryPolicy + // ", openLocalCache=" + openLocalCache + // '}'; // } // }
import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser; import org.w3c.dom.Element; import com.dangdang.config.service.zookeeper.ZookeeperConfigProfile;
package com.dangdang.config.service.support.spring; public class ZookeeperConfigProfileConfigBean extends AbstractSingleBeanDefinitionParser { @Override protected Class<?> getBeanClass(Element element) {
// Path: config-toolkit/src/main/java/com/dangdang/config/service/zookeeper/ZookeeperConfigProfile.java // public class ZookeeperConfigProfile extends ConfigProfile { // // private static final ExponentialBackoffRetry DEFAULT_RETRY_POLICY = new ExponentialBackoffRetry(1000, 3); // // /** // * zookeeper地址 // */ // private final String connectStr; // // /** // * 项目配置根目录 // */ // private final String rootNode; // // /** // * 重试策略 // */ // private final RetryPolicy retryPolicy; // // /** // * 是否开启本地缓存, 基础为当前用户目录下的.config-toolkit // */ // private final boolean openLocalCache; // // public ZookeeperConfigProfile(final String connectStr, final String rootNode, final String version) { // this(connectStr, rootNode, version, false); // } // // public ZookeeperConfigProfile(final String connectStr, final String rootNode, final String version, final boolean openLocalCache) { // this(connectStr, rootNode, version, openLocalCache, DEFAULT_RETRY_POLICY); // } // // public ZookeeperConfigProfile(final String connectStr, final String rootNode, final String version, final boolean openLocalCache, // final RetryPolicy retryPolicy) { // super(version); // // if(connectStr == null || rootNode == null || retryPolicy == null) { // throw new IllegalArgumentException(); // } // // this.connectStr = connectStr; // this.rootNode = rootNode; // this.retryPolicy = retryPolicy; // this.openLocalCache = openLocalCache; // } // // public String getConnectStr() { // return connectStr; // } // // public String getRootNode() { // return rootNode; // } // // public RetryPolicy getRetryPolicy() { // return retryPolicy; // } // // public String getVersionedRootNode() { // if (version == null) { // throw new IllegalArgumentException("Version cannot be null"); // } // return ZKPaths.makePath(rootNode, version); // } // // public boolean isOpenLocalCache() { // return openLocalCache; // } // // @Override // public String toString() { // return "ZookeeperConfigProfile{" + // "connectStr='" + connectStr + '\'' + // ", rootNode='" + rootNode + '\'' + // ", retryPolicy=" + retryPolicy + // ", openLocalCache=" + openLocalCache + // '}'; // } // } // Path: config-toolkit/src/main/java/com/dangdang/config/service/support/spring/ZookeeperConfigProfileConfigBean.java import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser; import org.w3c.dom.Element; import com.dangdang.config.service.zookeeper.ZookeeperConfigProfile; package com.dangdang.config.service.support.spring; public class ZookeeperConfigProfileConfigBean extends AbstractSingleBeanDefinitionParser { @Override protected Class<?> getBeanClass(Element element) {
return ZookeeperConfigProfile.class;
gdgand/android-rxjava
2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/SampleApplication.java
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/component/ApplicationComponent.java // @Singleton // @Component(modules = { ApplicationModule.class, DataModule.class }) // public interface ApplicationComponent { // Context context(); // ImgurApi imgurApi(); // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/module/ApplicationModule.java // @Module // public class ApplicationModule { // private Application application; // public ApplicationModule(Application application) { // this.application = application; // } // // @Provides // @Singleton // public Context context() { // return application; // } // // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/module/DataModule.java // @Module // public class DataModule { // // @Provides // @Singleton // public Converter.Factory converterFactory() { // return GsonConverterFactory.create(); // } // // // @Provides // @Singleton // public CallAdapter.Factory callAdapterFactory() { // return RxJavaCallAdapterFactory.create(); // } // // @Provides // @Singleton // public OkHttpClient okHttpClient() { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // // return new OkHttpClient.Builder() // .addInterceptor(interceptor) // .build(); // } // // @Provides // @Singleton // public Retrofit retrofit(OkHttpClient client, CallAdapter.Factory callAdapterFactory, Converter.Factory converterFactory) { // return new Retrofit.Builder() // .baseUrl("https://api.imgur.com") // .client(client) // .addCallAdapterFactory(callAdapterFactory) // .addConverterFactory(converterFactory) // .build(); // } // // @Provides // @Singleton // public ImgurApi imgurApi(Retrofit retrofit) { // return retrofit.create(ImgurApi.class); // } // }
import android.app.Application; import com.gdgand.rxjava.rxjavasample.hotandcold.di.component.ApplicationComponent; import com.gdgand.rxjava.rxjavasample.hotandcold.di.component.DaggerApplicationComponent; import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.ApplicationModule; import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.DataModule;
package com.gdgand.rxjava.rxjavasample.hotandcold; public class SampleApplication extends Application { private ApplicationComponent applicationComponent; @Override public void onCreate() { super.onCreate(); applicationComponent = createComponent(); } private ApplicationComponent createComponent() { return DaggerApplicationComponent.builder()
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/component/ApplicationComponent.java // @Singleton // @Component(modules = { ApplicationModule.class, DataModule.class }) // public interface ApplicationComponent { // Context context(); // ImgurApi imgurApi(); // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/module/ApplicationModule.java // @Module // public class ApplicationModule { // private Application application; // public ApplicationModule(Application application) { // this.application = application; // } // // @Provides // @Singleton // public Context context() { // return application; // } // // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/module/DataModule.java // @Module // public class DataModule { // // @Provides // @Singleton // public Converter.Factory converterFactory() { // return GsonConverterFactory.create(); // } // // // @Provides // @Singleton // public CallAdapter.Factory callAdapterFactory() { // return RxJavaCallAdapterFactory.create(); // } // // @Provides // @Singleton // public OkHttpClient okHttpClient() { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // // return new OkHttpClient.Builder() // .addInterceptor(interceptor) // .build(); // } // // @Provides // @Singleton // public Retrofit retrofit(OkHttpClient client, CallAdapter.Factory callAdapterFactory, Converter.Factory converterFactory) { // return new Retrofit.Builder() // .baseUrl("https://api.imgur.com") // .client(client) // .addCallAdapterFactory(callAdapterFactory) // .addConverterFactory(converterFactory) // .build(); // } // // @Provides // @Singleton // public ImgurApi imgurApi(Retrofit retrofit) { // return retrofit.create(ImgurApi.class); // } // } // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/SampleApplication.java import android.app.Application; import com.gdgand.rxjava.rxjavasample.hotandcold.di.component.ApplicationComponent; import com.gdgand.rxjava.rxjavasample.hotandcold.di.component.DaggerApplicationComponent; import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.ApplicationModule; import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.DataModule; package com.gdgand.rxjava.rxjavasample.hotandcold; public class SampleApplication extends Application { private ApplicationComponent applicationComponent; @Override public void onCreate() { super.onCreate(); applicationComponent = createComponent(); } private ApplicationComponent createComponent() { return DaggerApplicationComponent.builder()
.applicationModule(new ApplicationModule(this))
gdgand/android-rxjava
2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/SampleApplication.java
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/component/ApplicationComponent.java // @Singleton // @Component(modules = { ApplicationModule.class, DataModule.class }) // public interface ApplicationComponent { // Context context(); // ImgurApi imgurApi(); // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/module/ApplicationModule.java // @Module // public class ApplicationModule { // private Application application; // public ApplicationModule(Application application) { // this.application = application; // } // // @Provides // @Singleton // public Context context() { // return application; // } // // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/module/DataModule.java // @Module // public class DataModule { // // @Provides // @Singleton // public Converter.Factory converterFactory() { // return GsonConverterFactory.create(); // } // // // @Provides // @Singleton // public CallAdapter.Factory callAdapterFactory() { // return RxJavaCallAdapterFactory.create(); // } // // @Provides // @Singleton // public OkHttpClient okHttpClient() { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // // return new OkHttpClient.Builder() // .addInterceptor(interceptor) // .build(); // } // // @Provides // @Singleton // public Retrofit retrofit(OkHttpClient client, CallAdapter.Factory callAdapterFactory, Converter.Factory converterFactory) { // return new Retrofit.Builder() // .baseUrl("https://api.imgur.com") // .client(client) // .addCallAdapterFactory(callAdapterFactory) // .addConverterFactory(converterFactory) // .build(); // } // // @Provides // @Singleton // public ImgurApi imgurApi(Retrofit retrofit) { // return retrofit.create(ImgurApi.class); // } // }
import android.app.Application; import com.gdgand.rxjava.rxjavasample.hotandcold.di.component.ApplicationComponent; import com.gdgand.rxjava.rxjavasample.hotandcold.di.component.DaggerApplicationComponent; import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.ApplicationModule; import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.DataModule;
package com.gdgand.rxjava.rxjavasample.hotandcold; public class SampleApplication extends Application { private ApplicationComponent applicationComponent; @Override public void onCreate() { super.onCreate(); applicationComponent = createComponent(); } private ApplicationComponent createComponent() { return DaggerApplicationComponent.builder() .applicationModule(new ApplicationModule(this))
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/component/ApplicationComponent.java // @Singleton // @Component(modules = { ApplicationModule.class, DataModule.class }) // public interface ApplicationComponent { // Context context(); // ImgurApi imgurApi(); // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/module/ApplicationModule.java // @Module // public class ApplicationModule { // private Application application; // public ApplicationModule(Application application) { // this.application = application; // } // // @Provides // @Singleton // public Context context() { // return application; // } // // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/module/DataModule.java // @Module // public class DataModule { // // @Provides // @Singleton // public Converter.Factory converterFactory() { // return GsonConverterFactory.create(); // } // // // @Provides // @Singleton // public CallAdapter.Factory callAdapterFactory() { // return RxJavaCallAdapterFactory.create(); // } // // @Provides // @Singleton // public OkHttpClient okHttpClient() { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // // return new OkHttpClient.Builder() // .addInterceptor(interceptor) // .build(); // } // // @Provides // @Singleton // public Retrofit retrofit(OkHttpClient client, CallAdapter.Factory callAdapterFactory, Converter.Factory converterFactory) { // return new Retrofit.Builder() // .baseUrl("https://api.imgur.com") // .client(client) // .addCallAdapterFactory(callAdapterFactory) // .addConverterFactory(converterFactory) // .build(); // } // // @Provides // @Singleton // public ImgurApi imgurApi(Retrofit retrofit) { // return retrofit.create(ImgurApi.class); // } // } // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/SampleApplication.java import android.app.Application; import com.gdgand.rxjava.rxjavasample.hotandcold.di.component.ApplicationComponent; import com.gdgand.rxjava.rxjavasample.hotandcold.di.component.DaggerApplicationComponent; import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.ApplicationModule; import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.DataModule; package com.gdgand.rxjava.rxjavasample.hotandcold; public class SampleApplication extends Application { private ApplicationComponent applicationComponent; @Override public void onCreate() { super.onCreate(); applicationComponent = createComponent(); } private ApplicationComponent createComponent() { return DaggerApplicationComponent.builder() .applicationModule(new ApplicationModule(this))
.dataModule(new DataModule())
gdgand/android-rxjava
2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/Queue2Activity.java
// Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/adapter/Queue2Adapter.java // public class Queue2Adapter extends RecyclerView.Adapter<Queue2Adapter.QueueViewHolder> { // // private Context context; // private List<String> titles; // // public Queue2Adapter(Context context) { // this.context = context; // titles = new ArrayList<>(); // } // // public void add(String title) { // titles.add(title); // } // // @Override // public Queue2Adapter.QueueViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // // TextView view = new TextView(context); // view.setTextSize(20); // view.setPadding(20, 20, 20, 20); // return new QueueViewHolder(view); // } // // @Override // public void onBindViewHolder(Queue2Adapter.QueueViewHolder holder, int position) { // holder.tvTitle.setText(getItem(position)); // } // // private String getItem(int position) { // return titles.get(position); // } // // @Override // public int getItemCount() { // return titles.size(); // } // // public void add(int index, String title) { // titles.add(index, title); // } // // static class QueueViewHolder extends RecyclerView.ViewHolder { // TextView tvTitle; // // public QueueViewHolder(View itemView) { // super(itemView); // tvTitle = (TextView) itemView; // } // } // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/command/BottomCommand.java // public class BottomCommand implements Command { // private final Queue2Adapter adapter; // // public BottomCommand(Queue2Adapter adapter) { // // this.adapter = adapter; // } // // @Override // public void call() { // try { // Thread.sleep(700); // } catch (InterruptedException e) { // e.printStackTrace(); // } // Observable.just(adapter.getItemCount()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(integer -> { // adapter.add(0, "Bottom : " + String.valueOf(integer)); // adapter.notifyDataSetChanged(); // }); // } // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/command/Command.java // public interface Command { // void call(); // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/command/TopCommand.java // public class TopCommand implements Command { // private final Queue2Adapter adapter; // // public TopCommand(Queue2Adapter adapter) { // // this.adapter = adapter; // } // // @Override // public void call() { // try { // Thread.sleep(700); // } catch (InterruptedException e) { // e.printStackTrace(); // } // Observable.just(adapter.getItemCount()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(integer -> { // adapter.add("Top : " + String.valueOf(integer)); // adapter.notifyDataSetChanged(); // }); // // } // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import com.gdgand.rxjava.rxjavasample.R; import com.gdgand.rxjava.rxjavasample.queue.adapter.Queue2Adapter; import com.gdgand.rxjava.rxjavasample.queue.command.BottomCommand; import com.gdgand.rxjava.rxjavasample.queue.command.Command; import com.gdgand.rxjava.rxjavasample.queue.command.TopCommand; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import rx.schedulers.Schedulers; import rx.subjects.PublishSubject;
package com.gdgand.rxjava.rxjavasample.queue; public class Queue2Activity extends AppCompatActivity { @BindView(R.id.rv_queue2) RecyclerView rvQueue;
// Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/adapter/Queue2Adapter.java // public class Queue2Adapter extends RecyclerView.Adapter<Queue2Adapter.QueueViewHolder> { // // private Context context; // private List<String> titles; // // public Queue2Adapter(Context context) { // this.context = context; // titles = new ArrayList<>(); // } // // public void add(String title) { // titles.add(title); // } // // @Override // public Queue2Adapter.QueueViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // // TextView view = new TextView(context); // view.setTextSize(20); // view.setPadding(20, 20, 20, 20); // return new QueueViewHolder(view); // } // // @Override // public void onBindViewHolder(Queue2Adapter.QueueViewHolder holder, int position) { // holder.tvTitle.setText(getItem(position)); // } // // private String getItem(int position) { // return titles.get(position); // } // // @Override // public int getItemCount() { // return titles.size(); // } // // public void add(int index, String title) { // titles.add(index, title); // } // // static class QueueViewHolder extends RecyclerView.ViewHolder { // TextView tvTitle; // // public QueueViewHolder(View itemView) { // super(itemView); // tvTitle = (TextView) itemView; // } // } // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/command/BottomCommand.java // public class BottomCommand implements Command { // private final Queue2Adapter adapter; // // public BottomCommand(Queue2Adapter adapter) { // // this.adapter = adapter; // } // // @Override // public void call() { // try { // Thread.sleep(700); // } catch (InterruptedException e) { // e.printStackTrace(); // } // Observable.just(adapter.getItemCount()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(integer -> { // adapter.add(0, "Bottom : " + String.valueOf(integer)); // adapter.notifyDataSetChanged(); // }); // } // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/command/Command.java // public interface Command { // void call(); // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/command/TopCommand.java // public class TopCommand implements Command { // private final Queue2Adapter adapter; // // public TopCommand(Queue2Adapter adapter) { // // this.adapter = adapter; // } // // @Override // public void call() { // try { // Thread.sleep(700); // } catch (InterruptedException e) { // e.printStackTrace(); // } // Observable.just(adapter.getItemCount()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(integer -> { // adapter.add("Top : " + String.valueOf(integer)); // adapter.notifyDataSetChanged(); // }); // // } // } // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/Queue2Activity.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import com.gdgand.rxjava.rxjavasample.R; import com.gdgand.rxjava.rxjavasample.queue.adapter.Queue2Adapter; import com.gdgand.rxjava.rxjavasample.queue.command.BottomCommand; import com.gdgand.rxjava.rxjavasample.queue.command.Command; import com.gdgand.rxjava.rxjavasample.queue.command.TopCommand; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import rx.schedulers.Schedulers; import rx.subjects.PublishSubject; package com.gdgand.rxjava.rxjavasample.queue; public class Queue2Activity extends AppCompatActivity { @BindView(R.id.rv_queue2) RecyclerView rvQueue;
private PublishSubject<Command> commandQueue;
gdgand/android-rxjava
2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/Queue2Activity.java
// Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/adapter/Queue2Adapter.java // public class Queue2Adapter extends RecyclerView.Adapter<Queue2Adapter.QueueViewHolder> { // // private Context context; // private List<String> titles; // // public Queue2Adapter(Context context) { // this.context = context; // titles = new ArrayList<>(); // } // // public void add(String title) { // titles.add(title); // } // // @Override // public Queue2Adapter.QueueViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // // TextView view = new TextView(context); // view.setTextSize(20); // view.setPadding(20, 20, 20, 20); // return new QueueViewHolder(view); // } // // @Override // public void onBindViewHolder(Queue2Adapter.QueueViewHolder holder, int position) { // holder.tvTitle.setText(getItem(position)); // } // // private String getItem(int position) { // return titles.get(position); // } // // @Override // public int getItemCount() { // return titles.size(); // } // // public void add(int index, String title) { // titles.add(index, title); // } // // static class QueueViewHolder extends RecyclerView.ViewHolder { // TextView tvTitle; // // public QueueViewHolder(View itemView) { // super(itemView); // tvTitle = (TextView) itemView; // } // } // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/command/BottomCommand.java // public class BottomCommand implements Command { // private final Queue2Adapter adapter; // // public BottomCommand(Queue2Adapter adapter) { // // this.adapter = adapter; // } // // @Override // public void call() { // try { // Thread.sleep(700); // } catch (InterruptedException e) { // e.printStackTrace(); // } // Observable.just(adapter.getItemCount()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(integer -> { // adapter.add(0, "Bottom : " + String.valueOf(integer)); // adapter.notifyDataSetChanged(); // }); // } // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/command/Command.java // public interface Command { // void call(); // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/command/TopCommand.java // public class TopCommand implements Command { // private final Queue2Adapter adapter; // // public TopCommand(Queue2Adapter adapter) { // // this.adapter = adapter; // } // // @Override // public void call() { // try { // Thread.sleep(700); // } catch (InterruptedException e) { // e.printStackTrace(); // } // Observable.just(adapter.getItemCount()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(integer -> { // adapter.add("Top : " + String.valueOf(integer)); // adapter.notifyDataSetChanged(); // }); // // } // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import com.gdgand.rxjava.rxjavasample.R; import com.gdgand.rxjava.rxjavasample.queue.adapter.Queue2Adapter; import com.gdgand.rxjava.rxjavasample.queue.command.BottomCommand; import com.gdgand.rxjava.rxjavasample.queue.command.Command; import com.gdgand.rxjava.rxjavasample.queue.command.TopCommand; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import rx.schedulers.Schedulers; import rx.subjects.PublishSubject;
package com.gdgand.rxjava.rxjavasample.queue; public class Queue2Activity extends AppCompatActivity { @BindView(R.id.rv_queue2) RecyclerView rvQueue; private PublishSubject<Command> commandQueue;
// Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/adapter/Queue2Adapter.java // public class Queue2Adapter extends RecyclerView.Adapter<Queue2Adapter.QueueViewHolder> { // // private Context context; // private List<String> titles; // // public Queue2Adapter(Context context) { // this.context = context; // titles = new ArrayList<>(); // } // // public void add(String title) { // titles.add(title); // } // // @Override // public Queue2Adapter.QueueViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // // TextView view = new TextView(context); // view.setTextSize(20); // view.setPadding(20, 20, 20, 20); // return new QueueViewHolder(view); // } // // @Override // public void onBindViewHolder(Queue2Adapter.QueueViewHolder holder, int position) { // holder.tvTitle.setText(getItem(position)); // } // // private String getItem(int position) { // return titles.get(position); // } // // @Override // public int getItemCount() { // return titles.size(); // } // // public void add(int index, String title) { // titles.add(index, title); // } // // static class QueueViewHolder extends RecyclerView.ViewHolder { // TextView tvTitle; // // public QueueViewHolder(View itemView) { // super(itemView); // tvTitle = (TextView) itemView; // } // } // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/command/BottomCommand.java // public class BottomCommand implements Command { // private final Queue2Adapter adapter; // // public BottomCommand(Queue2Adapter adapter) { // // this.adapter = adapter; // } // // @Override // public void call() { // try { // Thread.sleep(700); // } catch (InterruptedException e) { // e.printStackTrace(); // } // Observable.just(adapter.getItemCount()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(integer -> { // adapter.add(0, "Bottom : " + String.valueOf(integer)); // adapter.notifyDataSetChanged(); // }); // } // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/command/Command.java // public interface Command { // void call(); // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/command/TopCommand.java // public class TopCommand implements Command { // private final Queue2Adapter adapter; // // public TopCommand(Queue2Adapter adapter) { // // this.adapter = adapter; // } // // @Override // public void call() { // try { // Thread.sleep(700); // } catch (InterruptedException e) { // e.printStackTrace(); // } // Observable.just(adapter.getItemCount()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(integer -> { // adapter.add("Top : " + String.valueOf(integer)); // adapter.notifyDataSetChanged(); // }); // // } // } // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/Queue2Activity.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import com.gdgand.rxjava.rxjavasample.R; import com.gdgand.rxjava.rxjavasample.queue.adapter.Queue2Adapter; import com.gdgand.rxjava.rxjavasample.queue.command.BottomCommand; import com.gdgand.rxjava.rxjavasample.queue.command.Command; import com.gdgand.rxjava.rxjavasample.queue.command.TopCommand; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import rx.schedulers.Schedulers; import rx.subjects.PublishSubject; package com.gdgand.rxjava.rxjavasample.queue; public class Queue2Activity extends AppCompatActivity { @BindView(R.id.rv_queue2) RecyclerView rvQueue; private PublishSubject<Command> commandQueue;
private Queue2Adapter adapter;
gdgand/android-rxjava
2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/Queue2Activity.java
// Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/adapter/Queue2Adapter.java // public class Queue2Adapter extends RecyclerView.Adapter<Queue2Adapter.QueueViewHolder> { // // private Context context; // private List<String> titles; // // public Queue2Adapter(Context context) { // this.context = context; // titles = new ArrayList<>(); // } // // public void add(String title) { // titles.add(title); // } // // @Override // public Queue2Adapter.QueueViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // // TextView view = new TextView(context); // view.setTextSize(20); // view.setPadding(20, 20, 20, 20); // return new QueueViewHolder(view); // } // // @Override // public void onBindViewHolder(Queue2Adapter.QueueViewHolder holder, int position) { // holder.tvTitle.setText(getItem(position)); // } // // private String getItem(int position) { // return titles.get(position); // } // // @Override // public int getItemCount() { // return titles.size(); // } // // public void add(int index, String title) { // titles.add(index, title); // } // // static class QueueViewHolder extends RecyclerView.ViewHolder { // TextView tvTitle; // // public QueueViewHolder(View itemView) { // super(itemView); // tvTitle = (TextView) itemView; // } // } // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/command/BottomCommand.java // public class BottomCommand implements Command { // private final Queue2Adapter adapter; // // public BottomCommand(Queue2Adapter adapter) { // // this.adapter = adapter; // } // // @Override // public void call() { // try { // Thread.sleep(700); // } catch (InterruptedException e) { // e.printStackTrace(); // } // Observable.just(adapter.getItemCount()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(integer -> { // adapter.add(0, "Bottom : " + String.valueOf(integer)); // adapter.notifyDataSetChanged(); // }); // } // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/command/Command.java // public interface Command { // void call(); // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/command/TopCommand.java // public class TopCommand implements Command { // private final Queue2Adapter adapter; // // public TopCommand(Queue2Adapter adapter) { // // this.adapter = adapter; // } // // @Override // public void call() { // try { // Thread.sleep(700); // } catch (InterruptedException e) { // e.printStackTrace(); // } // Observable.just(adapter.getItemCount()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(integer -> { // adapter.add("Top : " + String.valueOf(integer)); // adapter.notifyDataSetChanged(); // }); // // } // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import com.gdgand.rxjava.rxjavasample.R; import com.gdgand.rxjava.rxjavasample.queue.adapter.Queue2Adapter; import com.gdgand.rxjava.rxjavasample.queue.command.BottomCommand; import com.gdgand.rxjava.rxjavasample.queue.command.Command; import com.gdgand.rxjava.rxjavasample.queue.command.TopCommand; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import rx.schedulers.Schedulers; import rx.subjects.PublishSubject;
package com.gdgand.rxjava.rxjavasample.queue; public class Queue2Activity extends AppCompatActivity { @BindView(R.id.rv_queue2) RecyclerView rvQueue; private PublishSubject<Command> commandQueue; private Queue2Adapter adapter; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_queue2); ButterKnife.bind(this); initObject(); initViews(); } private void initObject() { commandQueue = PublishSubject.create(); commandQueue.onBackpressureBuffer() .observeOn(Schedulers.io()) .subscribe(Command::call, Throwable::printStackTrace); } private void initViews() { rvQueue.setLayoutManager(new LinearLayoutManager(Queue2Activity.this)); adapter = new Queue2Adapter(Queue2Activity.this); rvQueue.setAdapter(adapter); } @OnClick(R.id.btn_queue2_add_bottom) void onAddBottomClick() {
// Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/adapter/Queue2Adapter.java // public class Queue2Adapter extends RecyclerView.Adapter<Queue2Adapter.QueueViewHolder> { // // private Context context; // private List<String> titles; // // public Queue2Adapter(Context context) { // this.context = context; // titles = new ArrayList<>(); // } // // public void add(String title) { // titles.add(title); // } // // @Override // public Queue2Adapter.QueueViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // // TextView view = new TextView(context); // view.setTextSize(20); // view.setPadding(20, 20, 20, 20); // return new QueueViewHolder(view); // } // // @Override // public void onBindViewHolder(Queue2Adapter.QueueViewHolder holder, int position) { // holder.tvTitle.setText(getItem(position)); // } // // private String getItem(int position) { // return titles.get(position); // } // // @Override // public int getItemCount() { // return titles.size(); // } // // public void add(int index, String title) { // titles.add(index, title); // } // // static class QueueViewHolder extends RecyclerView.ViewHolder { // TextView tvTitle; // // public QueueViewHolder(View itemView) { // super(itemView); // tvTitle = (TextView) itemView; // } // } // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/command/BottomCommand.java // public class BottomCommand implements Command { // private final Queue2Adapter adapter; // // public BottomCommand(Queue2Adapter adapter) { // // this.adapter = adapter; // } // // @Override // public void call() { // try { // Thread.sleep(700); // } catch (InterruptedException e) { // e.printStackTrace(); // } // Observable.just(adapter.getItemCount()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(integer -> { // adapter.add(0, "Bottom : " + String.valueOf(integer)); // adapter.notifyDataSetChanged(); // }); // } // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/command/Command.java // public interface Command { // void call(); // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/command/TopCommand.java // public class TopCommand implements Command { // private final Queue2Adapter adapter; // // public TopCommand(Queue2Adapter adapter) { // // this.adapter = adapter; // } // // @Override // public void call() { // try { // Thread.sleep(700); // } catch (InterruptedException e) { // e.printStackTrace(); // } // Observable.just(adapter.getItemCount()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(integer -> { // adapter.add("Top : " + String.valueOf(integer)); // adapter.notifyDataSetChanged(); // }); // // } // } // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/Queue2Activity.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import com.gdgand.rxjava.rxjavasample.R; import com.gdgand.rxjava.rxjavasample.queue.adapter.Queue2Adapter; import com.gdgand.rxjava.rxjavasample.queue.command.BottomCommand; import com.gdgand.rxjava.rxjavasample.queue.command.Command; import com.gdgand.rxjava.rxjavasample.queue.command.TopCommand; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import rx.schedulers.Schedulers; import rx.subjects.PublishSubject; package com.gdgand.rxjava.rxjavasample.queue; public class Queue2Activity extends AppCompatActivity { @BindView(R.id.rv_queue2) RecyclerView rvQueue; private PublishSubject<Command> commandQueue; private Queue2Adapter adapter; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_queue2); ButterKnife.bind(this); initObject(); initViews(); } private void initObject() { commandQueue = PublishSubject.create(); commandQueue.onBackpressureBuffer() .observeOn(Schedulers.io()) .subscribe(Command::call, Throwable::printStackTrace); } private void initViews() { rvQueue.setLayoutManager(new LinearLayoutManager(Queue2Activity.this)); adapter = new Queue2Adapter(Queue2Activity.this); rvQueue.setAdapter(adapter); } @OnClick(R.id.btn_queue2_add_bottom) void onAddBottomClick() {
commandQueue.onNext(new BottomCommand(adapter));
gdgand/android-rxjava
2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/Queue2Activity.java
// Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/adapter/Queue2Adapter.java // public class Queue2Adapter extends RecyclerView.Adapter<Queue2Adapter.QueueViewHolder> { // // private Context context; // private List<String> titles; // // public Queue2Adapter(Context context) { // this.context = context; // titles = new ArrayList<>(); // } // // public void add(String title) { // titles.add(title); // } // // @Override // public Queue2Adapter.QueueViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // // TextView view = new TextView(context); // view.setTextSize(20); // view.setPadding(20, 20, 20, 20); // return new QueueViewHolder(view); // } // // @Override // public void onBindViewHolder(Queue2Adapter.QueueViewHolder holder, int position) { // holder.tvTitle.setText(getItem(position)); // } // // private String getItem(int position) { // return titles.get(position); // } // // @Override // public int getItemCount() { // return titles.size(); // } // // public void add(int index, String title) { // titles.add(index, title); // } // // static class QueueViewHolder extends RecyclerView.ViewHolder { // TextView tvTitle; // // public QueueViewHolder(View itemView) { // super(itemView); // tvTitle = (TextView) itemView; // } // } // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/command/BottomCommand.java // public class BottomCommand implements Command { // private final Queue2Adapter adapter; // // public BottomCommand(Queue2Adapter adapter) { // // this.adapter = adapter; // } // // @Override // public void call() { // try { // Thread.sleep(700); // } catch (InterruptedException e) { // e.printStackTrace(); // } // Observable.just(adapter.getItemCount()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(integer -> { // adapter.add(0, "Bottom : " + String.valueOf(integer)); // adapter.notifyDataSetChanged(); // }); // } // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/command/Command.java // public interface Command { // void call(); // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/command/TopCommand.java // public class TopCommand implements Command { // private final Queue2Adapter adapter; // // public TopCommand(Queue2Adapter adapter) { // // this.adapter = adapter; // } // // @Override // public void call() { // try { // Thread.sleep(700); // } catch (InterruptedException e) { // e.printStackTrace(); // } // Observable.just(adapter.getItemCount()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(integer -> { // adapter.add("Top : " + String.valueOf(integer)); // adapter.notifyDataSetChanged(); // }); // // } // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import com.gdgand.rxjava.rxjavasample.R; import com.gdgand.rxjava.rxjavasample.queue.adapter.Queue2Adapter; import com.gdgand.rxjava.rxjavasample.queue.command.BottomCommand; import com.gdgand.rxjava.rxjavasample.queue.command.Command; import com.gdgand.rxjava.rxjavasample.queue.command.TopCommand; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import rx.schedulers.Schedulers; import rx.subjects.PublishSubject;
protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_queue2); ButterKnife.bind(this); initObject(); initViews(); } private void initObject() { commandQueue = PublishSubject.create(); commandQueue.onBackpressureBuffer() .observeOn(Schedulers.io()) .subscribe(Command::call, Throwable::printStackTrace); } private void initViews() { rvQueue.setLayoutManager(new LinearLayoutManager(Queue2Activity.this)); adapter = new Queue2Adapter(Queue2Activity.this); rvQueue.setAdapter(adapter); } @OnClick(R.id.btn_queue2_add_bottom) void onAddBottomClick() { commandQueue.onNext(new BottomCommand(adapter)); } @OnClick(R.id.btn_queue2_add_top) void onAddTopClick() {
// Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/adapter/Queue2Adapter.java // public class Queue2Adapter extends RecyclerView.Adapter<Queue2Adapter.QueueViewHolder> { // // private Context context; // private List<String> titles; // // public Queue2Adapter(Context context) { // this.context = context; // titles = new ArrayList<>(); // } // // public void add(String title) { // titles.add(title); // } // // @Override // public Queue2Adapter.QueueViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // // TextView view = new TextView(context); // view.setTextSize(20); // view.setPadding(20, 20, 20, 20); // return new QueueViewHolder(view); // } // // @Override // public void onBindViewHolder(Queue2Adapter.QueueViewHolder holder, int position) { // holder.tvTitle.setText(getItem(position)); // } // // private String getItem(int position) { // return titles.get(position); // } // // @Override // public int getItemCount() { // return titles.size(); // } // // public void add(int index, String title) { // titles.add(index, title); // } // // static class QueueViewHolder extends RecyclerView.ViewHolder { // TextView tvTitle; // // public QueueViewHolder(View itemView) { // super(itemView); // tvTitle = (TextView) itemView; // } // } // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/command/BottomCommand.java // public class BottomCommand implements Command { // private final Queue2Adapter adapter; // // public BottomCommand(Queue2Adapter adapter) { // // this.adapter = adapter; // } // // @Override // public void call() { // try { // Thread.sleep(700); // } catch (InterruptedException e) { // e.printStackTrace(); // } // Observable.just(adapter.getItemCount()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(integer -> { // adapter.add(0, "Bottom : " + String.valueOf(integer)); // adapter.notifyDataSetChanged(); // }); // } // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/command/Command.java // public interface Command { // void call(); // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/command/TopCommand.java // public class TopCommand implements Command { // private final Queue2Adapter adapter; // // public TopCommand(Queue2Adapter adapter) { // // this.adapter = adapter; // } // // @Override // public void call() { // try { // Thread.sleep(700); // } catch (InterruptedException e) { // e.printStackTrace(); // } // Observable.just(adapter.getItemCount()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(integer -> { // adapter.add("Top : " + String.valueOf(integer)); // adapter.notifyDataSetChanged(); // }); // // } // } // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/Queue2Activity.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import com.gdgand.rxjava.rxjavasample.R; import com.gdgand.rxjava.rxjavasample.queue.adapter.Queue2Adapter; import com.gdgand.rxjava.rxjavasample.queue.command.BottomCommand; import com.gdgand.rxjava.rxjavasample.queue.command.Command; import com.gdgand.rxjava.rxjavasample.queue.command.TopCommand; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import rx.schedulers.Schedulers; import rx.subjects.PublishSubject; protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_queue2); ButterKnife.bind(this); initObject(); initViews(); } private void initObject() { commandQueue = PublishSubject.create(); commandQueue.onBackpressureBuffer() .observeOn(Schedulers.io()) .subscribe(Command::call, Throwable::printStackTrace); } private void initViews() { rvQueue.setLayoutManager(new LinearLayoutManager(Queue2Activity.this)); adapter = new Queue2Adapter(Queue2Activity.this); rvQueue.setAdapter(adapter); } @OnClick(R.id.btn_queue2_add_bottom) void onAddBottomClick() { commandQueue.onNext(new BottomCommand(adapter)); } @OnClick(R.id.btn_queue2_add_top) void onAddTopClick() {
commandQueue.onNext(new TopCommand(adapter));
gdgand/android-rxjava
2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/ImgurApiTest.java
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/module/DataModule.java // @Module // public class DataModule { // // @Provides // @Singleton // public Converter.Factory converterFactory() { // return GsonConverterFactory.create(); // } // // // @Provides // @Singleton // public CallAdapter.Factory callAdapterFactory() { // return RxJavaCallAdapterFactory.create(); // } // // @Provides // @Singleton // public OkHttpClient okHttpClient() { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // // return new OkHttpClient.Builder() // .addInterceptor(interceptor) // .build(); // } // // @Provides // @Singleton // public Retrofit retrofit(OkHttpClient client, CallAdapter.Factory callAdapterFactory, Converter.Factory converterFactory) { // return new Retrofit.Builder() // .baseUrl("https://api.imgur.com") // .client(client) // .addCallAdapterFactory(callAdapterFactory) // .addConverterFactory(converterFactory) // .build(); // } // // @Provides // @Singleton // public ImgurApi imgurApi(Retrofit retrofit) { // return retrofit.create(ImgurApi.class); // } // }
import com.annimon.stream.Stream; import com.gdgand.rxjava.rxjavasample.hotandcold.data.DaggerTestDataComponent; import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.DataModule; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import rx.observers.TestSubscriber; import java.util.Iterator; import java.util.List; import javax.inject.Inject; import static org.assertj.core.api.Assertions.assertThat;
package com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur; @Ignore("Ignore e2e test by default") public class ImgurApiTest { @Inject ImgurApi imgurApi; @Before public void setup() { DaggerTestDataComponent.builder()
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/module/DataModule.java // @Module // public class DataModule { // // @Provides // @Singleton // public Converter.Factory converterFactory() { // return GsonConverterFactory.create(); // } // // // @Provides // @Singleton // public CallAdapter.Factory callAdapterFactory() { // return RxJavaCallAdapterFactory.create(); // } // // @Provides // @Singleton // public OkHttpClient okHttpClient() { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // // return new OkHttpClient.Builder() // .addInterceptor(interceptor) // .build(); // } // // @Provides // @Singleton // public Retrofit retrofit(OkHttpClient client, CallAdapter.Factory callAdapterFactory, Converter.Factory converterFactory) { // return new Retrofit.Builder() // .baseUrl("https://api.imgur.com") // .client(client) // .addCallAdapterFactory(callAdapterFactory) // .addConverterFactory(converterFactory) // .build(); // } // // @Provides // @Singleton // public ImgurApi imgurApi(Retrofit retrofit) { // return retrofit.create(ImgurApi.class); // } // } // Path: 2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/ImgurApiTest.java import com.annimon.stream.Stream; import com.gdgand.rxjava.rxjavasample.hotandcold.data.DaggerTestDataComponent; import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.DataModule; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import rx.observers.TestSubscriber; import java.util.Iterator; import java.util.List; import javax.inject.Inject; import static org.assertj.core.api.Assertions.assertThat; package com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur; @Ignore("Ignore e2e test by default") public class ImgurApiTest { @Inject ImgurApi imgurApi; @Before public void setup() { DaggerTestDataComponent.builder()
.dataModule(new DataModule())
gdgand/android-rxjava
2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/module/ActivityModule.java
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/views/progress/ProgressIndicatorProvider.java // public class ProgressIndicatorProvider { // // private Activity activity; // // public ProgressIndicatorProvider(Activity activity) { // this.activity = activity; // } // // public ProgressDialog provide() { // return provide(activity.getString(R.string.message_progress)); // } // // public ProgressDialog provide(String message) { // ProgressDialog progressDialog = new ProgressDialog(activity); // progressDialog.setCancelable(false); // progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // progressDialog.setMessage(message); // return progressDialog; // } // // }
import android.app.Activity; import com.gdgand.rxjava.rxjavasample.hotandcold.di.PerActivity; import com.gdgand.rxjava.rxjavasample.hotandcold.views.progress.ProgressIndicatorProvider; import dagger.Module; import dagger.Provides;
package com.gdgand.rxjava.rxjavasample.hotandcold.di.module; @Module public class ActivityModule { private Activity activity; public ActivityModule(Activity activity) { this.activity = activity; } @Provides @PerActivity public Activity activity() { return activity; } @Provides @PerActivity
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/views/progress/ProgressIndicatorProvider.java // public class ProgressIndicatorProvider { // // private Activity activity; // // public ProgressIndicatorProvider(Activity activity) { // this.activity = activity; // } // // public ProgressDialog provide() { // return provide(activity.getString(R.string.message_progress)); // } // // public ProgressDialog provide(String message) { // ProgressDialog progressDialog = new ProgressDialog(activity); // progressDialog.setCancelable(false); // progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // progressDialog.setMessage(message); // return progressDialog; // } // // } // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/module/ActivityModule.java import android.app.Activity; import com.gdgand.rxjava.rxjavasample.hotandcold.di.PerActivity; import com.gdgand.rxjava.rxjavasample.hotandcold.views.progress.ProgressIndicatorProvider; import dagger.Module; import dagger.Provides; package com.gdgand.rxjava.rxjavasample.hotandcold.di.module; @Module public class ActivityModule { private Activity activity; public ActivityModule(Activity activity) { this.activity = activity; } @Provides @PerActivity public Activity activity() { return activity; } @Provides @PerActivity
public ProgressIndicatorProvider progressIndicatorProvider(Activity activity) {
gdgand/android-rxjava
2016-07-06_rxjava_tips/src/main/java/com/gdgand/rxjava/tips/example/ThirdExampleActivity.java
// Path: 2016-07-06_rxjava_tips/src/main/java/com/gdgand/rxjava/tips/MainActivity.java // public class MainActivity extends AppCompatActivity { // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // ButterKnife.bind(this); // } // // @OnClick(R.id.button1) // public void moveToExample1 () { // startActivity(new Intent(this, FirstExampleActivity.class)); // } // // @OnClick(R.id.button2) // public void moveToExample2 () { // startActivity(new Intent(this, SecondExampleActivity.class)); // } // // @OnClick(R.id.button3) // public void moveToExample3 () { // startActivity(new Intent(this, ThirdExampleActivity.class)); // } // } // // Path: 2016-07-06_rxjava_tips/src/main/java/com/gdgand/rxjava/tips/example/more/SafeObservable.java // public class SafeObservable<T> extends Observable<T> { // protected SafeObservable(OnSubscribe<T> f) { // super(f); // } // // public Subscription safeSubscribe(Subscriber<T> subscriber) { // WeakSubscriberDecorator<T> weakSubscriberDecorator = new WeakSubscriberDecorator<>(subscriber); // return subscribe(weakSubscriberDecorator); // } // // public Subscription safeSubscribe(final Action1<? super T> onNext) { // Action1<Throwable> onError = InternalObservableUtils.ERROR_NOT_IMPLEMENTED; // Action0 onCompleted = Actions.empty(); // Subscriber<T> subscriber = new ActionSubscriber<T>(onNext, onError, onCompleted); // WeakSubscriberDecorator<T> weakSubscriberDecorator = new WeakSubscriberDecorator<>(subscriber); // return subscribe(weakSubscriberDecorator); // } // // public Subscription safeSubscribe(final Action1<? super T> onNext, final Action1<Throwable> onError) { // Action0 onCompleted = Actions.empty(); // Subscriber<T> subscriber = new ActionSubscriber<T>(onNext, onError, onCompleted); // WeakSubscriberDecorator<T> weakSubscriberDecorator = new WeakSubscriberDecorator<>(subscriber); // return subscribe(weakSubscriberDecorator); // } // // public Subscription safeSubscribe(final Action1<? super T> onNext, // final Action1<Throwable> onError, final Action0 onCompleted) { // Subscriber<T> subscriber = new ActionSubscriber<T>(onNext, onError, onCompleted); // WeakSubscriberDecorator<T> weakSubscriberDecorator = new WeakSubscriberDecorator<>(subscriber); // return subscribe(weakSubscriberDecorator); // } // }
import android.os.Bundle; import android.support.v4.util.LruCache; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.widget.EditText; import android.widget.Toast; import com.gdgand.rxjava.tips.MainActivity; import com.gdgand.rxjava.tips.R; import com.gdgand.rxjava.tips.example.more.SafeObservable; import com.jakewharton.rxbinding.widget.RxTextView; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import butterknife.BindView; import butterknife.ButterKnife; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers;
package com.gdgand.rxjava.tips.example; //import rx.plugins.DebugHook; //import rx.plugins.DebugNotification; //import rx.plugins.DebugNotificationListener; //import rx.plugins.RxJavaPlugins; public class ThirdExampleActivity extends AppCompatActivity { @BindView(R.id.search_bar) EditText searchBar; @BindView(R.id.results) RecyclerView results; // static { // String TAG = "Rx-Debug Example"; // RxJavaPlugins.getInstance().registerObservableExecutionHook(new DebugHook(new DebugNotificationListener() { // public Object onNext(DebugNotification n) { // Log.v(TAG, "onNext on " + n); // return super.onNext(n); // } // // // public Object start(DebugNotification n) { // Log.v(TAG, "start on " + n); // return super.start(n); // } // // // public void complete(Object context) { // Log.v(TAG, "complete on " + context); // } // // public void error(Object context, Throwable e) { // Log.e(TAG, "error on " + context); // } // })); // } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_example); ButterKnife.bind(this); LinearLayoutManager layoutManager = new LinearLayoutManager(this); layoutManager.setOrientation(LinearLayoutManager.VERTICAL); results.setLayoutManager(layoutManager); results.setHasFixedSize(true); final SearchRecyclerAdapter adapter = new SearchRecyclerAdapter(Collections.emptyList()); results.setAdapter(adapter); Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.github.com") .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); LruCache<String, SearchResult> cache = new LruCache<>(5 * 1024 * 1024); // 5MiB final GitHubInteractor interactor = new GitHubInteractor(retrofit, cache); RxUserBus.subSafe().safeSubscribe((String s) -> { Toast.makeText(this, s, Toast.LENGTH_SHORT).show(); });
// Path: 2016-07-06_rxjava_tips/src/main/java/com/gdgand/rxjava/tips/MainActivity.java // public class MainActivity extends AppCompatActivity { // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // ButterKnife.bind(this); // } // // @OnClick(R.id.button1) // public void moveToExample1 () { // startActivity(new Intent(this, FirstExampleActivity.class)); // } // // @OnClick(R.id.button2) // public void moveToExample2 () { // startActivity(new Intent(this, SecondExampleActivity.class)); // } // // @OnClick(R.id.button3) // public void moveToExample3 () { // startActivity(new Intent(this, ThirdExampleActivity.class)); // } // } // // Path: 2016-07-06_rxjava_tips/src/main/java/com/gdgand/rxjava/tips/example/more/SafeObservable.java // public class SafeObservable<T> extends Observable<T> { // protected SafeObservable(OnSubscribe<T> f) { // super(f); // } // // public Subscription safeSubscribe(Subscriber<T> subscriber) { // WeakSubscriberDecorator<T> weakSubscriberDecorator = new WeakSubscriberDecorator<>(subscriber); // return subscribe(weakSubscriberDecorator); // } // // public Subscription safeSubscribe(final Action1<? super T> onNext) { // Action1<Throwable> onError = InternalObservableUtils.ERROR_NOT_IMPLEMENTED; // Action0 onCompleted = Actions.empty(); // Subscriber<T> subscriber = new ActionSubscriber<T>(onNext, onError, onCompleted); // WeakSubscriberDecorator<T> weakSubscriberDecorator = new WeakSubscriberDecorator<>(subscriber); // return subscribe(weakSubscriberDecorator); // } // // public Subscription safeSubscribe(final Action1<? super T> onNext, final Action1<Throwable> onError) { // Action0 onCompleted = Actions.empty(); // Subscriber<T> subscriber = new ActionSubscriber<T>(onNext, onError, onCompleted); // WeakSubscriberDecorator<T> weakSubscriberDecorator = new WeakSubscriberDecorator<>(subscriber); // return subscribe(weakSubscriberDecorator); // } // // public Subscription safeSubscribe(final Action1<? super T> onNext, // final Action1<Throwable> onError, final Action0 onCompleted) { // Subscriber<T> subscriber = new ActionSubscriber<T>(onNext, onError, onCompleted); // WeakSubscriberDecorator<T> weakSubscriberDecorator = new WeakSubscriberDecorator<>(subscriber); // return subscribe(weakSubscriberDecorator); // } // } // Path: 2016-07-06_rxjava_tips/src/main/java/com/gdgand/rxjava/tips/example/ThirdExampleActivity.java import android.os.Bundle; import android.support.v4.util.LruCache; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.widget.EditText; import android.widget.Toast; import com.gdgand.rxjava.tips.MainActivity; import com.gdgand.rxjava.tips.R; import com.gdgand.rxjava.tips.example.more.SafeObservable; import com.jakewharton.rxbinding.widget.RxTextView; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import butterknife.BindView; import butterknife.ButterKnife; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; package com.gdgand.rxjava.tips.example; //import rx.plugins.DebugHook; //import rx.plugins.DebugNotification; //import rx.plugins.DebugNotificationListener; //import rx.plugins.RxJavaPlugins; public class ThirdExampleActivity extends AppCompatActivity { @BindView(R.id.search_bar) EditText searchBar; @BindView(R.id.results) RecyclerView results; // static { // String TAG = "Rx-Debug Example"; // RxJavaPlugins.getInstance().registerObservableExecutionHook(new DebugHook(new DebugNotificationListener() { // public Object onNext(DebugNotification n) { // Log.v(TAG, "onNext on " + n); // return super.onNext(n); // } // // // public Object start(DebugNotification n) { // Log.v(TAG, "start on " + n); // return super.start(n); // } // // // public void complete(Object context) { // Log.v(TAG, "complete on " + context); // } // // public void error(Object context, Throwable e) { // Log.e(TAG, "error on " + context); // } // })); // } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_example); ButterKnife.bind(this); LinearLayoutManager layoutManager = new LinearLayoutManager(this); layoutManager.setOrientation(LinearLayoutManager.VERTICAL); results.setLayoutManager(layoutManager); results.setHasFixedSize(true); final SearchRecyclerAdapter adapter = new SearchRecyclerAdapter(Collections.emptyList()); results.setAdapter(adapter); Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.github.com") .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); LruCache<String, SearchResult> cache = new LruCache<>(5 * 1024 * 1024); // 5MiB final GitHubInteractor interactor = new GitHubInteractor(retrofit, cache); RxUserBus.subSafe().safeSubscribe((String s) -> { Toast.makeText(this, s, Toast.LENGTH_SHORT).show(); });
SafeObservable<List<SearchItem>> itemsObservable = (SafeObservable<List<SearchItem>>)
gdgand/android-rxjava
2016-07-06_rxjava_tips/src/main/java/com/gdgand/rxjava/tips/example/ThirdExampleActivity.java
// Path: 2016-07-06_rxjava_tips/src/main/java/com/gdgand/rxjava/tips/MainActivity.java // public class MainActivity extends AppCompatActivity { // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // ButterKnife.bind(this); // } // // @OnClick(R.id.button1) // public void moveToExample1 () { // startActivity(new Intent(this, FirstExampleActivity.class)); // } // // @OnClick(R.id.button2) // public void moveToExample2 () { // startActivity(new Intent(this, SecondExampleActivity.class)); // } // // @OnClick(R.id.button3) // public void moveToExample3 () { // startActivity(new Intent(this, ThirdExampleActivity.class)); // } // } // // Path: 2016-07-06_rxjava_tips/src/main/java/com/gdgand/rxjava/tips/example/more/SafeObservable.java // public class SafeObservable<T> extends Observable<T> { // protected SafeObservable(OnSubscribe<T> f) { // super(f); // } // // public Subscription safeSubscribe(Subscriber<T> subscriber) { // WeakSubscriberDecorator<T> weakSubscriberDecorator = new WeakSubscriberDecorator<>(subscriber); // return subscribe(weakSubscriberDecorator); // } // // public Subscription safeSubscribe(final Action1<? super T> onNext) { // Action1<Throwable> onError = InternalObservableUtils.ERROR_NOT_IMPLEMENTED; // Action0 onCompleted = Actions.empty(); // Subscriber<T> subscriber = new ActionSubscriber<T>(onNext, onError, onCompleted); // WeakSubscriberDecorator<T> weakSubscriberDecorator = new WeakSubscriberDecorator<>(subscriber); // return subscribe(weakSubscriberDecorator); // } // // public Subscription safeSubscribe(final Action1<? super T> onNext, final Action1<Throwable> onError) { // Action0 onCompleted = Actions.empty(); // Subscriber<T> subscriber = new ActionSubscriber<T>(onNext, onError, onCompleted); // WeakSubscriberDecorator<T> weakSubscriberDecorator = new WeakSubscriberDecorator<>(subscriber); // return subscribe(weakSubscriberDecorator); // } // // public Subscription safeSubscribe(final Action1<? super T> onNext, // final Action1<Throwable> onError, final Action0 onCompleted) { // Subscriber<T> subscriber = new ActionSubscriber<T>(onNext, onError, onCompleted); // WeakSubscriberDecorator<T> weakSubscriberDecorator = new WeakSubscriberDecorator<>(subscriber); // return subscribe(weakSubscriberDecorator); // } // }
import android.os.Bundle; import android.support.v4.util.LruCache; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.widget.EditText; import android.widget.Toast; import com.gdgand.rxjava.tips.MainActivity; import com.gdgand.rxjava.tips.R; import com.gdgand.rxjava.tips.example.more.SafeObservable; import com.jakewharton.rxbinding.widget.RxTextView; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import butterknife.BindView; import butterknife.ButterKnife; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers;
results.setHasFixedSize(true); final SearchRecyclerAdapter adapter = new SearchRecyclerAdapter(Collections.emptyList()); results.setAdapter(adapter); Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.github.com") .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); LruCache<String, SearchResult> cache = new LruCache<>(5 * 1024 * 1024); // 5MiB final GitHubInteractor interactor = new GitHubInteractor(retrofit, cache); RxUserBus.subSafe().safeSubscribe((String s) -> { Toast.makeText(this, s, Toast.LENGTH_SHORT).show(); }); SafeObservable<List<SearchItem>> itemsObservable = (SafeObservable<List<SearchItem>>) RxTextView.textChanges(searchBar) .observeOn(Schedulers.io()) .debounce(1, TimeUnit.SECONDS) .filter(charSequence -> charSequence.length() > 0) .switchMap((CharSequence seq) -> interactor.searchUsers(seq.toString())) .flatMap((SearchResult searchResult) -> Observable.from(searchResult.getItems()).limit(20).toList()) .observeOn(AndroidSchedulers.mainThread()); itemsObservable.safeSubscribe(adapter::refreshResults, throwable -> {
// Path: 2016-07-06_rxjava_tips/src/main/java/com/gdgand/rxjava/tips/MainActivity.java // public class MainActivity extends AppCompatActivity { // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // ButterKnife.bind(this); // } // // @OnClick(R.id.button1) // public void moveToExample1 () { // startActivity(new Intent(this, FirstExampleActivity.class)); // } // // @OnClick(R.id.button2) // public void moveToExample2 () { // startActivity(new Intent(this, SecondExampleActivity.class)); // } // // @OnClick(R.id.button3) // public void moveToExample3 () { // startActivity(new Intent(this, ThirdExampleActivity.class)); // } // } // // Path: 2016-07-06_rxjava_tips/src/main/java/com/gdgand/rxjava/tips/example/more/SafeObservable.java // public class SafeObservable<T> extends Observable<T> { // protected SafeObservable(OnSubscribe<T> f) { // super(f); // } // // public Subscription safeSubscribe(Subscriber<T> subscriber) { // WeakSubscriberDecorator<T> weakSubscriberDecorator = new WeakSubscriberDecorator<>(subscriber); // return subscribe(weakSubscriberDecorator); // } // // public Subscription safeSubscribe(final Action1<? super T> onNext) { // Action1<Throwable> onError = InternalObservableUtils.ERROR_NOT_IMPLEMENTED; // Action0 onCompleted = Actions.empty(); // Subscriber<T> subscriber = new ActionSubscriber<T>(onNext, onError, onCompleted); // WeakSubscriberDecorator<T> weakSubscriberDecorator = new WeakSubscriberDecorator<>(subscriber); // return subscribe(weakSubscriberDecorator); // } // // public Subscription safeSubscribe(final Action1<? super T> onNext, final Action1<Throwable> onError) { // Action0 onCompleted = Actions.empty(); // Subscriber<T> subscriber = new ActionSubscriber<T>(onNext, onError, onCompleted); // WeakSubscriberDecorator<T> weakSubscriberDecorator = new WeakSubscriberDecorator<>(subscriber); // return subscribe(weakSubscriberDecorator); // } // // public Subscription safeSubscribe(final Action1<? super T> onNext, // final Action1<Throwable> onError, final Action0 onCompleted) { // Subscriber<T> subscriber = new ActionSubscriber<T>(onNext, onError, onCompleted); // WeakSubscriberDecorator<T> weakSubscriberDecorator = new WeakSubscriberDecorator<>(subscriber); // return subscribe(weakSubscriberDecorator); // } // } // Path: 2016-07-06_rxjava_tips/src/main/java/com/gdgand/rxjava/tips/example/ThirdExampleActivity.java import android.os.Bundle; import android.support.v4.util.LruCache; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.widget.EditText; import android.widget.Toast; import com.gdgand.rxjava.tips.MainActivity; import com.gdgand.rxjava.tips.R; import com.gdgand.rxjava.tips.example.more.SafeObservable; import com.jakewharton.rxbinding.widget.RxTextView; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import butterknife.BindView; import butterknife.ButterKnife; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; results.setHasFixedSize(true); final SearchRecyclerAdapter adapter = new SearchRecyclerAdapter(Collections.emptyList()); results.setAdapter(adapter); Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.github.com") .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); LruCache<String, SearchResult> cache = new LruCache<>(5 * 1024 * 1024); // 5MiB final GitHubInteractor interactor = new GitHubInteractor(retrofit, cache); RxUserBus.subSafe().safeSubscribe((String s) -> { Toast.makeText(this, s, Toast.LENGTH_SHORT).show(); }); SafeObservable<List<SearchItem>> itemsObservable = (SafeObservable<List<SearchItem>>) RxTextView.textChanges(searchBar) .observeOn(Schedulers.io()) .debounce(1, TimeUnit.SECONDS) .filter(charSequence -> charSequence.length() > 0) .switchMap((CharSequence seq) -> interactor.searchUsers(seq.toString())) .flatMap((SearchResult searchResult) -> Observable.from(searchResult.getItems()).limit(20).toList()) .observeOn(AndroidSchedulers.mainThread()); itemsObservable.safeSubscribe(adapter::refreshResults, throwable -> {
Log.e(MainActivity.class.getName(), throwable.getMessage());
gdgand/android-rxjava
2016-07-06_rxjava_tips/src/main/java/com/gdgand/rxjava/tips/example/FirstExampleActivity.java
// Path: 2016-07-06_rxjava_tips/src/main/java/com/gdgand/rxjava/tips/MainActivity.java // public class MainActivity extends AppCompatActivity { // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // ButterKnife.bind(this); // } // // @OnClick(R.id.button1) // public void moveToExample1 () { // startActivity(new Intent(this, FirstExampleActivity.class)); // } // // @OnClick(R.id.button2) // public void moveToExample2 () { // startActivity(new Intent(this, SecondExampleActivity.class)); // } // // @OnClick(R.id.button3) // public void moveToExample3 () { // startActivity(new Intent(this, ThirdExampleActivity.class)); // } // }
import android.os.Bundle; import android.support.v4.util.LruCache; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.widget.EditText; import android.widget.Toast; import com.gdgand.rxjava.tips.MainActivity; import com.gdgand.rxjava.tips.R; import com.jakewharton.rxbinding.widget.RxTextView; import java.util.Collections; import java.util.concurrent.TimeUnit; import butterknife.BindView; import butterknife.ButterKnife; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import rx.subscriptions.CompositeSubscription;
layoutManager.setOrientation(LinearLayoutManager.VERTICAL); results.setLayoutManager(layoutManager); results.setHasFixedSize(true); final SearchRecyclerAdapter adapter = new SearchRecyclerAdapter(Collections.emptyList()); results.setAdapter(adapter); Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.github.com") .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); LruCache<String, SearchResult> cache = new LruCache<>(5 * 1024 * 1024); // 5MiB final GitHubInteractor interactor = new GitHubInteractor(retrofit, cache); subs.add(RxUserBus.sub().subscribe((String s) -> { Toast.makeText(this, s, Toast.LENGTH_SHORT).show(); })); subs.add(RxTextView.textChanges(searchBar) .observeOn(Schedulers.io()) .debounce(1, TimeUnit.SECONDS) .filter(charSequence -> charSequence.length() > 0) .switchMap((CharSequence seq) -> interactor.searchUsers(seq.toString())) .flatMap((SearchResult searchResult) -> Observable.from(searchResult.getItems()).limit(20).toList()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(adapter::refreshResults, throwable -> {
// Path: 2016-07-06_rxjava_tips/src/main/java/com/gdgand/rxjava/tips/MainActivity.java // public class MainActivity extends AppCompatActivity { // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // ButterKnife.bind(this); // } // // @OnClick(R.id.button1) // public void moveToExample1 () { // startActivity(new Intent(this, FirstExampleActivity.class)); // } // // @OnClick(R.id.button2) // public void moveToExample2 () { // startActivity(new Intent(this, SecondExampleActivity.class)); // } // // @OnClick(R.id.button3) // public void moveToExample3 () { // startActivity(new Intent(this, ThirdExampleActivity.class)); // } // } // Path: 2016-07-06_rxjava_tips/src/main/java/com/gdgand/rxjava/tips/example/FirstExampleActivity.java import android.os.Bundle; import android.support.v4.util.LruCache; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.widget.EditText; import android.widget.Toast; import com.gdgand.rxjava.tips.MainActivity; import com.gdgand.rxjava.tips.R; import com.jakewharton.rxbinding.widget.RxTextView; import java.util.Collections; import java.util.concurrent.TimeUnit; import butterknife.BindView; import butterknife.ButterKnife; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import rx.subscriptions.CompositeSubscription; layoutManager.setOrientation(LinearLayoutManager.VERTICAL); results.setLayoutManager(layoutManager); results.setHasFixedSize(true); final SearchRecyclerAdapter adapter = new SearchRecyclerAdapter(Collections.emptyList()); results.setAdapter(adapter); Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.github.com") .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); LruCache<String, SearchResult> cache = new LruCache<>(5 * 1024 * 1024); // 5MiB final GitHubInteractor interactor = new GitHubInteractor(retrofit, cache); subs.add(RxUserBus.sub().subscribe((String s) -> { Toast.makeText(this, s, Toast.LENGTH_SHORT).show(); })); subs.add(RxTextView.textChanges(searchBar) .observeOn(Schedulers.io()) .debounce(1, TimeUnit.SECONDS) .filter(charSequence -> charSequence.length() > 0) .switchMap((CharSequence seq) -> interactor.searchUsers(seq.toString())) .flatMap((SearchResult searchResult) -> Observable.from(searchResult.getItems()).limit(20).toList()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(adapter::refreshResults, throwable -> {
Log.e(MainActivity.class.getName(), throwable.getMessage());
gdgand/android-rxjava
2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvvm/imgur/MvvmViewModel.java
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/ImgurApi.java // public interface ImgurApi { // // @GET("/3/topics/defaults") // Observable<TopicResponse> defaultTopics(); // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/Topic.java // public class Topic { // private long id; // // private String name; // // private String description; // // private TopPost topPost; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public TopPost getTopPost() { // return topPost; // } // // public void setTopPost(TopPost topPost) { // this.topPost = topPost; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/TopicResponse.java // public class TopicResponse { // // private List<Topic> data; // // public void setData(List<Topic> data) { // this.data = data; // } // // public List<Topic> getData() { // return data; // } // }
import android.util.Log; import android.util.Pair; import com.annimon.stream.Collectors; import com.annimon.stream.Stream; import com.annimon.stream.function.Function; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.ImgurApi; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.Topic; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.TopicResponse; import com.jakewharton.rx.transformer.ReplayingShare; import rx.Observable; import rx.functions.Func1; import rx.schedulers.Schedulers; import rx.subjects.BehaviorSubject; import rx.subjects.PublishSubject; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.inject.Inject; import static rx.Observable.combineLatest; import static rx.schedulers.Schedulers.computation;
package com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvvm.imgur; public class MvvmViewModel { enum VisibleType { ALL, ODD, EVEN, }
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/ImgurApi.java // public interface ImgurApi { // // @GET("/3/topics/defaults") // Observable<TopicResponse> defaultTopics(); // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/Topic.java // public class Topic { // private long id; // // private String name; // // private String description; // // private TopPost topPost; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public TopPost getTopPost() { // return topPost; // } // // public void setTopPost(TopPost topPost) { // this.topPost = topPost; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/TopicResponse.java // public class TopicResponse { // // private List<Topic> data; // // public void setData(List<Topic> data) { // this.data = data; // } // // public List<Topic> getData() { // return data; // } // } // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvvm/imgur/MvvmViewModel.java import android.util.Log; import android.util.Pair; import com.annimon.stream.Collectors; import com.annimon.stream.Stream; import com.annimon.stream.function.Function; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.ImgurApi; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.Topic; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.TopicResponse; import com.jakewharton.rx.transformer.ReplayingShare; import rx.Observable; import rx.functions.Func1; import rx.schedulers.Schedulers; import rx.subjects.BehaviorSubject; import rx.subjects.PublishSubject; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.inject.Inject; import static rx.Observable.combineLatest; import static rx.schedulers.Schedulers.computation; package com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvvm.imgur; public class MvvmViewModel { enum VisibleType { ALL, ODD, EVEN, }
private ImgurApi imgurApi;
gdgand/android-rxjava
2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvvm/imgur/MvvmViewModel.java
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/ImgurApi.java // public interface ImgurApi { // // @GET("/3/topics/defaults") // Observable<TopicResponse> defaultTopics(); // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/Topic.java // public class Topic { // private long id; // // private String name; // // private String description; // // private TopPost topPost; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public TopPost getTopPost() { // return topPost; // } // // public void setTopPost(TopPost topPost) { // this.topPost = topPost; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/TopicResponse.java // public class TopicResponse { // // private List<Topic> data; // // public void setData(List<Topic> data) { // this.data = data; // } // // public List<Topic> getData() { // return data; // } // }
import android.util.Log; import android.util.Pair; import com.annimon.stream.Collectors; import com.annimon.stream.Stream; import com.annimon.stream.function.Function; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.ImgurApi; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.Topic; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.TopicResponse; import com.jakewharton.rx.transformer.ReplayingShare; import rx.Observable; import rx.functions.Func1; import rx.schedulers.Schedulers; import rx.subjects.BehaviorSubject; import rx.subjects.PublishSubject; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.inject.Inject; import static rx.Observable.combineLatest; import static rx.schedulers.Schedulers.computation;
package com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvvm.imgur; public class MvvmViewModel { enum VisibleType { ALL, ODD, EVEN, } private ImgurApi imgurApi;
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/ImgurApi.java // public interface ImgurApi { // // @GET("/3/topics/defaults") // Observable<TopicResponse> defaultTopics(); // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/Topic.java // public class Topic { // private long id; // // private String name; // // private String description; // // private TopPost topPost; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public TopPost getTopPost() { // return topPost; // } // // public void setTopPost(TopPost topPost) { // this.topPost = topPost; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/TopicResponse.java // public class TopicResponse { // // private List<Topic> data; // // public void setData(List<Topic> data) { // this.data = data; // } // // public List<Topic> getData() { // return data; // } // } // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvvm/imgur/MvvmViewModel.java import android.util.Log; import android.util.Pair; import com.annimon.stream.Collectors; import com.annimon.stream.Stream; import com.annimon.stream.function.Function; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.ImgurApi; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.Topic; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.TopicResponse; import com.jakewharton.rx.transformer.ReplayingShare; import rx.Observable; import rx.functions.Func1; import rx.schedulers.Schedulers; import rx.subjects.BehaviorSubject; import rx.subjects.PublishSubject; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.inject.Inject; import static rx.Observable.combineLatest; import static rx.schedulers.Schedulers.computation; package com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvvm.imgur; public class MvvmViewModel { enum VisibleType { ALL, ODD, EVEN, } private ImgurApi imgurApi;
private BehaviorSubject<List<Topic>> postsSubject = BehaviorSubject.create(Collections.<Topic>emptyList());
gdgand/android-rxjava
2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvvm/imgur/MvvmViewModel.java
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/ImgurApi.java // public interface ImgurApi { // // @GET("/3/topics/defaults") // Observable<TopicResponse> defaultTopics(); // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/Topic.java // public class Topic { // private long id; // // private String name; // // private String description; // // private TopPost topPost; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public TopPost getTopPost() { // return topPost; // } // // public void setTopPost(TopPost topPost) { // this.topPost = topPost; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/TopicResponse.java // public class TopicResponse { // // private List<Topic> data; // // public void setData(List<Topic> data) { // this.data = data; // } // // public List<Topic> getData() { // return data; // } // }
import android.util.Log; import android.util.Pair; import com.annimon.stream.Collectors; import com.annimon.stream.Stream; import com.annimon.stream.function.Function; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.ImgurApi; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.Topic; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.TopicResponse; import com.jakewharton.rx.transformer.ReplayingShare; import rx.Observable; import rx.functions.Func1; import rx.schedulers.Schedulers; import rx.subjects.BehaviorSubject; import rx.subjects.PublishSubject; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.inject.Inject; import static rx.Observable.combineLatest; import static rx.schedulers.Schedulers.computation;
public Observable<List<String>> getPosts() { return visibleTopicsObservable.onBackpressureBuffer() .map(topics -> Stream.of(topics).map(Topic::getName).collect(Collectors.toList()) ); } public Observable<Pair<Integer, Integer>> getCounts() { return visibleTopicsObservable.onBackpressureBuffer() .map(topics -> { int album = 0; int noAlbum = 0; for (Topic topic : topics) { if (topic.getTopPost().is_album()) { album++; } else { noAlbum++; } } return Pair.create(album, noAlbum); }); } public Observable<Throwable> getThrowable() { return throwableSubject.onBackpressureBuffer(); } public void refresh() { imgurApi.defaultTopics()
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/ImgurApi.java // public interface ImgurApi { // // @GET("/3/topics/defaults") // Observable<TopicResponse> defaultTopics(); // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/Topic.java // public class Topic { // private long id; // // private String name; // // private String description; // // private TopPost topPost; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public TopPost getTopPost() { // return topPost; // } // // public void setTopPost(TopPost topPost) { // this.topPost = topPost; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/TopicResponse.java // public class TopicResponse { // // private List<Topic> data; // // public void setData(List<Topic> data) { // this.data = data; // } // // public List<Topic> getData() { // return data; // } // } // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvvm/imgur/MvvmViewModel.java import android.util.Log; import android.util.Pair; import com.annimon.stream.Collectors; import com.annimon.stream.Stream; import com.annimon.stream.function.Function; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.ImgurApi; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.Topic; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.TopicResponse; import com.jakewharton.rx.transformer.ReplayingShare; import rx.Observable; import rx.functions.Func1; import rx.schedulers.Schedulers; import rx.subjects.BehaviorSubject; import rx.subjects.PublishSubject; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.inject.Inject; import static rx.Observable.combineLatest; import static rx.schedulers.Schedulers.computation; public Observable<List<String>> getPosts() { return visibleTopicsObservable.onBackpressureBuffer() .map(topics -> Stream.of(topics).map(Topic::getName).collect(Collectors.toList()) ); } public Observable<Pair<Integer, Integer>> getCounts() { return visibleTopicsObservable.onBackpressureBuffer() .map(topics -> { int album = 0; int noAlbum = 0; for (Topic topic : topics) { if (topic.getTopPost().is_album()) { album++; } else { noAlbum++; } } return Pair.create(album, noAlbum); }); } public Observable<Throwable> getThrowable() { return throwableSubject.onBackpressureBuffer(); } public void refresh() { imgurApi.defaultTopics()
.map(TopicResponse::getData)
gdgand/android-rxjava
2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/module/DataModule.java
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/ImgurApi.java // public interface ImgurApi { // // @GET("/3/topics/defaults") // Observable<TopicResponse> defaultTopics(); // }
import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.ImgurApi; import dagger.Module; import dagger.Provides; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.CallAdapter; import retrofit2.Converter; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import javax.inject.Singleton;
@Provides @Singleton public CallAdapter.Factory callAdapterFactory() { return RxJavaCallAdapterFactory.create(); } @Provides @Singleton public OkHttpClient okHttpClient() { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); return new OkHttpClient.Builder() .addInterceptor(interceptor) .build(); } @Provides @Singleton public Retrofit retrofit(OkHttpClient client, CallAdapter.Factory callAdapterFactory, Converter.Factory converterFactory) { return new Retrofit.Builder() .baseUrl("https://api.imgur.com") .client(client) .addCallAdapterFactory(callAdapterFactory) .addConverterFactory(converterFactory) .build(); } @Provides @Singleton
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/ImgurApi.java // public interface ImgurApi { // // @GET("/3/topics/defaults") // Observable<TopicResponse> defaultTopics(); // } // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/module/DataModule.java import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.ImgurApi; import dagger.Module; import dagger.Provides; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.CallAdapter; import retrofit2.Converter; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import javax.inject.Singleton; @Provides @Singleton public CallAdapter.Factory callAdapterFactory() { return RxJavaCallAdapterFactory.create(); } @Provides @Singleton public OkHttpClient okHttpClient() { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); return new OkHttpClient.Builder() .addInterceptor(interceptor) .build(); } @Provides @Singleton public Retrofit retrofit(OkHttpClient client, CallAdapter.Factory callAdapterFactory, Converter.Factory converterFactory) { return new Retrofit.Builder() .baseUrl("https://api.imgur.com") .client(client) .addCallAdapterFactory(callAdapterFactory) .addConverterFactory(converterFactory) .build(); } @Provides @Singleton
public ImgurApi imgurApi(Retrofit retrofit) {
gdgand/android-rxjava
2016-07-12_rxjava_in_action/src/main/java/com/androidhuman/example/rxjavainaction/rx/ChecksAvailabilityOnSubscribe.java
// Path: 2016-07-12_rxjava_in_action/src/main/java/com/androidhuman/example/rxjavainaction/error/ContentNotAvailableError.java // public final class ContentNotAvailableError extends Error { // // }
import com.androidhuman.example.rxjavainaction.error.ContentNotAvailableError; import com.androidhuman.example.rxjavainaction.model.Content; import rx.Observable; import rx.Subscriber;
package com.androidhuman.example.rxjavainaction.rx; final class ChecksAvailabilityOnSubscribe implements Observable.OnSubscribe<Void> { private final Content content; ChecksAvailabilityOnSubscribe(Content content) { this.content = content; } @Override public void call(Subscriber<? super Void> subscriber) { if (!subscriber.isUnsubscribed()) { if (content.isInService()) { // Content is available subscriber.onNext(null); subscriber.onCompleted(); } else { // Content is not available; Not in service
// Path: 2016-07-12_rxjava_in_action/src/main/java/com/androidhuman/example/rxjavainaction/error/ContentNotAvailableError.java // public final class ContentNotAvailableError extends Error { // // } // Path: 2016-07-12_rxjava_in_action/src/main/java/com/androidhuman/example/rxjavainaction/rx/ChecksAvailabilityOnSubscribe.java import com.androidhuman.example.rxjavainaction.error.ContentNotAvailableError; import com.androidhuman.example.rxjavainaction.model.Content; import rx.Observable; import rx.Subscriber; package com.androidhuman.example.rxjavainaction.rx; final class ChecksAvailabilityOnSubscribe implements Observable.OnSubscribe<Void> { private final Content content; ChecksAvailabilityOnSubscribe(Content content) { this.content = content; } @Override public void call(Subscriber<? super Void> subscriber) { if (!subscriber.isUnsubscribed()) { if (content.isInService()) { // Content is available subscriber.onNext(null); subscriber.onCompleted(); } else { // Content is not available; Not in service
subscriber.onError(new ContentNotAvailableError());
gdgand/android-rxjava
2016-07-06_rxjava_tips/src/main/java/com/gdgand/rxjava/tips/example/SecondExampleActivity.java
// Path: 2016-07-06_rxjava_tips/src/main/java/com/gdgand/rxjava/tips/MainActivity.java // public class MainActivity extends AppCompatActivity { // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // ButterKnife.bind(this); // } // // @OnClick(R.id.button1) // public void moveToExample1 () { // startActivity(new Intent(this, FirstExampleActivity.class)); // } // // @OnClick(R.id.button2) // public void moveToExample2 () { // startActivity(new Intent(this, SecondExampleActivity.class)); // } // // @OnClick(R.id.button3) // public void moveToExample3 () { // startActivity(new Intent(this, ThirdExampleActivity.class)); // } // }
import android.os.Bundle; import android.support.v4.util.LruCache; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.widget.EditText; import android.widget.Toast; import com.gdgand.rxjava.tips.MainActivity; import com.gdgand.rxjava.tips.R; import com.jakewharton.rxbinding.widget.RxTextView; import com.trello.rxlifecycle.components.support.RxAppCompatActivity; import java.util.Collections; import java.util.concurrent.TimeUnit; import butterknife.BindView; import butterknife.ButterKnife; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers;
results.setLayoutManager(layoutManager); results.setHasFixedSize(true); final SearchRecyclerAdapter adapter = new SearchRecyclerAdapter(Collections.emptyList()); results.setAdapter(adapter); Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.github.com") .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); LruCache<String, SearchResult> cache = new LruCache<>(5 * 1024 * 1024); // 5MiB final GitHubInteractor interactor = new GitHubInteractor(retrofit, cache); RxUserBus.sub().compose(bindToLifecycle()).subscribe((String s) -> { Toast.makeText(this, s, Toast.LENGTH_SHORT).show(); }); RxTextView.textChanges(searchBar) .compose(bindToLifecycle()) .observeOn(Schedulers.io()) .debounce(1, TimeUnit.SECONDS) .filter(charSequence -> charSequence.length() > 0) .switchMap((CharSequence seq) -> interactor.searchUsers(seq.toString())) .flatMap((SearchResult searchResult) -> Observable.from(searchResult.getItems()).limit(20).toList()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(adapter::refreshResults, throwable -> {
// Path: 2016-07-06_rxjava_tips/src/main/java/com/gdgand/rxjava/tips/MainActivity.java // public class MainActivity extends AppCompatActivity { // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // ButterKnife.bind(this); // } // // @OnClick(R.id.button1) // public void moveToExample1 () { // startActivity(new Intent(this, FirstExampleActivity.class)); // } // // @OnClick(R.id.button2) // public void moveToExample2 () { // startActivity(new Intent(this, SecondExampleActivity.class)); // } // // @OnClick(R.id.button3) // public void moveToExample3 () { // startActivity(new Intent(this, ThirdExampleActivity.class)); // } // } // Path: 2016-07-06_rxjava_tips/src/main/java/com/gdgand/rxjava/tips/example/SecondExampleActivity.java import android.os.Bundle; import android.support.v4.util.LruCache; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.widget.EditText; import android.widget.Toast; import com.gdgand.rxjava.tips.MainActivity; import com.gdgand.rxjava.tips.R; import com.jakewharton.rxbinding.widget.RxTextView; import com.trello.rxlifecycle.components.support.RxAppCompatActivity; import java.util.Collections; import java.util.concurrent.TimeUnit; import butterknife.BindView; import butterknife.ButterKnife; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; results.setLayoutManager(layoutManager); results.setHasFixedSize(true); final SearchRecyclerAdapter adapter = new SearchRecyclerAdapter(Collections.emptyList()); results.setAdapter(adapter); Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.github.com") .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); LruCache<String, SearchResult> cache = new LruCache<>(5 * 1024 * 1024); // 5MiB final GitHubInteractor interactor = new GitHubInteractor(retrofit, cache); RxUserBus.sub().compose(bindToLifecycle()).subscribe((String s) -> { Toast.makeText(this, s, Toast.LENGTH_SHORT).show(); }); RxTextView.textChanges(searchBar) .compose(bindToLifecycle()) .observeOn(Schedulers.io()) .debounce(1, TimeUnit.SECONDS) .filter(charSequence -> charSequence.length() > 0) .switchMap((CharSequence seq) -> interactor.searchUsers(seq.toString())) .flatMap((SearchResult searchResult) -> Observable.from(searchResult.getItems()).limit(20).toList()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(adapter::refreshResults, throwable -> {
Log.e(MainActivity.class.getName(), throwable.getMessage());
gdgand/android-rxjava
2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/BaseMvpActivity.java
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/utils/SubscriptionUtils.java // public class SubscriptionUtils { // /** // * Automatically adds to / removes from specified {@link CompositeSubscription} when subscribe / unsubscribe is called. // * Useful when subscribing observable repeatedly, as you do not need to manipulate CompositeSubscription manually. // */ // public static <T> Observable.Operator<T, T> composite(CompositeSubscription subscriptions) { // return subscriber -> { // subscriptions.add(subscriber); // subscriber.add(Subscriptions.create(() -> subscriptions.remove(subscriber))); // return subscriber; // }; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/views/progress/ProgressIndicatorProvider.java // public class ProgressIndicatorProvider { // // private Activity activity; // // public ProgressIndicatorProvider(Activity activity) { // this.activity = activity; // } // // public ProgressDialog provide() { // return provide(activity.getString(R.string.message_progress)); // } // // public ProgressDialog provide(String message) { // ProgressDialog progressDialog = new ProgressDialog(activity); // progressDialog.setCancelable(false); // progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // progressDialog.setMessage(message); // return progressDialog; // } // // }
import android.app.ProgressDialog; import android.widget.Toast; import com.gdgand.rxjava.rxjavasample.hotandcold.utils.SubscriptionUtils; import com.gdgand.rxjava.rxjavasample.hotandcold.views.progress.ProgressIndicatorProvider; import com.trello.rxlifecycle.components.RxActivity; import rx.Observable; import rx.functions.Action0; import rx.subscriptions.CompositeSubscription; import javax.inject.Inject;
package com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvp; public abstract class BaseMvpActivity extends RxActivity implements BaseMvpView { @Inject
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/utils/SubscriptionUtils.java // public class SubscriptionUtils { // /** // * Automatically adds to / removes from specified {@link CompositeSubscription} when subscribe / unsubscribe is called. // * Useful when subscribing observable repeatedly, as you do not need to manipulate CompositeSubscription manually. // */ // public static <T> Observable.Operator<T, T> composite(CompositeSubscription subscriptions) { // return subscriber -> { // subscriptions.add(subscriber); // subscriber.add(Subscriptions.create(() -> subscriptions.remove(subscriber))); // return subscriber; // }; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/views/progress/ProgressIndicatorProvider.java // public class ProgressIndicatorProvider { // // private Activity activity; // // public ProgressIndicatorProvider(Activity activity) { // this.activity = activity; // } // // public ProgressDialog provide() { // return provide(activity.getString(R.string.message_progress)); // } // // public ProgressDialog provide(String message) { // ProgressDialog progressDialog = new ProgressDialog(activity); // progressDialog.setCancelable(false); // progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // progressDialog.setMessage(message); // return progressDialog; // } // // } // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/BaseMvpActivity.java import android.app.ProgressDialog; import android.widget.Toast; import com.gdgand.rxjava.rxjavasample.hotandcold.utils.SubscriptionUtils; import com.gdgand.rxjava.rxjavasample.hotandcold.views.progress.ProgressIndicatorProvider; import com.trello.rxlifecycle.components.RxActivity; import rx.Observable; import rx.functions.Action0; import rx.subscriptions.CompositeSubscription; import javax.inject.Inject; package com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvp; public abstract class BaseMvpActivity extends RxActivity implements BaseMvpView { @Inject
ProgressIndicatorProvider progressIndicatorProvider;
gdgand/android-rxjava
2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/BaseMvpActivity.java
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/utils/SubscriptionUtils.java // public class SubscriptionUtils { // /** // * Automatically adds to / removes from specified {@link CompositeSubscription} when subscribe / unsubscribe is called. // * Useful when subscribing observable repeatedly, as you do not need to manipulate CompositeSubscription manually. // */ // public static <T> Observable.Operator<T, T> composite(CompositeSubscription subscriptions) { // return subscriber -> { // subscriptions.add(subscriber); // subscriber.add(Subscriptions.create(() -> subscriptions.remove(subscriber))); // return subscriber; // }; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/views/progress/ProgressIndicatorProvider.java // public class ProgressIndicatorProvider { // // private Activity activity; // // public ProgressIndicatorProvider(Activity activity) { // this.activity = activity; // } // // public ProgressDialog provide() { // return provide(activity.getString(R.string.message_progress)); // } // // public ProgressDialog provide(String message) { // ProgressDialog progressDialog = new ProgressDialog(activity); // progressDialog.setCancelable(false); // progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // progressDialog.setMessage(message); // return progressDialog; // } // // }
import android.app.ProgressDialog; import android.widget.Toast; import com.gdgand.rxjava.rxjavasample.hotandcold.utils.SubscriptionUtils; import com.gdgand.rxjava.rxjavasample.hotandcold.views.progress.ProgressIndicatorProvider; import com.trello.rxlifecycle.components.RxActivity; import rx.Observable; import rx.functions.Action0; import rx.subscriptions.CompositeSubscription; import javax.inject.Inject;
package com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvp; public abstract class BaseMvpActivity extends RxActivity implements BaseMvpView { @Inject ProgressIndicatorProvider progressIndicatorProvider; private CompositeSubscription subscriptions = new CompositeSubscription(); @Override public <T> Observable.Transformer<T, T> injectProgress() { ProgressDialog progress = progressIndicatorProvider.provide(); return observable -> observable .doOnSubscribe(progress::show) .doOnUnsubscribe((Action0) progress::dismiss); } @Override public <T> Observable.Transformer<T, T> bind() { return observable -> observable .compose(bindToLifecycle())
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/utils/SubscriptionUtils.java // public class SubscriptionUtils { // /** // * Automatically adds to / removes from specified {@link CompositeSubscription} when subscribe / unsubscribe is called. // * Useful when subscribing observable repeatedly, as you do not need to manipulate CompositeSubscription manually. // */ // public static <T> Observable.Operator<T, T> composite(CompositeSubscription subscriptions) { // return subscriber -> { // subscriptions.add(subscriber); // subscriber.add(Subscriptions.create(() -> subscriptions.remove(subscriber))); // return subscriber; // }; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/views/progress/ProgressIndicatorProvider.java // public class ProgressIndicatorProvider { // // private Activity activity; // // public ProgressIndicatorProvider(Activity activity) { // this.activity = activity; // } // // public ProgressDialog provide() { // return provide(activity.getString(R.string.message_progress)); // } // // public ProgressDialog provide(String message) { // ProgressDialog progressDialog = new ProgressDialog(activity); // progressDialog.setCancelable(false); // progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // progressDialog.setMessage(message); // return progressDialog; // } // // } // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/BaseMvpActivity.java import android.app.ProgressDialog; import android.widget.Toast; import com.gdgand.rxjava.rxjavasample.hotandcold.utils.SubscriptionUtils; import com.gdgand.rxjava.rxjavasample.hotandcold.views.progress.ProgressIndicatorProvider; import com.trello.rxlifecycle.components.RxActivity; import rx.Observable; import rx.functions.Action0; import rx.subscriptions.CompositeSubscription; import javax.inject.Inject; package com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvp; public abstract class BaseMvpActivity extends RxActivity implements BaseMvpView { @Inject ProgressIndicatorProvider progressIndicatorProvider; private CompositeSubscription subscriptions = new CompositeSubscription(); @Override public <T> Observable.Transformer<T, T> injectProgress() { ProgressDialog progress = progressIndicatorProvider.provide(); return observable -> observable .doOnSubscribe(progress::show) .doOnUnsubscribe((Action0) progress::dismiss); } @Override public <T> Observable.Transformer<T, T> bind() { return observable -> observable .compose(bindToLifecycle())
.lift(SubscriptionUtils.composite(subscriptions));
gdgand/android-rxjava
2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/component/ApplicationComponent.java
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/ImgurApi.java // public interface ImgurApi { // // @GET("/3/topics/defaults") // Observable<TopicResponse> defaultTopics(); // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/module/ApplicationModule.java // @Module // public class ApplicationModule { // private Application application; // public ApplicationModule(Application application) { // this.application = application; // } // // @Provides // @Singleton // public Context context() { // return application; // } // // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/module/DataModule.java // @Module // public class DataModule { // // @Provides // @Singleton // public Converter.Factory converterFactory() { // return GsonConverterFactory.create(); // } // // // @Provides // @Singleton // public CallAdapter.Factory callAdapterFactory() { // return RxJavaCallAdapterFactory.create(); // } // // @Provides // @Singleton // public OkHttpClient okHttpClient() { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // // return new OkHttpClient.Builder() // .addInterceptor(interceptor) // .build(); // } // // @Provides // @Singleton // public Retrofit retrofit(OkHttpClient client, CallAdapter.Factory callAdapterFactory, Converter.Factory converterFactory) { // return new Retrofit.Builder() // .baseUrl("https://api.imgur.com") // .client(client) // .addCallAdapterFactory(callAdapterFactory) // .addConverterFactory(converterFactory) // .build(); // } // // @Provides // @Singleton // public ImgurApi imgurApi(Retrofit retrofit) { // return retrofit.create(ImgurApi.class); // } // }
import android.content.Context; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.ImgurApi; import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.ApplicationModule; import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.DataModule; import dagger.Component; import javax.inject.Singleton;
package com.gdgand.rxjava.rxjavasample.hotandcold.di.component; @Singleton @Component(modules = { ApplicationModule.class, DataModule.class }) public interface ApplicationComponent { Context context();
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/ImgurApi.java // public interface ImgurApi { // // @GET("/3/topics/defaults") // Observable<TopicResponse> defaultTopics(); // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/module/ApplicationModule.java // @Module // public class ApplicationModule { // private Application application; // public ApplicationModule(Application application) { // this.application = application; // } // // @Provides // @Singleton // public Context context() { // return application; // } // // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/module/DataModule.java // @Module // public class DataModule { // // @Provides // @Singleton // public Converter.Factory converterFactory() { // return GsonConverterFactory.create(); // } // // // @Provides // @Singleton // public CallAdapter.Factory callAdapterFactory() { // return RxJavaCallAdapterFactory.create(); // } // // @Provides // @Singleton // public OkHttpClient okHttpClient() { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // // return new OkHttpClient.Builder() // .addInterceptor(interceptor) // .build(); // } // // @Provides // @Singleton // public Retrofit retrofit(OkHttpClient client, CallAdapter.Factory callAdapterFactory, Converter.Factory converterFactory) { // return new Retrofit.Builder() // .baseUrl("https://api.imgur.com") // .client(client) // .addCallAdapterFactory(callAdapterFactory) // .addConverterFactory(converterFactory) // .build(); // } // // @Provides // @Singleton // public ImgurApi imgurApi(Retrofit retrofit) { // return retrofit.create(ImgurApi.class); // } // } // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/component/ApplicationComponent.java import android.content.Context; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.ImgurApi; import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.ApplicationModule; import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.DataModule; import dagger.Component; import javax.inject.Singleton; package com.gdgand.rxjava.rxjavasample.hotandcold.di.component; @Singleton @Component(modules = { ApplicationModule.class, DataModule.class }) public interface ApplicationComponent { Context context();
ImgurApi imgurApi();
gdgand/android-rxjava
2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/scroll/adapter/NormalAdapter.java
// Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/scroll/realm/FasterListData.java // public class FasterListData extends RealmObject { // @PrimaryKey // private long position; // // public long getPosition() { // return position; // } // // public void setPosition(long position) { // this.position = position; // } // }
import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.gdgand.rxjava.rxjavasample.R; import com.gdgand.rxjava.rxjavasample.scroll.realm.FasterListData; import java.util.ArrayList; import java.util.List; import io.realm.Realm;
package com.gdgand.rxjava.rxjavasample.scroll.adapter; public class NormalAdapter extends RecyclerView.Adapter<FasterListViewHolder> { private Context context; private List<String> list; public NormalAdapter(Context context) { this.context = context; this.list = new ArrayList<>(); } @Override public FasterListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.item_fasterlist, parent, false); return new FasterListViewHolder(view); } @Override public void onBindViewHolder(FasterListViewHolder holder, int position) { try { Realm realm = Realm.getDefaultInstance();
// Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/scroll/realm/FasterListData.java // public class FasterListData extends RealmObject { // @PrimaryKey // private long position; // // public long getPosition() { // return position; // } // // public void setPosition(long position) { // this.position = position; // } // } // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/scroll/adapter/NormalAdapter.java import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.gdgand.rxjava.rxjavasample.R; import com.gdgand.rxjava.rxjavasample.scroll.realm.FasterListData; import java.util.ArrayList; import java.util.List; import io.realm.Realm; package com.gdgand.rxjava.rxjavasample.scroll.adapter; public class NormalAdapter extends RecyclerView.Adapter<FasterListViewHolder> { private Context context; private List<String> list; public NormalAdapter(Context context) { this.context = context; this.list = new ArrayList<>(); } @Override public FasterListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.item_fasterlist, parent, false); return new FasterListViewHolder(view); } @Override public void onBindViewHolder(FasterListViewHolder holder, int position) { try { Realm realm = Realm.getDefaultInstance();
long count = realm.where(FasterListData.class).greaterThanOrEqualTo("position", position)
gdgand/android-rxjava
2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvvm/imgur/MvvmActivity.java
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/SampleApplication.java // public class SampleApplication extends Application { // private ApplicationComponent applicationComponent; // // @Override // public void onCreate() { // super.onCreate(); // applicationComponent = createComponent(); // } // // private ApplicationComponent createComponent() { // return DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .dataModule(new DataModule()) // .build(); // } // // public ApplicationComponent getApplicationComponent() { // return applicationComponent; // } // // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/module/ActivityModule.java // @Module // public class ActivityModule { // // private Activity activity; // // public ActivityModule(Activity activity) { // this.activity = activity; // } // // @Provides // @PerActivity // public Activity activity() { // return activity; // } // // @Provides // @PerActivity // public ProgressIndicatorProvider progressIndicatorProvider(Activity activity) { // return new ProgressIndicatorProvider(activity); // } // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; import butterknife.BindView; import butterknife.ButterKnife; import com.gdgand.rxjava.rxjavasample.hotandcold.R; import com.gdgand.rxjava.rxjavasample.hotandcold.SampleApplication; import com.gdgand.rxjava.rxjavasample.hotandcold.di.component.DaggerActivityComponent; import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.ActivityModule; import rx.android.schedulers.AndroidSchedulers; import rx.subscriptions.CompositeSubscription; import javax.inject.Inject;
break; } }); onInject(); subscriptions = new CompositeSubscription(); subscriptions.add(viewModel.getPosts() .observeOn(AndroidSchedulers.mainThread()) .subscribe(adapter::setDatas, this::showError)); subscriptions.add(viewModel.getCounts() .observeOn(AndroidSchedulers.mainThread()) .subscribe(pair -> { textViewResult.setText(String.format("앨범 %d개, 앨범아닌건 %d개", pair.first, pair.second)); }, this::showError)); viewModel.refresh(); } @Override protected void onDestroy() { subscriptions.unsubscribe(); super.onDestroy(); } void onInject() { DaggerActivityComponent .builder()
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/SampleApplication.java // public class SampleApplication extends Application { // private ApplicationComponent applicationComponent; // // @Override // public void onCreate() { // super.onCreate(); // applicationComponent = createComponent(); // } // // private ApplicationComponent createComponent() { // return DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .dataModule(new DataModule()) // .build(); // } // // public ApplicationComponent getApplicationComponent() { // return applicationComponent; // } // // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/module/ActivityModule.java // @Module // public class ActivityModule { // // private Activity activity; // // public ActivityModule(Activity activity) { // this.activity = activity; // } // // @Provides // @PerActivity // public Activity activity() { // return activity; // } // // @Provides // @PerActivity // public ProgressIndicatorProvider progressIndicatorProvider(Activity activity) { // return new ProgressIndicatorProvider(activity); // } // } // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvvm/imgur/MvvmActivity.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; import butterknife.BindView; import butterknife.ButterKnife; import com.gdgand.rxjava.rxjavasample.hotandcold.R; import com.gdgand.rxjava.rxjavasample.hotandcold.SampleApplication; import com.gdgand.rxjava.rxjavasample.hotandcold.di.component.DaggerActivityComponent; import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.ActivityModule; import rx.android.schedulers.AndroidSchedulers; import rx.subscriptions.CompositeSubscription; import javax.inject.Inject; break; } }); onInject(); subscriptions = new CompositeSubscription(); subscriptions.add(viewModel.getPosts() .observeOn(AndroidSchedulers.mainThread()) .subscribe(adapter::setDatas, this::showError)); subscriptions.add(viewModel.getCounts() .observeOn(AndroidSchedulers.mainThread()) .subscribe(pair -> { textViewResult.setText(String.format("앨범 %d개, 앨범아닌건 %d개", pair.first, pair.second)); }, this::showError)); viewModel.refresh(); } @Override protected void onDestroy() { subscriptions.unsubscribe(); super.onDestroy(); } void onInject() { DaggerActivityComponent .builder()
.applicationComponent(((SampleApplication)getApplication()).getApplicationComponent())
gdgand/android-rxjava
2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvvm/imgur/MvvmActivity.java
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/SampleApplication.java // public class SampleApplication extends Application { // private ApplicationComponent applicationComponent; // // @Override // public void onCreate() { // super.onCreate(); // applicationComponent = createComponent(); // } // // private ApplicationComponent createComponent() { // return DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .dataModule(new DataModule()) // .build(); // } // // public ApplicationComponent getApplicationComponent() { // return applicationComponent; // } // // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/module/ActivityModule.java // @Module // public class ActivityModule { // // private Activity activity; // // public ActivityModule(Activity activity) { // this.activity = activity; // } // // @Provides // @PerActivity // public Activity activity() { // return activity; // } // // @Provides // @PerActivity // public ProgressIndicatorProvider progressIndicatorProvider(Activity activity) { // return new ProgressIndicatorProvider(activity); // } // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; import butterknife.BindView; import butterknife.ButterKnife; import com.gdgand.rxjava.rxjavasample.hotandcold.R; import com.gdgand.rxjava.rxjavasample.hotandcold.SampleApplication; import com.gdgand.rxjava.rxjavasample.hotandcold.di.component.DaggerActivityComponent; import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.ActivityModule; import rx.android.schedulers.AndroidSchedulers; import rx.subscriptions.CompositeSubscription; import javax.inject.Inject;
} }); onInject(); subscriptions = new CompositeSubscription(); subscriptions.add(viewModel.getPosts() .observeOn(AndroidSchedulers.mainThread()) .subscribe(adapter::setDatas, this::showError)); subscriptions.add(viewModel.getCounts() .observeOn(AndroidSchedulers.mainThread()) .subscribe(pair -> { textViewResult.setText(String.format("앨범 %d개, 앨범아닌건 %d개", pair.first, pair.second)); }, this::showError)); viewModel.refresh(); } @Override protected void onDestroy() { subscriptions.unsubscribe(); super.onDestroy(); } void onInject() { DaggerActivityComponent .builder() .applicationComponent(((SampleApplication)getApplication()).getApplicationComponent())
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/SampleApplication.java // public class SampleApplication extends Application { // private ApplicationComponent applicationComponent; // // @Override // public void onCreate() { // super.onCreate(); // applicationComponent = createComponent(); // } // // private ApplicationComponent createComponent() { // return DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .dataModule(new DataModule()) // .build(); // } // // public ApplicationComponent getApplicationComponent() { // return applicationComponent; // } // // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/module/ActivityModule.java // @Module // public class ActivityModule { // // private Activity activity; // // public ActivityModule(Activity activity) { // this.activity = activity; // } // // @Provides // @PerActivity // public Activity activity() { // return activity; // } // // @Provides // @PerActivity // public ProgressIndicatorProvider progressIndicatorProvider(Activity activity) { // return new ProgressIndicatorProvider(activity); // } // } // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvvm/imgur/MvvmActivity.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; import butterknife.BindView; import butterknife.ButterKnife; import com.gdgand.rxjava.rxjavasample.hotandcold.R; import com.gdgand.rxjava.rxjavasample.hotandcold.SampleApplication; import com.gdgand.rxjava.rxjavasample.hotandcold.di.component.DaggerActivityComponent; import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.ActivityModule; import rx.android.schedulers.AndroidSchedulers; import rx.subscriptions.CompositeSubscription; import javax.inject.Inject; } }); onInject(); subscriptions = new CompositeSubscription(); subscriptions.add(viewModel.getPosts() .observeOn(AndroidSchedulers.mainThread()) .subscribe(adapter::setDatas, this::showError)); subscriptions.add(viewModel.getCounts() .observeOn(AndroidSchedulers.mainThread()) .subscribe(pair -> { textViewResult.setText(String.format("앨범 %d개, 앨범아닌건 %d개", pair.first, pair.second)); }, this::showError)); viewModel.refresh(); } @Override protected void onDestroy() { subscriptions.unsubscribe(); super.onDestroy(); } void onInject() { DaggerActivityComponent .builder() .applicationComponent(((SampleApplication)getApplication()).getApplicationComponent())
.activityModule(new ActivityModule(this))
gdgand/android-rxjava
2016-07-06_rxjava_tips/src/main/java/com/gdgand/rxjava/tips/example/RxUserBus.java
// Path: 2016-07-06_rxjava_tips/src/main/java/com/gdgand/rxjava/tips/example/more/SafeObservable.java // public class SafeObservable<T> extends Observable<T> { // protected SafeObservable(OnSubscribe<T> f) { // super(f); // } // // public Subscription safeSubscribe(Subscriber<T> subscriber) { // WeakSubscriberDecorator<T> weakSubscriberDecorator = new WeakSubscriberDecorator<>(subscriber); // return subscribe(weakSubscriberDecorator); // } // // public Subscription safeSubscribe(final Action1<? super T> onNext) { // Action1<Throwable> onError = InternalObservableUtils.ERROR_NOT_IMPLEMENTED; // Action0 onCompleted = Actions.empty(); // Subscriber<T> subscriber = new ActionSubscriber<T>(onNext, onError, onCompleted); // WeakSubscriberDecorator<T> weakSubscriberDecorator = new WeakSubscriberDecorator<>(subscriber); // return subscribe(weakSubscriberDecorator); // } // // public Subscription safeSubscribe(final Action1<? super T> onNext, final Action1<Throwable> onError) { // Action0 onCompleted = Actions.empty(); // Subscriber<T> subscriber = new ActionSubscriber<T>(onNext, onError, onCompleted); // WeakSubscriberDecorator<T> weakSubscriberDecorator = new WeakSubscriberDecorator<>(subscriber); // return subscribe(weakSubscriberDecorator); // } // // public Subscription safeSubscribe(final Action1<? super T> onNext, // final Action1<Throwable> onError, final Action0 onCompleted) { // Subscriber<T> subscriber = new ActionSubscriber<T>(onNext, onError, onCompleted); // WeakSubscriberDecorator<T> weakSubscriberDecorator = new WeakSubscriberDecorator<>(subscriber); // return subscribe(weakSubscriberDecorator); // } // }
import com.gdgand.rxjava.tips.example.more.SafeObservable; import rx.Observable; import rx.subjects.PublishSubject;
package com.gdgand.rxjava.tips.example; // import com.fernandocejas.frodo.annotation.RxLogObservable; public final class RxUserBus { private static PublishSubject<String> bus = PublishSubject.create(); private RxUserBus() {} static Observable<String> sub() { return bus.asObservable(); } // @RxLogObservable(RxLogObservable.Scope.EVERYTHING)
// Path: 2016-07-06_rxjava_tips/src/main/java/com/gdgand/rxjava/tips/example/more/SafeObservable.java // public class SafeObservable<T> extends Observable<T> { // protected SafeObservable(OnSubscribe<T> f) { // super(f); // } // // public Subscription safeSubscribe(Subscriber<T> subscriber) { // WeakSubscriberDecorator<T> weakSubscriberDecorator = new WeakSubscriberDecorator<>(subscriber); // return subscribe(weakSubscriberDecorator); // } // // public Subscription safeSubscribe(final Action1<? super T> onNext) { // Action1<Throwable> onError = InternalObservableUtils.ERROR_NOT_IMPLEMENTED; // Action0 onCompleted = Actions.empty(); // Subscriber<T> subscriber = new ActionSubscriber<T>(onNext, onError, onCompleted); // WeakSubscriberDecorator<T> weakSubscriberDecorator = new WeakSubscriberDecorator<>(subscriber); // return subscribe(weakSubscriberDecorator); // } // // public Subscription safeSubscribe(final Action1<? super T> onNext, final Action1<Throwable> onError) { // Action0 onCompleted = Actions.empty(); // Subscriber<T> subscriber = new ActionSubscriber<T>(onNext, onError, onCompleted); // WeakSubscriberDecorator<T> weakSubscriberDecorator = new WeakSubscriberDecorator<>(subscriber); // return subscribe(weakSubscriberDecorator); // } // // public Subscription safeSubscribe(final Action1<? super T> onNext, // final Action1<Throwable> onError, final Action0 onCompleted) { // Subscriber<T> subscriber = new ActionSubscriber<T>(onNext, onError, onCompleted); // WeakSubscriberDecorator<T> weakSubscriberDecorator = new WeakSubscriberDecorator<>(subscriber); // return subscribe(weakSubscriberDecorator); // } // } // Path: 2016-07-06_rxjava_tips/src/main/java/com/gdgand/rxjava/tips/example/RxUserBus.java import com.gdgand.rxjava.tips.example.more.SafeObservable; import rx.Observable; import rx.subjects.PublishSubject; package com.gdgand.rxjava.tips.example; // import com.fernandocejas.frodo.annotation.RxLogObservable; public final class RxUserBus { private static PublishSubject<String> bus = PublishSubject.create(); private RxUserBus() {} static Observable<String> sub() { return bus.asObservable(); } // @RxLogObservable(RxLogObservable.Scope.EVERYTHING)
static SafeObservable<String> subSafe() {
gdgand/android-rxjava
2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/imgur/ImgurActivity.java
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/SampleApplication.java // public class SampleApplication extends Application { // private ApplicationComponent applicationComponent; // // @Override // public void onCreate() { // super.onCreate(); // applicationComponent = createComponent(); // } // // private ApplicationComponent createComponent() { // return DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .dataModule(new DataModule()) // .build(); // } // // public ApplicationComponent getApplicationComponent() { // return applicationComponent; // } // // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/Topic.java // public class Topic { // private long id; // // private String name; // // private String description; // // private TopPost topPost; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public TopPost getTopPost() { // return topPost; // } // // public void setTopPost(TopPost topPost) { // this.topPost = topPost; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/module/ActivityModule.java // @Module // public class ActivityModule { // // private Activity activity; // // public ActivityModule(Activity activity) { // this.activity = activity; // } // // @Provides // @PerActivity // public Activity activity() { // return activity; // } // // @Provides // @PerActivity // public ProgressIndicatorProvider progressIndicatorProvider(Activity activity) { // return new ProgressIndicatorProvider(activity); // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/BaseMvpActivity.java // public abstract class BaseMvpActivity extends RxActivity implements BaseMvpView { // // @Inject // ProgressIndicatorProvider progressIndicatorProvider; // // private CompositeSubscription subscriptions = new CompositeSubscription(); // // @Override // public <T> Observable.Transformer<T, T> injectProgress() { // ProgressDialog progress = progressIndicatorProvider.provide(); // return observable -> observable // .doOnSubscribe(progress::show) // .doOnUnsubscribe((Action0) progress::dismiss); // } // // @Override // public <T> Observable.Transformer<T, T> bind() { // return observable -> observable // .compose(bindToLifecycle()) // .lift(SubscriptionUtils.composite(subscriptions)); // } // // @Override // protected void onDestroy() { // subscriptions.unsubscribe(); // super.onDestroy(); // } // // @Override // public void showThrowable(Throwable throwable) { // Toast.makeText(this, throwable.getMessage(), Toast.LENGTH_LONG).show(); // } // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import com.gdgand.rxjava.rxjavasample.hotandcold.R; import com.gdgand.rxjava.rxjavasample.hotandcold.SampleApplication; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.Topic; import com.gdgand.rxjava.rxjavasample.hotandcold.di.component.DaggerActivityComponent; import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.ActivityModule; import com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvp.BaseMvpActivity; import java.util.List; import javax.inject.Inject;
package com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvp.imgur; public class ImgurActivity extends BaseMvpActivity implements ImgurMvpView { @Inject ImgurMvpPresenter presenter; @BindView(R.id.recyclerView) RecyclerView recyclerView; private ImgurAdapter adapter; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mvp_imgur); ButterKnife.bind(this); adapter = new ImgurAdapter(this); recyclerView.setAdapter(adapter); recyclerView.setLayoutManager(new LinearLayoutManager(this)); onInject(); presenter.attachView(this); presenter.refreshTopics(); } @Override protected void onDestroy() { presenter.detachView(); super.onDestroy(); } @OnClick(R.id.buttonSubmit) void clickSubmit() { presenter.refreshTopics(); } @Override
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/SampleApplication.java // public class SampleApplication extends Application { // private ApplicationComponent applicationComponent; // // @Override // public void onCreate() { // super.onCreate(); // applicationComponent = createComponent(); // } // // private ApplicationComponent createComponent() { // return DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .dataModule(new DataModule()) // .build(); // } // // public ApplicationComponent getApplicationComponent() { // return applicationComponent; // } // // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/Topic.java // public class Topic { // private long id; // // private String name; // // private String description; // // private TopPost topPost; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public TopPost getTopPost() { // return topPost; // } // // public void setTopPost(TopPost topPost) { // this.topPost = topPost; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/module/ActivityModule.java // @Module // public class ActivityModule { // // private Activity activity; // // public ActivityModule(Activity activity) { // this.activity = activity; // } // // @Provides // @PerActivity // public Activity activity() { // return activity; // } // // @Provides // @PerActivity // public ProgressIndicatorProvider progressIndicatorProvider(Activity activity) { // return new ProgressIndicatorProvider(activity); // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/BaseMvpActivity.java // public abstract class BaseMvpActivity extends RxActivity implements BaseMvpView { // // @Inject // ProgressIndicatorProvider progressIndicatorProvider; // // private CompositeSubscription subscriptions = new CompositeSubscription(); // // @Override // public <T> Observable.Transformer<T, T> injectProgress() { // ProgressDialog progress = progressIndicatorProvider.provide(); // return observable -> observable // .doOnSubscribe(progress::show) // .doOnUnsubscribe((Action0) progress::dismiss); // } // // @Override // public <T> Observable.Transformer<T, T> bind() { // return observable -> observable // .compose(bindToLifecycle()) // .lift(SubscriptionUtils.composite(subscriptions)); // } // // @Override // protected void onDestroy() { // subscriptions.unsubscribe(); // super.onDestroy(); // } // // @Override // public void showThrowable(Throwable throwable) { // Toast.makeText(this, throwable.getMessage(), Toast.LENGTH_LONG).show(); // } // } // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/imgur/ImgurActivity.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import com.gdgand.rxjava.rxjavasample.hotandcold.R; import com.gdgand.rxjava.rxjavasample.hotandcold.SampleApplication; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.Topic; import com.gdgand.rxjava.rxjavasample.hotandcold.di.component.DaggerActivityComponent; import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.ActivityModule; import com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvp.BaseMvpActivity; import java.util.List; import javax.inject.Inject; package com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvp.imgur; public class ImgurActivity extends BaseMvpActivity implements ImgurMvpView { @Inject ImgurMvpPresenter presenter; @BindView(R.id.recyclerView) RecyclerView recyclerView; private ImgurAdapter adapter; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mvp_imgur); ButterKnife.bind(this); adapter = new ImgurAdapter(this); recyclerView.setAdapter(adapter); recyclerView.setLayoutManager(new LinearLayoutManager(this)); onInject(); presenter.attachView(this); presenter.refreshTopics(); } @Override protected void onDestroy() { presenter.detachView(); super.onDestroy(); } @OnClick(R.id.buttonSubmit) void clickSubmit() { presenter.refreshTopics(); } @Override
public void showTopics(List<Topic> topics) {
gdgand/android-rxjava
2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/imgur/ImgurActivity.java
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/SampleApplication.java // public class SampleApplication extends Application { // private ApplicationComponent applicationComponent; // // @Override // public void onCreate() { // super.onCreate(); // applicationComponent = createComponent(); // } // // private ApplicationComponent createComponent() { // return DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .dataModule(new DataModule()) // .build(); // } // // public ApplicationComponent getApplicationComponent() { // return applicationComponent; // } // // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/Topic.java // public class Topic { // private long id; // // private String name; // // private String description; // // private TopPost topPost; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public TopPost getTopPost() { // return topPost; // } // // public void setTopPost(TopPost topPost) { // this.topPost = topPost; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/module/ActivityModule.java // @Module // public class ActivityModule { // // private Activity activity; // // public ActivityModule(Activity activity) { // this.activity = activity; // } // // @Provides // @PerActivity // public Activity activity() { // return activity; // } // // @Provides // @PerActivity // public ProgressIndicatorProvider progressIndicatorProvider(Activity activity) { // return new ProgressIndicatorProvider(activity); // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/BaseMvpActivity.java // public abstract class BaseMvpActivity extends RxActivity implements BaseMvpView { // // @Inject // ProgressIndicatorProvider progressIndicatorProvider; // // private CompositeSubscription subscriptions = new CompositeSubscription(); // // @Override // public <T> Observable.Transformer<T, T> injectProgress() { // ProgressDialog progress = progressIndicatorProvider.provide(); // return observable -> observable // .doOnSubscribe(progress::show) // .doOnUnsubscribe((Action0) progress::dismiss); // } // // @Override // public <T> Observable.Transformer<T, T> bind() { // return observable -> observable // .compose(bindToLifecycle()) // .lift(SubscriptionUtils.composite(subscriptions)); // } // // @Override // protected void onDestroy() { // subscriptions.unsubscribe(); // super.onDestroy(); // } // // @Override // public void showThrowable(Throwable throwable) { // Toast.makeText(this, throwable.getMessage(), Toast.LENGTH_LONG).show(); // } // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import com.gdgand.rxjava.rxjavasample.hotandcold.R; import com.gdgand.rxjava.rxjavasample.hotandcold.SampleApplication; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.Topic; import com.gdgand.rxjava.rxjavasample.hotandcold.di.component.DaggerActivityComponent; import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.ActivityModule; import com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvp.BaseMvpActivity; import java.util.List; import javax.inject.Inject;
adapter = new ImgurAdapter(this); recyclerView.setAdapter(adapter); recyclerView.setLayoutManager(new LinearLayoutManager(this)); onInject(); presenter.attachView(this); presenter.refreshTopics(); } @Override protected void onDestroy() { presenter.detachView(); super.onDestroy(); } @OnClick(R.id.buttonSubmit) void clickSubmit() { presenter.refreshTopics(); } @Override public void showTopics(List<Topic> topics) { adapter.setDatas(topics); } void onInject() { DaggerActivityComponent .builder()
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/SampleApplication.java // public class SampleApplication extends Application { // private ApplicationComponent applicationComponent; // // @Override // public void onCreate() { // super.onCreate(); // applicationComponent = createComponent(); // } // // private ApplicationComponent createComponent() { // return DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .dataModule(new DataModule()) // .build(); // } // // public ApplicationComponent getApplicationComponent() { // return applicationComponent; // } // // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/Topic.java // public class Topic { // private long id; // // private String name; // // private String description; // // private TopPost topPost; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public TopPost getTopPost() { // return topPost; // } // // public void setTopPost(TopPost topPost) { // this.topPost = topPost; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/module/ActivityModule.java // @Module // public class ActivityModule { // // private Activity activity; // // public ActivityModule(Activity activity) { // this.activity = activity; // } // // @Provides // @PerActivity // public Activity activity() { // return activity; // } // // @Provides // @PerActivity // public ProgressIndicatorProvider progressIndicatorProvider(Activity activity) { // return new ProgressIndicatorProvider(activity); // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/BaseMvpActivity.java // public abstract class BaseMvpActivity extends RxActivity implements BaseMvpView { // // @Inject // ProgressIndicatorProvider progressIndicatorProvider; // // private CompositeSubscription subscriptions = new CompositeSubscription(); // // @Override // public <T> Observable.Transformer<T, T> injectProgress() { // ProgressDialog progress = progressIndicatorProvider.provide(); // return observable -> observable // .doOnSubscribe(progress::show) // .doOnUnsubscribe((Action0) progress::dismiss); // } // // @Override // public <T> Observable.Transformer<T, T> bind() { // return observable -> observable // .compose(bindToLifecycle()) // .lift(SubscriptionUtils.composite(subscriptions)); // } // // @Override // protected void onDestroy() { // subscriptions.unsubscribe(); // super.onDestroy(); // } // // @Override // public void showThrowable(Throwable throwable) { // Toast.makeText(this, throwable.getMessage(), Toast.LENGTH_LONG).show(); // } // } // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/imgur/ImgurActivity.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import com.gdgand.rxjava.rxjavasample.hotandcold.R; import com.gdgand.rxjava.rxjavasample.hotandcold.SampleApplication; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.Topic; import com.gdgand.rxjava.rxjavasample.hotandcold.di.component.DaggerActivityComponent; import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.ActivityModule; import com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvp.BaseMvpActivity; import java.util.List; import javax.inject.Inject; adapter = new ImgurAdapter(this); recyclerView.setAdapter(adapter); recyclerView.setLayoutManager(new LinearLayoutManager(this)); onInject(); presenter.attachView(this); presenter.refreshTopics(); } @Override protected void onDestroy() { presenter.detachView(); super.onDestroy(); } @OnClick(R.id.buttonSubmit) void clickSubmit() { presenter.refreshTopics(); } @Override public void showTopics(List<Topic> topics) { adapter.setDatas(topics); } void onInject() { DaggerActivityComponent .builder()
.applicationComponent(((SampleApplication)getApplication()).getApplicationComponent())
gdgand/android-rxjava
2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/imgur/ImgurActivity.java
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/SampleApplication.java // public class SampleApplication extends Application { // private ApplicationComponent applicationComponent; // // @Override // public void onCreate() { // super.onCreate(); // applicationComponent = createComponent(); // } // // private ApplicationComponent createComponent() { // return DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .dataModule(new DataModule()) // .build(); // } // // public ApplicationComponent getApplicationComponent() { // return applicationComponent; // } // // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/Topic.java // public class Topic { // private long id; // // private String name; // // private String description; // // private TopPost topPost; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public TopPost getTopPost() { // return topPost; // } // // public void setTopPost(TopPost topPost) { // this.topPost = topPost; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/module/ActivityModule.java // @Module // public class ActivityModule { // // private Activity activity; // // public ActivityModule(Activity activity) { // this.activity = activity; // } // // @Provides // @PerActivity // public Activity activity() { // return activity; // } // // @Provides // @PerActivity // public ProgressIndicatorProvider progressIndicatorProvider(Activity activity) { // return new ProgressIndicatorProvider(activity); // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/BaseMvpActivity.java // public abstract class BaseMvpActivity extends RxActivity implements BaseMvpView { // // @Inject // ProgressIndicatorProvider progressIndicatorProvider; // // private CompositeSubscription subscriptions = new CompositeSubscription(); // // @Override // public <T> Observable.Transformer<T, T> injectProgress() { // ProgressDialog progress = progressIndicatorProvider.provide(); // return observable -> observable // .doOnSubscribe(progress::show) // .doOnUnsubscribe((Action0) progress::dismiss); // } // // @Override // public <T> Observable.Transformer<T, T> bind() { // return observable -> observable // .compose(bindToLifecycle()) // .lift(SubscriptionUtils.composite(subscriptions)); // } // // @Override // protected void onDestroy() { // subscriptions.unsubscribe(); // super.onDestroy(); // } // // @Override // public void showThrowable(Throwable throwable) { // Toast.makeText(this, throwable.getMessage(), Toast.LENGTH_LONG).show(); // } // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import com.gdgand.rxjava.rxjavasample.hotandcold.R; import com.gdgand.rxjava.rxjavasample.hotandcold.SampleApplication; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.Topic; import com.gdgand.rxjava.rxjavasample.hotandcold.di.component.DaggerActivityComponent; import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.ActivityModule; import com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvp.BaseMvpActivity; import java.util.List; import javax.inject.Inject;
adapter = new ImgurAdapter(this); recyclerView.setAdapter(adapter); recyclerView.setLayoutManager(new LinearLayoutManager(this)); onInject(); presenter.attachView(this); presenter.refreshTopics(); } @Override protected void onDestroy() { presenter.detachView(); super.onDestroy(); } @OnClick(R.id.buttonSubmit) void clickSubmit() { presenter.refreshTopics(); } @Override public void showTopics(List<Topic> topics) { adapter.setDatas(topics); } void onInject() { DaggerActivityComponent .builder() .applicationComponent(((SampleApplication)getApplication()).getApplicationComponent())
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/SampleApplication.java // public class SampleApplication extends Application { // private ApplicationComponent applicationComponent; // // @Override // public void onCreate() { // super.onCreate(); // applicationComponent = createComponent(); // } // // private ApplicationComponent createComponent() { // return DaggerApplicationComponent.builder() // .applicationModule(new ApplicationModule(this)) // .dataModule(new DataModule()) // .build(); // } // // public ApplicationComponent getApplicationComponent() { // return applicationComponent; // } // // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/Topic.java // public class Topic { // private long id; // // private String name; // // private String description; // // private TopPost topPost; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public TopPost getTopPost() { // return topPost; // } // // public void setTopPost(TopPost topPost) { // this.topPost = topPost; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/module/ActivityModule.java // @Module // public class ActivityModule { // // private Activity activity; // // public ActivityModule(Activity activity) { // this.activity = activity; // } // // @Provides // @PerActivity // public Activity activity() { // return activity; // } // // @Provides // @PerActivity // public ProgressIndicatorProvider progressIndicatorProvider(Activity activity) { // return new ProgressIndicatorProvider(activity); // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/BaseMvpActivity.java // public abstract class BaseMvpActivity extends RxActivity implements BaseMvpView { // // @Inject // ProgressIndicatorProvider progressIndicatorProvider; // // private CompositeSubscription subscriptions = new CompositeSubscription(); // // @Override // public <T> Observable.Transformer<T, T> injectProgress() { // ProgressDialog progress = progressIndicatorProvider.provide(); // return observable -> observable // .doOnSubscribe(progress::show) // .doOnUnsubscribe((Action0) progress::dismiss); // } // // @Override // public <T> Observable.Transformer<T, T> bind() { // return observable -> observable // .compose(bindToLifecycle()) // .lift(SubscriptionUtils.composite(subscriptions)); // } // // @Override // protected void onDestroy() { // subscriptions.unsubscribe(); // super.onDestroy(); // } // // @Override // public void showThrowable(Throwable throwable) { // Toast.makeText(this, throwable.getMessage(), Toast.LENGTH_LONG).show(); // } // } // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/imgur/ImgurActivity.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import com.gdgand.rxjava.rxjavasample.hotandcold.R; import com.gdgand.rxjava.rxjavasample.hotandcold.SampleApplication; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.Topic; import com.gdgand.rxjava.rxjavasample.hotandcold.di.component.DaggerActivityComponent; import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.ActivityModule; import com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvp.BaseMvpActivity; import java.util.List; import javax.inject.Inject; adapter = new ImgurAdapter(this); recyclerView.setAdapter(adapter); recyclerView.setLayoutManager(new LinearLayoutManager(this)); onInject(); presenter.attachView(this); presenter.refreshTopics(); } @Override protected void onDestroy() { presenter.detachView(); super.onDestroy(); } @OnClick(R.id.buttonSubmit) void clickSubmit() { presenter.refreshTopics(); } @Override public void showTopics(List<Topic> topics) { adapter.setDatas(topics); } void onInject() { DaggerActivityComponent .builder() .applicationComponent(((SampleApplication)getApplication()).getApplicationComponent())
.activityModule(new ActivityModule(this))
gdgand/android-rxjava
2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/component/ActivityComponent.java
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/module/ActivityModule.java // @Module // public class ActivityModule { // // private Activity activity; // // public ActivityModule(Activity activity) { // this.activity = activity; // } // // @Provides // @PerActivity // public Activity activity() { // return activity; // } // // @Provides // @PerActivity // public ProgressIndicatorProvider progressIndicatorProvider(Activity activity) { // return new ProgressIndicatorProvider(activity); // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/imgur/ImgurActivity.java // public class ImgurActivity extends BaseMvpActivity implements ImgurMvpView { // // @Inject // ImgurMvpPresenter presenter; // // @BindView(R.id.recyclerView) // RecyclerView recyclerView; // // private ImgurAdapter adapter; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_mvp_imgur); // ButterKnife.bind(this); // // adapter = new ImgurAdapter(this); // recyclerView.setAdapter(adapter); // recyclerView.setLayoutManager(new LinearLayoutManager(this)); // // onInject(); // // presenter.attachView(this); // presenter.refreshTopics(); // } // // @Override // protected void onDestroy() { // presenter.detachView(); // super.onDestroy(); // } // // @OnClick(R.id.buttonSubmit) // void clickSubmit() { // presenter.refreshTopics(); // } // // @Override // public void showTopics(List<Topic> topics) { // adapter.setDatas(topics); // } // // void onInject() { // DaggerActivityComponent // .builder() // .applicationComponent(((SampleApplication)getApplication()).getApplicationComponent()) // .activityModule(new ActivityModule(this)) // .build() // .inject(this); // } // // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvvm/imgur/MvvmActivity.java // public class MvvmActivity extends AppCompatActivity { // // @Inject // MvvmViewModel viewModel; // // @BindView(R.id.textViewResult) // TextView textViewResult; // // @BindView(R.id.recyclerView) // RecyclerView recyclerView; // // @BindView(R.id.radioGroup) // RadioGroup radioGroup; // // CompositeSubscription subscriptions; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_mvvm_imgur); // ButterKnife.bind(this); // // MvvmAdapter adapter = new MvvmAdapter(this); // recyclerView.setAdapter(adapter); // recyclerView.setLayoutManager(new LinearLayoutManager(this)); // radioGroup.setOnCheckedChangeListener((group, checkedId) -> { // switch (checkedId) { // case R.id.radioButtonAll: // viewModel.modifyVisibleType(MvvmViewModel.VisibleType.ALL); // break; // case R.id.radioButtonOdd: // viewModel.modifyVisibleType(MvvmViewModel.VisibleType.ODD); // break; // case R.id.radioButtonEven: // viewModel.modifyVisibleType(MvvmViewModel.VisibleType.EVEN); // break; // default: // break; // } // }); // // onInject(); // // subscriptions = new CompositeSubscription(); // // subscriptions.add(viewModel.getPosts() // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(adapter::setDatas, this::showError)); // // subscriptions.add(viewModel.getCounts() // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(pair -> { // textViewResult.setText(String.format("앨범 %d개, 앨범아닌건 %d개", pair.first, pair.second)); // }, this::showError)); // // viewModel.refresh(); // } // // @Override // protected void onDestroy() { // subscriptions.unsubscribe(); // super.onDestroy(); // } // // void onInject() { // DaggerActivityComponent // .builder() // .applicationComponent(((SampleApplication)getApplication()).getApplicationComponent()) // .activityModule(new ActivityModule(this)) // .build() // .inject(this); // } // // void showError(Throwable throwable) { // Toast.makeText(this, throwable.getMessage(), Toast.LENGTH_LONG).show(); // } // // }
import com.gdgand.rxjava.rxjavasample.hotandcold.di.PerActivity; import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.ActivityModule; import com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvp.imgur.ImgurActivity; import com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvvm.imgur.MvvmActivity; import dagger.Component;
package com.gdgand.rxjava.rxjavasample.hotandcold.di.component; @PerActivity @Component(dependencies = { ApplicationComponent.class }, modules = { ActivityModule.class }) public interface ActivityComponent {
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/module/ActivityModule.java // @Module // public class ActivityModule { // // private Activity activity; // // public ActivityModule(Activity activity) { // this.activity = activity; // } // // @Provides // @PerActivity // public Activity activity() { // return activity; // } // // @Provides // @PerActivity // public ProgressIndicatorProvider progressIndicatorProvider(Activity activity) { // return new ProgressIndicatorProvider(activity); // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/imgur/ImgurActivity.java // public class ImgurActivity extends BaseMvpActivity implements ImgurMvpView { // // @Inject // ImgurMvpPresenter presenter; // // @BindView(R.id.recyclerView) // RecyclerView recyclerView; // // private ImgurAdapter adapter; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_mvp_imgur); // ButterKnife.bind(this); // // adapter = new ImgurAdapter(this); // recyclerView.setAdapter(adapter); // recyclerView.setLayoutManager(new LinearLayoutManager(this)); // // onInject(); // // presenter.attachView(this); // presenter.refreshTopics(); // } // // @Override // protected void onDestroy() { // presenter.detachView(); // super.onDestroy(); // } // // @OnClick(R.id.buttonSubmit) // void clickSubmit() { // presenter.refreshTopics(); // } // // @Override // public void showTopics(List<Topic> topics) { // adapter.setDatas(topics); // } // // void onInject() { // DaggerActivityComponent // .builder() // .applicationComponent(((SampleApplication)getApplication()).getApplicationComponent()) // .activityModule(new ActivityModule(this)) // .build() // .inject(this); // } // // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvvm/imgur/MvvmActivity.java // public class MvvmActivity extends AppCompatActivity { // // @Inject // MvvmViewModel viewModel; // // @BindView(R.id.textViewResult) // TextView textViewResult; // // @BindView(R.id.recyclerView) // RecyclerView recyclerView; // // @BindView(R.id.radioGroup) // RadioGroup radioGroup; // // CompositeSubscription subscriptions; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_mvvm_imgur); // ButterKnife.bind(this); // // MvvmAdapter adapter = new MvvmAdapter(this); // recyclerView.setAdapter(adapter); // recyclerView.setLayoutManager(new LinearLayoutManager(this)); // radioGroup.setOnCheckedChangeListener((group, checkedId) -> { // switch (checkedId) { // case R.id.radioButtonAll: // viewModel.modifyVisibleType(MvvmViewModel.VisibleType.ALL); // break; // case R.id.radioButtonOdd: // viewModel.modifyVisibleType(MvvmViewModel.VisibleType.ODD); // break; // case R.id.radioButtonEven: // viewModel.modifyVisibleType(MvvmViewModel.VisibleType.EVEN); // break; // default: // break; // } // }); // // onInject(); // // subscriptions = new CompositeSubscription(); // // subscriptions.add(viewModel.getPosts() // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(adapter::setDatas, this::showError)); // // subscriptions.add(viewModel.getCounts() // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(pair -> { // textViewResult.setText(String.format("앨범 %d개, 앨범아닌건 %d개", pair.first, pair.second)); // }, this::showError)); // // viewModel.refresh(); // } // // @Override // protected void onDestroy() { // subscriptions.unsubscribe(); // super.onDestroy(); // } // // void onInject() { // DaggerActivityComponent // .builder() // .applicationComponent(((SampleApplication)getApplication()).getApplicationComponent()) // .activityModule(new ActivityModule(this)) // .build() // .inject(this); // } // // void showError(Throwable throwable) { // Toast.makeText(this, throwable.getMessage(), Toast.LENGTH_LONG).show(); // } // // } // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/component/ActivityComponent.java import com.gdgand.rxjava.rxjavasample.hotandcold.di.PerActivity; import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.ActivityModule; import com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvp.imgur.ImgurActivity; import com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvvm.imgur.MvvmActivity; import dagger.Component; package com.gdgand.rxjava.rxjavasample.hotandcold.di.component; @PerActivity @Component(dependencies = { ApplicationComponent.class }, modules = { ActivityModule.class }) public interface ActivityComponent {
void inject(MvvmActivity activity);
gdgand/android-rxjava
2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/component/ActivityComponent.java
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/module/ActivityModule.java // @Module // public class ActivityModule { // // private Activity activity; // // public ActivityModule(Activity activity) { // this.activity = activity; // } // // @Provides // @PerActivity // public Activity activity() { // return activity; // } // // @Provides // @PerActivity // public ProgressIndicatorProvider progressIndicatorProvider(Activity activity) { // return new ProgressIndicatorProvider(activity); // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/imgur/ImgurActivity.java // public class ImgurActivity extends BaseMvpActivity implements ImgurMvpView { // // @Inject // ImgurMvpPresenter presenter; // // @BindView(R.id.recyclerView) // RecyclerView recyclerView; // // private ImgurAdapter adapter; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_mvp_imgur); // ButterKnife.bind(this); // // adapter = new ImgurAdapter(this); // recyclerView.setAdapter(adapter); // recyclerView.setLayoutManager(new LinearLayoutManager(this)); // // onInject(); // // presenter.attachView(this); // presenter.refreshTopics(); // } // // @Override // protected void onDestroy() { // presenter.detachView(); // super.onDestroy(); // } // // @OnClick(R.id.buttonSubmit) // void clickSubmit() { // presenter.refreshTopics(); // } // // @Override // public void showTopics(List<Topic> topics) { // adapter.setDatas(topics); // } // // void onInject() { // DaggerActivityComponent // .builder() // .applicationComponent(((SampleApplication)getApplication()).getApplicationComponent()) // .activityModule(new ActivityModule(this)) // .build() // .inject(this); // } // // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvvm/imgur/MvvmActivity.java // public class MvvmActivity extends AppCompatActivity { // // @Inject // MvvmViewModel viewModel; // // @BindView(R.id.textViewResult) // TextView textViewResult; // // @BindView(R.id.recyclerView) // RecyclerView recyclerView; // // @BindView(R.id.radioGroup) // RadioGroup radioGroup; // // CompositeSubscription subscriptions; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_mvvm_imgur); // ButterKnife.bind(this); // // MvvmAdapter adapter = new MvvmAdapter(this); // recyclerView.setAdapter(adapter); // recyclerView.setLayoutManager(new LinearLayoutManager(this)); // radioGroup.setOnCheckedChangeListener((group, checkedId) -> { // switch (checkedId) { // case R.id.radioButtonAll: // viewModel.modifyVisibleType(MvvmViewModel.VisibleType.ALL); // break; // case R.id.radioButtonOdd: // viewModel.modifyVisibleType(MvvmViewModel.VisibleType.ODD); // break; // case R.id.radioButtonEven: // viewModel.modifyVisibleType(MvvmViewModel.VisibleType.EVEN); // break; // default: // break; // } // }); // // onInject(); // // subscriptions = new CompositeSubscription(); // // subscriptions.add(viewModel.getPosts() // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(adapter::setDatas, this::showError)); // // subscriptions.add(viewModel.getCounts() // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(pair -> { // textViewResult.setText(String.format("앨범 %d개, 앨범아닌건 %d개", pair.first, pair.second)); // }, this::showError)); // // viewModel.refresh(); // } // // @Override // protected void onDestroy() { // subscriptions.unsubscribe(); // super.onDestroy(); // } // // void onInject() { // DaggerActivityComponent // .builder() // .applicationComponent(((SampleApplication)getApplication()).getApplicationComponent()) // .activityModule(new ActivityModule(this)) // .build() // .inject(this); // } // // void showError(Throwable throwable) { // Toast.makeText(this, throwable.getMessage(), Toast.LENGTH_LONG).show(); // } // // }
import com.gdgand.rxjava.rxjavasample.hotandcold.di.PerActivity; import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.ActivityModule; import com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvp.imgur.ImgurActivity; import com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvvm.imgur.MvvmActivity; import dagger.Component;
package com.gdgand.rxjava.rxjavasample.hotandcold.di.component; @PerActivity @Component(dependencies = { ApplicationComponent.class }, modules = { ActivityModule.class }) public interface ActivityComponent { void inject(MvvmActivity activity);
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/module/ActivityModule.java // @Module // public class ActivityModule { // // private Activity activity; // // public ActivityModule(Activity activity) { // this.activity = activity; // } // // @Provides // @PerActivity // public Activity activity() { // return activity; // } // // @Provides // @PerActivity // public ProgressIndicatorProvider progressIndicatorProvider(Activity activity) { // return new ProgressIndicatorProvider(activity); // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/imgur/ImgurActivity.java // public class ImgurActivity extends BaseMvpActivity implements ImgurMvpView { // // @Inject // ImgurMvpPresenter presenter; // // @BindView(R.id.recyclerView) // RecyclerView recyclerView; // // private ImgurAdapter adapter; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_mvp_imgur); // ButterKnife.bind(this); // // adapter = new ImgurAdapter(this); // recyclerView.setAdapter(adapter); // recyclerView.setLayoutManager(new LinearLayoutManager(this)); // // onInject(); // // presenter.attachView(this); // presenter.refreshTopics(); // } // // @Override // protected void onDestroy() { // presenter.detachView(); // super.onDestroy(); // } // // @OnClick(R.id.buttonSubmit) // void clickSubmit() { // presenter.refreshTopics(); // } // // @Override // public void showTopics(List<Topic> topics) { // adapter.setDatas(topics); // } // // void onInject() { // DaggerActivityComponent // .builder() // .applicationComponent(((SampleApplication)getApplication()).getApplicationComponent()) // .activityModule(new ActivityModule(this)) // .build() // .inject(this); // } // // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvvm/imgur/MvvmActivity.java // public class MvvmActivity extends AppCompatActivity { // // @Inject // MvvmViewModel viewModel; // // @BindView(R.id.textViewResult) // TextView textViewResult; // // @BindView(R.id.recyclerView) // RecyclerView recyclerView; // // @BindView(R.id.radioGroup) // RadioGroup radioGroup; // // CompositeSubscription subscriptions; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_mvvm_imgur); // ButterKnife.bind(this); // // MvvmAdapter adapter = new MvvmAdapter(this); // recyclerView.setAdapter(adapter); // recyclerView.setLayoutManager(new LinearLayoutManager(this)); // radioGroup.setOnCheckedChangeListener((group, checkedId) -> { // switch (checkedId) { // case R.id.radioButtonAll: // viewModel.modifyVisibleType(MvvmViewModel.VisibleType.ALL); // break; // case R.id.radioButtonOdd: // viewModel.modifyVisibleType(MvvmViewModel.VisibleType.ODD); // break; // case R.id.radioButtonEven: // viewModel.modifyVisibleType(MvvmViewModel.VisibleType.EVEN); // break; // default: // break; // } // }); // // onInject(); // // subscriptions = new CompositeSubscription(); // // subscriptions.add(viewModel.getPosts() // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(adapter::setDatas, this::showError)); // // subscriptions.add(viewModel.getCounts() // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(pair -> { // textViewResult.setText(String.format("앨범 %d개, 앨범아닌건 %d개", pair.first, pair.second)); // }, this::showError)); // // viewModel.refresh(); // } // // @Override // protected void onDestroy() { // subscriptions.unsubscribe(); // super.onDestroy(); // } // // void onInject() { // DaggerActivityComponent // .builder() // .applicationComponent(((SampleApplication)getApplication()).getApplicationComponent()) // .activityModule(new ActivityModule(this)) // .build() // .inject(this); // } // // void showError(Throwable throwable) { // Toast.makeText(this, throwable.getMessage(), Toast.LENGTH_LONG).show(); // } // // } // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/component/ActivityComponent.java import com.gdgand.rxjava.rxjavasample.hotandcold.di.PerActivity; import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.ActivityModule; import com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvp.imgur.ImgurActivity; import com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvvm.imgur.MvvmActivity; import dagger.Component; package com.gdgand.rxjava.rxjavasample.hotandcold.di.component; @PerActivity @Component(dependencies = { ApplicationComponent.class }, modules = { ActivityModule.class }) public interface ActivityComponent { void inject(MvvmActivity activity);
void inject(ImgurActivity activity);
gdgand/android-rxjava
2016-07-12_rxjava_in_action/src/main/java/com/androidhuman/example/rxjavainaction/rx/ChecksBalanceOnSubscribe.java
// Path: 2016-07-12_rxjava_in_action/src/main/java/com/androidhuman/example/rxjavainaction/error/InsufficientBalanceError.java // public final class InsufficientBalanceError extends Error { // // private int amount; // // public InsufficientBalanceError(int amount) { // this.amount = amount; // } // // public int getAmount() { // return amount; // } // }
import com.androidhuman.example.rxjavainaction.error.InsufficientBalanceError; import com.androidhuman.example.rxjavainaction.model.Content; import com.androidhuman.example.rxjavainaction.model.User; import rx.Observable; import rx.Subscriber;
package com.androidhuman.example.rxjavainaction.rx; final class ChecksBalanceOnSubscribe implements Observable.OnSubscribe<Void> { private final Content content; private final User user; ChecksBalanceOnSubscribe(Content content, User user) { this.content = content; this.user = user; } @Override public void call(Subscriber<? super Void> subscriber) { if (!subscriber.isUnsubscribed()) { if (content.getPrice() <= user.getBalance()) { // Can purchase a content subscriber.onNext(null); subscriber.onCompleted(); } else { // Cannot purchase a content; balance is low subscriber.onError(
// Path: 2016-07-12_rxjava_in_action/src/main/java/com/androidhuman/example/rxjavainaction/error/InsufficientBalanceError.java // public final class InsufficientBalanceError extends Error { // // private int amount; // // public InsufficientBalanceError(int amount) { // this.amount = amount; // } // // public int getAmount() { // return amount; // } // } // Path: 2016-07-12_rxjava_in_action/src/main/java/com/androidhuman/example/rxjavainaction/rx/ChecksBalanceOnSubscribe.java import com.androidhuman.example.rxjavainaction.error.InsufficientBalanceError; import com.androidhuman.example.rxjavainaction.model.Content; import com.androidhuman.example.rxjavainaction.model.User; import rx.Observable; import rx.Subscriber; package com.androidhuman.example.rxjavainaction.rx; final class ChecksBalanceOnSubscribe implements Observable.OnSubscribe<Void> { private final Content content; private final User user; ChecksBalanceOnSubscribe(Content content, User user) { this.content = content; this.user = user; } @Override public void call(Subscriber<? super Void> subscriber) { if (!subscriber.isUnsubscribed()) { if (content.getPrice() <= user.getBalance()) { // Can purchase a content subscriber.onNext(null); subscriber.onCompleted(); } else { // Cannot purchase a content; balance is low subscriber.onError(
new InsufficientBalanceError(content.getPrice() - user.getBalance()));
gdgand/android-rxjava
2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/imgur/ImgurMvpPresenterTest.java
// Path: 2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/TestSchedulerProxy.java // public class TestSchedulerProxy { // // private static final TestScheduler SCHEDULER = new TestScheduler(); // private static final TestSchedulerProxy INSTANCE = new TestSchedulerProxy(); // // static { // try { // RxJavaPlugins.getInstance().registerSchedulersHook(new RxJavaSchedulersHook() { // @Override // public Scheduler getIOScheduler() { // return SCHEDULER; // } // // @Override // public Scheduler getComputationScheduler() { // return SCHEDULER; // } // // @Override // public Scheduler getNewThreadScheduler() { // return SCHEDULER; // } // }); // // RxAndroidPlugins.getInstance().registerSchedulersHook(new RxAndroidSchedulersHook() { // @Override // public Scheduler getMainThreadScheduler() { // return SCHEDULER; // } // }); // } catch (IllegalStateException e) { // throw new IllegalStateException("Schedulers class already initialized. " + // "Ensure you always use the TestSchedulerProxy in unit tests."); // } // } // // public static TestSchedulerProxy get() { // return INSTANCE; // } // // public void advanceBy(long delayTime, TimeUnit unit) { // SCHEDULER.advanceTimeBy(delayTime, unit); // } // // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/ImgurApi.java // public interface ImgurApi { // // @GET("/3/topics/defaults") // Observable<TopicResponse> defaultTopics(); // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/Topic.java // public class Topic { // private long id; // // private String name; // // private String description; // // private TopPost topPost; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public TopPost getTopPost() { // return topPost; // } // // public void setTopPost(TopPost topPost) { // this.topPost = topPost; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/TopicResponse.java // public class TopicResponse { // // private List<Topic> data; // // public void setData(List<Topic> data) { // this.data = data; // } // // public List<Topic> getData() { // return data; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/TestTransformer.java // public static <T> Observable.Transformer<T, T> pass() { // return observable -> observable; // }
import com.google.common.collect.Lists; import com.gdgand.rxjava.rxjavasample.hotandcold.TestSchedulerProxy; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.ImgurApi; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.Topic; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.TopicResponse; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.List; import java.util.concurrent.TimeUnit; import rx.Observable; import static com.gdgand.rxjava.rxjavasample.hotandcold.TestTransformer.pass; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify;
package com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvp.imgur; @RunWith(MockitoJUnitRunner.class) @Ignore("java.lang.IllegalStateException at ImgurMvpPresenterTest.java:52") public class ImgurMvpPresenterTest { @Mock
// Path: 2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/TestSchedulerProxy.java // public class TestSchedulerProxy { // // private static final TestScheduler SCHEDULER = new TestScheduler(); // private static final TestSchedulerProxy INSTANCE = new TestSchedulerProxy(); // // static { // try { // RxJavaPlugins.getInstance().registerSchedulersHook(new RxJavaSchedulersHook() { // @Override // public Scheduler getIOScheduler() { // return SCHEDULER; // } // // @Override // public Scheduler getComputationScheduler() { // return SCHEDULER; // } // // @Override // public Scheduler getNewThreadScheduler() { // return SCHEDULER; // } // }); // // RxAndroidPlugins.getInstance().registerSchedulersHook(new RxAndroidSchedulersHook() { // @Override // public Scheduler getMainThreadScheduler() { // return SCHEDULER; // } // }); // } catch (IllegalStateException e) { // throw new IllegalStateException("Schedulers class already initialized. " + // "Ensure you always use the TestSchedulerProxy in unit tests."); // } // } // // public static TestSchedulerProxy get() { // return INSTANCE; // } // // public void advanceBy(long delayTime, TimeUnit unit) { // SCHEDULER.advanceTimeBy(delayTime, unit); // } // // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/ImgurApi.java // public interface ImgurApi { // // @GET("/3/topics/defaults") // Observable<TopicResponse> defaultTopics(); // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/Topic.java // public class Topic { // private long id; // // private String name; // // private String description; // // private TopPost topPost; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public TopPost getTopPost() { // return topPost; // } // // public void setTopPost(TopPost topPost) { // this.topPost = topPost; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/TopicResponse.java // public class TopicResponse { // // private List<Topic> data; // // public void setData(List<Topic> data) { // this.data = data; // } // // public List<Topic> getData() { // return data; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/TestTransformer.java // public static <T> Observable.Transformer<T, T> pass() { // return observable -> observable; // } // Path: 2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/imgur/ImgurMvpPresenterTest.java import com.google.common.collect.Lists; import com.gdgand.rxjava.rxjavasample.hotandcold.TestSchedulerProxy; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.ImgurApi; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.Topic; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.TopicResponse; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.List; import java.util.concurrent.TimeUnit; import rx.Observable; import static com.gdgand.rxjava.rxjavasample.hotandcold.TestTransformer.pass; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; package com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvp.imgur; @RunWith(MockitoJUnitRunner.class) @Ignore("java.lang.IllegalStateException at ImgurMvpPresenterTest.java:52") public class ImgurMvpPresenterTest { @Mock
ImgurApi imgurApi;
gdgand/android-rxjava
2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/imgur/ImgurMvpPresenterTest.java
// Path: 2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/TestSchedulerProxy.java // public class TestSchedulerProxy { // // private static final TestScheduler SCHEDULER = new TestScheduler(); // private static final TestSchedulerProxy INSTANCE = new TestSchedulerProxy(); // // static { // try { // RxJavaPlugins.getInstance().registerSchedulersHook(new RxJavaSchedulersHook() { // @Override // public Scheduler getIOScheduler() { // return SCHEDULER; // } // // @Override // public Scheduler getComputationScheduler() { // return SCHEDULER; // } // // @Override // public Scheduler getNewThreadScheduler() { // return SCHEDULER; // } // }); // // RxAndroidPlugins.getInstance().registerSchedulersHook(new RxAndroidSchedulersHook() { // @Override // public Scheduler getMainThreadScheduler() { // return SCHEDULER; // } // }); // } catch (IllegalStateException e) { // throw new IllegalStateException("Schedulers class already initialized. " + // "Ensure you always use the TestSchedulerProxy in unit tests."); // } // } // // public static TestSchedulerProxy get() { // return INSTANCE; // } // // public void advanceBy(long delayTime, TimeUnit unit) { // SCHEDULER.advanceTimeBy(delayTime, unit); // } // // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/ImgurApi.java // public interface ImgurApi { // // @GET("/3/topics/defaults") // Observable<TopicResponse> defaultTopics(); // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/Topic.java // public class Topic { // private long id; // // private String name; // // private String description; // // private TopPost topPost; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public TopPost getTopPost() { // return topPost; // } // // public void setTopPost(TopPost topPost) { // this.topPost = topPost; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/TopicResponse.java // public class TopicResponse { // // private List<Topic> data; // // public void setData(List<Topic> data) { // this.data = data; // } // // public List<Topic> getData() { // return data; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/TestTransformer.java // public static <T> Observable.Transformer<T, T> pass() { // return observable -> observable; // }
import com.google.common.collect.Lists; import com.gdgand.rxjava.rxjavasample.hotandcold.TestSchedulerProxy; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.ImgurApi; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.Topic; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.TopicResponse; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.List; import java.util.concurrent.TimeUnit; import rx.Observable; import static com.gdgand.rxjava.rxjavasample.hotandcold.TestTransformer.pass; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify;
package com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvp.imgur; @RunWith(MockitoJUnitRunner.class) @Ignore("java.lang.IllegalStateException at ImgurMvpPresenterTest.java:52") public class ImgurMvpPresenterTest { @Mock ImgurApi imgurApi; @Mock ImgurMvpView view; @InjectMocks ImgurMvpPresenter presenter; @Before public void setup() { presenter.attachView(view);
// Path: 2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/TestSchedulerProxy.java // public class TestSchedulerProxy { // // private static final TestScheduler SCHEDULER = new TestScheduler(); // private static final TestSchedulerProxy INSTANCE = new TestSchedulerProxy(); // // static { // try { // RxJavaPlugins.getInstance().registerSchedulersHook(new RxJavaSchedulersHook() { // @Override // public Scheduler getIOScheduler() { // return SCHEDULER; // } // // @Override // public Scheduler getComputationScheduler() { // return SCHEDULER; // } // // @Override // public Scheduler getNewThreadScheduler() { // return SCHEDULER; // } // }); // // RxAndroidPlugins.getInstance().registerSchedulersHook(new RxAndroidSchedulersHook() { // @Override // public Scheduler getMainThreadScheduler() { // return SCHEDULER; // } // }); // } catch (IllegalStateException e) { // throw new IllegalStateException("Schedulers class already initialized. " + // "Ensure you always use the TestSchedulerProxy in unit tests."); // } // } // // public static TestSchedulerProxy get() { // return INSTANCE; // } // // public void advanceBy(long delayTime, TimeUnit unit) { // SCHEDULER.advanceTimeBy(delayTime, unit); // } // // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/ImgurApi.java // public interface ImgurApi { // // @GET("/3/topics/defaults") // Observable<TopicResponse> defaultTopics(); // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/Topic.java // public class Topic { // private long id; // // private String name; // // private String description; // // private TopPost topPost; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public TopPost getTopPost() { // return topPost; // } // // public void setTopPost(TopPost topPost) { // this.topPost = topPost; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/TopicResponse.java // public class TopicResponse { // // private List<Topic> data; // // public void setData(List<Topic> data) { // this.data = data; // } // // public List<Topic> getData() { // return data; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/TestTransformer.java // public static <T> Observable.Transformer<T, T> pass() { // return observable -> observable; // } // Path: 2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/imgur/ImgurMvpPresenterTest.java import com.google.common.collect.Lists; import com.gdgand.rxjava.rxjavasample.hotandcold.TestSchedulerProxy; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.ImgurApi; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.Topic; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.TopicResponse; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.List; import java.util.concurrent.TimeUnit; import rx.Observable; import static com.gdgand.rxjava.rxjavasample.hotandcold.TestTransformer.pass; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; package com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvp.imgur; @RunWith(MockitoJUnitRunner.class) @Ignore("java.lang.IllegalStateException at ImgurMvpPresenterTest.java:52") public class ImgurMvpPresenterTest { @Mock ImgurApi imgurApi; @Mock ImgurMvpView view; @InjectMocks ImgurMvpPresenter presenter; @Before public void setup() { presenter.attachView(view);
given(view.bind()).willReturn(pass());
gdgand/android-rxjava
2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/imgur/ImgurMvpPresenterTest.java
// Path: 2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/TestSchedulerProxy.java // public class TestSchedulerProxy { // // private static final TestScheduler SCHEDULER = new TestScheduler(); // private static final TestSchedulerProxy INSTANCE = new TestSchedulerProxy(); // // static { // try { // RxJavaPlugins.getInstance().registerSchedulersHook(new RxJavaSchedulersHook() { // @Override // public Scheduler getIOScheduler() { // return SCHEDULER; // } // // @Override // public Scheduler getComputationScheduler() { // return SCHEDULER; // } // // @Override // public Scheduler getNewThreadScheduler() { // return SCHEDULER; // } // }); // // RxAndroidPlugins.getInstance().registerSchedulersHook(new RxAndroidSchedulersHook() { // @Override // public Scheduler getMainThreadScheduler() { // return SCHEDULER; // } // }); // } catch (IllegalStateException e) { // throw new IllegalStateException("Schedulers class already initialized. " + // "Ensure you always use the TestSchedulerProxy in unit tests."); // } // } // // public static TestSchedulerProxy get() { // return INSTANCE; // } // // public void advanceBy(long delayTime, TimeUnit unit) { // SCHEDULER.advanceTimeBy(delayTime, unit); // } // // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/ImgurApi.java // public interface ImgurApi { // // @GET("/3/topics/defaults") // Observable<TopicResponse> defaultTopics(); // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/Topic.java // public class Topic { // private long id; // // private String name; // // private String description; // // private TopPost topPost; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public TopPost getTopPost() { // return topPost; // } // // public void setTopPost(TopPost topPost) { // this.topPost = topPost; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/TopicResponse.java // public class TopicResponse { // // private List<Topic> data; // // public void setData(List<Topic> data) { // this.data = data; // } // // public List<Topic> getData() { // return data; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/TestTransformer.java // public static <T> Observable.Transformer<T, T> pass() { // return observable -> observable; // }
import com.google.common.collect.Lists; import com.gdgand.rxjava.rxjavasample.hotandcold.TestSchedulerProxy; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.ImgurApi; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.Topic; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.TopicResponse; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.List; import java.util.concurrent.TimeUnit; import rx.Observable; import static com.gdgand.rxjava.rxjavasample.hotandcold.TestTransformer.pass; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify;
package com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvp.imgur; @RunWith(MockitoJUnitRunner.class) @Ignore("java.lang.IllegalStateException at ImgurMvpPresenterTest.java:52") public class ImgurMvpPresenterTest { @Mock ImgurApi imgurApi; @Mock ImgurMvpView view; @InjectMocks ImgurMvpPresenter presenter; @Before public void setup() { presenter.attachView(view); given(view.bind()).willReturn(pass()); given(view.injectProgress()).willReturn(pass()); } @After public void finish() { presenter.detachView(); }
// Path: 2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/TestSchedulerProxy.java // public class TestSchedulerProxy { // // private static final TestScheduler SCHEDULER = new TestScheduler(); // private static final TestSchedulerProxy INSTANCE = new TestSchedulerProxy(); // // static { // try { // RxJavaPlugins.getInstance().registerSchedulersHook(new RxJavaSchedulersHook() { // @Override // public Scheduler getIOScheduler() { // return SCHEDULER; // } // // @Override // public Scheduler getComputationScheduler() { // return SCHEDULER; // } // // @Override // public Scheduler getNewThreadScheduler() { // return SCHEDULER; // } // }); // // RxAndroidPlugins.getInstance().registerSchedulersHook(new RxAndroidSchedulersHook() { // @Override // public Scheduler getMainThreadScheduler() { // return SCHEDULER; // } // }); // } catch (IllegalStateException e) { // throw new IllegalStateException("Schedulers class already initialized. " + // "Ensure you always use the TestSchedulerProxy in unit tests."); // } // } // // public static TestSchedulerProxy get() { // return INSTANCE; // } // // public void advanceBy(long delayTime, TimeUnit unit) { // SCHEDULER.advanceTimeBy(delayTime, unit); // } // // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/ImgurApi.java // public interface ImgurApi { // // @GET("/3/topics/defaults") // Observable<TopicResponse> defaultTopics(); // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/Topic.java // public class Topic { // private long id; // // private String name; // // private String description; // // private TopPost topPost; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public TopPost getTopPost() { // return topPost; // } // // public void setTopPost(TopPost topPost) { // this.topPost = topPost; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/TopicResponse.java // public class TopicResponse { // // private List<Topic> data; // // public void setData(List<Topic> data) { // this.data = data; // } // // public List<Topic> getData() { // return data; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/TestTransformer.java // public static <T> Observable.Transformer<T, T> pass() { // return observable -> observable; // } // Path: 2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/imgur/ImgurMvpPresenterTest.java import com.google.common.collect.Lists; import com.gdgand.rxjava.rxjavasample.hotandcold.TestSchedulerProxy; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.ImgurApi; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.Topic; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.TopicResponse; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.List; import java.util.concurrent.TimeUnit; import rx.Observable; import static com.gdgand.rxjava.rxjavasample.hotandcold.TestTransformer.pass; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; package com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvp.imgur; @RunWith(MockitoJUnitRunner.class) @Ignore("java.lang.IllegalStateException at ImgurMvpPresenterTest.java:52") public class ImgurMvpPresenterTest { @Mock ImgurApi imgurApi; @Mock ImgurMvpView view; @InjectMocks ImgurMvpPresenter presenter; @Before public void setup() { presenter.attachView(view); given(view.bind()).willReturn(pass()); given(view.injectProgress()).willReturn(pass()); } @After public void finish() { presenter.detachView(); }
TestSchedulerProxy proxy = TestSchedulerProxy.get();
gdgand/android-rxjava
2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/imgur/ImgurMvpPresenterTest.java
// Path: 2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/TestSchedulerProxy.java // public class TestSchedulerProxy { // // private static final TestScheduler SCHEDULER = new TestScheduler(); // private static final TestSchedulerProxy INSTANCE = new TestSchedulerProxy(); // // static { // try { // RxJavaPlugins.getInstance().registerSchedulersHook(new RxJavaSchedulersHook() { // @Override // public Scheduler getIOScheduler() { // return SCHEDULER; // } // // @Override // public Scheduler getComputationScheduler() { // return SCHEDULER; // } // // @Override // public Scheduler getNewThreadScheduler() { // return SCHEDULER; // } // }); // // RxAndroidPlugins.getInstance().registerSchedulersHook(new RxAndroidSchedulersHook() { // @Override // public Scheduler getMainThreadScheduler() { // return SCHEDULER; // } // }); // } catch (IllegalStateException e) { // throw new IllegalStateException("Schedulers class already initialized. " + // "Ensure you always use the TestSchedulerProxy in unit tests."); // } // } // // public static TestSchedulerProxy get() { // return INSTANCE; // } // // public void advanceBy(long delayTime, TimeUnit unit) { // SCHEDULER.advanceTimeBy(delayTime, unit); // } // // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/ImgurApi.java // public interface ImgurApi { // // @GET("/3/topics/defaults") // Observable<TopicResponse> defaultTopics(); // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/Topic.java // public class Topic { // private long id; // // private String name; // // private String description; // // private TopPost topPost; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public TopPost getTopPost() { // return topPost; // } // // public void setTopPost(TopPost topPost) { // this.topPost = topPost; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/TopicResponse.java // public class TopicResponse { // // private List<Topic> data; // // public void setData(List<Topic> data) { // this.data = data; // } // // public List<Topic> getData() { // return data; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/TestTransformer.java // public static <T> Observable.Transformer<T, T> pass() { // return observable -> observable; // }
import com.google.common.collect.Lists; import com.gdgand.rxjava.rxjavasample.hotandcold.TestSchedulerProxy; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.ImgurApi; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.Topic; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.TopicResponse; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.List; import java.util.concurrent.TimeUnit; import rx.Observable; import static com.gdgand.rxjava.rxjavasample.hotandcold.TestTransformer.pass; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify;
package com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvp.imgur; @RunWith(MockitoJUnitRunner.class) @Ignore("java.lang.IllegalStateException at ImgurMvpPresenterTest.java:52") public class ImgurMvpPresenterTest { @Mock ImgurApi imgurApi; @Mock ImgurMvpView view; @InjectMocks ImgurMvpPresenter presenter; @Before public void setup() { presenter.attachView(view); given(view.bind()).willReturn(pass()); given(view.injectProgress()).willReturn(pass()); } @After public void finish() { presenter.detachView(); } TestSchedulerProxy proxy = TestSchedulerProxy.get(); @Test public void testRefreshTopics() throws Exception { // given
// Path: 2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/TestSchedulerProxy.java // public class TestSchedulerProxy { // // private static final TestScheduler SCHEDULER = new TestScheduler(); // private static final TestSchedulerProxy INSTANCE = new TestSchedulerProxy(); // // static { // try { // RxJavaPlugins.getInstance().registerSchedulersHook(new RxJavaSchedulersHook() { // @Override // public Scheduler getIOScheduler() { // return SCHEDULER; // } // // @Override // public Scheduler getComputationScheduler() { // return SCHEDULER; // } // // @Override // public Scheduler getNewThreadScheduler() { // return SCHEDULER; // } // }); // // RxAndroidPlugins.getInstance().registerSchedulersHook(new RxAndroidSchedulersHook() { // @Override // public Scheduler getMainThreadScheduler() { // return SCHEDULER; // } // }); // } catch (IllegalStateException e) { // throw new IllegalStateException("Schedulers class already initialized. " + // "Ensure you always use the TestSchedulerProxy in unit tests."); // } // } // // public static TestSchedulerProxy get() { // return INSTANCE; // } // // public void advanceBy(long delayTime, TimeUnit unit) { // SCHEDULER.advanceTimeBy(delayTime, unit); // } // // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/ImgurApi.java // public interface ImgurApi { // // @GET("/3/topics/defaults") // Observable<TopicResponse> defaultTopics(); // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/Topic.java // public class Topic { // private long id; // // private String name; // // private String description; // // private TopPost topPost; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public TopPost getTopPost() { // return topPost; // } // // public void setTopPost(TopPost topPost) { // this.topPost = topPost; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/TopicResponse.java // public class TopicResponse { // // private List<Topic> data; // // public void setData(List<Topic> data) { // this.data = data; // } // // public List<Topic> getData() { // return data; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/TestTransformer.java // public static <T> Observable.Transformer<T, T> pass() { // return observable -> observable; // } // Path: 2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/imgur/ImgurMvpPresenterTest.java import com.google.common.collect.Lists; import com.gdgand.rxjava.rxjavasample.hotandcold.TestSchedulerProxy; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.ImgurApi; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.Topic; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.TopicResponse; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.List; import java.util.concurrent.TimeUnit; import rx.Observable; import static com.gdgand.rxjava.rxjavasample.hotandcold.TestTransformer.pass; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; package com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvp.imgur; @RunWith(MockitoJUnitRunner.class) @Ignore("java.lang.IllegalStateException at ImgurMvpPresenterTest.java:52") public class ImgurMvpPresenterTest { @Mock ImgurApi imgurApi; @Mock ImgurMvpView view; @InjectMocks ImgurMvpPresenter presenter; @Before public void setup() { presenter.attachView(view); given(view.bind()).willReturn(pass()); given(view.injectProgress()).willReturn(pass()); } @After public void finish() { presenter.detachView(); } TestSchedulerProxy proxy = TestSchedulerProxy.get(); @Test public void testRefreshTopics() throws Exception { // given
TopicResponse response = new TopicResponse();
gdgand/android-rxjava
2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/imgur/ImgurMvpPresenterTest.java
// Path: 2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/TestSchedulerProxy.java // public class TestSchedulerProxy { // // private static final TestScheduler SCHEDULER = new TestScheduler(); // private static final TestSchedulerProxy INSTANCE = new TestSchedulerProxy(); // // static { // try { // RxJavaPlugins.getInstance().registerSchedulersHook(new RxJavaSchedulersHook() { // @Override // public Scheduler getIOScheduler() { // return SCHEDULER; // } // // @Override // public Scheduler getComputationScheduler() { // return SCHEDULER; // } // // @Override // public Scheduler getNewThreadScheduler() { // return SCHEDULER; // } // }); // // RxAndroidPlugins.getInstance().registerSchedulersHook(new RxAndroidSchedulersHook() { // @Override // public Scheduler getMainThreadScheduler() { // return SCHEDULER; // } // }); // } catch (IllegalStateException e) { // throw new IllegalStateException("Schedulers class already initialized. " + // "Ensure you always use the TestSchedulerProxy in unit tests."); // } // } // // public static TestSchedulerProxy get() { // return INSTANCE; // } // // public void advanceBy(long delayTime, TimeUnit unit) { // SCHEDULER.advanceTimeBy(delayTime, unit); // } // // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/ImgurApi.java // public interface ImgurApi { // // @GET("/3/topics/defaults") // Observable<TopicResponse> defaultTopics(); // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/Topic.java // public class Topic { // private long id; // // private String name; // // private String description; // // private TopPost topPost; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public TopPost getTopPost() { // return topPost; // } // // public void setTopPost(TopPost topPost) { // this.topPost = topPost; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/TopicResponse.java // public class TopicResponse { // // private List<Topic> data; // // public void setData(List<Topic> data) { // this.data = data; // } // // public List<Topic> getData() { // return data; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/TestTransformer.java // public static <T> Observable.Transformer<T, T> pass() { // return observable -> observable; // }
import com.google.common.collect.Lists; import com.gdgand.rxjava.rxjavasample.hotandcold.TestSchedulerProxy; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.ImgurApi; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.Topic; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.TopicResponse; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.List; import java.util.concurrent.TimeUnit; import rx.Observable; import static com.gdgand.rxjava.rxjavasample.hotandcold.TestTransformer.pass; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify;
package com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvp.imgur; @RunWith(MockitoJUnitRunner.class) @Ignore("java.lang.IllegalStateException at ImgurMvpPresenterTest.java:52") public class ImgurMvpPresenterTest { @Mock ImgurApi imgurApi; @Mock ImgurMvpView view; @InjectMocks ImgurMvpPresenter presenter; @Before public void setup() { presenter.attachView(view); given(view.bind()).willReturn(pass()); given(view.injectProgress()).willReturn(pass()); } @After public void finish() { presenter.detachView(); } TestSchedulerProxy proxy = TestSchedulerProxy.get(); @Test public void testRefreshTopics() throws Exception { // given TopicResponse response = new TopicResponse();
// Path: 2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/TestSchedulerProxy.java // public class TestSchedulerProxy { // // private static final TestScheduler SCHEDULER = new TestScheduler(); // private static final TestSchedulerProxy INSTANCE = new TestSchedulerProxy(); // // static { // try { // RxJavaPlugins.getInstance().registerSchedulersHook(new RxJavaSchedulersHook() { // @Override // public Scheduler getIOScheduler() { // return SCHEDULER; // } // // @Override // public Scheduler getComputationScheduler() { // return SCHEDULER; // } // // @Override // public Scheduler getNewThreadScheduler() { // return SCHEDULER; // } // }); // // RxAndroidPlugins.getInstance().registerSchedulersHook(new RxAndroidSchedulersHook() { // @Override // public Scheduler getMainThreadScheduler() { // return SCHEDULER; // } // }); // } catch (IllegalStateException e) { // throw new IllegalStateException("Schedulers class already initialized. " + // "Ensure you always use the TestSchedulerProxy in unit tests."); // } // } // // public static TestSchedulerProxy get() { // return INSTANCE; // } // // public void advanceBy(long delayTime, TimeUnit unit) { // SCHEDULER.advanceTimeBy(delayTime, unit); // } // // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/ImgurApi.java // public interface ImgurApi { // // @GET("/3/topics/defaults") // Observable<TopicResponse> defaultTopics(); // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/Topic.java // public class Topic { // private long id; // // private String name; // // private String description; // // private TopPost topPost; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public TopPost getTopPost() { // return topPost; // } // // public void setTopPost(TopPost topPost) { // this.topPost = topPost; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/TopicResponse.java // public class TopicResponse { // // private List<Topic> data; // // public void setData(List<Topic> data) { // this.data = data; // } // // public List<Topic> getData() { // return data; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/TestTransformer.java // public static <T> Observable.Transformer<T, T> pass() { // return observable -> observable; // } // Path: 2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/imgur/ImgurMvpPresenterTest.java import com.google.common.collect.Lists; import com.gdgand.rxjava.rxjavasample.hotandcold.TestSchedulerProxy; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.ImgurApi; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.Topic; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.TopicResponse; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.List; import java.util.concurrent.TimeUnit; import rx.Observable; import static com.gdgand.rxjava.rxjavasample.hotandcold.TestTransformer.pass; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; package com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvp.imgur; @RunWith(MockitoJUnitRunner.class) @Ignore("java.lang.IllegalStateException at ImgurMvpPresenterTest.java:52") public class ImgurMvpPresenterTest { @Mock ImgurApi imgurApi; @Mock ImgurMvpView view; @InjectMocks ImgurMvpPresenter presenter; @Before public void setup() { presenter.attachView(view); given(view.bind()).willReturn(pass()); given(view.injectProgress()).willReturn(pass()); } @After public void finish() { presenter.detachView(); } TestSchedulerProxy proxy = TestSchedulerProxy.get(); @Test public void testRefreshTopics() throws Exception { // given TopicResponse response = new TopicResponse();
List<Topic> topics = Lists.newArrayList(new Topic(), new Topic(), new Topic());
gdgand/android-rxjava
2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/main/adapter/MainAdapter.java
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/views/recyclerview/RecyclerOnItemClickListener.java // public interface RecyclerOnItemClickListener { // // void onItemClick(RecyclerView.Adapter adapter, int position); // }
import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; import com.gdgand.rxjava.rxjavasample.hotandcold.R; import com.gdgand.rxjava.rxjavasample.hotandcold.views.recyclerview.RecyclerOnItemClickListener; import java.util.ArrayList; import java.util.List;
package com.gdgand.rxjava.rxjavasample.hotandcold.presentation.main.adapter; public class MainAdapter extends RecyclerView.Adapter<MainAdapter.MainViewHolder> { private List<String> textList; private Context context;
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/views/recyclerview/RecyclerOnItemClickListener.java // public interface RecyclerOnItemClickListener { // // void onItemClick(RecyclerView.Adapter adapter, int position); // } // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/main/adapter/MainAdapter.java import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; import com.gdgand.rxjava.rxjavasample.hotandcold.R; import com.gdgand.rxjava.rxjavasample.hotandcold.views.recyclerview.RecyclerOnItemClickListener; import java.util.ArrayList; import java.util.List; package com.gdgand.rxjava.rxjavasample.hotandcold.presentation.main.adapter; public class MainAdapter extends RecyclerView.Adapter<MainAdapter.MainViewHolder> { private List<String> textList; private Context context;
private RecyclerOnItemClickListener onItemClickListener;
gdgand/android-rxjava
2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/imgur/ImgurMvpPresenter.java
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/ImgurApi.java // public interface ImgurApi { // // @GET("/3/topics/defaults") // Observable<TopicResponse> defaultTopics(); // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/TopicResponse.java // public class TopicResponse { // // private List<Topic> data; // // public void setData(List<Topic> data) { // this.data = data; // } // // public List<Topic> getData() { // return data; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/BasePresenter.java // public abstract class BasePresenter<VIEW extends BaseMvpView> { // // private VIEW view; // // public void attachView(VIEW view) { // this.view = view; // } // // public void detachView() { // view = null; // } // // protected VIEW view() { // return view; // } // }
import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.ImgurApi; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.TopicResponse; import com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvp.BasePresenter; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import javax.inject.Inject;
package com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvp.imgur; public class ImgurMvpPresenter extends BasePresenter<ImgurMvpView> { private ImgurApi imgurApi; @Inject public ImgurMvpPresenter(ImgurApi imgurApi) { this.imgurApi = imgurApi; } public void refreshTopics() { imgurApi.defaultTopics()
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/ImgurApi.java // public interface ImgurApi { // // @GET("/3/topics/defaults") // Observable<TopicResponse> defaultTopics(); // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/TopicResponse.java // public class TopicResponse { // // private List<Topic> data; // // public void setData(List<Topic> data) { // this.data = data; // } // // public List<Topic> getData() { // return data; // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/BasePresenter.java // public abstract class BasePresenter<VIEW extends BaseMvpView> { // // private VIEW view; // // public void attachView(VIEW view) { // this.view = view; // } // // public void detachView() { // view = null; // } // // protected VIEW view() { // return view; // } // } // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/imgur/ImgurMvpPresenter.java import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.ImgurApi; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.TopicResponse; import com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvp.BasePresenter; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import javax.inject.Inject; package com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvp.imgur; public class ImgurMvpPresenter extends BasePresenter<ImgurMvpView> { private ImgurApi imgurApi; @Inject public ImgurMvpPresenter(ImgurApi imgurApi) { this.imgurApi = imgurApi; } public void refreshTopics() { imgurApi.defaultTopics()
.map(TopicResponse::getData)
gdgand/android-rxjava
2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/imgur/ImgurAdapter.java
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/Topic.java // public class Topic { // private long id; // // private String name; // // private String description; // // private TopPost topPost; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public TopPost getTopPost() { // return topPost; // } // // public void setTopPost(TopPost topPost) { // this.topPost = topPost; // } // }
import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; import com.gdgand.rxjava.rxjavasample.hotandcold.R; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.Topic; import java.util.Collections; import java.util.List;
package com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvp.imgur; public class ImgurAdapter extends RecyclerView.Adapter<ImgurAdapter.ViewHolder> { private Context context;
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/Topic.java // public class Topic { // private long id; // // private String name; // // private String description; // // private TopPost topPost; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public TopPost getTopPost() { // return topPost; // } // // public void setTopPost(TopPost topPost) { // this.topPost = topPost; // } // } // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/imgur/ImgurAdapter.java import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; import com.gdgand.rxjava.rxjavasample.hotandcold.R; import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.Topic; import java.util.Collections; import java.util.List; package com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvp.imgur; public class ImgurAdapter extends RecyclerView.Adapter<ImgurAdapter.ViewHolder> { private Context context;
private List<Topic> topics = Collections.emptyList();
gdgand/android-rxjava
2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/hotandcold/HotAndColdActivity.java
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/hotandcold/adapter/HotAndColdAdapter.java // public class HotAndColdAdapter extends RecyclerView.Adapter<HotAndColdAdapter.ViewHolder> { // // private Context context; // private List<String> items = new ArrayList<>(); // // public HotAndColdAdapter(Context context) { // this.context = context; // } // // public void clearItems() { // this.items = new ArrayList<>(); // notifyDataSetChanged(); // } // // public void addItem(String item) { // items.add(item); // notifyDataSetChanged(); // } // // @Override // public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // View view = LayoutInflater.from(context).inflate(R.layout.item_hot_and_cold, parent, false); // return new ViewHolder(view); // } // // @Override // public void onBindViewHolder(ViewHolder holder, int position) { // holder.textViewItem.setText(getItem(position)); // } // // public String getItem(int position) { // return items.get(position); // } // // @Override // public int getItemCount() { // return items.size(); // } // // static class ViewHolder extends RecyclerView.ViewHolder { // // @BindView(R.id.textViewItem) // TextView textViewItem; // // public ViewHolder(View itemView) { // super(itemView); // ButterKnife.bind(this, itemView); // } // } // }
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.widget.RadioGroup; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import com.gdgand.rxjava.rxjavasample.hotandcold.R; import com.gdgand.rxjava.rxjavasample.hotandcold.presentation.hotandcold.adapter.HotAndColdAdapter; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.subjects.ReplaySubject; import java.util.Random;
package com.gdgand.rxjava.rxjavasample.hotandcold.presentation.hotandcold; /** * ReplaySubject 에서 Hot And Cold Observable 동작 */ public class HotAndColdActivity extends AppCompatActivity { @BindView(R.id.radioGroup) RadioGroup radioGroup; @BindView(R.id.recyclerView1) RecyclerView recyclerView1; @BindView(R.id.recyclerView2) RecyclerView recyclerView2; ReplaySubject<Integer> subject = ReplaySubject.create();
// Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/hotandcold/adapter/HotAndColdAdapter.java // public class HotAndColdAdapter extends RecyclerView.Adapter<HotAndColdAdapter.ViewHolder> { // // private Context context; // private List<String> items = new ArrayList<>(); // // public HotAndColdAdapter(Context context) { // this.context = context; // } // // public void clearItems() { // this.items = new ArrayList<>(); // notifyDataSetChanged(); // } // // public void addItem(String item) { // items.add(item); // notifyDataSetChanged(); // } // // @Override // public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // View view = LayoutInflater.from(context).inflate(R.layout.item_hot_and_cold, parent, false); // return new ViewHolder(view); // } // // @Override // public void onBindViewHolder(ViewHolder holder, int position) { // holder.textViewItem.setText(getItem(position)); // } // // public String getItem(int position) { // return items.get(position); // } // // @Override // public int getItemCount() { // return items.size(); // } // // static class ViewHolder extends RecyclerView.ViewHolder { // // @BindView(R.id.textViewItem) // TextView textViewItem; // // public ViewHolder(View itemView) { // super(itemView); // ButterKnife.bind(this, itemView); // } // } // } // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/hotandcold/HotAndColdActivity.java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.widget.RadioGroup; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import com.gdgand.rxjava.rxjavasample.hotandcold.R; import com.gdgand.rxjava.rxjavasample.hotandcold.presentation.hotandcold.adapter.HotAndColdAdapter; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.subjects.ReplaySubject; import java.util.Random; package com.gdgand.rxjava.rxjavasample.hotandcold.presentation.hotandcold; /** * ReplaySubject 에서 Hot And Cold Observable 동작 */ public class HotAndColdActivity extends AppCompatActivity { @BindView(R.id.radioGroup) RadioGroup radioGroup; @BindView(R.id.recyclerView1) RecyclerView recyclerView1; @BindView(R.id.recyclerView2) RecyclerView recyclerView2; ReplaySubject<Integer> subject = ReplaySubject.create();
HotAndColdAdapter adapter1;
gdgand/android-rxjava
2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/main/adapter/MainAdapter.java
// Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/views/recyclerview/RecyclerOnItemClickListener.java // public interface RecyclerOnItemClickListener { // // void onItemClick(RecyclerView.Adapter adapter, int position); // }
import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.gdgand.rxjava.rxjavasample.R; import com.gdgand.rxjava.rxjavasample.views.recyclerview.RecyclerOnItemClickListener; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife;
package com.gdgand.rxjava.rxjavasample.main.adapter; public class MainAdapter extends RecyclerView.Adapter<MainAdapter.MainViewHolder> { private List<String> textList; private Context context;
// Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/views/recyclerview/RecyclerOnItemClickListener.java // public interface RecyclerOnItemClickListener { // // void onItemClick(RecyclerView.Adapter adapter, int position); // } // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/main/adapter/MainAdapter.java import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.gdgand.rxjava.rxjavasample.R; import com.gdgand.rxjava.rxjavasample.views.recyclerview.RecyclerOnItemClickListener; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; package com.gdgand.rxjava.rxjavasample.main.adapter; public class MainAdapter extends RecyclerView.Adapter<MainAdapter.MainViewHolder> { private List<String> textList; private Context context;
private RecyclerOnItemClickListener onItemClickListener;
gdgand/android-rxjava
2016-07-12_rxjava_in_action/src/test/java/com/androidhuman/example/rxjavainaction/rx/RxContentTestJava.java
// Path: 2016-07-12_rxjava_in_action/src/main/java/com/androidhuman/example/rxjavainaction/error/ContentNotAvailableError.java // public final class ContentNotAvailableError extends Error { // // } // // Path: 2016-07-12_rxjava_in_action/src/main/java/com/androidhuman/example/rxjavainaction/error/ContentRatingError.java // public final class ContentRatingError extends Error { // // } // // Path: 2016-07-12_rxjava_in_action/src/main/java/com/androidhuman/example/rxjavainaction/error/InsufficientBalanceError.java // public final class InsufficientBalanceError extends Error { // // private int amount; // // public InsufficientBalanceError(int amount) { // this.amount = amount; // } // // public int getAmount() { // return amount; // } // }
import com.androidhuman.example.rxjavainaction.error.ContentNotAvailableError; import com.androidhuman.example.rxjavainaction.error.ContentRatingError; import com.androidhuman.example.rxjavainaction.error.InsufficientBalanceError; import com.androidhuman.example.rxjavainaction.model.Content; import com.androidhuman.example.rxjavainaction.model.User; import org.junit.Test; import rx.Observable; import rx.Subscription; import rx.functions.Func3; import rx.observers.TestSubscriber; import static org.junit.Assert.assertEquals;
package com.androidhuman.example.rxjavainaction.rx; public class RxContentTestJava { @Test public void testChecksAvailability() { Content content = new Content("test", 100, true, false); TestSubscriber<Void> sub = new TestSubscriber<>(); Subscription s = RxContent.checksAvailability(content).subscribe(sub); s.unsubscribe(); sub.assertNoErrors(); sub.assertCompleted(); sub.assertValue(null); } @Test public void testChecksAvailability_notInService() { Content content = new Content("test", 100, false, false); TestSubscriber<Void> sub = new TestSubscriber<>(); Subscription s = RxContent.checksAvailability(content).subscribe(sub); s.unsubscribe();
// Path: 2016-07-12_rxjava_in_action/src/main/java/com/androidhuman/example/rxjavainaction/error/ContentNotAvailableError.java // public final class ContentNotAvailableError extends Error { // // } // // Path: 2016-07-12_rxjava_in_action/src/main/java/com/androidhuman/example/rxjavainaction/error/ContentRatingError.java // public final class ContentRatingError extends Error { // // } // // Path: 2016-07-12_rxjava_in_action/src/main/java/com/androidhuman/example/rxjavainaction/error/InsufficientBalanceError.java // public final class InsufficientBalanceError extends Error { // // private int amount; // // public InsufficientBalanceError(int amount) { // this.amount = amount; // } // // public int getAmount() { // return amount; // } // } // Path: 2016-07-12_rxjava_in_action/src/test/java/com/androidhuman/example/rxjavainaction/rx/RxContentTestJava.java import com.androidhuman.example.rxjavainaction.error.ContentNotAvailableError; import com.androidhuman.example.rxjavainaction.error.ContentRatingError; import com.androidhuman.example.rxjavainaction.error.InsufficientBalanceError; import com.androidhuman.example.rxjavainaction.model.Content; import com.androidhuman.example.rxjavainaction.model.User; import org.junit.Test; import rx.Observable; import rx.Subscription; import rx.functions.Func3; import rx.observers.TestSubscriber; import static org.junit.Assert.assertEquals; package com.androidhuman.example.rxjavainaction.rx; public class RxContentTestJava { @Test public void testChecksAvailability() { Content content = new Content("test", 100, true, false); TestSubscriber<Void> sub = new TestSubscriber<>(); Subscription s = RxContent.checksAvailability(content).subscribe(sub); s.unsubscribe(); sub.assertNoErrors(); sub.assertCompleted(); sub.assertValue(null); } @Test public void testChecksAvailability_notInService() { Content content = new Content("test", 100, false, false); TestSubscriber<Void> sub = new TestSubscriber<>(); Subscription s = RxContent.checksAvailability(content).subscribe(sub); s.unsubscribe();
sub.assertError(ContentNotAvailableError.class);
gdgand/android-rxjava
2016-07-12_rxjava_in_action/src/test/java/com/androidhuman/example/rxjavainaction/rx/RxContentTestJava.java
// Path: 2016-07-12_rxjava_in_action/src/main/java/com/androidhuman/example/rxjavainaction/error/ContentNotAvailableError.java // public final class ContentNotAvailableError extends Error { // // } // // Path: 2016-07-12_rxjava_in_action/src/main/java/com/androidhuman/example/rxjavainaction/error/ContentRatingError.java // public final class ContentRatingError extends Error { // // } // // Path: 2016-07-12_rxjava_in_action/src/main/java/com/androidhuman/example/rxjavainaction/error/InsufficientBalanceError.java // public final class InsufficientBalanceError extends Error { // // private int amount; // // public InsufficientBalanceError(int amount) { // this.amount = amount; // } // // public int getAmount() { // return amount; // } // }
import com.androidhuman.example.rxjavainaction.error.ContentNotAvailableError; import com.androidhuman.example.rxjavainaction.error.ContentRatingError; import com.androidhuman.example.rxjavainaction.error.InsufficientBalanceError; import com.androidhuman.example.rxjavainaction.model.Content; import com.androidhuman.example.rxjavainaction.model.User; import org.junit.Test; import rx.Observable; import rx.Subscription; import rx.functions.Func3; import rx.observers.TestSubscriber; import static org.junit.Assert.assertEquals;
TestSubscriber<Void> sub = new TestSubscriber<>(); Subscription s = RxContent.checksAvailability(content).subscribe(sub); s.unsubscribe(); sub.assertError(ContentNotAvailableError.class); } @Test public void testChecksBalance() { Content content = new Content("test", 100, true, false); User user = new User("Foobar", true, 100); TestSubscriber<Void> sub = new TestSubscriber<>(); Subscription s = RxContent.checksBalance(content, user).subscribe(sub); s.unsubscribe(); sub.assertNoErrors(); sub.assertCompleted(); sub.assertValue(null); } @Test public void testChecksBalance_lowBalance() { Content content = new Content("test", 100, true, false); User user = new User("Foobar", true, 99); TestSubscriber<Void> sub = new TestSubscriber<>(); Subscription s = RxContent.checksBalance(content, user).subscribe(sub); s.unsubscribe();
// Path: 2016-07-12_rxjava_in_action/src/main/java/com/androidhuman/example/rxjavainaction/error/ContentNotAvailableError.java // public final class ContentNotAvailableError extends Error { // // } // // Path: 2016-07-12_rxjava_in_action/src/main/java/com/androidhuman/example/rxjavainaction/error/ContentRatingError.java // public final class ContentRatingError extends Error { // // } // // Path: 2016-07-12_rxjava_in_action/src/main/java/com/androidhuman/example/rxjavainaction/error/InsufficientBalanceError.java // public final class InsufficientBalanceError extends Error { // // private int amount; // // public InsufficientBalanceError(int amount) { // this.amount = amount; // } // // public int getAmount() { // return amount; // } // } // Path: 2016-07-12_rxjava_in_action/src/test/java/com/androidhuman/example/rxjavainaction/rx/RxContentTestJava.java import com.androidhuman.example.rxjavainaction.error.ContentNotAvailableError; import com.androidhuman.example.rxjavainaction.error.ContentRatingError; import com.androidhuman.example.rxjavainaction.error.InsufficientBalanceError; import com.androidhuman.example.rxjavainaction.model.Content; import com.androidhuman.example.rxjavainaction.model.User; import org.junit.Test; import rx.Observable; import rx.Subscription; import rx.functions.Func3; import rx.observers.TestSubscriber; import static org.junit.Assert.assertEquals; TestSubscriber<Void> sub = new TestSubscriber<>(); Subscription s = RxContent.checksAvailability(content).subscribe(sub); s.unsubscribe(); sub.assertError(ContentNotAvailableError.class); } @Test public void testChecksBalance() { Content content = new Content("test", 100, true, false); User user = new User("Foobar", true, 100); TestSubscriber<Void> sub = new TestSubscriber<>(); Subscription s = RxContent.checksBalance(content, user).subscribe(sub); s.unsubscribe(); sub.assertNoErrors(); sub.assertCompleted(); sub.assertValue(null); } @Test public void testChecksBalance_lowBalance() { Content content = new Content("test", 100, true, false); User user = new User("Foobar", true, 99); TestSubscriber<Void> sub = new TestSubscriber<>(); Subscription s = RxContent.checksBalance(content, user).subscribe(sub); s.unsubscribe();
sub.assertError(InsufficientBalanceError.class);
gdgand/android-rxjava
2016-07-12_rxjava_in_action/src/test/java/com/androidhuman/example/rxjavainaction/rx/RxContentTestJava.java
// Path: 2016-07-12_rxjava_in_action/src/main/java/com/androidhuman/example/rxjavainaction/error/ContentNotAvailableError.java // public final class ContentNotAvailableError extends Error { // // } // // Path: 2016-07-12_rxjava_in_action/src/main/java/com/androidhuman/example/rxjavainaction/error/ContentRatingError.java // public final class ContentRatingError extends Error { // // } // // Path: 2016-07-12_rxjava_in_action/src/main/java/com/androidhuman/example/rxjavainaction/error/InsufficientBalanceError.java // public final class InsufficientBalanceError extends Error { // // private int amount; // // public InsufficientBalanceError(int amount) { // this.amount = amount; // } // // public int getAmount() { // return amount; // } // }
import com.androidhuman.example.rxjavainaction.error.ContentNotAvailableError; import com.androidhuman.example.rxjavainaction.error.ContentRatingError; import com.androidhuman.example.rxjavainaction.error.InsufficientBalanceError; import com.androidhuman.example.rxjavainaction.model.Content; import com.androidhuman.example.rxjavainaction.model.User; import org.junit.Test; import rx.Observable; import rx.Subscription; import rx.functions.Func3; import rx.observers.TestSubscriber; import static org.junit.Assert.assertEquals;
sub.assertError(InsufficientBalanceError.class); //noinspection ThrowableResultOfMethodCallIgnored InsufficientBalanceError e = (InsufficientBalanceError) sub.getOnErrorEvents().get(0); assertEquals(1, e.getAmount()); } @Test public void testChecksContentRating() { Content content = new Content("test", 100, true, true); User user = new User("Foobar", true, 100); TestSubscriber<Void> sub = new TestSubscriber<>(); Subscription s = RxContent.checksContentRating(content, user).subscribe(sub); s.unsubscribe(); sub.assertNoErrors(); sub.assertCompleted(); sub.assertValue(null); } @Test public void testChecksContentRating_forbidden() { Content content = new Content("test", 100, true, true); User user = new User("Foobar", false, 100); TestSubscriber<Void> sub = new TestSubscriber<>(); Subscription s = RxContent.checksContentRating(content, user).subscribe(sub); s.unsubscribe();
// Path: 2016-07-12_rxjava_in_action/src/main/java/com/androidhuman/example/rxjavainaction/error/ContentNotAvailableError.java // public final class ContentNotAvailableError extends Error { // // } // // Path: 2016-07-12_rxjava_in_action/src/main/java/com/androidhuman/example/rxjavainaction/error/ContentRatingError.java // public final class ContentRatingError extends Error { // // } // // Path: 2016-07-12_rxjava_in_action/src/main/java/com/androidhuman/example/rxjavainaction/error/InsufficientBalanceError.java // public final class InsufficientBalanceError extends Error { // // private int amount; // // public InsufficientBalanceError(int amount) { // this.amount = amount; // } // // public int getAmount() { // return amount; // } // } // Path: 2016-07-12_rxjava_in_action/src/test/java/com/androidhuman/example/rxjavainaction/rx/RxContentTestJava.java import com.androidhuman.example.rxjavainaction.error.ContentNotAvailableError; import com.androidhuman.example.rxjavainaction.error.ContentRatingError; import com.androidhuman.example.rxjavainaction.error.InsufficientBalanceError; import com.androidhuman.example.rxjavainaction.model.Content; import com.androidhuman.example.rxjavainaction.model.User; import org.junit.Test; import rx.Observable; import rx.Subscription; import rx.functions.Func3; import rx.observers.TestSubscriber; import static org.junit.Assert.assertEquals; sub.assertError(InsufficientBalanceError.class); //noinspection ThrowableResultOfMethodCallIgnored InsufficientBalanceError e = (InsufficientBalanceError) sub.getOnErrorEvents().get(0); assertEquals(1, e.getAmount()); } @Test public void testChecksContentRating() { Content content = new Content("test", 100, true, true); User user = new User("Foobar", true, 100); TestSubscriber<Void> sub = new TestSubscriber<>(); Subscription s = RxContent.checksContentRating(content, user).subscribe(sub); s.unsubscribe(); sub.assertNoErrors(); sub.assertCompleted(); sub.assertValue(null); } @Test public void testChecksContentRating_forbidden() { Content content = new Content("test", 100, true, true); User user = new User("Foobar", false, 100); TestSubscriber<Void> sub = new TestSubscriber<>(); Subscription s = RxContent.checksContentRating(content, user).subscribe(sub); s.unsubscribe();
sub.assertError(ContentRatingError.class);
gdgand/android-rxjava
2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/scroll/adapter/FasterAdapter.java
// Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/scroll/realm/FasterListData.java // public class FasterListData extends RealmObject { // @PrimaryKey // private long position; // // public long getPosition() { // return position; // } // // public void setPosition(long position) { // this.position = position; // } // }
import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.gdgand.rxjava.rxjavasample.R; import com.gdgand.rxjava.rxjavasample.scroll.realm.FasterListData; import java.util.ArrayList; import java.util.List; import io.realm.Realm; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers;
package com.gdgand.rxjava.rxjavasample.scroll.adapter; public class FasterAdapter extends RecyclerView.Adapter<FasterListViewHolder> { private Context context; private List<String> list; public FasterAdapter(Context context) { this.context = context; list = new ArrayList<>(); } @Override public FasterListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.item_fasterlist, parent, false); return new FasterListViewHolder(view); } @Override public void onBindViewHolder(FasterListViewHolder holder, int position) { Observable.just(position) .subscribeOn(Schedulers.io()) .map(index -> { try { Realm realm = Realm.getDefaultInstance();
// Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/scroll/realm/FasterListData.java // public class FasterListData extends RealmObject { // @PrimaryKey // private long position; // // public long getPosition() { // return position; // } // // public void setPosition(long position) { // this.position = position; // } // } // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/scroll/adapter/FasterAdapter.java import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.gdgand.rxjava.rxjavasample.R; import com.gdgand.rxjava.rxjavasample.scroll.realm.FasterListData; import java.util.ArrayList; import java.util.List; import io.realm.Realm; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; package com.gdgand.rxjava.rxjavasample.scroll.adapter; public class FasterAdapter extends RecyclerView.Adapter<FasterListViewHolder> { private Context context; private List<String> list; public FasterAdapter(Context context) { this.context = context; list = new ArrayList<>(); } @Override public FasterListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.item_fasterlist, parent, false); return new FasterListViewHolder(view); } @Override public void onBindViewHolder(FasterListViewHolder holder, int position) { Observable.just(position) .subscribeOn(Schedulers.io()) .map(index -> { try { Realm realm = Realm.getDefaultInstance();
long count = realm.where(FasterListData.class).greaterThanOrEqualTo("position", position)
gdgand/android-rxjava
2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/Queue1Activity.java
// Path: 2016-06-08_queue/app/src/main/java-fcm/com/gdgand/rxjava/rxjavasample/fcm/message/event/NotificationEvent.java // public class NotificationEvent { // private String index; // private String message; // // public NotificationEvent(String index, String message) { // // this.index = index; // this.message = message; // } // // public String getIndex() { // return index; // } // // public void setIndex(String index) { // this.index = index; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // }
import android.app.Notification; import android.app.NotificationManager; import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.util.Pair; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.gdgand.rxjava.rxjavasample.R; import com.gdgand.rxjava.rxjavasample.fcm.message.event.NotificationEvent; import com.google.firebase.iid.FirebaseInstanceId; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import java.util.concurrent.TimeUnit; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import rx.subjects.PublishSubject;
setContentView(R.layout.activity_queue); ButterKnife.bind(this); initObject(); String token = FirebaseInstanceId.getInstance().getToken(); System.out.println("token : " + token); EventBus.getDefault().register(this); } @Override protected void onDestroy() { EventBus.getDefault().unregister(this); super.onDestroy(); } private void initObject() { notificationManager = ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)); subject = PublishSubject.create(); subject.onBackpressureBuffer() .throttleLast(700, TimeUnit.MILLISECONDS) .subscribe(pair -> { notifyMessage(pair.first, pair.second); }); } @Subscribe
// Path: 2016-06-08_queue/app/src/main/java-fcm/com/gdgand/rxjava/rxjavasample/fcm/message/event/NotificationEvent.java // public class NotificationEvent { // private String index; // private String message; // // public NotificationEvent(String index, String message) { // // this.index = index; // this.message = message; // } // // public String getIndex() { // return index; // } // // public void setIndex(String index) { // this.index = index; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // } // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/queue/Queue1Activity.java import android.app.Notification; import android.app.NotificationManager; import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.util.Pair; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.gdgand.rxjava.rxjavasample.R; import com.gdgand.rxjava.rxjavasample.fcm.message.event.NotificationEvent; import com.google.firebase.iid.FirebaseInstanceId; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import java.util.concurrent.TimeUnit; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import rx.subjects.PublishSubject; setContentView(R.layout.activity_queue); ButterKnife.bind(this); initObject(); String token = FirebaseInstanceId.getInstance().getToken(); System.out.println("token : " + token); EventBus.getDefault().register(this); } @Override protected void onDestroy() { EventBus.getDefault().unregister(this); super.onDestroy(); } private void initObject() { notificationManager = ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)); subject = PublishSubject.create(); subject.onBackpressureBuffer() .throttleLast(700, TimeUnit.MILLISECONDS) .subscribe(pair -> { notifyMessage(pair.first, pair.second); }); } @Subscribe
public void onNotificationEvent(NotificationEvent event) {
gdgand/android-rxjava
2016-07-12_rxjava_in_action/src/main/java/com/androidhuman/example/rxjavainaction/rx/ChecksContentRatingOnSubscribe.java
// Path: 2016-07-12_rxjava_in_action/src/main/java/com/androidhuman/example/rxjavainaction/error/ContentRatingError.java // public final class ContentRatingError extends Error { // // }
import com.androidhuman.example.rxjavainaction.error.ContentRatingError; import com.androidhuman.example.rxjavainaction.model.Content; import com.androidhuman.example.rxjavainaction.model.User; import rx.Observable; import rx.Subscriber;
package com.androidhuman.example.rxjavainaction.rx; final class ChecksContentRatingOnSubscribe implements Observable.OnSubscribe<Void> { private final Content content; private final User user; ChecksContentRatingOnSubscribe(Content content, User user) { this.content = content; this.user = user; } @Override public void call(Subscriber<? super Void> subscriber) { if (!subscriber.isUnsubscribed()) { if (content.isAdult() && user.isAdult()) { // Content is available subscriber.onNext(null); subscriber.onCompleted(); } else { // Content is not available; Rating is not suitable for user
// Path: 2016-07-12_rxjava_in_action/src/main/java/com/androidhuman/example/rxjavainaction/error/ContentRatingError.java // public final class ContentRatingError extends Error { // // } // Path: 2016-07-12_rxjava_in_action/src/main/java/com/androidhuman/example/rxjavainaction/rx/ChecksContentRatingOnSubscribe.java import com.androidhuman.example.rxjavainaction.error.ContentRatingError; import com.androidhuman.example.rxjavainaction.model.Content; import com.androidhuman.example.rxjavainaction.model.User; import rx.Observable; import rx.Subscriber; package com.androidhuman.example.rxjavainaction.rx; final class ChecksContentRatingOnSubscribe implements Observable.OnSubscribe<Void> { private final Content content; private final User user; ChecksContentRatingOnSubscribe(Content content, User user) { this.content = content; this.user = user; } @Override public void call(Subscriber<? super Void> subscriber) { if (!subscriber.isUnsubscribed()) { if (content.isAdult() && user.isAdult()) { // Content is available subscriber.onNext(null); subscriber.onCompleted(); } else { // Content is not available; Rating is not suitable for user
subscriber.onError(new ContentRatingError());
gdgand/android-rxjava
2016-06-08_queue/app/src/main/java-fcm/com/gdgand/rxjava/rxjavasample/fcm/message/MessageReceiverService.java
// Path: 2016-06-08_queue/app/src/main/java-fcm/com/gdgand/rxjava/rxjavasample/fcm/message/event/NotificationEvent.java // public class NotificationEvent { // private String index; // private String message; // // public NotificationEvent(String index, String message) { // // this.index = index; // this.message = message; // } // // public String getIndex() { // return index; // } // // public void setIndex(String index) { // this.index = index; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // }
import android.util.Log; import com.gdgand.rxjava.rxjavasample.fcm.message.event.NotificationEvent; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; import org.greenrobot.eventbus.EventBus; import java.util.Map;
package com.gdgand.rxjava.rxjavasample.fcm.message; public class MessageReceiverService extends FirebaseMessagingService { private static final String TAG = "MessageReceiverService"; @Override public void onMessageReceived(RemoteMessage remoteMessage) { super.onMessageReceived(remoteMessage); Map<String, String> data = remoteMessage.getData(); Log.d(TAG, "onMessageReceived: " + data.toString()); String index = data.get("index"); String message = data.get("message");
// Path: 2016-06-08_queue/app/src/main/java-fcm/com/gdgand/rxjava/rxjavasample/fcm/message/event/NotificationEvent.java // public class NotificationEvent { // private String index; // private String message; // // public NotificationEvent(String index, String message) { // // this.index = index; // this.message = message; // } // // public String getIndex() { // return index; // } // // public void setIndex(String index) { // this.index = index; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // } // Path: 2016-06-08_queue/app/src/main/java-fcm/com/gdgand/rxjava/rxjavasample/fcm/message/MessageReceiverService.java import android.util.Log; import com.gdgand.rxjava.rxjavasample.fcm.message.event.NotificationEvent; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; import org.greenrobot.eventbus.EventBus; import java.util.Map; package com.gdgand.rxjava.rxjavasample.fcm.message; public class MessageReceiverService extends FirebaseMessagingService { private static final String TAG = "MessageReceiverService"; @Override public void onMessageReceived(RemoteMessage remoteMessage) { super.onMessageReceived(remoteMessage); Map<String, String> data = remoteMessage.getData(); Log.d(TAG, "onMessageReceived: " + data.toString()); String index = data.get("index"); String message = data.get("message");
NotificationEvent event = new NotificationEvent(index, message);
gdgand/android-rxjava
2016-06-22-OneStream_VS_Multicast/src/main/java/com/gdgand/rxjava/onestreamvsmulticast/MainActivity.java
// Path: 2016-06-22-OneStream_VS_Multicast/src/main/java/com/gdgand/rxjava/onestreamvsmulticast/command/MulticastCommand.java // public class MulticastCommand implements Command { // private final TextView tvMain; // // public MulticastCommand(TextView tvMain) { // // this.tvMain = tvMain; // } // // @Override // public void call() { // Observable<String> stringObservable = Observable.just("a1", "a2", "b3", "b4", "a5", "b6") // .publish().refCount(); // // stringObservable.observeOn(Schedulers.io()) // .filter(it -> it.contains("a")) // .doOnNext(it -> { // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // }) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(s -> { // tvMain.setText(tvMain.getText() + "\n" + s); // }); // // stringObservable.observeOn(Schedulers.io()) // .filter(it -> it.contains("b")) // .doOnNext(it -> { // try { // Thread.sleep(300); // } catch (InterruptedException e) { // e.printStackTrace(); // } // }) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(s -> { // tvMain.setText(tvMain.getText() + "\n" + s); // }); // // } // } // // Path: 2016-06-22-OneStream_VS_Multicast/src/main/java/com/gdgand/rxjava/onestreamvsmulticast/command/OneStreamCommand.java // public class OneStreamCommand implements Command { // private final TextView tvMain; // // public OneStreamCommand(TextView tvMain) { // // this.tvMain = tvMain; // } // // @Override // public void call() { // Observable.just("a1", "a2", "b3", "b4", "a5", "b6") // .concatMap(it -> { // // if (it.contains("a")) { // return Observable.just(it) // .compose(this::observableA); // } else if (it.contains("b")) { // return Observable.just(it) // .compose(this::observableB); // } else { // return Observable.just(it); // } // // }) // .subscribe(); // // } // // private Observable<String> observableB(Observable<String> stringObservable) { // return stringObservable.observeOn(Schedulers.io()) // .doOnNext(s -> { // try { // Thread.sleep(300); // } catch (InterruptedException e) { // e.printStackTrace(); // } // }) // .observeOn(AndroidSchedulers.mainThread()) // .doOnNext(s1 -> tvMain.setText(tvMain.getText() + "\n" + s1)); // } // // private Observable<String> observableA(Observable<String> stringObservable) { // return stringObservable.observeOn(Schedulers.io()) // .doOnNext(s -> { // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // }) // .observeOn(AndroidSchedulers.mainThread()) // .doOnNext(s1 -> tvMain.setText(tvMain.getText() + "\n" + s1)); // } // }
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.gdgand.rxjava.onestreamvsmulticast.command.MulticastCommand; import com.gdgand.rxjava.onestreamvsmulticast.command.OneStreamCommand; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick;
package com.gdgand.rxjava.onestreamvsmulticast; public class MainActivity extends AppCompatActivity { @BindView(R.id.tv_main) TextView tvMain; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); } @OnClick(R.id.btn_multi) void onMulticastClick() { tvMain.setText("");
// Path: 2016-06-22-OneStream_VS_Multicast/src/main/java/com/gdgand/rxjava/onestreamvsmulticast/command/MulticastCommand.java // public class MulticastCommand implements Command { // private final TextView tvMain; // // public MulticastCommand(TextView tvMain) { // // this.tvMain = tvMain; // } // // @Override // public void call() { // Observable<String> stringObservable = Observable.just("a1", "a2", "b3", "b4", "a5", "b6") // .publish().refCount(); // // stringObservable.observeOn(Schedulers.io()) // .filter(it -> it.contains("a")) // .doOnNext(it -> { // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // }) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(s -> { // tvMain.setText(tvMain.getText() + "\n" + s); // }); // // stringObservable.observeOn(Schedulers.io()) // .filter(it -> it.contains("b")) // .doOnNext(it -> { // try { // Thread.sleep(300); // } catch (InterruptedException e) { // e.printStackTrace(); // } // }) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(s -> { // tvMain.setText(tvMain.getText() + "\n" + s); // }); // // } // } // // Path: 2016-06-22-OneStream_VS_Multicast/src/main/java/com/gdgand/rxjava/onestreamvsmulticast/command/OneStreamCommand.java // public class OneStreamCommand implements Command { // private final TextView tvMain; // // public OneStreamCommand(TextView tvMain) { // // this.tvMain = tvMain; // } // // @Override // public void call() { // Observable.just("a1", "a2", "b3", "b4", "a5", "b6") // .concatMap(it -> { // // if (it.contains("a")) { // return Observable.just(it) // .compose(this::observableA); // } else if (it.contains("b")) { // return Observable.just(it) // .compose(this::observableB); // } else { // return Observable.just(it); // } // // }) // .subscribe(); // // } // // private Observable<String> observableB(Observable<String> stringObservable) { // return stringObservable.observeOn(Schedulers.io()) // .doOnNext(s -> { // try { // Thread.sleep(300); // } catch (InterruptedException e) { // e.printStackTrace(); // } // }) // .observeOn(AndroidSchedulers.mainThread()) // .doOnNext(s1 -> tvMain.setText(tvMain.getText() + "\n" + s1)); // } // // private Observable<String> observableA(Observable<String> stringObservable) { // return stringObservable.observeOn(Schedulers.io()) // .doOnNext(s -> { // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // }) // .observeOn(AndroidSchedulers.mainThread()) // .doOnNext(s1 -> tvMain.setText(tvMain.getText() + "\n" + s1)); // } // } // Path: 2016-06-22-OneStream_VS_Multicast/src/main/java/com/gdgand/rxjava/onestreamvsmulticast/MainActivity.java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.gdgand.rxjava.onestreamvsmulticast.command.MulticastCommand; import com.gdgand.rxjava.onestreamvsmulticast.command.OneStreamCommand; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; package com.gdgand.rxjava.onestreamvsmulticast; public class MainActivity extends AppCompatActivity { @BindView(R.id.tv_main) TextView tvMain; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); } @OnClick(R.id.btn_multi) void onMulticastClick() { tvMain.setText("");
new MulticastCommand(tvMain).call();
gdgand/android-rxjava
2016-06-22-OneStream_VS_Multicast/src/main/java/com/gdgand/rxjava/onestreamvsmulticast/MainActivity.java
// Path: 2016-06-22-OneStream_VS_Multicast/src/main/java/com/gdgand/rxjava/onestreamvsmulticast/command/MulticastCommand.java // public class MulticastCommand implements Command { // private final TextView tvMain; // // public MulticastCommand(TextView tvMain) { // // this.tvMain = tvMain; // } // // @Override // public void call() { // Observable<String> stringObservable = Observable.just("a1", "a2", "b3", "b4", "a5", "b6") // .publish().refCount(); // // stringObservable.observeOn(Schedulers.io()) // .filter(it -> it.contains("a")) // .doOnNext(it -> { // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // }) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(s -> { // tvMain.setText(tvMain.getText() + "\n" + s); // }); // // stringObservable.observeOn(Schedulers.io()) // .filter(it -> it.contains("b")) // .doOnNext(it -> { // try { // Thread.sleep(300); // } catch (InterruptedException e) { // e.printStackTrace(); // } // }) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(s -> { // tvMain.setText(tvMain.getText() + "\n" + s); // }); // // } // } // // Path: 2016-06-22-OneStream_VS_Multicast/src/main/java/com/gdgand/rxjava/onestreamvsmulticast/command/OneStreamCommand.java // public class OneStreamCommand implements Command { // private final TextView tvMain; // // public OneStreamCommand(TextView tvMain) { // // this.tvMain = tvMain; // } // // @Override // public void call() { // Observable.just("a1", "a2", "b3", "b4", "a5", "b6") // .concatMap(it -> { // // if (it.contains("a")) { // return Observable.just(it) // .compose(this::observableA); // } else if (it.contains("b")) { // return Observable.just(it) // .compose(this::observableB); // } else { // return Observable.just(it); // } // // }) // .subscribe(); // // } // // private Observable<String> observableB(Observable<String> stringObservable) { // return stringObservable.observeOn(Schedulers.io()) // .doOnNext(s -> { // try { // Thread.sleep(300); // } catch (InterruptedException e) { // e.printStackTrace(); // } // }) // .observeOn(AndroidSchedulers.mainThread()) // .doOnNext(s1 -> tvMain.setText(tvMain.getText() + "\n" + s1)); // } // // private Observable<String> observableA(Observable<String> stringObservable) { // return stringObservable.observeOn(Schedulers.io()) // .doOnNext(s -> { // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // }) // .observeOn(AndroidSchedulers.mainThread()) // .doOnNext(s1 -> tvMain.setText(tvMain.getText() + "\n" + s1)); // } // }
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.gdgand.rxjava.onestreamvsmulticast.command.MulticastCommand; import com.gdgand.rxjava.onestreamvsmulticast.command.OneStreamCommand; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick;
package com.gdgand.rxjava.onestreamvsmulticast; public class MainActivity extends AppCompatActivity { @BindView(R.id.tv_main) TextView tvMain; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); } @OnClick(R.id.btn_multi) void onMulticastClick() { tvMain.setText(""); new MulticastCommand(tvMain).call(); } @OnClick(R.id.btn_one) void onOnestreamClick() { tvMain.setText("");
// Path: 2016-06-22-OneStream_VS_Multicast/src/main/java/com/gdgand/rxjava/onestreamvsmulticast/command/MulticastCommand.java // public class MulticastCommand implements Command { // private final TextView tvMain; // // public MulticastCommand(TextView tvMain) { // // this.tvMain = tvMain; // } // // @Override // public void call() { // Observable<String> stringObservable = Observable.just("a1", "a2", "b3", "b4", "a5", "b6") // .publish().refCount(); // // stringObservable.observeOn(Schedulers.io()) // .filter(it -> it.contains("a")) // .doOnNext(it -> { // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // }) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(s -> { // tvMain.setText(tvMain.getText() + "\n" + s); // }); // // stringObservable.observeOn(Schedulers.io()) // .filter(it -> it.contains("b")) // .doOnNext(it -> { // try { // Thread.sleep(300); // } catch (InterruptedException e) { // e.printStackTrace(); // } // }) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(s -> { // tvMain.setText(tvMain.getText() + "\n" + s); // }); // // } // } // // Path: 2016-06-22-OneStream_VS_Multicast/src/main/java/com/gdgand/rxjava/onestreamvsmulticast/command/OneStreamCommand.java // public class OneStreamCommand implements Command { // private final TextView tvMain; // // public OneStreamCommand(TextView tvMain) { // // this.tvMain = tvMain; // } // // @Override // public void call() { // Observable.just("a1", "a2", "b3", "b4", "a5", "b6") // .concatMap(it -> { // // if (it.contains("a")) { // return Observable.just(it) // .compose(this::observableA); // } else if (it.contains("b")) { // return Observable.just(it) // .compose(this::observableB); // } else { // return Observable.just(it); // } // // }) // .subscribe(); // // } // // private Observable<String> observableB(Observable<String> stringObservable) { // return stringObservable.observeOn(Schedulers.io()) // .doOnNext(s -> { // try { // Thread.sleep(300); // } catch (InterruptedException e) { // e.printStackTrace(); // } // }) // .observeOn(AndroidSchedulers.mainThread()) // .doOnNext(s1 -> tvMain.setText(tvMain.getText() + "\n" + s1)); // } // // private Observable<String> observableA(Observable<String> stringObservable) { // return stringObservable.observeOn(Schedulers.io()) // .doOnNext(s -> { // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // }) // .observeOn(AndroidSchedulers.mainThread()) // .doOnNext(s1 -> tvMain.setText(tvMain.getText() + "\n" + s1)); // } // } // Path: 2016-06-22-OneStream_VS_Multicast/src/main/java/com/gdgand/rxjava/onestreamvsmulticast/MainActivity.java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.gdgand.rxjava.onestreamvsmulticast.command.MulticastCommand; import com.gdgand.rxjava.onestreamvsmulticast.command.OneStreamCommand; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; package com.gdgand.rxjava.onestreamvsmulticast; public class MainActivity extends AppCompatActivity { @BindView(R.id.tv_main) TextView tvMain; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); } @OnClick(R.id.btn_multi) void onMulticastClick() { tvMain.setText(""); new MulticastCommand(tvMain).call(); } @OnClick(R.id.btn_one) void onOnestreamClick() { tvMain.setText("");
new OneStreamCommand(tvMain).call();
gdgand/android-rxjava
2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/scroll/FasterListActivity.java
// Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/scroll/adapter/FasterAdapter.java // public class FasterAdapter extends RecyclerView.Adapter<FasterListViewHolder> { // // private Context context; // // private List<String> list; // // public FasterAdapter(Context context) { // this.context = context; // list = new ArrayList<>(); // } // // @Override // public FasterListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // View view = LayoutInflater.from(context).inflate(R.layout.item_fasterlist, parent, false); // return new FasterListViewHolder(view); // } // // @Override // public void onBindViewHolder(FasterListViewHolder holder, int position) { // Observable.just(position) // .subscribeOn(Schedulers.io()) // .map(index -> { // // try { // Realm realm = Realm.getDefaultInstance(); // long count = realm.where(FasterListData.class).greaterThanOrEqualTo("position", position) // .count(); // Thread.sleep(10); // return getItem(position) + ", count : " + count; // } catch (InterruptedException e) { // e.printStackTrace(); // } // return ""; // // }).observeOn(AndroidSchedulers.mainThread()) // .subscribe(s -> { // holder.tvTitle.setText(s); // }); // } // // private String getItem(int position) { // return list.get(position); // } // // public void addAll(List<String> list) { // this.list.addAll(list); // } // // public void add(String value) { // this.list.add(value); // } // // @Override // public int getItemCount() { // return list.size(); // } // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/scroll/adapter/NormalAdapter.java // public class NormalAdapter extends RecyclerView.Adapter<FasterListViewHolder> { // // private Context context; // private List<String> list; // // public NormalAdapter(Context context) { // this.context = context; // this.list = new ArrayList<>(); // } // // @Override // public FasterListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // // View view = LayoutInflater.from(context).inflate(R.layout.item_fasterlist, parent, false); // return new FasterListViewHolder(view); // } // // @Override // public void onBindViewHolder(FasterListViewHolder holder, int position) { // // // try { // Realm realm = Realm.getDefaultInstance(); // long count = realm.where(FasterListData.class).greaterThanOrEqualTo("position", position) // .count(); // Thread.sleep(10); // holder.tvTitle.setText(getItem(position) + ", count : " + count); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // // } // // private String getItem(int position) { // return list.get(position); // } // // public void addAll(List<String> list) { // this.list.addAll(list); // } // // public void add(String value) { // this.list.add(value); // } // // // @Override // public int getItemCount() { // return list.size(); // } // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/scroll/realm/FasterListData.java // public class FasterListData extends RealmObject { // @PrimaryKey // private long position; // // public long getPosition() { // return position; // } // // public void setPosition(long position) { // this.position = position; // } // }
import android.app.ProgressDialog; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import com.gdgand.rxjava.rxjavasample.R; import com.gdgand.rxjava.rxjavasample.scroll.adapter.FasterAdapter; import com.gdgand.rxjava.rxjavasample.scroll.adapter.NormalAdapter; import com.gdgand.rxjava.rxjavasample.scroll.realm.FasterListData; import butterknife.BindView; import butterknife.ButterKnife; import io.realm.Realm; import io.realm.RealmConfiguration; import rx.Observable;
package com.gdgand.rxjava.rxjavasample.scroll; public class FasterListActivity extends AppCompatActivity { @BindView(R.id.list_fasterlist) RecyclerView lvFasterList;
// Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/scroll/adapter/FasterAdapter.java // public class FasterAdapter extends RecyclerView.Adapter<FasterListViewHolder> { // // private Context context; // // private List<String> list; // // public FasterAdapter(Context context) { // this.context = context; // list = new ArrayList<>(); // } // // @Override // public FasterListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // View view = LayoutInflater.from(context).inflate(R.layout.item_fasterlist, parent, false); // return new FasterListViewHolder(view); // } // // @Override // public void onBindViewHolder(FasterListViewHolder holder, int position) { // Observable.just(position) // .subscribeOn(Schedulers.io()) // .map(index -> { // // try { // Realm realm = Realm.getDefaultInstance(); // long count = realm.where(FasterListData.class).greaterThanOrEqualTo("position", position) // .count(); // Thread.sleep(10); // return getItem(position) + ", count : " + count; // } catch (InterruptedException e) { // e.printStackTrace(); // } // return ""; // // }).observeOn(AndroidSchedulers.mainThread()) // .subscribe(s -> { // holder.tvTitle.setText(s); // }); // } // // private String getItem(int position) { // return list.get(position); // } // // public void addAll(List<String> list) { // this.list.addAll(list); // } // // public void add(String value) { // this.list.add(value); // } // // @Override // public int getItemCount() { // return list.size(); // } // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/scroll/adapter/NormalAdapter.java // public class NormalAdapter extends RecyclerView.Adapter<FasterListViewHolder> { // // private Context context; // private List<String> list; // // public NormalAdapter(Context context) { // this.context = context; // this.list = new ArrayList<>(); // } // // @Override // public FasterListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // // View view = LayoutInflater.from(context).inflate(R.layout.item_fasterlist, parent, false); // return new FasterListViewHolder(view); // } // // @Override // public void onBindViewHolder(FasterListViewHolder holder, int position) { // // // try { // Realm realm = Realm.getDefaultInstance(); // long count = realm.where(FasterListData.class).greaterThanOrEqualTo("position", position) // .count(); // Thread.sleep(10); // holder.tvTitle.setText(getItem(position) + ", count : " + count); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // // } // // private String getItem(int position) { // return list.get(position); // } // // public void addAll(List<String> list) { // this.list.addAll(list); // } // // public void add(String value) { // this.list.add(value); // } // // // @Override // public int getItemCount() { // return list.size(); // } // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/scroll/realm/FasterListData.java // public class FasterListData extends RealmObject { // @PrimaryKey // private long position; // // public long getPosition() { // return position; // } // // public void setPosition(long position) { // this.position = position; // } // } // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/scroll/FasterListActivity.java import android.app.ProgressDialog; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import com.gdgand.rxjava.rxjavasample.R; import com.gdgand.rxjava.rxjavasample.scroll.adapter.FasterAdapter; import com.gdgand.rxjava.rxjavasample.scroll.adapter.NormalAdapter; import com.gdgand.rxjava.rxjavasample.scroll.realm.FasterListData; import butterknife.BindView; import butterknife.ButterKnife; import io.realm.Realm; import io.realm.RealmConfiguration; import rx.Observable; package com.gdgand.rxjava.rxjavasample.scroll; public class FasterListActivity extends AppCompatActivity { @BindView(R.id.list_fasterlist) RecyclerView lvFasterList;
private FasterAdapter fasterAdapter;
gdgand/android-rxjava
2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/scroll/FasterListActivity.java
// Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/scroll/adapter/FasterAdapter.java // public class FasterAdapter extends RecyclerView.Adapter<FasterListViewHolder> { // // private Context context; // // private List<String> list; // // public FasterAdapter(Context context) { // this.context = context; // list = new ArrayList<>(); // } // // @Override // public FasterListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // View view = LayoutInflater.from(context).inflate(R.layout.item_fasterlist, parent, false); // return new FasterListViewHolder(view); // } // // @Override // public void onBindViewHolder(FasterListViewHolder holder, int position) { // Observable.just(position) // .subscribeOn(Schedulers.io()) // .map(index -> { // // try { // Realm realm = Realm.getDefaultInstance(); // long count = realm.where(FasterListData.class).greaterThanOrEqualTo("position", position) // .count(); // Thread.sleep(10); // return getItem(position) + ", count : " + count; // } catch (InterruptedException e) { // e.printStackTrace(); // } // return ""; // // }).observeOn(AndroidSchedulers.mainThread()) // .subscribe(s -> { // holder.tvTitle.setText(s); // }); // } // // private String getItem(int position) { // return list.get(position); // } // // public void addAll(List<String> list) { // this.list.addAll(list); // } // // public void add(String value) { // this.list.add(value); // } // // @Override // public int getItemCount() { // return list.size(); // } // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/scroll/adapter/NormalAdapter.java // public class NormalAdapter extends RecyclerView.Adapter<FasterListViewHolder> { // // private Context context; // private List<String> list; // // public NormalAdapter(Context context) { // this.context = context; // this.list = new ArrayList<>(); // } // // @Override // public FasterListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // // View view = LayoutInflater.from(context).inflate(R.layout.item_fasterlist, parent, false); // return new FasterListViewHolder(view); // } // // @Override // public void onBindViewHolder(FasterListViewHolder holder, int position) { // // // try { // Realm realm = Realm.getDefaultInstance(); // long count = realm.where(FasterListData.class).greaterThanOrEqualTo("position", position) // .count(); // Thread.sleep(10); // holder.tvTitle.setText(getItem(position) + ", count : " + count); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // // } // // private String getItem(int position) { // return list.get(position); // } // // public void addAll(List<String> list) { // this.list.addAll(list); // } // // public void add(String value) { // this.list.add(value); // } // // // @Override // public int getItemCount() { // return list.size(); // } // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/scroll/realm/FasterListData.java // public class FasterListData extends RealmObject { // @PrimaryKey // private long position; // // public long getPosition() { // return position; // } // // public void setPosition(long position) { // this.position = position; // } // }
import android.app.ProgressDialog; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import com.gdgand.rxjava.rxjavasample.R; import com.gdgand.rxjava.rxjavasample.scroll.adapter.FasterAdapter; import com.gdgand.rxjava.rxjavasample.scroll.adapter.NormalAdapter; import com.gdgand.rxjava.rxjavasample.scroll.realm.FasterListData; import butterknife.BindView; import butterknife.ButterKnife; import io.realm.Realm; import io.realm.RealmConfiguration; import rx.Observable;
package com.gdgand.rxjava.rxjavasample.scroll; public class FasterListActivity extends AppCompatActivity { @BindView(R.id.list_fasterlist) RecyclerView lvFasterList; private FasterAdapter fasterAdapter;
// Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/scroll/adapter/FasterAdapter.java // public class FasterAdapter extends RecyclerView.Adapter<FasterListViewHolder> { // // private Context context; // // private List<String> list; // // public FasterAdapter(Context context) { // this.context = context; // list = new ArrayList<>(); // } // // @Override // public FasterListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // View view = LayoutInflater.from(context).inflate(R.layout.item_fasterlist, parent, false); // return new FasterListViewHolder(view); // } // // @Override // public void onBindViewHolder(FasterListViewHolder holder, int position) { // Observable.just(position) // .subscribeOn(Schedulers.io()) // .map(index -> { // // try { // Realm realm = Realm.getDefaultInstance(); // long count = realm.where(FasterListData.class).greaterThanOrEqualTo("position", position) // .count(); // Thread.sleep(10); // return getItem(position) + ", count : " + count; // } catch (InterruptedException e) { // e.printStackTrace(); // } // return ""; // // }).observeOn(AndroidSchedulers.mainThread()) // .subscribe(s -> { // holder.tvTitle.setText(s); // }); // } // // private String getItem(int position) { // return list.get(position); // } // // public void addAll(List<String> list) { // this.list.addAll(list); // } // // public void add(String value) { // this.list.add(value); // } // // @Override // public int getItemCount() { // return list.size(); // } // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/scroll/adapter/NormalAdapter.java // public class NormalAdapter extends RecyclerView.Adapter<FasterListViewHolder> { // // private Context context; // private List<String> list; // // public NormalAdapter(Context context) { // this.context = context; // this.list = new ArrayList<>(); // } // // @Override // public FasterListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // // View view = LayoutInflater.from(context).inflate(R.layout.item_fasterlist, parent, false); // return new FasterListViewHolder(view); // } // // @Override // public void onBindViewHolder(FasterListViewHolder holder, int position) { // // // try { // Realm realm = Realm.getDefaultInstance(); // long count = realm.where(FasterListData.class).greaterThanOrEqualTo("position", position) // .count(); // Thread.sleep(10); // holder.tvTitle.setText(getItem(position) + ", count : " + count); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // // } // // private String getItem(int position) { // return list.get(position); // } // // public void addAll(List<String> list) { // this.list.addAll(list); // } // // public void add(String value) { // this.list.add(value); // } // // // @Override // public int getItemCount() { // return list.size(); // } // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/scroll/realm/FasterListData.java // public class FasterListData extends RealmObject { // @PrimaryKey // private long position; // // public long getPosition() { // return position; // } // // public void setPosition(long position) { // this.position = position; // } // } // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/scroll/FasterListActivity.java import android.app.ProgressDialog; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import com.gdgand.rxjava.rxjavasample.R; import com.gdgand.rxjava.rxjavasample.scroll.adapter.FasterAdapter; import com.gdgand.rxjava.rxjavasample.scroll.adapter.NormalAdapter; import com.gdgand.rxjava.rxjavasample.scroll.realm.FasterListData; import butterknife.BindView; import butterknife.ButterKnife; import io.realm.Realm; import io.realm.RealmConfiguration; import rx.Observable; package com.gdgand.rxjava.rxjavasample.scroll; public class FasterListActivity extends AppCompatActivity { @BindView(R.id.list_fasterlist) RecyclerView lvFasterList; private FasterAdapter fasterAdapter;
private NormalAdapter normalAdapter;
gdgand/android-rxjava
2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/scroll/FasterListActivity.java
// Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/scroll/adapter/FasterAdapter.java // public class FasterAdapter extends RecyclerView.Adapter<FasterListViewHolder> { // // private Context context; // // private List<String> list; // // public FasterAdapter(Context context) { // this.context = context; // list = new ArrayList<>(); // } // // @Override // public FasterListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // View view = LayoutInflater.from(context).inflate(R.layout.item_fasterlist, parent, false); // return new FasterListViewHolder(view); // } // // @Override // public void onBindViewHolder(FasterListViewHolder holder, int position) { // Observable.just(position) // .subscribeOn(Schedulers.io()) // .map(index -> { // // try { // Realm realm = Realm.getDefaultInstance(); // long count = realm.where(FasterListData.class).greaterThanOrEqualTo("position", position) // .count(); // Thread.sleep(10); // return getItem(position) + ", count : " + count; // } catch (InterruptedException e) { // e.printStackTrace(); // } // return ""; // // }).observeOn(AndroidSchedulers.mainThread()) // .subscribe(s -> { // holder.tvTitle.setText(s); // }); // } // // private String getItem(int position) { // return list.get(position); // } // // public void addAll(List<String> list) { // this.list.addAll(list); // } // // public void add(String value) { // this.list.add(value); // } // // @Override // public int getItemCount() { // return list.size(); // } // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/scroll/adapter/NormalAdapter.java // public class NormalAdapter extends RecyclerView.Adapter<FasterListViewHolder> { // // private Context context; // private List<String> list; // // public NormalAdapter(Context context) { // this.context = context; // this.list = new ArrayList<>(); // } // // @Override // public FasterListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // // View view = LayoutInflater.from(context).inflate(R.layout.item_fasterlist, parent, false); // return new FasterListViewHolder(view); // } // // @Override // public void onBindViewHolder(FasterListViewHolder holder, int position) { // // // try { // Realm realm = Realm.getDefaultInstance(); // long count = realm.where(FasterListData.class).greaterThanOrEqualTo("position", position) // .count(); // Thread.sleep(10); // holder.tvTitle.setText(getItem(position) + ", count : " + count); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // // } // // private String getItem(int position) { // return list.get(position); // } // // public void addAll(List<String> list) { // this.list.addAll(list); // } // // public void add(String value) { // this.list.add(value); // } // // // @Override // public int getItemCount() { // return list.size(); // } // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/scroll/realm/FasterListData.java // public class FasterListData extends RealmObject { // @PrimaryKey // private long position; // // public long getPosition() { // return position; // } // // public void setPosition(long position) { // this.position = position; // } // }
import android.app.ProgressDialog; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import com.gdgand.rxjava.rxjavasample.R; import com.gdgand.rxjava.rxjavasample.scroll.adapter.FasterAdapter; import com.gdgand.rxjava.rxjavasample.scroll.adapter.NormalAdapter; import com.gdgand.rxjava.rxjavasample.scroll.realm.FasterListData; import butterknife.BindView; import butterknife.ButterKnife; import io.realm.Realm; import io.realm.RealmConfiguration; import rx.Observable;
package com.gdgand.rxjava.rxjavasample.scroll; public class FasterListActivity extends AppCompatActivity { @BindView(R.id.list_fasterlist) RecyclerView lvFasterList; private FasterAdapter fasterAdapter; private NormalAdapter normalAdapter; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fasterlist); setUpActionbar(); ButterKnife.bind(this); fasterAdapter = new FasterAdapter(FasterListActivity.this); normalAdapter = new NormalAdapter(FasterListActivity.this); ProgressDialog dialog = ProgressDialog.show(FasterListActivity.this, null, "로딩 중...", true); Realm.setDefaultConfiguration(new RealmConfiguration.Builder(FasterListActivity.this) .build()); Realm realm = Realm.getDefaultInstance(); realm.beginTransaction(); realm.deleteAll(); realm.commitTransaction(); realm.executeTransactionAsync(realm1 -> { Observable.range(1, 13000) .subscribe(index -> {
// Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/scroll/adapter/FasterAdapter.java // public class FasterAdapter extends RecyclerView.Adapter<FasterListViewHolder> { // // private Context context; // // private List<String> list; // // public FasterAdapter(Context context) { // this.context = context; // list = new ArrayList<>(); // } // // @Override // public FasterListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // View view = LayoutInflater.from(context).inflate(R.layout.item_fasterlist, parent, false); // return new FasterListViewHolder(view); // } // // @Override // public void onBindViewHolder(FasterListViewHolder holder, int position) { // Observable.just(position) // .subscribeOn(Schedulers.io()) // .map(index -> { // // try { // Realm realm = Realm.getDefaultInstance(); // long count = realm.where(FasterListData.class).greaterThanOrEqualTo("position", position) // .count(); // Thread.sleep(10); // return getItem(position) + ", count : " + count; // } catch (InterruptedException e) { // e.printStackTrace(); // } // return ""; // // }).observeOn(AndroidSchedulers.mainThread()) // .subscribe(s -> { // holder.tvTitle.setText(s); // }); // } // // private String getItem(int position) { // return list.get(position); // } // // public void addAll(List<String> list) { // this.list.addAll(list); // } // // public void add(String value) { // this.list.add(value); // } // // @Override // public int getItemCount() { // return list.size(); // } // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/scroll/adapter/NormalAdapter.java // public class NormalAdapter extends RecyclerView.Adapter<FasterListViewHolder> { // // private Context context; // private List<String> list; // // public NormalAdapter(Context context) { // this.context = context; // this.list = new ArrayList<>(); // } // // @Override // public FasterListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // // View view = LayoutInflater.from(context).inflate(R.layout.item_fasterlist, parent, false); // return new FasterListViewHolder(view); // } // // @Override // public void onBindViewHolder(FasterListViewHolder holder, int position) { // // // try { // Realm realm = Realm.getDefaultInstance(); // long count = realm.where(FasterListData.class).greaterThanOrEqualTo("position", position) // .count(); // Thread.sleep(10); // holder.tvTitle.setText(getItem(position) + ", count : " + count); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // // } // // private String getItem(int position) { // return list.get(position); // } // // public void addAll(List<String> list) { // this.list.addAll(list); // } // // public void add(String value) { // this.list.add(value); // } // // // @Override // public int getItemCount() { // return list.size(); // } // } // // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/scroll/realm/FasterListData.java // public class FasterListData extends RealmObject { // @PrimaryKey // private long position; // // public long getPosition() { // return position; // } // // public void setPosition(long position) { // this.position = position; // } // } // Path: 2016-06-08_queue/app/src/main/java/com/gdgand/rxjava/rxjavasample/scroll/FasterListActivity.java import android.app.ProgressDialog; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import com.gdgand.rxjava.rxjavasample.R; import com.gdgand.rxjava.rxjavasample.scroll.adapter.FasterAdapter; import com.gdgand.rxjava.rxjavasample.scroll.adapter.NormalAdapter; import com.gdgand.rxjava.rxjavasample.scroll.realm.FasterListData; import butterknife.BindView; import butterknife.ButterKnife; import io.realm.Realm; import io.realm.RealmConfiguration; import rx.Observable; package com.gdgand.rxjava.rxjavasample.scroll; public class FasterListActivity extends AppCompatActivity { @BindView(R.id.list_fasterlist) RecyclerView lvFasterList; private FasterAdapter fasterAdapter; private NormalAdapter normalAdapter; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fasterlist); setUpActionbar(); ButterKnife.bind(this); fasterAdapter = new FasterAdapter(FasterListActivity.this); normalAdapter = new NormalAdapter(FasterListActivity.this); ProgressDialog dialog = ProgressDialog.show(FasterListActivity.this, null, "로딩 중...", true); Realm.setDefaultConfiguration(new RealmConfiguration.Builder(FasterListActivity.this) .build()); Realm realm = Realm.getDefaultInstance(); realm.beginTransaction(); realm.deleteAll(); realm.commitTransaction(); realm.executeTransactionAsync(realm1 -> { Observable.range(1, 13000) .subscribe(index -> {
FasterListData object = realm1.createObject(FasterListData.class);
gdgand/android-rxjava
2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/TestDataComponent.java
// Path: 2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/ImgurApiTest.java // @Ignore("Ignore e2e test by default") // public class ImgurApiTest { // // @Inject // ImgurApi imgurApi; // // @Before // public void setup() { // DaggerTestDataComponent.builder() // .dataModule(new DataModule()) // .build() // .inject(this); // } // // @Test // public void testDefaultTopicsWithTestSubscriber() throws Exception { // // given // TestSubscriber<TopicResponse> subscriber = TestSubscriber.create(); // // // when // imgurApi.defaultTopics().subscribe(subscriber); // // // then // subscriber.awaitTerminalEvent(); // List<TopicResponse> items = subscriber.getOnNextEvents(); // // assertThat(items).hasSize(1); // Stream.of(items).forEach(value -> assertThat(value.getData()).isNotEmpty()); // } // // @Test // public void testDefaultTopicsWithBlocking() throws Exception { // // given // // // when // Iterator<TopicResponse> response = imgurApi.defaultTopics().toBlocking().getIterator(); // // // then // assertThat(response).hasSize(1); // Stream.of(response).forEach(value -> assertThat(value.getData()).isNotEmpty()); // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/module/DataModule.java // @Module // public class DataModule { // // @Provides // @Singleton // public Converter.Factory converterFactory() { // return GsonConverterFactory.create(); // } // // // @Provides // @Singleton // public CallAdapter.Factory callAdapterFactory() { // return RxJavaCallAdapterFactory.create(); // } // // @Provides // @Singleton // public OkHttpClient okHttpClient() { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // // return new OkHttpClient.Builder() // .addInterceptor(interceptor) // .build(); // } // // @Provides // @Singleton // public Retrofit retrofit(OkHttpClient client, CallAdapter.Factory callAdapterFactory, Converter.Factory converterFactory) { // return new Retrofit.Builder() // .baseUrl("https://api.imgur.com") // .client(client) // .addCallAdapterFactory(callAdapterFactory) // .addConverterFactory(converterFactory) // .build(); // } // // @Provides // @Singleton // public ImgurApi imgurApi(Retrofit retrofit) { // return retrofit.create(ImgurApi.class); // } // }
import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.ImgurApiTest; import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.DataModule; import dagger.Component; import javax.inject.Singleton;
package com.gdgand.rxjava.rxjavasample.hotandcold.data; @Singleton @Component(modules = { DataModule.class }) public interface TestDataComponent {
// Path: 2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/imgur/ImgurApiTest.java // @Ignore("Ignore e2e test by default") // public class ImgurApiTest { // // @Inject // ImgurApi imgurApi; // // @Before // public void setup() { // DaggerTestDataComponent.builder() // .dataModule(new DataModule()) // .build() // .inject(this); // } // // @Test // public void testDefaultTopicsWithTestSubscriber() throws Exception { // // given // TestSubscriber<TopicResponse> subscriber = TestSubscriber.create(); // // // when // imgurApi.defaultTopics().subscribe(subscriber); // // // then // subscriber.awaitTerminalEvent(); // List<TopicResponse> items = subscriber.getOnNextEvents(); // // assertThat(items).hasSize(1); // Stream.of(items).forEach(value -> assertThat(value.getData()).isNotEmpty()); // } // // @Test // public void testDefaultTopicsWithBlocking() throws Exception { // // given // // // when // Iterator<TopicResponse> response = imgurApi.defaultTopics().toBlocking().getIterator(); // // // then // assertThat(response).hasSize(1); // Stream.of(response).forEach(value -> assertThat(value.getData()).isNotEmpty()); // } // } // // Path: 2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/di/module/DataModule.java // @Module // public class DataModule { // // @Provides // @Singleton // public Converter.Factory converterFactory() { // return GsonConverterFactory.create(); // } // // // @Provides // @Singleton // public CallAdapter.Factory callAdapterFactory() { // return RxJavaCallAdapterFactory.create(); // } // // @Provides // @Singleton // public OkHttpClient okHttpClient() { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // // return new OkHttpClient.Builder() // .addInterceptor(interceptor) // .build(); // } // // @Provides // @Singleton // public Retrofit retrofit(OkHttpClient client, CallAdapter.Factory callAdapterFactory, Converter.Factory converterFactory) { // return new Retrofit.Builder() // .baseUrl("https://api.imgur.com") // .client(client) // .addCallAdapterFactory(callAdapterFactory) // .addConverterFactory(converterFactory) // .build(); // } // // @Provides // @Singleton // public ImgurApi imgurApi(Retrofit retrofit) { // return retrofit.create(ImgurApi.class); // } // } // Path: 2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/data/TestDataComponent.java import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.ImgurApiTest; import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.DataModule; import dagger.Component; import javax.inject.Singleton; package com.gdgand.rxjava.rxjavasample.hotandcold.data; @Singleton @Component(modules = { DataModule.class }) public interface TestDataComponent {
void inject(ImgurApiTest imgurApiTest);
carryxyh/Electrons
electrons/src/test/java/com/ziyuan/TestListener.java
// Path: electrons/src/main/java/com/ziyuan/events/Electron.java // public abstract class Electron extends EventObject { // // /** // * 发生的时间戳 // */ // private long timestamp; // // /** // * 该事件的权重,在限流中起作用,默认为1 // */ // private int weight = 1; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public Electron(Object source) { // super(source); // this.timestamp = System.currentTimeMillis(); // } // // public final long getTimestamp() { // return this.timestamp; // } // // public final int getWeight() { // return weight; // } // // public final void setWeight(int weight) { // this.weight = weight; // } // }
import com.ziyuan.events.Electron;
package com.ziyuan; /** * TestListener * * @author ziyuan * @since 2017-03-16 */ public class TestListener implements ElectronsListener { @Override
// Path: electrons/src/main/java/com/ziyuan/events/Electron.java // public abstract class Electron extends EventObject { // // /** // * 发生的时间戳 // */ // private long timestamp; // // /** // * 该事件的权重,在限流中起作用,默认为1 // */ // private int weight = 1; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public Electron(Object source) { // super(source); // this.timestamp = System.currentTimeMillis(); // } // // public final long getTimestamp() { // return this.timestamp; // } // // public final int getWeight() { // return weight; // } // // public final void setWeight(int weight) { // this.weight = weight; // } // } // Path: electrons/src/test/java/com/ziyuan/TestListener.java import com.ziyuan.events.Electron; package com.ziyuan; /** * TestListener * * @author ziyuan * @since 2017-03-16 */ public class TestListener implements ElectronsListener { @Override
public void onEvent(Electron electrons) throws Exception {
carryxyh/Electrons
electrons/src/test/java/com/ziyuan/AppTest.java
// Path: electrons/src/main/java/com/ziyuan/delegate/DropDelegate.java // public class DropDelegate extends AbstractDelegatePublisher { // // private static Logger logger = LoggerFactory.getLogger(DropDelegate.class); // // public DropDelegate(EleCircuit eleCircuit) { // super(eleCircuit); // } // // public void publish(String tag, Electron electron) { // try { // super.getEleCircuit().publish(tag, electron); // } catch (Exception e) { // logger.warn("Publish failed and drop the electron : { tag: " + tag + "electron: " + electron.toString() + "}", e); // } // } // } // // Path: electrons/src/main/java/com/ziyuan/events/HomelessEle.java // public final class HomelessEle extends Electron { // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public HomelessEle(Object source) { // super(source); // } // }
import com.ziyuan.delegate.DropDelegate; import com.ziyuan.events.HomelessEle; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import java.lang.reflect.Method; import java.lang.reflect.Type;
package com.ziyuan; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AppTest(String testName) { super(testName); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite(AppTest.class); } /** * Rigourous Test :-) */ public void testApp() {
// Path: electrons/src/main/java/com/ziyuan/delegate/DropDelegate.java // public class DropDelegate extends AbstractDelegatePublisher { // // private static Logger logger = LoggerFactory.getLogger(DropDelegate.class); // // public DropDelegate(EleCircuit eleCircuit) { // super(eleCircuit); // } // // public void publish(String tag, Electron electron) { // try { // super.getEleCircuit().publish(tag, electron); // } catch (Exception e) { // logger.warn("Publish failed and drop the electron : { tag: " + tag + "electron: " + electron.toString() + "}", e); // } // } // } // // Path: electrons/src/main/java/com/ziyuan/events/HomelessEle.java // public final class HomelessEle extends Electron { // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public HomelessEle(Object source) { // super(source); // } // } // Path: electrons/src/test/java/com/ziyuan/AppTest.java import com.ziyuan.delegate.DropDelegate; import com.ziyuan.events.HomelessEle; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import java.lang.reflect.Method; import java.lang.reflect.Type; package com.ziyuan; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AppTest(String testName) { super(testName); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite(AppTest.class); } /** * Rigourous Test :-) */ public void testApp() {
System.out.println(HomelessEle.class.isAssignableFrom(HomelessEle.class));
carryxyh/Electrons
electrons/src/test/java/com/ziyuan/AppTest.java
// Path: electrons/src/main/java/com/ziyuan/delegate/DropDelegate.java // public class DropDelegate extends AbstractDelegatePublisher { // // private static Logger logger = LoggerFactory.getLogger(DropDelegate.class); // // public DropDelegate(EleCircuit eleCircuit) { // super(eleCircuit); // } // // public void publish(String tag, Electron electron) { // try { // super.getEleCircuit().publish(tag, electron); // } catch (Exception e) { // logger.warn("Publish failed and drop the electron : { tag: " + tag + "electron: " + electron.toString() + "}", e); // } // } // } // // Path: electrons/src/main/java/com/ziyuan/events/HomelessEle.java // public final class HomelessEle extends Electron { // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public HomelessEle(Object source) { // super(source); // } // }
import com.ziyuan.delegate.DropDelegate; import com.ziyuan.events.HomelessEle; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import java.lang.reflect.Method; import java.lang.reflect.Type;
package com.ziyuan; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AppTest(String testName) { super(testName); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite(AppTest.class); } /** * Rigourous Test :-) */ public void testApp() { System.out.println(HomelessEle.class.isAssignableFrom(HomelessEle.class)); System.out.println(2 << 6); ElectronsListener electronsListener = new TestListener(); Listener ann = electronsListener.getClass().getAnnotation(Listener.class); System.out.println(ann.id()); System.out.println("2".split(",")[0]); } //com.ziyuan.events.Electron public void testMethodParam() {
// Path: electrons/src/main/java/com/ziyuan/delegate/DropDelegate.java // public class DropDelegate extends AbstractDelegatePublisher { // // private static Logger logger = LoggerFactory.getLogger(DropDelegate.class); // // public DropDelegate(EleCircuit eleCircuit) { // super(eleCircuit); // } // // public void publish(String tag, Electron electron) { // try { // super.getEleCircuit().publish(tag, electron); // } catch (Exception e) { // logger.warn("Publish failed and drop the electron : { tag: " + tag + "electron: " + electron.toString() + "}", e); // } // } // } // // Path: electrons/src/main/java/com/ziyuan/events/HomelessEle.java // public final class HomelessEle extends Electron { // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public HomelessEle(Object source) { // super(source); // } // } // Path: electrons/src/test/java/com/ziyuan/AppTest.java import com.ziyuan.delegate.DropDelegate; import com.ziyuan.events.HomelessEle; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import java.lang.reflect.Method; import java.lang.reflect.Type; package com.ziyuan; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AppTest(String testName) { super(testName); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite(AppTest.class); } /** * Rigourous Test :-) */ public void testApp() { System.out.println(HomelessEle.class.isAssignableFrom(HomelessEle.class)); System.out.println(2 << 6); ElectronsListener electronsListener = new TestListener(); Listener ann = electronsListener.getClass().getAnnotation(Listener.class); System.out.println(ann.id()); System.out.println("2".split(",")[0]); } //com.ziyuan.events.Electron public void testMethodParam() {
Method[] methods = DropDelegate.class.getMethods();
carryxyh/Electrons
electrons/src/main/java/com/ziyuan/chain/ListenerChainBuilder.java
// Path: electrons/src/main/java/com/ziyuan/ElectronsHolder.java // public final class ElectronsHolder { // // /** // * 电子 // */ // private Electron electron; // // /** // * 要执行的监听器,这里已经排好序了 // */ // private List<ElectronsListener> listeners; // // public Electron getElectron() { // return electron; // } // // public void setElectron(Electron electron) { // this.electron = electron; // } // // public List<ElectronsListener> getListeners() { // return listeners; // } // // public void setListeners(List<ElectronsListener> listeners) { // this.listeners = listeners; // } // // /** // * 处理 // * // * @throws Exception 处理过程中的异常,同样抛出去 // */ // public boolean handle() throws Exception { // if (CollectionUtils.isEmpty(listeners)) { // return false; // } // for (ElectronsListener listener : listeners) { // listener.onEvent(electron); // } // return true; // } // // @Override // public String toString() { // return electron.getSource().getClass().getSimpleName() + " - "; // } // } // // Path: electrons/src/main/java/com/ziyuan/ElectronsListener.java // public interface ElectronsListener<E extends Electron> extends Serializable { // // /** // * 处理事件 // * // * @param electrons 电子 // * @throws Exception 处理过程中的异常,比较建议抛出,方便熔断 // */ // void onEvent(E electrons) throws Exception; // }
import com.lmax.disruptor.EventHandler; import com.lmax.disruptor.dsl.Disruptor; import com.ziyuan.ElectronsHolder; import com.ziyuan.ElectronsListener; import com.ziyuan.Listener; import lombok.Getter; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import java.io.Serializable; import java.util.*;
package com.ziyuan.chain; /** * ListenerChainBuilder 构造listener链的辅助类 * 老版本使用,现在已经废弃,仅做纪念T T * * @author ziyuan * @since 2017-03-09 */ @Deprecated public final class ListenerChainBuilder { /** * 不允许初始化 */ private ListenerChainBuilder() { } /** * 构建监听器链 * * @param disruptor disruptor * @param electronsListeners listeners */
// Path: electrons/src/main/java/com/ziyuan/ElectronsHolder.java // public final class ElectronsHolder { // // /** // * 电子 // */ // private Electron electron; // // /** // * 要执行的监听器,这里已经排好序了 // */ // private List<ElectronsListener> listeners; // // public Electron getElectron() { // return electron; // } // // public void setElectron(Electron electron) { // this.electron = electron; // } // // public List<ElectronsListener> getListeners() { // return listeners; // } // // public void setListeners(List<ElectronsListener> listeners) { // this.listeners = listeners; // } // // /** // * 处理 // * // * @throws Exception 处理过程中的异常,同样抛出去 // */ // public boolean handle() throws Exception { // if (CollectionUtils.isEmpty(listeners)) { // return false; // } // for (ElectronsListener listener : listeners) { // listener.onEvent(electron); // } // return true; // } // // @Override // public String toString() { // return electron.getSource().getClass().getSimpleName() + " - "; // } // } // // Path: electrons/src/main/java/com/ziyuan/ElectronsListener.java // public interface ElectronsListener<E extends Electron> extends Serializable { // // /** // * 处理事件 // * // * @param electrons 电子 // * @throws Exception 处理过程中的异常,比较建议抛出,方便熔断 // */ // void onEvent(E electrons) throws Exception; // } // Path: electrons/src/main/java/com/ziyuan/chain/ListenerChainBuilder.java import com.lmax.disruptor.EventHandler; import com.lmax.disruptor.dsl.Disruptor; import com.ziyuan.ElectronsHolder; import com.ziyuan.ElectronsListener; import com.ziyuan.Listener; import lombok.Getter; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import java.io.Serializable; import java.util.*; package com.ziyuan.chain; /** * ListenerChainBuilder 构造listener链的辅助类 * 老版本使用,现在已经废弃,仅做纪念T T * * @author ziyuan * @since 2017-03-09 */ @Deprecated public final class ListenerChainBuilder { /** * 不允许初始化 */ private ListenerChainBuilder() { } /** * 构建监听器链 * * @param disruptor disruptor * @param electronsListeners listeners */
public final static void buildChain(Disruptor<ElectronsHolder> disruptor, List<ElectronsListener> electronsListeners) {
carryxyh/Electrons
electrons/src/main/java/com/ziyuan/chain/ListenerChainBuilder.java
// Path: electrons/src/main/java/com/ziyuan/ElectronsHolder.java // public final class ElectronsHolder { // // /** // * 电子 // */ // private Electron electron; // // /** // * 要执行的监听器,这里已经排好序了 // */ // private List<ElectronsListener> listeners; // // public Electron getElectron() { // return electron; // } // // public void setElectron(Electron electron) { // this.electron = electron; // } // // public List<ElectronsListener> getListeners() { // return listeners; // } // // public void setListeners(List<ElectronsListener> listeners) { // this.listeners = listeners; // } // // /** // * 处理 // * // * @throws Exception 处理过程中的异常,同样抛出去 // */ // public boolean handle() throws Exception { // if (CollectionUtils.isEmpty(listeners)) { // return false; // } // for (ElectronsListener listener : listeners) { // listener.onEvent(electron); // } // return true; // } // // @Override // public String toString() { // return electron.getSource().getClass().getSimpleName() + " - "; // } // } // // Path: electrons/src/main/java/com/ziyuan/ElectronsListener.java // public interface ElectronsListener<E extends Electron> extends Serializable { // // /** // * 处理事件 // * // * @param electrons 电子 // * @throws Exception 处理过程中的异常,比较建议抛出,方便熔断 // */ // void onEvent(E electrons) throws Exception; // }
import com.lmax.disruptor.EventHandler; import com.lmax.disruptor.dsl.Disruptor; import com.ziyuan.ElectronsHolder; import com.ziyuan.ElectronsListener; import com.ziyuan.Listener; import lombok.Getter; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import java.io.Serializable; import java.util.*;
package com.ziyuan.chain; /** * ListenerChainBuilder 构造listener链的辅助类 * 老版本使用,现在已经废弃,仅做纪念T T * * @author ziyuan * @since 2017-03-09 */ @Deprecated public final class ListenerChainBuilder { /** * 不允许初始化 */ private ListenerChainBuilder() { } /** * 构建监听器链 * * @param disruptor disruptor * @param electronsListeners listeners */
// Path: electrons/src/main/java/com/ziyuan/ElectronsHolder.java // public final class ElectronsHolder { // // /** // * 电子 // */ // private Electron electron; // // /** // * 要执行的监听器,这里已经排好序了 // */ // private List<ElectronsListener> listeners; // // public Electron getElectron() { // return electron; // } // // public void setElectron(Electron electron) { // this.electron = electron; // } // // public List<ElectronsListener> getListeners() { // return listeners; // } // // public void setListeners(List<ElectronsListener> listeners) { // this.listeners = listeners; // } // // /** // * 处理 // * // * @throws Exception 处理过程中的异常,同样抛出去 // */ // public boolean handle() throws Exception { // if (CollectionUtils.isEmpty(listeners)) { // return false; // } // for (ElectronsListener listener : listeners) { // listener.onEvent(electron); // } // return true; // } // // @Override // public String toString() { // return electron.getSource().getClass().getSimpleName() + " - "; // } // } // // Path: electrons/src/main/java/com/ziyuan/ElectronsListener.java // public interface ElectronsListener<E extends Electron> extends Serializable { // // /** // * 处理事件 // * // * @param electrons 电子 // * @throws Exception 处理过程中的异常,比较建议抛出,方便熔断 // */ // void onEvent(E electrons) throws Exception; // } // Path: electrons/src/main/java/com/ziyuan/chain/ListenerChainBuilder.java import com.lmax.disruptor.EventHandler; import com.lmax.disruptor.dsl.Disruptor; import com.ziyuan.ElectronsHolder; import com.ziyuan.ElectronsListener; import com.ziyuan.Listener; import lombok.Getter; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import java.io.Serializable; import java.util.*; package com.ziyuan.chain; /** * ListenerChainBuilder 构造listener链的辅助类 * 老版本使用,现在已经废弃,仅做纪念T T * * @author ziyuan * @since 2017-03-09 */ @Deprecated public final class ListenerChainBuilder { /** * 不允许初始化 */ private ListenerChainBuilder() { } /** * 构建监听器链 * * @param disruptor disruptor * @param electronsListeners listeners */
public final static void buildChain(Disruptor<ElectronsHolder> disruptor, List<ElectronsListener> electronsListeners) {
carryxyh/Electrons
electrons/src/main/java/com/ziyuan/util/TypeSafeUtil.java
// Path: electrons/src/main/java/com/ziyuan/Config.java // @Data // @ToString // public final class Config { // // /** // * 电路是否打开,目前只支持true,后面总线可能用队列,则关闭时用队列 // */ // private boolean eleOpen; // // /** // * 电路数量 // */ // private int circuitNum; // // /** // * 特殊电路的数量(如果存在特殊电路,这个值才会生效) // */ // private int specCircuitNum; // // /** // * 电路长度,即buffer的size 默认512 // */ // private int circuitLen; // // /** // * 默认的特殊电路的长度 128 // */ // private int specCircuitLen; // // /** // * 默认扫所有 // */ // private String scanPackage; // // /** // * 默认不扫描jar包 // */ // private boolean scanJar; // // /*------------------------------------限流相关---------------------------------------*/ // // /** // * 是否开启限流 // */ // private boolean limitRate; // // /** // * 是否预热 // */ // private boolean warmup; // // /** // * 预热1分钟 // */ // private int warmupPeriod; // // /** // * 默认单位分钟,默认预热1分钟 // */ // private TimeUnit warmPeriodUnit; // // /** // * 每秒64个令牌 // */ // private double permitsPerSecond; // // /*------------------------------------熔断相关 默认:每两分钟内出现5个错误,就休息3分钟---------------------------------------*/ // // /** // * 是否开启熔断 // */ // private boolean breaker; // // /** // * 单位时间内错误数 // */ // private int errorNum; // // /** // * 单位时间内 // */ // private int perUnit; // // /** // * 单位 // */ // private TimeUnit unit; // // /** // * 关闭熔断的阈值 // */ // private int closeThreshold; // // /** // * 休息多久 // */ // private int rest; // // /** // * 休息的单位 // */ // private TimeUnit restUnit; // }
import com.typesafe.config.ConfigFactory; import com.ziyuan.Config; import java.util.concurrent.TimeUnit;
package com.ziyuan.util; /** * TypeSafeUtil * 根据typesafe处理config的工具类 * * @author ziyuan * @since 2017-06-15 */ public final class TypeSafeUtil { private static final String CONF_PATH = "eleconfig.conf"; private static final String M = "m"; private static final String H = "h"; private static final String S = "s";
// Path: electrons/src/main/java/com/ziyuan/Config.java // @Data // @ToString // public final class Config { // // /** // * 电路是否打开,目前只支持true,后面总线可能用队列,则关闭时用队列 // */ // private boolean eleOpen; // // /** // * 电路数量 // */ // private int circuitNum; // // /** // * 特殊电路的数量(如果存在特殊电路,这个值才会生效) // */ // private int specCircuitNum; // // /** // * 电路长度,即buffer的size 默认512 // */ // private int circuitLen; // // /** // * 默认的特殊电路的长度 128 // */ // private int specCircuitLen; // // /** // * 默认扫所有 // */ // private String scanPackage; // // /** // * 默认不扫描jar包 // */ // private boolean scanJar; // // /*------------------------------------限流相关---------------------------------------*/ // // /** // * 是否开启限流 // */ // private boolean limitRate; // // /** // * 是否预热 // */ // private boolean warmup; // // /** // * 预热1分钟 // */ // private int warmupPeriod; // // /** // * 默认单位分钟,默认预热1分钟 // */ // private TimeUnit warmPeriodUnit; // // /** // * 每秒64个令牌 // */ // private double permitsPerSecond; // // /*------------------------------------熔断相关 默认:每两分钟内出现5个错误,就休息3分钟---------------------------------------*/ // // /** // * 是否开启熔断 // */ // private boolean breaker; // // /** // * 单位时间内错误数 // */ // private int errorNum; // // /** // * 单位时间内 // */ // private int perUnit; // // /** // * 单位 // */ // private TimeUnit unit; // // /** // * 关闭熔断的阈值 // */ // private int closeThreshold; // // /** // * 休息多久 // */ // private int rest; // // /** // * 休息的单位 // */ // private TimeUnit restUnit; // } // Path: electrons/src/main/java/com/ziyuan/util/TypeSafeUtil.java import com.typesafe.config.ConfigFactory; import com.ziyuan.Config; import java.util.concurrent.TimeUnit; package com.ziyuan.util; /** * TypeSafeUtil * 根据typesafe处理config的工具类 * * @author ziyuan * @since 2017-06-15 */ public final class TypeSafeUtil { private static final String CONF_PATH = "eleconfig.conf"; private static final String M = "m"; private static final String H = "h"; private static final String S = "s";
public static final Config getConfig() {
carryxyh/Electrons
electrons/src/main/java/com/ziyuan/channel/SpecChannel.java
// Path: electrons/src/main/java/com/ziyuan/ElectronsHolder.java // public final class ElectronsHolder { // // /** // * 电子 // */ // private Electron electron; // // /** // * 要执行的监听器,这里已经排好序了 // */ // private List<ElectronsListener> listeners; // // public Electron getElectron() { // return electron; // } // // public void setElectron(Electron electron) { // this.electron = electron; // } // // public List<ElectronsListener> getListeners() { // return listeners; // } // // public void setListeners(List<ElectronsListener> listeners) { // this.listeners = listeners; // } // // /** // * 处理 // * // * @throws Exception 处理过程中的异常,同样抛出去 // */ // public boolean handle() throws Exception { // if (CollectionUtils.isEmpty(listeners)) { // return false; // } // for (ElectronsListener listener : listeners) { // listener.onEvent(electron); // } // return true; // } // // @Override // public String toString() { // return electron.getSource().getClass().getSimpleName() + " - "; // } // } // // Path: electrons/src/main/java/com/ziyuan/exceptions/OpNotSupportException.java // public class OpNotSupportException extends Exception { // // public OpNotSupportException() { // super("Operation not support !"); // } // }
import com.lmax.disruptor.dsl.Disruptor; import com.ziyuan.ElectronsHolder; import com.ziyuan.exceptions.OpNotSupportException; import lombok.Getter; import lombok.Setter; import org.apache.commons.lang3.concurrent.EventCountCircuitBreaker;
package com.ziyuan.channel; /** * SpecChannel 特殊管道,用于处理after逻辑 * * @author ziyuan * @since 2017-03-10 */ public class SpecChannel extends AbstractChannel { public SpecChannel(Disruptor<ElectronsHolder> disruptor) { super(disruptor); } @Setter @Getter private EventCountCircuitBreaker breaker; @Override
// Path: electrons/src/main/java/com/ziyuan/ElectronsHolder.java // public final class ElectronsHolder { // // /** // * 电子 // */ // private Electron electron; // // /** // * 要执行的监听器,这里已经排好序了 // */ // private List<ElectronsListener> listeners; // // public Electron getElectron() { // return electron; // } // // public void setElectron(Electron electron) { // this.electron = electron; // } // // public List<ElectronsListener> getListeners() { // return listeners; // } // // public void setListeners(List<ElectronsListener> listeners) { // this.listeners = listeners; // } // // /** // * 处理 // * // * @throws Exception 处理过程中的异常,同样抛出去 // */ // public boolean handle() throws Exception { // if (CollectionUtils.isEmpty(listeners)) { // return false; // } // for (ElectronsListener listener : listeners) { // listener.onEvent(electron); // } // return true; // } // // @Override // public String toString() { // return electron.getSource().getClass().getSimpleName() + " - "; // } // } // // Path: electrons/src/main/java/com/ziyuan/exceptions/OpNotSupportException.java // public class OpNotSupportException extends Exception { // // public OpNotSupportException() { // super("Operation not support !"); // } // } // Path: electrons/src/main/java/com/ziyuan/channel/SpecChannel.java import com.lmax.disruptor.dsl.Disruptor; import com.ziyuan.ElectronsHolder; import com.ziyuan.exceptions.OpNotSupportException; import lombok.Getter; import lombok.Setter; import org.apache.commons.lang3.concurrent.EventCountCircuitBreaker; package com.ziyuan.channel; /** * SpecChannel 特殊管道,用于处理after逻辑 * * @author ziyuan * @since 2017-03-10 */ public class SpecChannel extends AbstractChannel { public SpecChannel(Disruptor<ElectronsHolder> disruptor) { super(disruptor); } @Setter @Getter private EventCountCircuitBreaker breaker; @Override
public boolean handle(ElectronsHolder electronsHolder) throws OpNotSupportException {
carryxyh/Electrons
electrons/src/main/java/com/ziyuan/channel/AbstractChannel.java
// Path: electrons/src/main/java/com/ziyuan/ElectronsHolder.java // public final class ElectronsHolder { // // /** // * 电子 // */ // private Electron electron; // // /** // * 要执行的监听器,这里已经排好序了 // */ // private List<ElectronsListener> listeners; // // public Electron getElectron() { // return electron; // } // // public void setElectron(Electron electron) { // this.electron = electron; // } // // public List<ElectronsListener> getListeners() { // return listeners; // } // // public void setListeners(List<ElectronsListener> listeners) { // this.listeners = listeners; // } // // /** // * 处理 // * // * @throws Exception 处理过程中的异常,同样抛出去 // */ // public boolean handle() throws Exception { // if (CollectionUtils.isEmpty(listeners)) { // return false; // } // for (ElectronsListener listener : listeners) { // listener.onEvent(electron); // } // return true; // } // // @Override // public String toString() { // return electron.getSource().getClass().getSimpleName() + " - "; // } // }
import com.google.common.util.concurrent.RateLimiter; import com.lmax.disruptor.EventTranslatorOneArg; import com.lmax.disruptor.RingBuffer; import com.lmax.disruptor.dsl.Disruptor; import com.ziyuan.ElectronsHolder; import lombok.Getter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.TimeUnit;
package com.ziyuan.channel; /** * AbstractChannel * * @author ziyuan * @since 2017-03-08 */ public abstract class AbstractChannel implements Channel { /** * logger */ protected static final Logger LOGGER = LoggerFactory.getLogger(AbstractChannel.class); /** * 限流 */ private RateLimiter rateLimiter; /** * 是否开启限速 */ @Getter private boolean limitRate; /** * 开启 */ protected volatile boolean opened; /** * disruptor */ @Getter
// Path: electrons/src/main/java/com/ziyuan/ElectronsHolder.java // public final class ElectronsHolder { // // /** // * 电子 // */ // private Electron electron; // // /** // * 要执行的监听器,这里已经排好序了 // */ // private List<ElectronsListener> listeners; // // public Electron getElectron() { // return electron; // } // // public void setElectron(Electron electron) { // this.electron = electron; // } // // public List<ElectronsListener> getListeners() { // return listeners; // } // // public void setListeners(List<ElectronsListener> listeners) { // this.listeners = listeners; // } // // /** // * 处理 // * // * @throws Exception 处理过程中的异常,同样抛出去 // */ // public boolean handle() throws Exception { // if (CollectionUtils.isEmpty(listeners)) { // return false; // } // for (ElectronsListener listener : listeners) { // listener.onEvent(electron); // } // return true; // } // // @Override // public String toString() { // return electron.getSource().getClass().getSimpleName() + " - "; // } // } // Path: electrons/src/main/java/com/ziyuan/channel/AbstractChannel.java import com.google.common.util.concurrent.RateLimiter; import com.lmax.disruptor.EventTranslatorOneArg; import com.lmax.disruptor.RingBuffer; import com.lmax.disruptor.dsl.Disruptor; import com.ziyuan.ElectronsHolder; import lombok.Getter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.TimeUnit; package com.ziyuan.channel; /** * AbstractChannel * * @author ziyuan * @since 2017-03-08 */ public abstract class AbstractChannel implements Channel { /** * logger */ protected static final Logger LOGGER = LoggerFactory.getLogger(AbstractChannel.class); /** * 限流 */ private RateLimiter rateLimiter; /** * 是否开启限速 */ @Getter private boolean limitRate; /** * 开启 */ protected volatile boolean opened; /** * disruptor */ @Getter
private final Disruptor<ElectronsHolder> disruptor;
carryxyh/Electrons
electrons/src/main/java/com/ziyuan/channel/Channel.java
// Path: electrons/src/main/java/com/ziyuan/ElectronsHolder.java // public final class ElectronsHolder { // // /** // * 电子 // */ // private Electron electron; // // /** // * 要执行的监听器,这里已经排好序了 // */ // private List<ElectronsListener> listeners; // // public Electron getElectron() { // return electron; // } // // public void setElectron(Electron electron) { // this.electron = electron; // } // // public List<ElectronsListener> getListeners() { // return listeners; // } // // public void setListeners(List<ElectronsListener> listeners) { // this.listeners = listeners; // } // // /** // * 处理 // * // * @throws Exception 处理过程中的异常,同样抛出去 // */ // public boolean handle() throws Exception { // if (CollectionUtils.isEmpty(listeners)) { // return false; // } // for (ElectronsListener listener : listeners) { // listener.onEvent(electron); // } // return true; // } // // @Override // public String toString() { // return electron.getSource().getClass().getSimpleName() + " - "; // } // } // // Path: electrons/src/main/java/com/ziyuan/exceptions/OpNotSupportException.java // public class OpNotSupportException extends Exception { // // public OpNotSupportException() { // super("Operation not support !"); // } // }
import com.ziyuan.ElectronsHolder; import com.ziyuan.exceptions.OpNotSupportException; import java.io.Serializable; import java.util.concurrent.TimeUnit;
package com.ziyuan.channel; /** * Channel * * @author ziyuan * @since 2017-03-08 */ public interface Channel extends Serializable { /** * 根据disruptor开启一个通道 */ void open(); /** * 关闭管道 */ void close(); /** * 发布事件 */
// Path: electrons/src/main/java/com/ziyuan/ElectronsHolder.java // public final class ElectronsHolder { // // /** // * 电子 // */ // private Electron electron; // // /** // * 要执行的监听器,这里已经排好序了 // */ // private List<ElectronsListener> listeners; // // public Electron getElectron() { // return electron; // } // // public void setElectron(Electron electron) { // this.electron = electron; // } // // public List<ElectronsListener> getListeners() { // return listeners; // } // // public void setListeners(List<ElectronsListener> listeners) { // this.listeners = listeners; // } // // /** // * 处理 // * // * @throws Exception 处理过程中的异常,同样抛出去 // */ // public boolean handle() throws Exception { // if (CollectionUtils.isEmpty(listeners)) { // return false; // } // for (ElectronsListener listener : listeners) { // listener.onEvent(electron); // } // return true; // } // // @Override // public String toString() { // return electron.getSource().getClass().getSimpleName() + " - "; // } // } // // Path: electrons/src/main/java/com/ziyuan/exceptions/OpNotSupportException.java // public class OpNotSupportException extends Exception { // // public OpNotSupportException() { // super("Operation not support !"); // } // } // Path: electrons/src/main/java/com/ziyuan/channel/Channel.java import com.ziyuan.ElectronsHolder; import com.ziyuan.exceptions.OpNotSupportException; import java.io.Serializable; import java.util.concurrent.TimeUnit; package com.ziyuan.channel; /** * Channel * * @author ziyuan * @since 2017-03-08 */ public interface Channel extends Serializable { /** * 根据disruptor开启一个通道 */ void open(); /** * 关闭管道 */ void close(); /** * 发布事件 */
boolean publish(ElectronsHolder electronsHolder) throws Exception;
carryxyh/Electrons
electrons/src/main/java/com/ziyuan/channel/Channel.java
// Path: electrons/src/main/java/com/ziyuan/ElectronsHolder.java // public final class ElectronsHolder { // // /** // * 电子 // */ // private Electron electron; // // /** // * 要执行的监听器,这里已经排好序了 // */ // private List<ElectronsListener> listeners; // // public Electron getElectron() { // return electron; // } // // public void setElectron(Electron electron) { // this.electron = electron; // } // // public List<ElectronsListener> getListeners() { // return listeners; // } // // public void setListeners(List<ElectronsListener> listeners) { // this.listeners = listeners; // } // // /** // * 处理 // * // * @throws Exception 处理过程中的异常,同样抛出去 // */ // public boolean handle() throws Exception { // if (CollectionUtils.isEmpty(listeners)) { // return false; // } // for (ElectronsListener listener : listeners) { // listener.onEvent(electron); // } // return true; // } // // @Override // public String toString() { // return electron.getSource().getClass().getSimpleName() + " - "; // } // } // // Path: electrons/src/main/java/com/ziyuan/exceptions/OpNotSupportException.java // public class OpNotSupportException extends Exception { // // public OpNotSupportException() { // super("Operation not support !"); // } // }
import com.ziyuan.ElectronsHolder; import com.ziyuan.exceptions.OpNotSupportException; import java.io.Serializable; import java.util.concurrent.TimeUnit;
package com.ziyuan.channel; /** * Channel * * @author ziyuan * @since 2017-03-08 */ public interface Channel extends Serializable { /** * 根据disruptor开启一个通道 */ void open(); /** * 关闭管道 */ void close(); /** * 发布事件 */ boolean publish(ElectronsHolder electronsHolder) throws Exception; /** * 同步处理 */
// Path: electrons/src/main/java/com/ziyuan/ElectronsHolder.java // public final class ElectronsHolder { // // /** // * 电子 // */ // private Electron electron; // // /** // * 要执行的监听器,这里已经排好序了 // */ // private List<ElectronsListener> listeners; // // public Electron getElectron() { // return electron; // } // // public void setElectron(Electron electron) { // this.electron = electron; // } // // public List<ElectronsListener> getListeners() { // return listeners; // } // // public void setListeners(List<ElectronsListener> listeners) { // this.listeners = listeners; // } // // /** // * 处理 // * // * @throws Exception 处理过程中的异常,同样抛出去 // */ // public boolean handle() throws Exception { // if (CollectionUtils.isEmpty(listeners)) { // return false; // } // for (ElectronsListener listener : listeners) { // listener.onEvent(electron); // } // return true; // } // // @Override // public String toString() { // return electron.getSource().getClass().getSimpleName() + " - "; // } // } // // Path: electrons/src/main/java/com/ziyuan/exceptions/OpNotSupportException.java // public class OpNotSupportException extends Exception { // // public OpNotSupportException() { // super("Operation not support !"); // } // } // Path: electrons/src/main/java/com/ziyuan/channel/Channel.java import com.ziyuan.ElectronsHolder; import com.ziyuan.exceptions.OpNotSupportException; import java.io.Serializable; import java.util.concurrent.TimeUnit; package com.ziyuan.channel; /** * Channel * * @author ziyuan * @since 2017-03-08 */ public interface Channel extends Serializable { /** * 根据disruptor开启一个通道 */ void open(); /** * 关闭管道 */ void close(); /** * 发布事件 */ boolean publish(ElectronsHolder electronsHolder) throws Exception; /** * 同步处理 */
boolean handle(ElectronsHolder electronsHolder) throws OpNotSupportException;
tim740/skUtilities
src/uk/tim740/skUtilities/skUtilities.java
// Path: src/uk/tim740/skUtilities/util/EffReloadConfig.java // public class EffReloadConfig extends Effect { // private Expression<String> str; // // @Override // protected void execute(Event e) { // try { // Bukkit.getPluginManager().getPlugin(str.getSingle(e)).reloadConfig(); // } catch (Exception x) { // skUtilities.prSysE("'" + str + "' isn't a real plugin!", getClass().getSimpleName(), x); // } // } // // @SuppressWarnings("unchecked") // @Override // public boolean init(Expression<?>[] e, int i, Kleenean k, SkriptParser.ParseResult p) { // str = (Expression<String>) e[0]; // return true; // } // // @Override // public String toString(@Nullable Event e, boolean b) { // return getClass().getName(); // } // }
import ch.njol.skript.Skript; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.plugin.java.JavaPlugin; import uk.tim740.skUtilities.util.EffReloadConfig; import java.io.File; import java.net.URL; import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.DecimalFormat; import java.time.Duration;
prSysI(""); } catch (Exception x) { skUtilities.prSysE(x.getMessage(), getClass().getSimpleName(), x); } } String ls = ""; try { if (getConfig().getBoolean("loadConversions", true)) { ls += "Conversions,"; Reg.convert(); } if (getConfig().getBoolean("loadFiles", true)) { ls += " Files,"; Reg.files(); } if (getConfig().getBoolean("loadYaml", true)) { ls += " Yaml,"; Reg.yaml(); } if (getConfig().getBoolean("loadUrls", true)) { ls += " Urls,"; Reg.url(); } if (getConfig().getBoolean("loadUtilities", true)) { ls += " Utilities"; Reg.utils(); } } catch (Exception e) { e.printStackTrace(); }
// Path: src/uk/tim740/skUtilities/util/EffReloadConfig.java // public class EffReloadConfig extends Effect { // private Expression<String> str; // // @Override // protected void execute(Event e) { // try { // Bukkit.getPluginManager().getPlugin(str.getSingle(e)).reloadConfig(); // } catch (Exception x) { // skUtilities.prSysE("'" + str + "' isn't a real plugin!", getClass().getSimpleName(), x); // } // } // // @SuppressWarnings("unchecked") // @Override // public boolean init(Expression<?>[] e, int i, Kleenean k, SkriptParser.ParseResult p) { // str = (Expression<String>) e[0]; // return true; // } // // @Override // public String toString(@Nullable Event e, boolean b) { // return getClass().getName(); // } // } // Path: src/uk/tim740/skUtilities/skUtilities.java import ch.njol.skript.Skript; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.plugin.java.JavaPlugin; import uk.tim740.skUtilities.util.EffReloadConfig; import java.io.File; import java.net.URL; import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.DecimalFormat; import java.time.Duration; prSysI(""); } catch (Exception x) { skUtilities.prSysE(x.getMessage(), getClass().getSimpleName(), x); } } String ls = ""; try { if (getConfig().getBoolean("loadConversions", true)) { ls += "Conversions,"; Reg.convert(); } if (getConfig().getBoolean("loadFiles", true)) { ls += " Files,"; Reg.files(); } if (getConfig().getBoolean("loadYaml", true)) { ls += " Yaml,"; Reg.yaml(); } if (getConfig().getBoolean("loadUrls", true)) { ls += " Urls,"; Reg.url(); } if (getConfig().getBoolean("loadUtilities", true)) { ls += " Utilities"; Reg.utils(); } } catch (Exception e) { e.printStackTrace(); }
Skript.registerEffect(EffReloadConfig.class, "reload %string%'s config", "reload config of %string%");
diffplug/durian-rx
src/test/java/com/diffplug/common/rx/RxOrderedSetTest.java
// Path: src/main/java/com/diffplug/common/rx/RxOrderedSet.java // public enum OnDuplicate { // /** Throws an error when a duplicate is encountered. */ // ERROR, // /** Resolve duplicates by taking the first duplicate in the list. */ // TAKE_FIRST, // /** Resolve duplicates by taking the last duplicate in the list. */ // TAKE_LAST // }
import com.diffplug.common.collect.ImmutableList; import com.diffplug.common.rx.RxOrderedSet.OnDuplicate; import java.util.Arrays; import java.util.List; import org.junit.Assert; import org.junit.Test;
/* * Copyright 2020 DiffPlug * * 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 * * https://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.diffplug.common.rx; public class RxOrderedSetTest { @Test public void testDisallowDuplicates() { // first and last
// Path: src/main/java/com/diffplug/common/rx/RxOrderedSet.java // public enum OnDuplicate { // /** Throws an error when a duplicate is encountered. */ // ERROR, // /** Resolve duplicates by taking the first duplicate in the list. */ // TAKE_FIRST, // /** Resolve duplicates by taking the last duplicate in the list. */ // TAKE_LAST // } // Path: src/test/java/com/diffplug/common/rx/RxOrderedSetTest.java import com.diffplug.common.collect.ImmutableList; import com.diffplug.common.rx.RxOrderedSet.OnDuplicate; import java.util.Arrays; import java.util.List; import org.junit.Assert; import org.junit.Test; /* * Copyright 2020 DiffPlug * * 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 * * https://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.diffplug.common.rx; public class RxOrderedSetTest { @Test public void testDisallowDuplicates() { // first and last
testCase(Arrays.asList(1, 2, 3, 4, 5), Arrays.asList(1, 2, 3, 4, 5, 1), OnDuplicate.TAKE_FIRST, Arrays.asList(1, 2, 3, 4, 5));
googlemaps/java-fleetengine-auth
src/main/java/com/google/fleetengine/auth/token/factory/signer/DefaultServiceAccountSigner.java
// Path: src/main/java/com/google/fleetengine/auth/token/FleetEngineToken.java // @AutoValue // public abstract class FleetEngineToken { // /** Token creation timestamp. */ // public abstract Date creationTimestamp(); // // /** Token expiration timestamp. */ // public abstract Date expirationTimestamp(); // // /** Audience (aud claim) of the JWT. */ // public abstract String audience(); // // /** Signed and base64 encoded JWT. */ // @Nullable // public abstract String jwt(); // // /** Scope of the authorization token. */ // public abstract FleetEngineTokenType tokenType(); // // /** Custom authorization claims written to JWT. */ // public abstract FleetEngineTokenClaims authorizationClaims(); // // /** Provides a builder for {@link FleetEngineToken}. */ // public static Builder builder() { // return new AutoValue_FleetEngineToken.Builder() // .setAudience(CommonConstants.DEFAULT_JWT_AUDIENCE); // } // // public abstract FleetEngineToken.Builder toBuilder(); // // /** Builder class for FleetEngineToken. */ // @AutoValue.Builder // public abstract static class Builder { // // /** Setter for token creation timestamp. */ // public abstract Builder setCreationTimestamp(Date creationTimestamp); // // /** Setter for token expiration timestamp. */ // public abstract Builder setExpirationTimestamp(Date expirationTimestamp); // // /** Setter for a signed JWT to be associated with the token object. */ // public abstract Builder setJwt(String token); // // /** Setter for the token type defining the scope of the token. */ // public abstract Builder setTokenType(FleetEngineTokenType type); // // /** Setter for token audience (aud claim). */ // public abstract Builder setAudience(String audience); // // /** Sets custom authorization claims written to JWT. */ // public abstract Builder setAuthorizationClaims(FleetEngineTokenClaims claims); // // /** Builds the token object. */ // public abstract FleetEngineToken build(); // } // } // // Path: src/main/java/com/google/fleetengine/auth/token/factory/signer/util/CommonConstants.java // public final class CommonConstants { // /* JWT name of the authorization claim. */ // public static final String JWT_CLAIM_AUTHORIZATION_PROPERTY = "authorization"; // // /* Default value of the JWT audience (aud claim). */ // public static final String DEFAULT_JWT_AUDIENCE = "https://fleetengine.googleapis.com/"; // // private CommonConstants() {} // }
import com.auth0.jwt.JWT; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.SignatureVerificationException; import com.auth0.jwt.interfaces.DecodedJWT; import com.google.auth.oauth2.GoogleCredentials; import com.google.auth.oauth2.ServiceAccountCredentials; import com.google.common.annotations.VisibleForTesting; import com.google.fleetengine.auth.token.FleetEngineToken; import com.google.fleetengine.auth.token.factory.signer.util.CommonConstants; import java.io.IOException;
// Copyright 2021 Google LLC // // 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.fleetengine.auth.token.factory.signer; /** * Signs Fleet Engine tokens with the GCP service account that is running the application. * * <p>The default service account that the application is running under <b>MUST</b> have the * iam.serviceAccounts.signBlob permission. This is typically acquired through the "Service Account * Token Creator" role. * * <p>The default service account <b>MUST</b> have the same role as the {@link * com.google.fleetengine.auth.token.FleetEngineTokenType} of the token being signed. */ public class DefaultServiceAccountSigner implements Signer { private static final String ALGORITHM_NAME = "RS256"; private static final String ALGORITHM_DESCRIPTION = "SHA256withRSA"; private final ServiceAccountSignerCredentials serviceAccountCredentials; /** * Creates signer that uses the currently running service account. * * @throws SignerInitializationException if the credentials cannot be created in the current * environment OR if the default user is not a service account. */ public static DefaultServiceAccountSigner create() throws SignerInitializationException { GoogleCredentials defaultCredentials; try { defaultCredentials = GoogleCredentials.getApplicationDefault(); } catch (IOException e) { throw new SignerInitializationException( "Could not retrieve credentials for default application.", e); } return create(defaultCredentials); } @VisibleForTesting static DefaultServiceAccountSigner create(GoogleCredentials defaultCredentials) throws SignerInitializationException { if (!(defaultCredentials instanceof ServiceAccountCredentials)) { throw new SignerInitializationException( "GCP default user account running the application is a NOT a service account."); } return new DefaultServiceAccountSigner( new ServiceAccountSignerCredentials((ServiceAccountCredentials) defaultCredentials)); } /** Constructor. */ @VisibleForTesting DefaultServiceAccountSigner(ServiceAccountSignerCredentials serviceAccountCredentials) { this.serviceAccountCredentials = serviceAccountCredentials; } /** * Signs a provided Fleet Engine token with the default service account. * * <p>The default service account that the application is running under <b>MUST</b> have the * iam.serviceAccounts.signBlob permission. This is typically acquired through the "Service * Account Token Creator" role. * * <p>The default service account <b>MUST</b> have the same role as the {@link * com.google.fleetengine.auth.token.FleetEngineTokenType} of the token being signed. * * @param token Fleet Engine token to sign * @return same value as the {@code token} parameter except with the JWT property set to a valid * JWT */ @Override
// Path: src/main/java/com/google/fleetengine/auth/token/FleetEngineToken.java // @AutoValue // public abstract class FleetEngineToken { // /** Token creation timestamp. */ // public abstract Date creationTimestamp(); // // /** Token expiration timestamp. */ // public abstract Date expirationTimestamp(); // // /** Audience (aud claim) of the JWT. */ // public abstract String audience(); // // /** Signed and base64 encoded JWT. */ // @Nullable // public abstract String jwt(); // // /** Scope of the authorization token. */ // public abstract FleetEngineTokenType tokenType(); // // /** Custom authorization claims written to JWT. */ // public abstract FleetEngineTokenClaims authorizationClaims(); // // /** Provides a builder for {@link FleetEngineToken}. */ // public static Builder builder() { // return new AutoValue_FleetEngineToken.Builder() // .setAudience(CommonConstants.DEFAULT_JWT_AUDIENCE); // } // // public abstract FleetEngineToken.Builder toBuilder(); // // /** Builder class for FleetEngineToken. */ // @AutoValue.Builder // public abstract static class Builder { // // /** Setter for token creation timestamp. */ // public abstract Builder setCreationTimestamp(Date creationTimestamp); // // /** Setter for token expiration timestamp. */ // public abstract Builder setExpirationTimestamp(Date expirationTimestamp); // // /** Setter for a signed JWT to be associated with the token object. */ // public abstract Builder setJwt(String token); // // /** Setter for the token type defining the scope of the token. */ // public abstract Builder setTokenType(FleetEngineTokenType type); // // /** Setter for token audience (aud claim). */ // public abstract Builder setAudience(String audience); // // /** Sets custom authorization claims written to JWT. */ // public abstract Builder setAuthorizationClaims(FleetEngineTokenClaims claims); // // /** Builds the token object. */ // public abstract FleetEngineToken build(); // } // } // // Path: src/main/java/com/google/fleetengine/auth/token/factory/signer/util/CommonConstants.java // public final class CommonConstants { // /* JWT name of the authorization claim. */ // public static final String JWT_CLAIM_AUTHORIZATION_PROPERTY = "authorization"; // // /* Default value of the JWT audience (aud claim). */ // public static final String DEFAULT_JWT_AUDIENCE = "https://fleetengine.googleapis.com/"; // // private CommonConstants() {} // } // Path: src/main/java/com/google/fleetengine/auth/token/factory/signer/DefaultServiceAccountSigner.java import com.auth0.jwt.JWT; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.SignatureVerificationException; import com.auth0.jwt.interfaces.DecodedJWT; import com.google.auth.oauth2.GoogleCredentials; import com.google.auth.oauth2.ServiceAccountCredentials; import com.google.common.annotations.VisibleForTesting; import com.google.fleetengine.auth.token.FleetEngineToken; import com.google.fleetengine.auth.token.factory.signer.util.CommonConstants; import java.io.IOException; // Copyright 2021 Google LLC // // 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.fleetengine.auth.token.factory.signer; /** * Signs Fleet Engine tokens with the GCP service account that is running the application. * * <p>The default service account that the application is running under <b>MUST</b> have the * iam.serviceAccounts.signBlob permission. This is typically acquired through the "Service Account * Token Creator" role. * * <p>The default service account <b>MUST</b> have the same role as the {@link * com.google.fleetengine.auth.token.FleetEngineTokenType} of the token being signed. */ public class DefaultServiceAccountSigner implements Signer { private static final String ALGORITHM_NAME = "RS256"; private static final String ALGORITHM_DESCRIPTION = "SHA256withRSA"; private final ServiceAccountSignerCredentials serviceAccountCredentials; /** * Creates signer that uses the currently running service account. * * @throws SignerInitializationException if the credentials cannot be created in the current * environment OR if the default user is not a service account. */ public static DefaultServiceAccountSigner create() throws SignerInitializationException { GoogleCredentials defaultCredentials; try { defaultCredentials = GoogleCredentials.getApplicationDefault(); } catch (IOException e) { throw new SignerInitializationException( "Could not retrieve credentials for default application.", e); } return create(defaultCredentials); } @VisibleForTesting static DefaultServiceAccountSigner create(GoogleCredentials defaultCredentials) throws SignerInitializationException { if (!(defaultCredentials instanceof ServiceAccountCredentials)) { throw new SignerInitializationException( "GCP default user account running the application is a NOT a service account."); } return new DefaultServiceAccountSigner( new ServiceAccountSignerCredentials((ServiceAccountCredentials) defaultCredentials)); } /** Constructor. */ @VisibleForTesting DefaultServiceAccountSigner(ServiceAccountSignerCredentials serviceAccountCredentials) { this.serviceAccountCredentials = serviceAccountCredentials; } /** * Signs a provided Fleet Engine token with the default service account. * * <p>The default service account that the application is running under <b>MUST</b> have the * iam.serviceAccounts.signBlob permission. This is typically acquired through the "Service * Account Token Creator" role. * * <p>The default service account <b>MUST</b> have the same role as the {@link * com.google.fleetengine.auth.token.FleetEngineTokenType} of the token being signed. * * @param token Fleet Engine token to sign * @return same value as the {@code token} parameter except with the JWT property set to a valid * JWT */ @Override
public FleetEngineToken sign(FleetEngineToken token) {
googlemaps/java-fleetengine-auth
src/main/java/com/google/fleetengine/auth/token/factory/signer/DefaultServiceAccountSigner.java
// Path: src/main/java/com/google/fleetengine/auth/token/FleetEngineToken.java // @AutoValue // public abstract class FleetEngineToken { // /** Token creation timestamp. */ // public abstract Date creationTimestamp(); // // /** Token expiration timestamp. */ // public abstract Date expirationTimestamp(); // // /** Audience (aud claim) of the JWT. */ // public abstract String audience(); // // /** Signed and base64 encoded JWT. */ // @Nullable // public abstract String jwt(); // // /** Scope of the authorization token. */ // public abstract FleetEngineTokenType tokenType(); // // /** Custom authorization claims written to JWT. */ // public abstract FleetEngineTokenClaims authorizationClaims(); // // /** Provides a builder for {@link FleetEngineToken}. */ // public static Builder builder() { // return new AutoValue_FleetEngineToken.Builder() // .setAudience(CommonConstants.DEFAULT_JWT_AUDIENCE); // } // // public abstract FleetEngineToken.Builder toBuilder(); // // /** Builder class for FleetEngineToken. */ // @AutoValue.Builder // public abstract static class Builder { // // /** Setter for token creation timestamp. */ // public abstract Builder setCreationTimestamp(Date creationTimestamp); // // /** Setter for token expiration timestamp. */ // public abstract Builder setExpirationTimestamp(Date expirationTimestamp); // // /** Setter for a signed JWT to be associated with the token object. */ // public abstract Builder setJwt(String token); // // /** Setter for the token type defining the scope of the token. */ // public abstract Builder setTokenType(FleetEngineTokenType type); // // /** Setter for token audience (aud claim). */ // public abstract Builder setAudience(String audience); // // /** Sets custom authorization claims written to JWT. */ // public abstract Builder setAuthorizationClaims(FleetEngineTokenClaims claims); // // /** Builds the token object. */ // public abstract FleetEngineToken build(); // } // } // // Path: src/main/java/com/google/fleetengine/auth/token/factory/signer/util/CommonConstants.java // public final class CommonConstants { // /* JWT name of the authorization claim. */ // public static final String JWT_CLAIM_AUTHORIZATION_PROPERTY = "authorization"; // // /* Default value of the JWT audience (aud claim). */ // public static final String DEFAULT_JWT_AUDIENCE = "https://fleetengine.googleapis.com/"; // // private CommonConstants() {} // }
import com.auth0.jwt.JWT; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.SignatureVerificationException; import com.auth0.jwt.interfaces.DecodedJWT; import com.google.auth.oauth2.GoogleCredentials; import com.google.auth.oauth2.ServiceAccountCredentials; import com.google.common.annotations.VisibleForTesting; import com.google.fleetengine.auth.token.FleetEngineToken; import com.google.fleetengine.auth.token.factory.signer.util.CommonConstants; import java.io.IOException;
/** Constructor. */ @VisibleForTesting DefaultServiceAccountSigner(ServiceAccountSignerCredentials serviceAccountCredentials) { this.serviceAccountCredentials = serviceAccountCredentials; } /** * Signs a provided Fleet Engine token with the default service account. * * <p>The default service account that the application is running under <b>MUST</b> have the * iam.serviceAccounts.signBlob permission. This is typically acquired through the "Service * Account Token Creator" role. * * <p>The default service account <b>MUST</b> have the same role as the {@link * com.google.fleetengine.auth.token.FleetEngineTokenType} of the token being signed. * * @param token Fleet Engine token to sign * @return same value as the {@code token} parameter except with the JWT property set to a valid * JWT */ @Override public FleetEngineToken sign(FleetEngineToken token) { String signedToken = JWT.create() .withIssuer(serviceAccountCredentials.getClientEmail()) .withSubject(serviceAccountCredentials.getClientEmail()) .withAudience(token.audience()) .withExpiresAt(token.expirationTimestamp()) .withIssuedAt(token.creationTimestamp()) .withClaim(
// Path: src/main/java/com/google/fleetengine/auth/token/FleetEngineToken.java // @AutoValue // public abstract class FleetEngineToken { // /** Token creation timestamp. */ // public abstract Date creationTimestamp(); // // /** Token expiration timestamp. */ // public abstract Date expirationTimestamp(); // // /** Audience (aud claim) of the JWT. */ // public abstract String audience(); // // /** Signed and base64 encoded JWT. */ // @Nullable // public abstract String jwt(); // // /** Scope of the authorization token. */ // public abstract FleetEngineTokenType tokenType(); // // /** Custom authorization claims written to JWT. */ // public abstract FleetEngineTokenClaims authorizationClaims(); // // /** Provides a builder for {@link FleetEngineToken}. */ // public static Builder builder() { // return new AutoValue_FleetEngineToken.Builder() // .setAudience(CommonConstants.DEFAULT_JWT_AUDIENCE); // } // // public abstract FleetEngineToken.Builder toBuilder(); // // /** Builder class for FleetEngineToken. */ // @AutoValue.Builder // public abstract static class Builder { // // /** Setter for token creation timestamp. */ // public abstract Builder setCreationTimestamp(Date creationTimestamp); // // /** Setter for token expiration timestamp. */ // public abstract Builder setExpirationTimestamp(Date expirationTimestamp); // // /** Setter for a signed JWT to be associated with the token object. */ // public abstract Builder setJwt(String token); // // /** Setter for the token type defining the scope of the token. */ // public abstract Builder setTokenType(FleetEngineTokenType type); // // /** Setter for token audience (aud claim). */ // public abstract Builder setAudience(String audience); // // /** Sets custom authorization claims written to JWT. */ // public abstract Builder setAuthorizationClaims(FleetEngineTokenClaims claims); // // /** Builds the token object. */ // public abstract FleetEngineToken build(); // } // } // // Path: src/main/java/com/google/fleetengine/auth/token/factory/signer/util/CommonConstants.java // public final class CommonConstants { // /* JWT name of the authorization claim. */ // public static final String JWT_CLAIM_AUTHORIZATION_PROPERTY = "authorization"; // // /* Default value of the JWT audience (aud claim). */ // public static final String DEFAULT_JWT_AUDIENCE = "https://fleetengine.googleapis.com/"; // // private CommonConstants() {} // } // Path: src/main/java/com/google/fleetengine/auth/token/factory/signer/DefaultServiceAccountSigner.java import com.auth0.jwt.JWT; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.SignatureVerificationException; import com.auth0.jwt.interfaces.DecodedJWT; import com.google.auth.oauth2.GoogleCredentials; import com.google.auth.oauth2.ServiceAccountCredentials; import com.google.common.annotations.VisibleForTesting; import com.google.fleetengine.auth.token.FleetEngineToken; import com.google.fleetengine.auth.token.factory.signer.util.CommonConstants; import java.io.IOException; /** Constructor. */ @VisibleForTesting DefaultServiceAccountSigner(ServiceAccountSignerCredentials serviceAccountCredentials) { this.serviceAccountCredentials = serviceAccountCredentials; } /** * Signs a provided Fleet Engine token with the default service account. * * <p>The default service account that the application is running under <b>MUST</b> have the * iam.serviceAccounts.signBlob permission. This is typically acquired through the "Service * Account Token Creator" role. * * <p>The default service account <b>MUST</b> have the same role as the {@link * com.google.fleetengine.auth.token.FleetEngineTokenType} of the token being signed. * * @param token Fleet Engine token to sign * @return same value as the {@code token} parameter except with the JWT property set to a valid * JWT */ @Override public FleetEngineToken sign(FleetEngineToken token) { String signedToken = JWT.create() .withIssuer(serviceAccountCredentials.getClientEmail()) .withSubject(serviceAccountCredentials.getClientEmail()) .withAudience(token.audience()) .withExpiresAt(token.expirationTimestamp()) .withIssuedAt(token.creationTimestamp()) .withClaim(
CommonConstants.JWT_CLAIM_AUTHORIZATION_PROPERTY,
googlemaps/java-fleetengine-auth
sample/src/main/java/com/google/fleetengine/auth/sample/validation/ConsumerTokenValidationScript.java
// Path: src/main/java/com/google/fleetengine/auth/token/TripClaims.java // public class TripClaims implements FleetEngineTokenClaims { // private static final String WILDCARD = "*"; // static final String CLAIM_TRIP_ID = "tripid"; // private final boolean isWildcard; // // private final ImmutableMap<String, String> map; // // /** // * Creates a trip claim that works with any trip. // * // * @return custom auth claim // */ // public static TripClaims create() { // return new TripClaims(WILDCARD); // } // // /** // * Creates a trip claim with an id. // * // * @param tripId id of the trip id on the token scope // * @return custom auth claim // * @throws IllegalArgumentException when tripId is null or empty // */ // public static TripClaims create(String tripId) { // if (Strings.isNullOrEmpty(tripId)) { // throw new IllegalArgumentException("tripId must have a value"); // } // return new TripClaims(tripId); // } // // /** Indicates whether the claim restricts access to just one trip. */ // @Override // public boolean isWildcard() { // return isWildcard; // } // // private TripClaims(String tripId) { // map = ImmutableMap.of(CLAIM_TRIP_ID, tripId); // isWildcard = WILDCARD.equals(tripId); // } // // /** {@inheritDoc} */ // @Override // public ImmutableMap<String, String> toMap() { // return map; // } // }
import com.google.fleetengine.auth.token.TripClaims;
// Copyright 2021 Google LLC // // 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.fleetengine.auth.sample.validation; /** Validates that consumer tokens provide the correct level of access. */ public class ConsumerTokenValidationScript { private final SampleScriptRuntime runtime; private final SampleScriptConfiguration configuration; private final CommandsFactory commandsFactory; /** Constructor. */ public ConsumerTokenValidationScript( SampleScriptRuntime runtime, SampleScriptConfiguration configuration, CommandsFactory commandsFactory) { this.runtime = runtime; this.configuration = configuration; this.commandsFactory = commandsFactory; } /** * Run validation script. * * @param tripId existing trip id */ public void run(String tripId) throws Throwable { // Tokens are minted with the consumer role and authorized to access tripId. TripCommands tripCommands = commandsFactory.createTripCommands( configuration.getFleetEngineAddress(), configuration.getProviderId(),
// Path: src/main/java/com/google/fleetengine/auth/token/TripClaims.java // public class TripClaims implements FleetEngineTokenClaims { // private static final String WILDCARD = "*"; // static final String CLAIM_TRIP_ID = "tripid"; // private final boolean isWildcard; // // private final ImmutableMap<String, String> map; // // /** // * Creates a trip claim that works with any trip. // * // * @return custom auth claim // */ // public static TripClaims create() { // return new TripClaims(WILDCARD); // } // // /** // * Creates a trip claim with an id. // * // * @param tripId id of the trip id on the token scope // * @return custom auth claim // * @throws IllegalArgumentException when tripId is null or empty // */ // public static TripClaims create(String tripId) { // if (Strings.isNullOrEmpty(tripId)) { // throw new IllegalArgumentException("tripId must have a value"); // } // return new TripClaims(tripId); // } // // /** Indicates whether the claim restricts access to just one trip. */ // @Override // public boolean isWildcard() { // return isWildcard; // } // // private TripClaims(String tripId) { // map = ImmutableMap.of(CLAIM_TRIP_ID, tripId); // isWildcard = WILDCARD.equals(tripId); // } // // /** {@inheritDoc} */ // @Override // public ImmutableMap<String, String> toMap() { // return map; // } // } // Path: sample/src/main/java/com/google/fleetengine/auth/sample/validation/ConsumerTokenValidationScript.java import com.google.fleetengine.auth.token.TripClaims; // Copyright 2021 Google LLC // // 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.fleetengine.auth.sample.validation; /** Validates that consumer tokens provide the correct level of access. */ public class ConsumerTokenValidationScript { private final SampleScriptRuntime runtime; private final SampleScriptConfiguration configuration; private final CommandsFactory commandsFactory; /** Constructor. */ public ConsumerTokenValidationScript( SampleScriptRuntime runtime, SampleScriptConfiguration configuration, CommandsFactory commandsFactory) { this.runtime = runtime; this.configuration = configuration; this.commandsFactory = commandsFactory; } /** * Run validation script. * * @param tripId existing trip id */ public void run(String tripId) throws Throwable { // Tokens are minted with the consumer role and authorized to access tripId. TripCommands tripCommands = commandsFactory.createTripCommands( configuration.getFleetEngineAddress(), configuration.getProviderId(),
() -> configuration.getMinter().getConsumerToken(TripClaims.create(tripId)));
googlemaps/java-fleetengine-auth
sample/src/main/java/com/google/fleetengine/auth/sample/validation/DriverTokenValidationScript.java
// Path: src/main/java/com/google/fleetengine/auth/token/VehicleClaims.java // public class VehicleClaims implements FleetEngineTokenClaims { // private static final String WILDCARD = "*"; // static final String CLAIM_VEHICLE_ID = "vehicleid"; // private final boolean isWildcard; // // private final ImmutableMap<String, String> map; // // /** // * Creates a vehicle claim that works with any vehicle. // * // * @return custom auth claim // */ // public static VehicleClaims create() { // return new VehicleClaims(WILDCARD); // } // // /** Indicates whether the claim restricts access to just one vehicle. */ // @Override // public boolean isWildcard() { // return isWildcard; // } // // /** // * Creates a vehicle claim with an id. // * // * @param vehicleId id of the vehicle id on the token scope // * @return custom auth claim // * @throws IllegalArgumentException when vehicleId is null or empty // */ // public static VehicleClaims create(String vehicleId) { // if (Strings.isNullOrEmpty(vehicleId)) { // throw new IllegalArgumentException("vehicleId must have a value"); // } // return new VehicleClaims(vehicleId); // } // // private VehicleClaims(String vehicleId) { // map = ImmutableMap.of(CLAIM_VEHICLE_ID, vehicleId); // isWildcard = WILDCARD.equals(vehicleId); // } // // /** {@inheritDoc} */ // @Override // public ImmutableMap<String, String> toMap() { // return map; // } // }
import com.google.fleetengine.auth.token.VehicleClaims;
// Copyright 2021 Google LLC // // 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.fleetengine.auth.sample.validation; /** Validates that driver tokens provide the correct level of access. */ public class DriverTokenValidationScript { private final SampleScriptRuntime runtime; private final SampleScriptConfiguration configuration; private final CommandsFactory commandsFactory; /** Constructor. */ public DriverTokenValidationScript( SampleScriptRuntime runtime, SampleScriptConfiguration configuration, CommandsFactory commandsFactory) { this.runtime = runtime; this.configuration = configuration; this.commandsFactory = commandsFactory; } /** * Run validation script. * * @param vehicleId existing vehicle id */ public void run(String vehicleId) throws Throwable { // Tokens are minted with the driver role and authorized to access vehicleId. VehicleCommands vehicleCommands = commandsFactory.createVehicleCommands( configuration.getFleetEngineAddress(), configuration.getProviderId(),
// Path: src/main/java/com/google/fleetengine/auth/token/VehicleClaims.java // public class VehicleClaims implements FleetEngineTokenClaims { // private static final String WILDCARD = "*"; // static final String CLAIM_VEHICLE_ID = "vehicleid"; // private final boolean isWildcard; // // private final ImmutableMap<String, String> map; // // /** // * Creates a vehicle claim that works with any vehicle. // * // * @return custom auth claim // */ // public static VehicleClaims create() { // return new VehicleClaims(WILDCARD); // } // // /** Indicates whether the claim restricts access to just one vehicle. */ // @Override // public boolean isWildcard() { // return isWildcard; // } // // /** // * Creates a vehicle claim with an id. // * // * @param vehicleId id of the vehicle id on the token scope // * @return custom auth claim // * @throws IllegalArgumentException when vehicleId is null or empty // */ // public static VehicleClaims create(String vehicleId) { // if (Strings.isNullOrEmpty(vehicleId)) { // throw new IllegalArgumentException("vehicleId must have a value"); // } // return new VehicleClaims(vehicleId); // } // // private VehicleClaims(String vehicleId) { // map = ImmutableMap.of(CLAIM_VEHICLE_ID, vehicleId); // isWildcard = WILDCARD.equals(vehicleId); // } // // /** {@inheritDoc} */ // @Override // public ImmutableMap<String, String> toMap() { // return map; // } // } // Path: sample/src/main/java/com/google/fleetengine/auth/sample/validation/DriverTokenValidationScript.java import com.google.fleetengine.auth.token.VehicleClaims; // Copyright 2021 Google LLC // // 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.fleetengine.auth.sample.validation; /** Validates that driver tokens provide the correct level of access. */ public class DriverTokenValidationScript { private final SampleScriptRuntime runtime; private final SampleScriptConfiguration configuration; private final CommandsFactory commandsFactory; /** Constructor. */ public DriverTokenValidationScript( SampleScriptRuntime runtime, SampleScriptConfiguration configuration, CommandsFactory commandsFactory) { this.runtime = runtime; this.configuration = configuration; this.commandsFactory = commandsFactory; } /** * Run validation script. * * @param vehicleId existing vehicle id */ public void run(String vehicleId) throws Throwable { // Tokens are minted with the driver role and authorized to access vehicleId. VehicleCommands vehicleCommands = commandsFactory.createVehicleCommands( configuration.getFleetEngineAddress(), configuration.getProviderId(),
() -> configuration.getMinter().getDriverToken(VehicleClaims.create(vehicleId)));
googlemaps/java-fleetengine-auth
src/main/java/com/google/fleetengine/auth/client/FleetEngineAuthClientHeaderProvider.java
// Path: src/main/java/com/google/fleetengine/auth/token/factory/signer/SigningTokenException.java // public class SigningTokenException extends Exception { // /** // * Constructs a {@code SigningTokenException} with the specified detail message. // * // * @param message The detail message (which is saved for later retrieval by the {@link // * #getMessage()} method) // */ // public SigningTokenException(String message) { // this(message, null); // } // // /** // * Constructs a {@code SigningTokenException} with the specified detail message. // * // * @param message The detail message (which is saved for later retrieval by the {@link // * #getMessage()} method) // * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). // * (A null value is permitted, and indicates that the cause is nonexistent or unknown.) // */ // public SigningTokenException(String message, Throwable cause) { // super(message, cause); // } // }
import com.google.api.gax.rpc.FixedHeaderProvider; import com.google.api.gax.rpc.HeaderProvider; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.google.fleetengine.auth.token.factory.signer.SigningTokenException; import java.util.Map;
// Copyright 2021 Google LLC // // 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.fleetengine.auth.client; /** * Provides a valid Fleet Engine JWT on the header of an outgoing gRPC request. * * <p>A secondary header provider can be added that provides additional headers. In the event that * the other header provider also contains an authorization header, that header is overwritten. * * <p>Works with generated GAPIC classes. For correct usage, see {@link * FleetEngineClientSettingsModifier}. */ public class FleetEngineAuthClientHeaderProvider implements HeaderProvider { private static final String AUTHORIZATION_HEADER_NAME = "authorization"; @VisibleForTesting final FleetEngineTokenProvider tokenProvider; @VisibleForTesting final HeaderProvider underlyingHeaderProvider; /** * Creates {@link FleetEngineAuthClientHeaderProvider}. * * @param tokenProvider provides fleet engine tokens * @return constructed header provider */ public static FleetEngineAuthClientHeaderProvider create(FleetEngineTokenProvider tokenProvider) { return new FleetEngineAuthClientHeaderProvider(tokenProvider, FixedHeaderProvider.create()); } /** * Creates {@link FleetEngineAuthClientHeaderProvider}. * * @param tokenProvider provides fleet engine tokens * @param underlyingHeaderProvider provides additional headers to the outbound request. * @return constructed header provider */ public static FleetEngineAuthClientHeaderProvider create( FleetEngineTokenProvider tokenProvider, HeaderProvider underlyingHeaderProvider) { return new FleetEngineAuthClientHeaderProvider(tokenProvider, underlyingHeaderProvider); } private FleetEngineAuthClientHeaderProvider( FleetEngineTokenProvider tokenProvider, HeaderProvider underlyingHeaderProvider) { this.underlyingHeaderProvider = underlyingHeaderProvider; this.tokenProvider = tokenProvider; } /** {@inheritDoc} */ @Override public Map<String, String> getHeaders() { try { // If the underlying provider has an authorization header, skip. Map<String, String> underlyingMap = Maps.filterEntries( underlyingHeaderProvider.getHeaders(), entry -> !AUTHORIZATION_HEADER_NAME.equals(entry.getKey())); return new ImmutableMap.Builder<String, String>() .putAll(underlyingMap) .put( AUTHORIZATION_HEADER_NAME, String.format("Bearer %s", tokenProvider.getSignedToken().jwt())) .buildOrThrow();
// Path: src/main/java/com/google/fleetengine/auth/token/factory/signer/SigningTokenException.java // public class SigningTokenException extends Exception { // /** // * Constructs a {@code SigningTokenException} with the specified detail message. // * // * @param message The detail message (which is saved for later retrieval by the {@link // * #getMessage()} method) // */ // public SigningTokenException(String message) { // this(message, null); // } // // /** // * Constructs a {@code SigningTokenException} with the specified detail message. // * // * @param message The detail message (which is saved for later retrieval by the {@link // * #getMessage()} method) // * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). // * (A null value is permitted, and indicates that the cause is nonexistent or unknown.) // */ // public SigningTokenException(String message, Throwable cause) { // super(message, cause); // } // } // Path: src/main/java/com/google/fleetengine/auth/client/FleetEngineAuthClientHeaderProvider.java import com.google.api.gax.rpc.FixedHeaderProvider; import com.google.api.gax.rpc.HeaderProvider; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.google.fleetengine.auth.token.factory.signer.SigningTokenException; import java.util.Map; // Copyright 2021 Google LLC // // 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.fleetengine.auth.client; /** * Provides a valid Fleet Engine JWT on the header of an outgoing gRPC request. * * <p>A secondary header provider can be added that provides additional headers. In the event that * the other header provider also contains an authorization header, that header is overwritten. * * <p>Works with generated GAPIC classes. For correct usage, see {@link * FleetEngineClientSettingsModifier}. */ public class FleetEngineAuthClientHeaderProvider implements HeaderProvider { private static final String AUTHORIZATION_HEADER_NAME = "authorization"; @VisibleForTesting final FleetEngineTokenProvider tokenProvider; @VisibleForTesting final HeaderProvider underlyingHeaderProvider; /** * Creates {@link FleetEngineAuthClientHeaderProvider}. * * @param tokenProvider provides fleet engine tokens * @return constructed header provider */ public static FleetEngineAuthClientHeaderProvider create(FleetEngineTokenProvider tokenProvider) { return new FleetEngineAuthClientHeaderProvider(tokenProvider, FixedHeaderProvider.create()); } /** * Creates {@link FleetEngineAuthClientHeaderProvider}. * * @param tokenProvider provides fleet engine tokens * @param underlyingHeaderProvider provides additional headers to the outbound request. * @return constructed header provider */ public static FleetEngineAuthClientHeaderProvider create( FleetEngineTokenProvider tokenProvider, HeaderProvider underlyingHeaderProvider) { return new FleetEngineAuthClientHeaderProvider(tokenProvider, underlyingHeaderProvider); } private FleetEngineAuthClientHeaderProvider( FleetEngineTokenProvider tokenProvider, HeaderProvider underlyingHeaderProvider) { this.underlyingHeaderProvider = underlyingHeaderProvider; this.tokenProvider = tokenProvider; } /** {@inheritDoc} */ @Override public Map<String, String> getHeaders() { try { // If the underlying provider has an authorization header, skip. Map<String, String> underlyingMap = Maps.filterEntries( underlyingHeaderProvider.getHeaders(), entry -> !AUTHORIZATION_HEADER_NAME.equals(entry.getKey())); return new ImmutableMap.Builder<String, String>() .putAll(underlyingMap) .put( AUTHORIZATION_HEADER_NAME, String.format("Bearer %s", tokenProvider.getSignedToken().jwt())) .buildOrThrow();
} catch (SigningTokenException e) {
googlemaps/java-fleetengine-auth
src/main/java/com/google/fleetengine/auth/token/factory/signer/ImpersonatedSigner.java
// Path: src/main/java/com/google/fleetengine/auth/token/FleetEngineToken.java // @AutoValue // public abstract class FleetEngineToken { // /** Token creation timestamp. */ // public abstract Date creationTimestamp(); // // /** Token expiration timestamp. */ // public abstract Date expirationTimestamp(); // // /** Audience (aud claim) of the JWT. */ // public abstract String audience(); // // /** Signed and base64 encoded JWT. */ // @Nullable // public abstract String jwt(); // // /** Scope of the authorization token. */ // public abstract FleetEngineTokenType tokenType(); // // /** Custom authorization claims written to JWT. */ // public abstract FleetEngineTokenClaims authorizationClaims(); // // /** Provides a builder for {@link FleetEngineToken}. */ // public static Builder builder() { // return new AutoValue_FleetEngineToken.Builder() // .setAudience(CommonConstants.DEFAULT_JWT_AUDIENCE); // } // // public abstract FleetEngineToken.Builder toBuilder(); // // /** Builder class for FleetEngineToken. */ // @AutoValue.Builder // public abstract static class Builder { // // /** Setter for token creation timestamp. */ // public abstract Builder setCreationTimestamp(Date creationTimestamp); // // /** Setter for token expiration timestamp. */ // public abstract Builder setExpirationTimestamp(Date expirationTimestamp); // // /** Setter for a signed JWT to be associated with the token object. */ // public abstract Builder setJwt(String token); // // /** Setter for the token type defining the scope of the token. */ // public abstract Builder setTokenType(FleetEngineTokenType type); // // /** Setter for token audience (aud claim). */ // public abstract Builder setAudience(String audience); // // /** Sets custom authorization claims written to JWT. */ // public abstract Builder setAuthorizationClaims(FleetEngineTokenClaims claims); // // /** Builds the token object. */ // public abstract FleetEngineToken build(); // } // } // // Path: src/main/java/com/google/fleetengine/auth/token/factory/signer/util/CommonConstants.java // public final class CommonConstants { // /* JWT name of the authorization claim. */ // public static final String JWT_CLAIM_AUTHORIZATION_PROPERTY = "authorization"; // // /* Default value of the JWT audience (aud claim). */ // public static final String DEFAULT_JWT_AUDIENCE = "https://fleetengine.googleapis.com/"; // // private CommonConstants() {} // }
import com.auth0.jwt.JWT; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.SignatureVerificationException; import com.auth0.jwt.interfaces.DecodedJWT; import com.google.auth.oauth2.GoogleCredentials; import com.google.auth.oauth2.ImpersonatedCredentials; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.fleetengine.auth.token.FleetEngineToken; import com.google.fleetengine.auth.token.factory.signer.util.CommonConstants; import java.io.IOException; import java.util.Arrays;
ImpersonatedSigner(ImpersonatedAccountSignerCredentials credentials) { this.impersonatedCredentials = credentials; } /** * Creates the impersonated credentials builder that will be used to sign a provided Fleet Engine * token. * * <p>Strictly exists for unit testing purposes since {@code AutoValue} classes cannot be mocked. */ private static ImpersonatedCredentials.Builder createImpersonatedCredentials( String serviceAccount, GoogleCredentials defaultCredentials) { return ImpersonatedCredentials.newBuilder() .setSourceCredentials(defaultCredentials) // Sets the service account that the signer was created with. .setTargetPrincipal(serviceAccount) .setScopes(IAM_SCOPE); } /** * Signs a provided Fleet Engine token. * * <p>The impersonated service account should match the role according to the {@link * com.google.fleetengine.auth.token.FleetEngineTokenType} of the provided token. * * @param token Fleet Engine token to sign * @return same value as the {@code token} parameter except with the JWT property set to a valid * JWT */ @Override
// Path: src/main/java/com/google/fleetengine/auth/token/FleetEngineToken.java // @AutoValue // public abstract class FleetEngineToken { // /** Token creation timestamp. */ // public abstract Date creationTimestamp(); // // /** Token expiration timestamp. */ // public abstract Date expirationTimestamp(); // // /** Audience (aud claim) of the JWT. */ // public abstract String audience(); // // /** Signed and base64 encoded JWT. */ // @Nullable // public abstract String jwt(); // // /** Scope of the authorization token. */ // public abstract FleetEngineTokenType tokenType(); // // /** Custom authorization claims written to JWT. */ // public abstract FleetEngineTokenClaims authorizationClaims(); // // /** Provides a builder for {@link FleetEngineToken}. */ // public static Builder builder() { // return new AutoValue_FleetEngineToken.Builder() // .setAudience(CommonConstants.DEFAULT_JWT_AUDIENCE); // } // // public abstract FleetEngineToken.Builder toBuilder(); // // /** Builder class for FleetEngineToken. */ // @AutoValue.Builder // public abstract static class Builder { // // /** Setter for token creation timestamp. */ // public abstract Builder setCreationTimestamp(Date creationTimestamp); // // /** Setter for token expiration timestamp. */ // public abstract Builder setExpirationTimestamp(Date expirationTimestamp); // // /** Setter for a signed JWT to be associated with the token object. */ // public abstract Builder setJwt(String token); // // /** Setter for the token type defining the scope of the token. */ // public abstract Builder setTokenType(FleetEngineTokenType type); // // /** Setter for token audience (aud claim). */ // public abstract Builder setAudience(String audience); // // /** Sets custom authorization claims written to JWT. */ // public abstract Builder setAuthorizationClaims(FleetEngineTokenClaims claims); // // /** Builds the token object. */ // public abstract FleetEngineToken build(); // } // } // // Path: src/main/java/com/google/fleetengine/auth/token/factory/signer/util/CommonConstants.java // public final class CommonConstants { // /* JWT name of the authorization claim. */ // public static final String JWT_CLAIM_AUTHORIZATION_PROPERTY = "authorization"; // // /* Default value of the JWT audience (aud claim). */ // public static final String DEFAULT_JWT_AUDIENCE = "https://fleetengine.googleapis.com/"; // // private CommonConstants() {} // } // Path: src/main/java/com/google/fleetengine/auth/token/factory/signer/ImpersonatedSigner.java import com.auth0.jwt.JWT; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.SignatureVerificationException; import com.auth0.jwt.interfaces.DecodedJWT; import com.google.auth.oauth2.GoogleCredentials; import com.google.auth.oauth2.ImpersonatedCredentials; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.fleetengine.auth.token.FleetEngineToken; import com.google.fleetengine.auth.token.factory.signer.util.CommonConstants; import java.io.IOException; import java.util.Arrays; ImpersonatedSigner(ImpersonatedAccountSignerCredentials credentials) { this.impersonatedCredentials = credentials; } /** * Creates the impersonated credentials builder that will be used to sign a provided Fleet Engine * token. * * <p>Strictly exists for unit testing purposes since {@code AutoValue} classes cannot be mocked. */ private static ImpersonatedCredentials.Builder createImpersonatedCredentials( String serviceAccount, GoogleCredentials defaultCredentials) { return ImpersonatedCredentials.newBuilder() .setSourceCredentials(defaultCredentials) // Sets the service account that the signer was created with. .setTargetPrincipal(serviceAccount) .setScopes(IAM_SCOPE); } /** * Signs a provided Fleet Engine token. * * <p>The impersonated service account should match the role according to the {@link * com.google.fleetengine.auth.token.FleetEngineTokenType} of the provided token. * * @param token Fleet Engine token to sign * @return same value as the {@code token} parameter except with the JWT property set to a valid * JWT */ @Override
public FleetEngineToken sign(FleetEngineToken token) {
googlemaps/java-fleetengine-auth
src/main/java/com/google/fleetengine/auth/token/factory/signer/ImpersonatedSigner.java
// Path: src/main/java/com/google/fleetengine/auth/token/FleetEngineToken.java // @AutoValue // public abstract class FleetEngineToken { // /** Token creation timestamp. */ // public abstract Date creationTimestamp(); // // /** Token expiration timestamp. */ // public abstract Date expirationTimestamp(); // // /** Audience (aud claim) of the JWT. */ // public abstract String audience(); // // /** Signed and base64 encoded JWT. */ // @Nullable // public abstract String jwt(); // // /** Scope of the authorization token. */ // public abstract FleetEngineTokenType tokenType(); // // /** Custom authorization claims written to JWT. */ // public abstract FleetEngineTokenClaims authorizationClaims(); // // /** Provides a builder for {@link FleetEngineToken}. */ // public static Builder builder() { // return new AutoValue_FleetEngineToken.Builder() // .setAudience(CommonConstants.DEFAULT_JWT_AUDIENCE); // } // // public abstract FleetEngineToken.Builder toBuilder(); // // /** Builder class for FleetEngineToken. */ // @AutoValue.Builder // public abstract static class Builder { // // /** Setter for token creation timestamp. */ // public abstract Builder setCreationTimestamp(Date creationTimestamp); // // /** Setter for token expiration timestamp. */ // public abstract Builder setExpirationTimestamp(Date expirationTimestamp); // // /** Setter for a signed JWT to be associated with the token object. */ // public abstract Builder setJwt(String token); // // /** Setter for the token type defining the scope of the token. */ // public abstract Builder setTokenType(FleetEngineTokenType type); // // /** Setter for token audience (aud claim). */ // public abstract Builder setAudience(String audience); // // /** Sets custom authorization claims written to JWT. */ // public abstract Builder setAuthorizationClaims(FleetEngineTokenClaims claims); // // /** Builds the token object. */ // public abstract FleetEngineToken build(); // } // } // // Path: src/main/java/com/google/fleetengine/auth/token/factory/signer/util/CommonConstants.java // public final class CommonConstants { // /* JWT name of the authorization claim. */ // public static final String JWT_CLAIM_AUTHORIZATION_PROPERTY = "authorization"; // // /* Default value of the JWT audience (aud claim). */ // public static final String DEFAULT_JWT_AUDIENCE = "https://fleetengine.googleapis.com/"; // // private CommonConstants() {} // }
import com.auth0.jwt.JWT; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.SignatureVerificationException; import com.auth0.jwt.interfaces.DecodedJWT; import com.google.auth.oauth2.GoogleCredentials; import com.google.auth.oauth2.ImpersonatedCredentials; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.fleetengine.auth.token.FleetEngineToken; import com.google.fleetengine.auth.token.factory.signer.util.CommonConstants; import java.io.IOException; import java.util.Arrays;
*/ private static ImpersonatedCredentials.Builder createImpersonatedCredentials( String serviceAccount, GoogleCredentials defaultCredentials) { return ImpersonatedCredentials.newBuilder() .setSourceCredentials(defaultCredentials) // Sets the service account that the signer was created with. .setTargetPrincipal(serviceAccount) .setScopes(IAM_SCOPE); } /** * Signs a provided Fleet Engine token. * * <p>The impersonated service account should match the role according to the {@link * com.google.fleetengine.auth.token.FleetEngineTokenType} of the provided token. * * @param token Fleet Engine token to sign * @return same value as the {@code token} parameter except with the JWT property set to a valid * JWT */ @Override public FleetEngineToken sign(FleetEngineToken token) { String signedToken = JWT.create() .withIssuer(impersonatedCredentials.getAccount()) .withSubject(impersonatedCredentials.getAccount()) .withAudience(token.audience()) .withExpiresAt(token.expirationTimestamp()) .withIssuedAt(token.creationTimestamp()) .withClaim(
// Path: src/main/java/com/google/fleetengine/auth/token/FleetEngineToken.java // @AutoValue // public abstract class FleetEngineToken { // /** Token creation timestamp. */ // public abstract Date creationTimestamp(); // // /** Token expiration timestamp. */ // public abstract Date expirationTimestamp(); // // /** Audience (aud claim) of the JWT. */ // public abstract String audience(); // // /** Signed and base64 encoded JWT. */ // @Nullable // public abstract String jwt(); // // /** Scope of the authorization token. */ // public abstract FleetEngineTokenType tokenType(); // // /** Custom authorization claims written to JWT. */ // public abstract FleetEngineTokenClaims authorizationClaims(); // // /** Provides a builder for {@link FleetEngineToken}. */ // public static Builder builder() { // return new AutoValue_FleetEngineToken.Builder() // .setAudience(CommonConstants.DEFAULT_JWT_AUDIENCE); // } // // public abstract FleetEngineToken.Builder toBuilder(); // // /** Builder class for FleetEngineToken. */ // @AutoValue.Builder // public abstract static class Builder { // // /** Setter for token creation timestamp. */ // public abstract Builder setCreationTimestamp(Date creationTimestamp); // // /** Setter for token expiration timestamp. */ // public abstract Builder setExpirationTimestamp(Date expirationTimestamp); // // /** Setter for a signed JWT to be associated with the token object. */ // public abstract Builder setJwt(String token); // // /** Setter for the token type defining the scope of the token. */ // public abstract Builder setTokenType(FleetEngineTokenType type); // // /** Setter for token audience (aud claim). */ // public abstract Builder setAudience(String audience); // // /** Sets custom authorization claims written to JWT. */ // public abstract Builder setAuthorizationClaims(FleetEngineTokenClaims claims); // // /** Builds the token object. */ // public abstract FleetEngineToken build(); // } // } // // Path: src/main/java/com/google/fleetengine/auth/token/factory/signer/util/CommonConstants.java // public final class CommonConstants { // /* JWT name of the authorization claim. */ // public static final String JWT_CLAIM_AUTHORIZATION_PROPERTY = "authorization"; // // /* Default value of the JWT audience (aud claim). */ // public static final String DEFAULT_JWT_AUDIENCE = "https://fleetengine.googleapis.com/"; // // private CommonConstants() {} // } // Path: src/main/java/com/google/fleetengine/auth/token/factory/signer/ImpersonatedSigner.java import com.auth0.jwt.JWT; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.SignatureVerificationException; import com.auth0.jwt.interfaces.DecodedJWT; import com.google.auth.oauth2.GoogleCredentials; import com.google.auth.oauth2.ImpersonatedCredentials; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.fleetengine.auth.token.FleetEngineToken; import com.google.fleetengine.auth.token.factory.signer.util.CommonConstants; import java.io.IOException; import java.util.Arrays; */ private static ImpersonatedCredentials.Builder createImpersonatedCredentials( String serviceAccount, GoogleCredentials defaultCredentials) { return ImpersonatedCredentials.newBuilder() .setSourceCredentials(defaultCredentials) // Sets the service account that the signer was created with. .setTargetPrincipal(serviceAccount) .setScopes(IAM_SCOPE); } /** * Signs a provided Fleet Engine token. * * <p>The impersonated service account should match the role according to the {@link * com.google.fleetengine.auth.token.FleetEngineTokenType} of the provided token. * * @param token Fleet Engine token to sign * @return same value as the {@code token} parameter except with the JWT property set to a valid * JWT */ @Override public FleetEngineToken sign(FleetEngineToken token) { String signedToken = JWT.create() .withIssuer(impersonatedCredentials.getAccount()) .withSubject(impersonatedCredentials.getAccount()) .withAudience(token.audience()) .withExpiresAt(token.expirationTimestamp()) .withIssuedAt(token.creationTimestamp()) .withClaim(
CommonConstants.JWT_CLAIM_AUTHORIZATION_PROPERTY,
googlemaps/java-fleetengine-auth
src/test/java/com/google/fleetengine/auth/FleetEngineTokenExpiryValidatorTest.java
// Path: src/main/java/com/google/fleetengine/auth/token/FleetEngineToken.java // @AutoValue // public abstract class FleetEngineToken { // /** Token creation timestamp. */ // public abstract Date creationTimestamp(); // // /** Token expiration timestamp. */ // public abstract Date expirationTimestamp(); // // /** Audience (aud claim) of the JWT. */ // public abstract String audience(); // // /** Signed and base64 encoded JWT. */ // @Nullable // public abstract String jwt(); // // /** Scope of the authorization token. */ // public abstract FleetEngineTokenType tokenType(); // // /** Custom authorization claims written to JWT. */ // public abstract FleetEngineTokenClaims authorizationClaims(); // // /** Provides a builder for {@link FleetEngineToken}. */ // public static Builder builder() { // return new AutoValue_FleetEngineToken.Builder() // .setAudience(CommonConstants.DEFAULT_JWT_AUDIENCE); // } // // public abstract FleetEngineToken.Builder toBuilder(); // // /** Builder class for FleetEngineToken. */ // @AutoValue.Builder // public abstract static class Builder { // // /** Setter for token creation timestamp. */ // public abstract Builder setCreationTimestamp(Date creationTimestamp); // // /** Setter for token expiration timestamp. */ // public abstract Builder setExpirationTimestamp(Date expirationTimestamp); // // /** Setter for a signed JWT to be associated with the token object. */ // public abstract Builder setJwt(String token); // // /** Setter for the token type defining the scope of the token. */ // public abstract Builder setTokenType(FleetEngineTokenType type); // // /** Setter for token audience (aud claim). */ // public abstract Builder setAudience(String audience); // // /** Sets custom authorization claims written to JWT. */ // public abstract Builder setAuthorizationClaims(FleetEngineTokenClaims claims); // // /** Builds the token object. */ // public abstract FleetEngineToken build(); // } // } // // Path: src/main/java/com/google/fleetengine/auth/token/FleetEngineTokenType.java // public enum FleetEngineTokenType { // /** // * Consumer tokens are usually service accounts associated with the Fleet Engine Consumer SDK User // * role on the Google Cloud project. // */ // CONSUMER, // // /** // * Server tokens are usually service accounts associated with the Fleet Engine Super User role on // * the Google Cloud project. // */ // SERVER, // // /** // * Driver tokens are usually service accounts associated with the Fleet Engine Driver SDK User // * role on the Google Cloud project. // */ // DRIVER, // // /** // * Delivery server tokens are usually service accounts associated with the Fleet Engine Delivery // * Super User role on the Google Cloud project. // */ // DELIVERY_SERVER, // // /** // * Driver tokens are usually service accounts associated with the Fleet Engine Delivery Consumer // * User role on the Google Cloud project. // */ // DELIVERY_CONSUMER, // // /** // * Driver tokens are usually service accounts associated with the Fleet Engine Delivery Untrusted // * Driver User role on the Google Cloud project. // */ // UNTRUSTED_DELIVERY_DRIVER, // // /** // * Driver tokens are usually service accounts associated with the Fleet Engine Delivery Trusted // * Driver User role on the Google Cloud project. // */ // TRUSTED_DELIVERY_DRIVER, // // /** // * Fleet reader tokens are usually service accounts associated with the Fleet Engine Delivery // * Fleet Reader User role on the Google Cloud project. // */ // DELIVERY_FLEET_READER, // // /** Custom token type associated with any Fleet Engine Role on the Google Cloud project. */ // CUSTOM, // }
import static com.google.common.truth.Truth.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.google.fleetengine.auth.token.FleetEngineToken; import com.google.fleetengine.auth.token.FleetEngineTokenType; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.util.Date; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4;
// Copyright 2021 Google LLC // // 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.fleetengine.auth; @RunWith(JUnit4.class) public class FleetEngineTokenExpiryValidatorTest {
// Path: src/main/java/com/google/fleetengine/auth/token/FleetEngineToken.java // @AutoValue // public abstract class FleetEngineToken { // /** Token creation timestamp. */ // public abstract Date creationTimestamp(); // // /** Token expiration timestamp. */ // public abstract Date expirationTimestamp(); // // /** Audience (aud claim) of the JWT. */ // public abstract String audience(); // // /** Signed and base64 encoded JWT. */ // @Nullable // public abstract String jwt(); // // /** Scope of the authorization token. */ // public abstract FleetEngineTokenType tokenType(); // // /** Custom authorization claims written to JWT. */ // public abstract FleetEngineTokenClaims authorizationClaims(); // // /** Provides a builder for {@link FleetEngineToken}. */ // public static Builder builder() { // return new AutoValue_FleetEngineToken.Builder() // .setAudience(CommonConstants.DEFAULT_JWT_AUDIENCE); // } // // public abstract FleetEngineToken.Builder toBuilder(); // // /** Builder class for FleetEngineToken. */ // @AutoValue.Builder // public abstract static class Builder { // // /** Setter for token creation timestamp. */ // public abstract Builder setCreationTimestamp(Date creationTimestamp); // // /** Setter for token expiration timestamp. */ // public abstract Builder setExpirationTimestamp(Date expirationTimestamp); // // /** Setter for a signed JWT to be associated with the token object. */ // public abstract Builder setJwt(String token); // // /** Setter for the token type defining the scope of the token. */ // public abstract Builder setTokenType(FleetEngineTokenType type); // // /** Setter for token audience (aud claim). */ // public abstract Builder setAudience(String audience); // // /** Sets custom authorization claims written to JWT. */ // public abstract Builder setAuthorizationClaims(FleetEngineTokenClaims claims); // // /** Builds the token object. */ // public abstract FleetEngineToken build(); // } // } // // Path: src/main/java/com/google/fleetengine/auth/token/FleetEngineTokenType.java // public enum FleetEngineTokenType { // /** // * Consumer tokens are usually service accounts associated with the Fleet Engine Consumer SDK User // * role on the Google Cloud project. // */ // CONSUMER, // // /** // * Server tokens are usually service accounts associated with the Fleet Engine Super User role on // * the Google Cloud project. // */ // SERVER, // // /** // * Driver tokens are usually service accounts associated with the Fleet Engine Driver SDK User // * role on the Google Cloud project. // */ // DRIVER, // // /** // * Delivery server tokens are usually service accounts associated with the Fleet Engine Delivery // * Super User role on the Google Cloud project. // */ // DELIVERY_SERVER, // // /** // * Driver tokens are usually service accounts associated with the Fleet Engine Delivery Consumer // * User role on the Google Cloud project. // */ // DELIVERY_CONSUMER, // // /** // * Driver tokens are usually service accounts associated with the Fleet Engine Delivery Untrusted // * Driver User role on the Google Cloud project. // */ // UNTRUSTED_DELIVERY_DRIVER, // // /** // * Driver tokens are usually service accounts associated with the Fleet Engine Delivery Trusted // * Driver User role on the Google Cloud project. // */ // TRUSTED_DELIVERY_DRIVER, // // /** // * Fleet reader tokens are usually service accounts associated with the Fleet Engine Delivery // * Fleet Reader User role on the Google Cloud project. // */ // DELIVERY_FLEET_READER, // // /** Custom token type associated with any Fleet Engine Role on the Google Cloud project. */ // CUSTOM, // } // Path: src/test/java/com/google/fleetengine/auth/FleetEngineTokenExpiryValidatorTest.java import static com.google.common.truth.Truth.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.google.fleetengine.auth.token.FleetEngineToken; import com.google.fleetengine.auth.token.FleetEngineTokenType; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.util.Date; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; // Copyright 2021 Google LLC // // 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.fleetengine.auth; @RunWith(JUnit4.class) public class FleetEngineTokenExpiryValidatorTest {
private FleetEngineToken defaultToken;
googlemaps/java-fleetengine-auth
src/test/java/com/google/fleetengine/auth/FleetEngineTokenExpiryValidatorTest.java
// Path: src/main/java/com/google/fleetengine/auth/token/FleetEngineToken.java // @AutoValue // public abstract class FleetEngineToken { // /** Token creation timestamp. */ // public abstract Date creationTimestamp(); // // /** Token expiration timestamp. */ // public abstract Date expirationTimestamp(); // // /** Audience (aud claim) of the JWT. */ // public abstract String audience(); // // /** Signed and base64 encoded JWT. */ // @Nullable // public abstract String jwt(); // // /** Scope of the authorization token. */ // public abstract FleetEngineTokenType tokenType(); // // /** Custom authorization claims written to JWT. */ // public abstract FleetEngineTokenClaims authorizationClaims(); // // /** Provides a builder for {@link FleetEngineToken}. */ // public static Builder builder() { // return new AutoValue_FleetEngineToken.Builder() // .setAudience(CommonConstants.DEFAULT_JWT_AUDIENCE); // } // // public abstract FleetEngineToken.Builder toBuilder(); // // /** Builder class for FleetEngineToken. */ // @AutoValue.Builder // public abstract static class Builder { // // /** Setter for token creation timestamp. */ // public abstract Builder setCreationTimestamp(Date creationTimestamp); // // /** Setter for token expiration timestamp. */ // public abstract Builder setExpirationTimestamp(Date expirationTimestamp); // // /** Setter for a signed JWT to be associated with the token object. */ // public abstract Builder setJwt(String token); // // /** Setter for the token type defining the scope of the token. */ // public abstract Builder setTokenType(FleetEngineTokenType type); // // /** Setter for token audience (aud claim). */ // public abstract Builder setAudience(String audience); // // /** Sets custom authorization claims written to JWT. */ // public abstract Builder setAuthorizationClaims(FleetEngineTokenClaims claims); // // /** Builds the token object. */ // public abstract FleetEngineToken build(); // } // } // // Path: src/main/java/com/google/fleetengine/auth/token/FleetEngineTokenType.java // public enum FleetEngineTokenType { // /** // * Consumer tokens are usually service accounts associated with the Fleet Engine Consumer SDK User // * role on the Google Cloud project. // */ // CONSUMER, // // /** // * Server tokens are usually service accounts associated with the Fleet Engine Super User role on // * the Google Cloud project. // */ // SERVER, // // /** // * Driver tokens are usually service accounts associated with the Fleet Engine Driver SDK User // * role on the Google Cloud project. // */ // DRIVER, // // /** // * Delivery server tokens are usually service accounts associated with the Fleet Engine Delivery // * Super User role on the Google Cloud project. // */ // DELIVERY_SERVER, // // /** // * Driver tokens are usually service accounts associated with the Fleet Engine Delivery Consumer // * User role on the Google Cloud project. // */ // DELIVERY_CONSUMER, // // /** // * Driver tokens are usually service accounts associated with the Fleet Engine Delivery Untrusted // * Driver User role on the Google Cloud project. // */ // UNTRUSTED_DELIVERY_DRIVER, // // /** // * Driver tokens are usually service accounts associated with the Fleet Engine Delivery Trusted // * Driver User role on the Google Cloud project. // */ // TRUSTED_DELIVERY_DRIVER, // // /** // * Fleet reader tokens are usually service accounts associated with the Fleet Engine Delivery // * Fleet Reader User role on the Google Cloud project. // */ // DELIVERY_FLEET_READER, // // /** Custom token type associated with any Fleet Engine Role on the Google Cloud project. */ // CUSTOM, // }
import static com.google.common.truth.Truth.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.google.fleetengine.auth.token.FleetEngineToken; import com.google.fleetengine.auth.token.FleetEngineTokenType; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.util.Date; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4;
// Copyright 2021 Google LLC // // 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.fleetengine.auth; @RunWith(JUnit4.class) public class FleetEngineTokenExpiryValidatorTest { private FleetEngineToken defaultToken; private Clock fakeNowClock; @Before public void setup() { this.fakeNowClock = mock(Clock.class); // Setup default token, expiration timestamp will be changed in each test method. defaultToken = FleetEngineToken.builder() .setCreationTimestamp(Date.from(Instant.EPOCH)) .setExpirationTimestamp(Date.from(Instant.EPOCH)) .setAuthorizationClaims(EmptyFleetEngineTokenClaims.INSTANCE)
// Path: src/main/java/com/google/fleetengine/auth/token/FleetEngineToken.java // @AutoValue // public abstract class FleetEngineToken { // /** Token creation timestamp. */ // public abstract Date creationTimestamp(); // // /** Token expiration timestamp. */ // public abstract Date expirationTimestamp(); // // /** Audience (aud claim) of the JWT. */ // public abstract String audience(); // // /** Signed and base64 encoded JWT. */ // @Nullable // public abstract String jwt(); // // /** Scope of the authorization token. */ // public abstract FleetEngineTokenType tokenType(); // // /** Custom authorization claims written to JWT. */ // public abstract FleetEngineTokenClaims authorizationClaims(); // // /** Provides a builder for {@link FleetEngineToken}. */ // public static Builder builder() { // return new AutoValue_FleetEngineToken.Builder() // .setAudience(CommonConstants.DEFAULT_JWT_AUDIENCE); // } // // public abstract FleetEngineToken.Builder toBuilder(); // // /** Builder class for FleetEngineToken. */ // @AutoValue.Builder // public abstract static class Builder { // // /** Setter for token creation timestamp. */ // public abstract Builder setCreationTimestamp(Date creationTimestamp); // // /** Setter for token expiration timestamp. */ // public abstract Builder setExpirationTimestamp(Date expirationTimestamp); // // /** Setter for a signed JWT to be associated with the token object. */ // public abstract Builder setJwt(String token); // // /** Setter for the token type defining the scope of the token. */ // public abstract Builder setTokenType(FleetEngineTokenType type); // // /** Setter for token audience (aud claim). */ // public abstract Builder setAudience(String audience); // // /** Sets custom authorization claims written to JWT. */ // public abstract Builder setAuthorizationClaims(FleetEngineTokenClaims claims); // // /** Builds the token object. */ // public abstract FleetEngineToken build(); // } // } // // Path: src/main/java/com/google/fleetengine/auth/token/FleetEngineTokenType.java // public enum FleetEngineTokenType { // /** // * Consumer tokens are usually service accounts associated with the Fleet Engine Consumer SDK User // * role on the Google Cloud project. // */ // CONSUMER, // // /** // * Server tokens are usually service accounts associated with the Fleet Engine Super User role on // * the Google Cloud project. // */ // SERVER, // // /** // * Driver tokens are usually service accounts associated with the Fleet Engine Driver SDK User // * role on the Google Cloud project. // */ // DRIVER, // // /** // * Delivery server tokens are usually service accounts associated with the Fleet Engine Delivery // * Super User role on the Google Cloud project. // */ // DELIVERY_SERVER, // // /** // * Driver tokens are usually service accounts associated with the Fleet Engine Delivery Consumer // * User role on the Google Cloud project. // */ // DELIVERY_CONSUMER, // // /** // * Driver tokens are usually service accounts associated with the Fleet Engine Delivery Untrusted // * Driver User role on the Google Cloud project. // */ // UNTRUSTED_DELIVERY_DRIVER, // // /** // * Driver tokens are usually service accounts associated with the Fleet Engine Delivery Trusted // * Driver User role on the Google Cloud project. // */ // TRUSTED_DELIVERY_DRIVER, // // /** // * Fleet reader tokens are usually service accounts associated with the Fleet Engine Delivery // * Fleet Reader User role on the Google Cloud project. // */ // DELIVERY_FLEET_READER, // // /** Custom token type associated with any Fleet Engine Role on the Google Cloud project. */ // CUSTOM, // } // Path: src/test/java/com/google/fleetengine/auth/FleetEngineTokenExpiryValidatorTest.java import static com.google.common.truth.Truth.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.google.fleetengine.auth.token.FleetEngineToken; import com.google.fleetengine.auth.token.FleetEngineTokenType; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.util.Date; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; // Copyright 2021 Google LLC // // 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.fleetengine.auth; @RunWith(JUnit4.class) public class FleetEngineTokenExpiryValidatorTest { private FleetEngineToken defaultToken; private Clock fakeNowClock; @Before public void setup() { this.fakeNowClock = mock(Clock.class); // Setup default token, expiration timestamp will be changed in each test method. defaultToken = FleetEngineToken.builder() .setCreationTimestamp(Date.from(Instant.EPOCH)) .setExpirationTimestamp(Date.from(Instant.EPOCH)) .setAuthorizationClaims(EmptyFleetEngineTokenClaims.INSTANCE)
.setTokenType(FleetEngineTokenType.SERVER)
googlemaps/java-fleetengine-auth
sample/src/main/java/com/google/fleetengine/auth/sample/CommandLineRuntime.java
// Path: sample/src/main/java/com/google/fleetengine/auth/sample/validation/SampleScriptException.java // public class SampleScriptException extends Exception { // // /** // * Constructs a {@code SampleScriptException} with the specified detail message. // * // * @param message The detail message (which is saved for later retrieval by the {@link // * #getMessage()} method) // */ // public SampleScriptException(String message) { // this(message, null); // } // // /** // * Constructs a {@code SampleScriptException} with the specified detail message. // * // * @param message The detail message (which is saved for later retrieval by the {@link // * #getMessage()} method) // * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). // * (A null value is permitted, and indicates that the cause is nonexistent or unknown.) // */ // public SampleScriptException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: sample/src/main/java/com/google/fleetengine/auth/sample/validation/SampleScriptRuntime.java // public interface SampleScriptRuntime { // // /** // * Run a command that can throw an exception. // * // * @param commandName human readable name that describes the command // * @param command runnable command // * @throws Throwable signals that the command failed // */ // void runCommand(String commandName, ThrowingRunnable command) throws Throwable; // // /** // * Expects that {@code command} throws {@link io.grpc.StatusRuntimeException} with code {@code // * io.grpc.Status.PERMISSION_DENIED}. If that exception is thrown but with a different code, then // * {@link SampleScriptException} is thrown. // * // * @param commandName human readable name that describes the command // * @param command runnable command // * @throws Throwable signals that the command failed // */ // void expectPermissionDenied(String commandName, ThrowingRunnable command) throws Throwable; // } // // Path: sample/src/main/java/com/google/fleetengine/auth/sample/validation/ThrowingRunnable.java // public interface ThrowingRunnable { // /** Runs code. */ // void run() throws Throwable; // }
import static io.grpc.Status.PERMISSION_DENIED; import com.google.fleetengine.auth.sample.validation.SampleScriptException; import com.google.fleetengine.auth.sample.validation.SampleScriptRuntime; import com.google.fleetengine.auth.sample.validation.ThrowingRunnable; import io.grpc.StatusRuntimeException;
// Copyright 2021 Google LLC // // 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.fleetengine.auth.sample; /** * Create runtime for a command line application. * * <p>Success and Failure messages are displayed within the terminal. */ final class CommandLineRuntime implements SampleScriptRuntime { private static final String EXPECTED_PERMISSION_DENIED_MESSAGE = "Expected StatusRuntimeException with code PERMISSION_DENIED."; private static final String ANSI_RESET = "\u001B[0m"; private static final String ANSI_RED = "\u001B[31m"; private static final String ANSI_GREEN = "\u001B[32m"; private static final String ANSI_YELLOW = "\033[0;33m"; /** Create runtime. */ public static SampleScriptRuntime create() { return new CommandLineRuntime(); } private CommandLineRuntime() {} /** * Runs a given command and displays whether or not it was successful. A failure is communicated * by the command throwing an Exception. * * @param commandName displayed immediately before the {@code command} is run * @param command command to run * @throws Throwable signals that the {@code command} failed */ @Override
// Path: sample/src/main/java/com/google/fleetengine/auth/sample/validation/SampleScriptException.java // public class SampleScriptException extends Exception { // // /** // * Constructs a {@code SampleScriptException} with the specified detail message. // * // * @param message The detail message (which is saved for later retrieval by the {@link // * #getMessage()} method) // */ // public SampleScriptException(String message) { // this(message, null); // } // // /** // * Constructs a {@code SampleScriptException} with the specified detail message. // * // * @param message The detail message (which is saved for later retrieval by the {@link // * #getMessage()} method) // * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). // * (A null value is permitted, and indicates that the cause is nonexistent or unknown.) // */ // public SampleScriptException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: sample/src/main/java/com/google/fleetengine/auth/sample/validation/SampleScriptRuntime.java // public interface SampleScriptRuntime { // // /** // * Run a command that can throw an exception. // * // * @param commandName human readable name that describes the command // * @param command runnable command // * @throws Throwable signals that the command failed // */ // void runCommand(String commandName, ThrowingRunnable command) throws Throwable; // // /** // * Expects that {@code command} throws {@link io.grpc.StatusRuntimeException} with code {@code // * io.grpc.Status.PERMISSION_DENIED}. If that exception is thrown but with a different code, then // * {@link SampleScriptException} is thrown. // * // * @param commandName human readable name that describes the command // * @param command runnable command // * @throws Throwable signals that the command failed // */ // void expectPermissionDenied(String commandName, ThrowingRunnable command) throws Throwable; // } // // Path: sample/src/main/java/com/google/fleetengine/auth/sample/validation/ThrowingRunnable.java // public interface ThrowingRunnable { // /** Runs code. */ // void run() throws Throwable; // } // Path: sample/src/main/java/com/google/fleetengine/auth/sample/CommandLineRuntime.java import static io.grpc.Status.PERMISSION_DENIED; import com.google.fleetengine.auth.sample.validation.SampleScriptException; import com.google.fleetengine.auth.sample.validation.SampleScriptRuntime; import com.google.fleetengine.auth.sample.validation.ThrowingRunnable; import io.grpc.StatusRuntimeException; // Copyright 2021 Google LLC // // 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.fleetengine.auth.sample; /** * Create runtime for a command line application. * * <p>Success and Failure messages are displayed within the terminal. */ final class CommandLineRuntime implements SampleScriptRuntime { private static final String EXPECTED_PERMISSION_DENIED_MESSAGE = "Expected StatusRuntimeException with code PERMISSION_DENIED."; private static final String ANSI_RESET = "\u001B[0m"; private static final String ANSI_RED = "\u001B[31m"; private static final String ANSI_GREEN = "\u001B[32m"; private static final String ANSI_YELLOW = "\033[0;33m"; /** Create runtime. */ public static SampleScriptRuntime create() { return new CommandLineRuntime(); } private CommandLineRuntime() {} /** * Runs a given command and displays whether or not it was successful. A failure is communicated * by the command throwing an Exception. * * @param commandName displayed immediately before the {@code command} is run * @param command command to run * @throws Throwable signals that the {@code command} failed */ @Override
public void runCommand(String commandName, ThrowingRunnable command) throws Throwable {
googlemaps/java-fleetengine-auth
sample/src/main/java/com/google/fleetengine/auth/sample/CommandLineRuntime.java
// Path: sample/src/main/java/com/google/fleetengine/auth/sample/validation/SampleScriptException.java // public class SampleScriptException extends Exception { // // /** // * Constructs a {@code SampleScriptException} with the specified detail message. // * // * @param message The detail message (which is saved for later retrieval by the {@link // * #getMessage()} method) // */ // public SampleScriptException(String message) { // this(message, null); // } // // /** // * Constructs a {@code SampleScriptException} with the specified detail message. // * // * @param message The detail message (which is saved for later retrieval by the {@link // * #getMessage()} method) // * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). // * (A null value is permitted, and indicates that the cause is nonexistent or unknown.) // */ // public SampleScriptException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: sample/src/main/java/com/google/fleetengine/auth/sample/validation/SampleScriptRuntime.java // public interface SampleScriptRuntime { // // /** // * Run a command that can throw an exception. // * // * @param commandName human readable name that describes the command // * @param command runnable command // * @throws Throwable signals that the command failed // */ // void runCommand(String commandName, ThrowingRunnable command) throws Throwable; // // /** // * Expects that {@code command} throws {@link io.grpc.StatusRuntimeException} with code {@code // * io.grpc.Status.PERMISSION_DENIED}. If that exception is thrown but with a different code, then // * {@link SampleScriptException} is thrown. // * // * @param commandName human readable name that describes the command // * @param command runnable command // * @throws Throwable signals that the command failed // */ // void expectPermissionDenied(String commandName, ThrowingRunnable command) throws Throwable; // } // // Path: sample/src/main/java/com/google/fleetengine/auth/sample/validation/ThrowingRunnable.java // public interface ThrowingRunnable { // /** Runs code. */ // void run() throws Throwable; // }
import static io.grpc.Status.PERMISSION_DENIED; import com.google.fleetengine.auth.sample.validation.SampleScriptException; import com.google.fleetengine.auth.sample.validation.SampleScriptRuntime; import com.google.fleetengine.auth.sample.validation.ThrowingRunnable; import io.grpc.StatusRuntimeException;
// Copyright 2021 Google LLC // // 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.fleetengine.auth.sample; /** * Create runtime for a command line application. * * <p>Success and Failure messages are displayed within the terminal. */ final class CommandLineRuntime implements SampleScriptRuntime { private static final String EXPECTED_PERMISSION_DENIED_MESSAGE = "Expected StatusRuntimeException with code PERMISSION_DENIED."; private static final String ANSI_RESET = "\u001B[0m"; private static final String ANSI_RED = "\u001B[31m"; private static final String ANSI_GREEN = "\u001B[32m"; private static final String ANSI_YELLOW = "\033[0;33m"; /** Create runtime. */ public static SampleScriptRuntime create() { return new CommandLineRuntime(); } private CommandLineRuntime() {} /** * Runs a given command and displays whether or not it was successful. A failure is communicated * by the command throwing an Exception. * * @param commandName displayed immediately before the {@code command} is run * @param command command to run * @throws Throwable signals that the {@code command} failed */ @Override public void runCommand(String commandName, ThrowingRunnable command) throws Throwable { System.out.printf("%s... ", commandName); try { command.run(); } catch (Exception exception) { System.out.printf("%sFAIL!%s\n", ANSI_RED, ANSI_RESET); throw exception; } System.out.printf("%sSUCCESS%s\n", ANSI_GREEN, ANSI_RESET); } /** {@inheritDoc} */ @Override public void expectPermissionDenied(String commandName, ThrowingRunnable command) throws Throwable { runCommand( commandName, () -> { try { command.run(); } catch (com.google.api.gax.rpc.PermissionDeniedException e) { if (e.getCause() instanceof StatusRuntimeException) { checkException((StatusRuntimeException) e.getCause()); } } catch (StatusRuntimeException e) { checkException(e); } }); } private void checkException(StatusRuntimeException cause) throws Throwable { if (!PERMISSION_DENIED.getCode().equals(cause.getStatus().getCode())) {
// Path: sample/src/main/java/com/google/fleetengine/auth/sample/validation/SampleScriptException.java // public class SampleScriptException extends Exception { // // /** // * Constructs a {@code SampleScriptException} with the specified detail message. // * // * @param message The detail message (which is saved for later retrieval by the {@link // * #getMessage()} method) // */ // public SampleScriptException(String message) { // this(message, null); // } // // /** // * Constructs a {@code SampleScriptException} with the specified detail message. // * // * @param message The detail message (which is saved for later retrieval by the {@link // * #getMessage()} method) // * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). // * (A null value is permitted, and indicates that the cause is nonexistent or unknown.) // */ // public SampleScriptException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: sample/src/main/java/com/google/fleetengine/auth/sample/validation/SampleScriptRuntime.java // public interface SampleScriptRuntime { // // /** // * Run a command that can throw an exception. // * // * @param commandName human readable name that describes the command // * @param command runnable command // * @throws Throwable signals that the command failed // */ // void runCommand(String commandName, ThrowingRunnable command) throws Throwable; // // /** // * Expects that {@code command} throws {@link io.grpc.StatusRuntimeException} with code {@code // * io.grpc.Status.PERMISSION_DENIED}. If that exception is thrown but with a different code, then // * {@link SampleScriptException} is thrown. // * // * @param commandName human readable name that describes the command // * @param command runnable command // * @throws Throwable signals that the command failed // */ // void expectPermissionDenied(String commandName, ThrowingRunnable command) throws Throwable; // } // // Path: sample/src/main/java/com/google/fleetengine/auth/sample/validation/ThrowingRunnable.java // public interface ThrowingRunnable { // /** Runs code. */ // void run() throws Throwable; // } // Path: sample/src/main/java/com/google/fleetengine/auth/sample/CommandLineRuntime.java import static io.grpc.Status.PERMISSION_DENIED; import com.google.fleetengine.auth.sample.validation.SampleScriptException; import com.google.fleetengine.auth.sample.validation.SampleScriptRuntime; import com.google.fleetengine.auth.sample.validation.ThrowingRunnable; import io.grpc.StatusRuntimeException; // Copyright 2021 Google LLC // // 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.fleetengine.auth.sample; /** * Create runtime for a command line application. * * <p>Success and Failure messages are displayed within the terminal. */ final class CommandLineRuntime implements SampleScriptRuntime { private static final String EXPECTED_PERMISSION_DENIED_MESSAGE = "Expected StatusRuntimeException with code PERMISSION_DENIED."; private static final String ANSI_RESET = "\u001B[0m"; private static final String ANSI_RED = "\u001B[31m"; private static final String ANSI_GREEN = "\u001B[32m"; private static final String ANSI_YELLOW = "\033[0;33m"; /** Create runtime. */ public static SampleScriptRuntime create() { return new CommandLineRuntime(); } private CommandLineRuntime() {} /** * Runs a given command and displays whether or not it was successful. A failure is communicated * by the command throwing an Exception. * * @param commandName displayed immediately before the {@code command} is run * @param command command to run * @throws Throwable signals that the {@code command} failed */ @Override public void runCommand(String commandName, ThrowingRunnable command) throws Throwable { System.out.printf("%s... ", commandName); try { command.run(); } catch (Exception exception) { System.out.printf("%sFAIL!%s\n", ANSI_RED, ANSI_RESET); throw exception; } System.out.printf("%sSUCCESS%s\n", ANSI_GREEN, ANSI_RESET); } /** {@inheritDoc} */ @Override public void expectPermissionDenied(String commandName, ThrowingRunnable command) throws Throwable { runCommand( commandName, () -> { try { command.run(); } catch (com.google.api.gax.rpc.PermissionDeniedException e) { if (e.getCause() instanceof StatusRuntimeException) { checkException((StatusRuntimeException) e.getCause()); } } catch (StatusRuntimeException e) { checkException(e); } }); } private void checkException(StatusRuntimeException cause) throws Throwable { if (!PERMISSION_DENIED.getCode().equals(cause.getStatus().getCode())) {
throw new SampleScriptException(EXPECTED_PERMISSION_DENIED_MESSAGE, cause);
googlemaps/java-fleetengine-auth
src/main/java/com/google/fleetengine/auth/token/FleetEngineToken.java
// Path: src/main/java/com/google/fleetengine/auth/token/factory/signer/util/CommonConstants.java // public final class CommonConstants { // /* JWT name of the authorization claim. */ // public static final String JWT_CLAIM_AUTHORIZATION_PROPERTY = "authorization"; // // /* Default value of the JWT audience (aud claim). */ // public static final String DEFAULT_JWT_AUDIENCE = "https://fleetengine.googleapis.com/"; // // private CommonConstants() {} // }
import com.google.auto.value.AutoValue; import com.google.fleetengine.auth.token.factory.signer.util.CommonConstants; import java.util.Date; import javax.annotation.Nullable;
// Copyright 2021 Google LLC // // 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.fleetengine.auth.token; /** * Provides the authorization information needed to establish communication with Fleet Engine * servers. */ @AutoValue public abstract class FleetEngineToken { /** Token creation timestamp. */ public abstract Date creationTimestamp(); /** Token expiration timestamp. */ public abstract Date expirationTimestamp(); /** Audience (aud claim) of the JWT. */ public abstract String audience(); /** Signed and base64 encoded JWT. */ @Nullable public abstract String jwt(); /** Scope of the authorization token. */ public abstract FleetEngineTokenType tokenType(); /** Custom authorization claims written to JWT. */ public abstract FleetEngineTokenClaims authorizationClaims(); /** Provides a builder for {@link FleetEngineToken}. */ public static Builder builder() { return new AutoValue_FleetEngineToken.Builder()
// Path: src/main/java/com/google/fleetengine/auth/token/factory/signer/util/CommonConstants.java // public final class CommonConstants { // /* JWT name of the authorization claim. */ // public static final String JWT_CLAIM_AUTHORIZATION_PROPERTY = "authorization"; // // /* Default value of the JWT audience (aud claim). */ // public static final String DEFAULT_JWT_AUDIENCE = "https://fleetengine.googleapis.com/"; // // private CommonConstants() {} // } // Path: src/main/java/com/google/fleetengine/auth/token/FleetEngineToken.java import com.google.auto.value.AutoValue; import com.google.fleetengine.auth.token.factory.signer.util.CommonConstants; import java.util.Date; import javax.annotation.Nullable; // Copyright 2021 Google LLC // // 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.fleetengine.auth.token; /** * Provides the authorization information needed to establish communication with Fleet Engine * servers. */ @AutoValue public abstract class FleetEngineToken { /** Token creation timestamp. */ public abstract Date creationTimestamp(); /** Token expiration timestamp. */ public abstract Date expirationTimestamp(); /** Audience (aud claim) of the JWT. */ public abstract String audience(); /** Signed and base64 encoded JWT. */ @Nullable public abstract String jwt(); /** Scope of the authorization token. */ public abstract FleetEngineTokenType tokenType(); /** Custom authorization claims written to JWT. */ public abstract FleetEngineTokenClaims authorizationClaims(); /** Provides a builder for {@link FleetEngineToken}. */ public static Builder builder() { return new AutoValue_FleetEngineToken.Builder()
.setAudience(CommonConstants.DEFAULT_JWT_AUDIENCE);
googlemaps/java-fleetengine-auth
src/main/java/com/google/fleetengine/auth/client/FleetEngineAuthClientInterceptor.java
// Path: src/main/java/com/google/fleetengine/auth/token/FleetEngineToken.java // @AutoValue // public abstract class FleetEngineToken { // /** Token creation timestamp. */ // public abstract Date creationTimestamp(); // // /** Token expiration timestamp. */ // public abstract Date expirationTimestamp(); // // /** Audience (aud claim) of the JWT. */ // public abstract String audience(); // // /** Signed and base64 encoded JWT. */ // @Nullable // public abstract String jwt(); // // /** Scope of the authorization token. */ // public abstract FleetEngineTokenType tokenType(); // // /** Custom authorization claims written to JWT. */ // public abstract FleetEngineTokenClaims authorizationClaims(); // // /** Provides a builder for {@link FleetEngineToken}. */ // public static Builder builder() { // return new AutoValue_FleetEngineToken.Builder() // .setAudience(CommonConstants.DEFAULT_JWT_AUDIENCE); // } // // public abstract FleetEngineToken.Builder toBuilder(); // // /** Builder class for FleetEngineToken. */ // @AutoValue.Builder // public abstract static class Builder { // // /** Setter for token creation timestamp. */ // public abstract Builder setCreationTimestamp(Date creationTimestamp); // // /** Setter for token expiration timestamp. */ // public abstract Builder setExpirationTimestamp(Date expirationTimestamp); // // /** Setter for a signed JWT to be associated with the token object. */ // public abstract Builder setJwt(String token); // // /** Setter for the token type defining the scope of the token. */ // public abstract Builder setTokenType(FleetEngineTokenType type); // // /** Setter for token audience (aud claim). */ // public abstract Builder setAudience(String audience); // // /** Sets custom authorization claims written to JWT. */ // public abstract Builder setAuthorizationClaims(FleetEngineTokenClaims claims); // // /** Builds the token object. */ // public abstract FleetEngineToken build(); // } // } // // Path: src/main/java/com/google/fleetengine/auth/token/factory/signer/SigningTokenException.java // public class SigningTokenException extends Exception { // /** // * Constructs a {@code SigningTokenException} with the specified detail message. // * // * @param message The detail message (which is saved for later retrieval by the {@link // * #getMessage()} method) // */ // public SigningTokenException(String message) { // this(message, null); // } // // /** // * Constructs a {@code SigningTokenException} with the specified detail message. // * // * @param message The detail message (which is saved for later retrieval by the {@link // * #getMessage()} method) // * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). // * (A null value is permitted, and indicates that the cause is nonexistent or unknown.) // */ // public SigningTokenException(String message, Throwable cause) { // super(message, cause); // } // }
import com.google.common.annotations.VisibleForTesting; import com.google.fleetengine.auth.token.FleetEngineToken; import com.google.fleetengine.auth.token.factory.signer.SigningTokenException; import io.grpc.CallOptions; import io.grpc.Channel; import io.grpc.ClientCall; import io.grpc.ClientInterceptor; import io.grpc.ForwardingClientCall; import io.grpc.Metadata; import io.grpc.MethodDescriptor;
// Copyright 2021 Google LLC // // 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.fleetengine.auth.client; /** * Intercepts an outgoing gRPC request and attaches a valid Fleet Engine JWT to the header. * * <p>Works with generated gRPC stubby classes: * * <pre>{@code channel = ManagedChannelBuilder.forTarget(fleetEngineAddress) * .intercept(FleetEngineAuthClientInterceptor#create(fleetEngineTokenProvider)) * .build(); * VehicleServiceBlockingStub stub = VehicleServiceGrpc.newBlockingStub(channel);}</pre> */ public class FleetEngineAuthClientInterceptor implements ClientInterceptor { /** Authorization header name. */ private static final Metadata.Key<String> AUTHORIZATION_HEADER = Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER); private final FleetEngineTokenProvider tokenProvider; /** * Creates a gRPC client interceptor that attaches tokens from {@code tokenProvider} to outgoing * gRPC requests. * * @param tokenProvider provides valid Fleet Engine JWTs for an outgoing gRPC request. */ public static FleetEngineAuthClientInterceptor create(FleetEngineTokenProvider tokenProvider) { return new FleetEngineAuthClientInterceptor(tokenProvider); } /** Constructor. */ private FleetEngineAuthClientInterceptor(FleetEngineTokenProvider tokenProvider) { this.tokenProvider = tokenProvider; } /** * Overrides {@link ClientInterceptor#interceptCall(MethodDescriptor, CallOptions, Channel)} and * attaches a Fleet Engine JWT to the header of the outgoing gRPC request. */ @Override public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall( MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) { ClientCall<ReqT, RespT> call = next.newCall(method, callOptions); return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(call) { @Override public void start(Listener<RespT> responseListener, Metadata headers) { addAuthorizationHeader(headers); super.start(responseListener, headers); } }; } /** Adds the signed base64 encode JWT to the header. */ @VisibleForTesting void addAuthorizationHeader(Metadata headers) { try {
// Path: src/main/java/com/google/fleetengine/auth/token/FleetEngineToken.java // @AutoValue // public abstract class FleetEngineToken { // /** Token creation timestamp. */ // public abstract Date creationTimestamp(); // // /** Token expiration timestamp. */ // public abstract Date expirationTimestamp(); // // /** Audience (aud claim) of the JWT. */ // public abstract String audience(); // // /** Signed and base64 encoded JWT. */ // @Nullable // public abstract String jwt(); // // /** Scope of the authorization token. */ // public abstract FleetEngineTokenType tokenType(); // // /** Custom authorization claims written to JWT. */ // public abstract FleetEngineTokenClaims authorizationClaims(); // // /** Provides a builder for {@link FleetEngineToken}. */ // public static Builder builder() { // return new AutoValue_FleetEngineToken.Builder() // .setAudience(CommonConstants.DEFAULT_JWT_AUDIENCE); // } // // public abstract FleetEngineToken.Builder toBuilder(); // // /** Builder class for FleetEngineToken. */ // @AutoValue.Builder // public abstract static class Builder { // // /** Setter for token creation timestamp. */ // public abstract Builder setCreationTimestamp(Date creationTimestamp); // // /** Setter for token expiration timestamp. */ // public abstract Builder setExpirationTimestamp(Date expirationTimestamp); // // /** Setter for a signed JWT to be associated with the token object. */ // public abstract Builder setJwt(String token); // // /** Setter for the token type defining the scope of the token. */ // public abstract Builder setTokenType(FleetEngineTokenType type); // // /** Setter for token audience (aud claim). */ // public abstract Builder setAudience(String audience); // // /** Sets custom authorization claims written to JWT. */ // public abstract Builder setAuthorizationClaims(FleetEngineTokenClaims claims); // // /** Builds the token object. */ // public abstract FleetEngineToken build(); // } // } // // Path: src/main/java/com/google/fleetengine/auth/token/factory/signer/SigningTokenException.java // public class SigningTokenException extends Exception { // /** // * Constructs a {@code SigningTokenException} with the specified detail message. // * // * @param message The detail message (which is saved for later retrieval by the {@link // * #getMessage()} method) // */ // public SigningTokenException(String message) { // this(message, null); // } // // /** // * Constructs a {@code SigningTokenException} with the specified detail message. // * // * @param message The detail message (which is saved for later retrieval by the {@link // * #getMessage()} method) // * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). // * (A null value is permitted, and indicates that the cause is nonexistent or unknown.) // */ // public SigningTokenException(String message, Throwable cause) { // super(message, cause); // } // } // Path: src/main/java/com/google/fleetengine/auth/client/FleetEngineAuthClientInterceptor.java import com.google.common.annotations.VisibleForTesting; import com.google.fleetengine.auth.token.FleetEngineToken; import com.google.fleetengine.auth.token.factory.signer.SigningTokenException; import io.grpc.CallOptions; import io.grpc.Channel; import io.grpc.ClientCall; import io.grpc.ClientInterceptor; import io.grpc.ForwardingClientCall; import io.grpc.Metadata; import io.grpc.MethodDescriptor; // Copyright 2021 Google LLC // // 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.fleetengine.auth.client; /** * Intercepts an outgoing gRPC request and attaches a valid Fleet Engine JWT to the header. * * <p>Works with generated gRPC stubby classes: * * <pre>{@code channel = ManagedChannelBuilder.forTarget(fleetEngineAddress) * .intercept(FleetEngineAuthClientInterceptor#create(fleetEngineTokenProvider)) * .build(); * VehicleServiceBlockingStub stub = VehicleServiceGrpc.newBlockingStub(channel);}</pre> */ public class FleetEngineAuthClientInterceptor implements ClientInterceptor { /** Authorization header name. */ private static final Metadata.Key<String> AUTHORIZATION_HEADER = Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER); private final FleetEngineTokenProvider tokenProvider; /** * Creates a gRPC client interceptor that attaches tokens from {@code tokenProvider} to outgoing * gRPC requests. * * @param tokenProvider provides valid Fleet Engine JWTs for an outgoing gRPC request. */ public static FleetEngineAuthClientInterceptor create(FleetEngineTokenProvider tokenProvider) { return new FleetEngineAuthClientInterceptor(tokenProvider); } /** Constructor. */ private FleetEngineAuthClientInterceptor(FleetEngineTokenProvider tokenProvider) { this.tokenProvider = tokenProvider; } /** * Overrides {@link ClientInterceptor#interceptCall(MethodDescriptor, CallOptions, Channel)} and * attaches a Fleet Engine JWT to the header of the outgoing gRPC request. */ @Override public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall( MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) { ClientCall<ReqT, RespT> call = next.newCall(method, callOptions); return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(call) { @Override public void start(Listener<RespT> responseListener, Metadata headers) { addAuthorizationHeader(headers); super.start(responseListener, headers); } }; } /** Adds the signed base64 encode JWT to the header. */ @VisibleForTesting void addAuthorizationHeader(Metadata headers) { try {
FleetEngineToken token = tokenProvider.getSignedToken();
googlemaps/java-fleetengine-auth
src/main/java/com/google/fleetengine/auth/client/FleetEngineAuthClientInterceptor.java
// Path: src/main/java/com/google/fleetengine/auth/token/FleetEngineToken.java // @AutoValue // public abstract class FleetEngineToken { // /** Token creation timestamp. */ // public abstract Date creationTimestamp(); // // /** Token expiration timestamp. */ // public abstract Date expirationTimestamp(); // // /** Audience (aud claim) of the JWT. */ // public abstract String audience(); // // /** Signed and base64 encoded JWT. */ // @Nullable // public abstract String jwt(); // // /** Scope of the authorization token. */ // public abstract FleetEngineTokenType tokenType(); // // /** Custom authorization claims written to JWT. */ // public abstract FleetEngineTokenClaims authorizationClaims(); // // /** Provides a builder for {@link FleetEngineToken}. */ // public static Builder builder() { // return new AutoValue_FleetEngineToken.Builder() // .setAudience(CommonConstants.DEFAULT_JWT_AUDIENCE); // } // // public abstract FleetEngineToken.Builder toBuilder(); // // /** Builder class for FleetEngineToken. */ // @AutoValue.Builder // public abstract static class Builder { // // /** Setter for token creation timestamp. */ // public abstract Builder setCreationTimestamp(Date creationTimestamp); // // /** Setter for token expiration timestamp. */ // public abstract Builder setExpirationTimestamp(Date expirationTimestamp); // // /** Setter for a signed JWT to be associated with the token object. */ // public abstract Builder setJwt(String token); // // /** Setter for the token type defining the scope of the token. */ // public abstract Builder setTokenType(FleetEngineTokenType type); // // /** Setter for token audience (aud claim). */ // public abstract Builder setAudience(String audience); // // /** Sets custom authorization claims written to JWT. */ // public abstract Builder setAuthorizationClaims(FleetEngineTokenClaims claims); // // /** Builds the token object. */ // public abstract FleetEngineToken build(); // } // } // // Path: src/main/java/com/google/fleetengine/auth/token/factory/signer/SigningTokenException.java // public class SigningTokenException extends Exception { // /** // * Constructs a {@code SigningTokenException} with the specified detail message. // * // * @param message The detail message (which is saved for later retrieval by the {@link // * #getMessage()} method) // */ // public SigningTokenException(String message) { // this(message, null); // } // // /** // * Constructs a {@code SigningTokenException} with the specified detail message. // * // * @param message The detail message (which is saved for later retrieval by the {@link // * #getMessage()} method) // * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). // * (A null value is permitted, and indicates that the cause is nonexistent or unknown.) // */ // public SigningTokenException(String message, Throwable cause) { // super(message, cause); // } // }
import com.google.common.annotations.VisibleForTesting; import com.google.fleetengine.auth.token.FleetEngineToken; import com.google.fleetengine.auth.token.factory.signer.SigningTokenException; import io.grpc.CallOptions; import io.grpc.Channel; import io.grpc.ClientCall; import io.grpc.ClientInterceptor; import io.grpc.ForwardingClientCall; import io.grpc.Metadata; import io.grpc.MethodDescriptor;
// Copyright 2021 Google LLC // // 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.fleetengine.auth.client; /** * Intercepts an outgoing gRPC request and attaches a valid Fleet Engine JWT to the header. * * <p>Works with generated gRPC stubby classes: * * <pre>{@code channel = ManagedChannelBuilder.forTarget(fleetEngineAddress) * .intercept(FleetEngineAuthClientInterceptor#create(fleetEngineTokenProvider)) * .build(); * VehicleServiceBlockingStub stub = VehicleServiceGrpc.newBlockingStub(channel);}</pre> */ public class FleetEngineAuthClientInterceptor implements ClientInterceptor { /** Authorization header name. */ private static final Metadata.Key<String> AUTHORIZATION_HEADER = Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER); private final FleetEngineTokenProvider tokenProvider; /** * Creates a gRPC client interceptor that attaches tokens from {@code tokenProvider} to outgoing * gRPC requests. * * @param tokenProvider provides valid Fleet Engine JWTs for an outgoing gRPC request. */ public static FleetEngineAuthClientInterceptor create(FleetEngineTokenProvider tokenProvider) { return new FleetEngineAuthClientInterceptor(tokenProvider); } /** Constructor. */ private FleetEngineAuthClientInterceptor(FleetEngineTokenProvider tokenProvider) { this.tokenProvider = tokenProvider; } /** * Overrides {@link ClientInterceptor#interceptCall(MethodDescriptor, CallOptions, Channel)} and * attaches a Fleet Engine JWT to the header of the outgoing gRPC request. */ @Override public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall( MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) { ClientCall<ReqT, RespT> call = next.newCall(method, callOptions); return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(call) { @Override public void start(Listener<RespT> responseListener, Metadata headers) { addAuthorizationHeader(headers); super.start(responseListener, headers); } }; } /** Adds the signed base64 encode JWT to the header. */ @VisibleForTesting void addAuthorizationHeader(Metadata headers) { try { FleetEngineToken token = tokenProvider.getSignedToken(); headers.put(AUTHORIZATION_HEADER, String.format("Bearer %s", token.jwt()));
// Path: src/main/java/com/google/fleetengine/auth/token/FleetEngineToken.java // @AutoValue // public abstract class FleetEngineToken { // /** Token creation timestamp. */ // public abstract Date creationTimestamp(); // // /** Token expiration timestamp. */ // public abstract Date expirationTimestamp(); // // /** Audience (aud claim) of the JWT. */ // public abstract String audience(); // // /** Signed and base64 encoded JWT. */ // @Nullable // public abstract String jwt(); // // /** Scope of the authorization token. */ // public abstract FleetEngineTokenType tokenType(); // // /** Custom authorization claims written to JWT. */ // public abstract FleetEngineTokenClaims authorizationClaims(); // // /** Provides a builder for {@link FleetEngineToken}. */ // public static Builder builder() { // return new AutoValue_FleetEngineToken.Builder() // .setAudience(CommonConstants.DEFAULT_JWT_AUDIENCE); // } // // public abstract FleetEngineToken.Builder toBuilder(); // // /** Builder class for FleetEngineToken. */ // @AutoValue.Builder // public abstract static class Builder { // // /** Setter for token creation timestamp. */ // public abstract Builder setCreationTimestamp(Date creationTimestamp); // // /** Setter for token expiration timestamp. */ // public abstract Builder setExpirationTimestamp(Date expirationTimestamp); // // /** Setter for a signed JWT to be associated with the token object. */ // public abstract Builder setJwt(String token); // // /** Setter for the token type defining the scope of the token. */ // public abstract Builder setTokenType(FleetEngineTokenType type); // // /** Setter for token audience (aud claim). */ // public abstract Builder setAudience(String audience); // // /** Sets custom authorization claims written to JWT. */ // public abstract Builder setAuthorizationClaims(FleetEngineTokenClaims claims); // // /** Builds the token object. */ // public abstract FleetEngineToken build(); // } // } // // Path: src/main/java/com/google/fleetengine/auth/token/factory/signer/SigningTokenException.java // public class SigningTokenException extends Exception { // /** // * Constructs a {@code SigningTokenException} with the specified detail message. // * // * @param message The detail message (which is saved for later retrieval by the {@link // * #getMessage()} method) // */ // public SigningTokenException(String message) { // this(message, null); // } // // /** // * Constructs a {@code SigningTokenException} with the specified detail message. // * // * @param message The detail message (which is saved for later retrieval by the {@link // * #getMessage()} method) // * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). // * (A null value is permitted, and indicates that the cause is nonexistent or unknown.) // */ // public SigningTokenException(String message, Throwable cause) { // super(message, cause); // } // } // Path: src/main/java/com/google/fleetengine/auth/client/FleetEngineAuthClientInterceptor.java import com.google.common.annotations.VisibleForTesting; import com.google.fleetengine.auth.token.FleetEngineToken; import com.google.fleetengine.auth.token.factory.signer.SigningTokenException; import io.grpc.CallOptions; import io.grpc.Channel; import io.grpc.ClientCall; import io.grpc.ClientInterceptor; import io.grpc.ForwardingClientCall; import io.grpc.Metadata; import io.grpc.MethodDescriptor; // Copyright 2021 Google LLC // // 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.fleetengine.auth.client; /** * Intercepts an outgoing gRPC request and attaches a valid Fleet Engine JWT to the header. * * <p>Works with generated gRPC stubby classes: * * <pre>{@code channel = ManagedChannelBuilder.forTarget(fleetEngineAddress) * .intercept(FleetEngineAuthClientInterceptor#create(fleetEngineTokenProvider)) * .build(); * VehicleServiceBlockingStub stub = VehicleServiceGrpc.newBlockingStub(channel);}</pre> */ public class FleetEngineAuthClientInterceptor implements ClientInterceptor { /** Authorization header name. */ private static final Metadata.Key<String> AUTHORIZATION_HEADER = Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER); private final FleetEngineTokenProvider tokenProvider; /** * Creates a gRPC client interceptor that attaches tokens from {@code tokenProvider} to outgoing * gRPC requests. * * @param tokenProvider provides valid Fleet Engine JWTs for an outgoing gRPC request. */ public static FleetEngineAuthClientInterceptor create(FleetEngineTokenProvider tokenProvider) { return new FleetEngineAuthClientInterceptor(tokenProvider); } /** Constructor. */ private FleetEngineAuthClientInterceptor(FleetEngineTokenProvider tokenProvider) { this.tokenProvider = tokenProvider; } /** * Overrides {@link ClientInterceptor#interceptCall(MethodDescriptor, CallOptions, Channel)} and * attaches a Fleet Engine JWT to the header of the outgoing gRPC request. */ @Override public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall( MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) { ClientCall<ReqT, RespT> call = next.newCall(method, callOptions); return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(call) { @Override public void start(Listener<RespT> responseListener, Metadata headers) { addAuthorizationHeader(headers); super.start(responseListener, headers); } }; } /** Adds the signed base64 encode JWT to the header. */ @VisibleForTesting void addAuthorizationHeader(Metadata headers) { try { FleetEngineToken token = tokenProvider.getSignedToken(); headers.put(AUTHORIZATION_HEADER, String.format("Bearer %s", token.jwt()));
} catch (SigningTokenException e) {
googlemaps/java-fleetengine-auth
src/main/java/com/google/fleetengine/auth/FleetEngineAuthTokenStateManager.java
// Path: src/main/java/com/google/fleetengine/auth/token/FleetEngineToken.java // @AutoValue // public abstract class FleetEngineToken { // /** Token creation timestamp. */ // public abstract Date creationTimestamp(); // // /** Token expiration timestamp. */ // public abstract Date expirationTimestamp(); // // /** Audience (aud claim) of the JWT. */ // public abstract String audience(); // // /** Signed and base64 encoded JWT. */ // @Nullable // public abstract String jwt(); // // /** Scope of the authorization token. */ // public abstract FleetEngineTokenType tokenType(); // // /** Custom authorization claims written to JWT. */ // public abstract FleetEngineTokenClaims authorizationClaims(); // // /** Provides a builder for {@link FleetEngineToken}. */ // public static Builder builder() { // return new AutoValue_FleetEngineToken.Builder() // .setAudience(CommonConstants.DEFAULT_JWT_AUDIENCE); // } // // public abstract FleetEngineToken.Builder toBuilder(); // // /** Builder class for FleetEngineToken. */ // @AutoValue.Builder // public abstract static class Builder { // // /** Setter for token creation timestamp. */ // public abstract Builder setCreationTimestamp(Date creationTimestamp); // // /** Setter for token expiration timestamp. */ // public abstract Builder setExpirationTimestamp(Date expirationTimestamp); // // /** Setter for a signed JWT to be associated with the token object. */ // public abstract Builder setJwt(String token); // // /** Setter for the token type defining the scope of the token. */ // public abstract Builder setTokenType(FleetEngineTokenType type); // // /** Setter for token audience (aud claim). */ // public abstract Builder setAudience(String audience); // // /** Sets custom authorization claims written to JWT. */ // public abstract Builder setAuthorizationClaims(FleetEngineTokenClaims claims); // // /** Builds the token object. */ // public abstract FleetEngineToken build(); // } // } // // Path: src/main/java/com/google/fleetengine/auth/token/factory/signer/Signer.java // public interface Signer { // // /** // * Signs a provided Fleet Engine token. // * // * @param token Fleet Engine token to sign // * @return same value as the {@code token} parameter except with the JWT property set to a valid // * JWT // */ // FleetEngineToken sign(FleetEngineToken token) throws SigningTokenException; // } // // Path: src/main/java/com/google/fleetengine/auth/token/factory/signer/SigningTokenException.java // public class SigningTokenException extends Exception { // /** // * Constructs a {@code SigningTokenException} with the specified detail message. // * // * @param message The detail message (which is saved for later retrieval by the {@link // * #getMessage()} method) // */ // public SigningTokenException(String message) { // this(message, null); // } // // /** // * Constructs a {@code SigningTokenException} with the specified detail message. // * // * @param message The detail message (which is saved for later retrieval by the {@link // * #getMessage()} method) // * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). // * (A null value is permitted, and indicates that the cause is nonexistent or unknown.) // */ // public SigningTokenException(String message, Throwable cause) { // super(message, cause); // } // }
import com.google.fleetengine.auth.token.FleetEngineToken; import com.google.fleetengine.auth.token.factory.signer.Signer; import com.google.fleetengine.auth.token.factory.signer.SigningTokenException; import java.time.Duration;
// Copyright 2021 Google LLC // // 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.fleetengine.auth; /** * Provides non-expired Fleet Engine tokens. * * <p>Tokens can be freshly minted each time or reused. * * <p>Tokens are guaranteed to not expire for a duration of {@link * FleetEngineAuthTokenStateManager#EXPIRATION_WINDOW_DURATION} (currently 5 minutes.) */ public interface FleetEngineAuthTokenStateManager { /** * Tokens returned from any of the {@code findOrCreateToken} methods are guaranteed to be valid * for the given expiration window (currently 5 minutes.) */ Duration EXPIRATION_WINDOW_DURATION = Duration.ofMinutes(5); /** * Either signs {@code token} or reuses an existing non-expired token. * * @param signer signer used to sign the token * @param token unsigned token * @return Signed Fleet Engine token that is guaranteed not to expire for the next {@link * FleetEngineAuthTokenStateManager#EXPIRATION_WINDOW_DURATION} */
// Path: src/main/java/com/google/fleetengine/auth/token/FleetEngineToken.java // @AutoValue // public abstract class FleetEngineToken { // /** Token creation timestamp. */ // public abstract Date creationTimestamp(); // // /** Token expiration timestamp. */ // public abstract Date expirationTimestamp(); // // /** Audience (aud claim) of the JWT. */ // public abstract String audience(); // // /** Signed and base64 encoded JWT. */ // @Nullable // public abstract String jwt(); // // /** Scope of the authorization token. */ // public abstract FleetEngineTokenType tokenType(); // // /** Custom authorization claims written to JWT. */ // public abstract FleetEngineTokenClaims authorizationClaims(); // // /** Provides a builder for {@link FleetEngineToken}. */ // public static Builder builder() { // return new AutoValue_FleetEngineToken.Builder() // .setAudience(CommonConstants.DEFAULT_JWT_AUDIENCE); // } // // public abstract FleetEngineToken.Builder toBuilder(); // // /** Builder class for FleetEngineToken. */ // @AutoValue.Builder // public abstract static class Builder { // // /** Setter for token creation timestamp. */ // public abstract Builder setCreationTimestamp(Date creationTimestamp); // // /** Setter for token expiration timestamp. */ // public abstract Builder setExpirationTimestamp(Date expirationTimestamp); // // /** Setter for a signed JWT to be associated with the token object. */ // public abstract Builder setJwt(String token); // // /** Setter for the token type defining the scope of the token. */ // public abstract Builder setTokenType(FleetEngineTokenType type); // // /** Setter for token audience (aud claim). */ // public abstract Builder setAudience(String audience); // // /** Sets custom authorization claims written to JWT. */ // public abstract Builder setAuthorizationClaims(FleetEngineTokenClaims claims); // // /** Builds the token object. */ // public abstract FleetEngineToken build(); // } // } // // Path: src/main/java/com/google/fleetengine/auth/token/factory/signer/Signer.java // public interface Signer { // // /** // * Signs a provided Fleet Engine token. // * // * @param token Fleet Engine token to sign // * @return same value as the {@code token} parameter except with the JWT property set to a valid // * JWT // */ // FleetEngineToken sign(FleetEngineToken token) throws SigningTokenException; // } // // Path: src/main/java/com/google/fleetengine/auth/token/factory/signer/SigningTokenException.java // public class SigningTokenException extends Exception { // /** // * Constructs a {@code SigningTokenException} with the specified detail message. // * // * @param message The detail message (which is saved for later retrieval by the {@link // * #getMessage()} method) // */ // public SigningTokenException(String message) { // this(message, null); // } // // /** // * Constructs a {@code SigningTokenException} with the specified detail message. // * // * @param message The detail message (which is saved for later retrieval by the {@link // * #getMessage()} method) // * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). // * (A null value is permitted, and indicates that the cause is nonexistent or unknown.) // */ // public SigningTokenException(String message, Throwable cause) { // super(message, cause); // } // } // Path: src/main/java/com/google/fleetengine/auth/FleetEngineAuthTokenStateManager.java import com.google.fleetengine.auth.token.FleetEngineToken; import com.google.fleetengine.auth.token.factory.signer.Signer; import com.google.fleetengine.auth.token.factory.signer.SigningTokenException; import java.time.Duration; // Copyright 2021 Google LLC // // 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.fleetengine.auth; /** * Provides non-expired Fleet Engine tokens. * * <p>Tokens can be freshly minted each time or reused. * * <p>Tokens are guaranteed to not expire for a duration of {@link * FleetEngineAuthTokenStateManager#EXPIRATION_WINDOW_DURATION} (currently 5 minutes.) */ public interface FleetEngineAuthTokenStateManager { /** * Tokens returned from any of the {@code findOrCreateToken} methods are guaranteed to be valid * for the given expiration window (currently 5 minutes.) */ Duration EXPIRATION_WINDOW_DURATION = Duration.ofMinutes(5); /** * Either signs {@code token} or reuses an existing non-expired token. * * @param signer signer used to sign the token * @param token unsigned token * @return Signed Fleet Engine token that is guaranteed not to expire for the next {@link * FleetEngineAuthTokenStateManager#EXPIRATION_WINDOW_DURATION} */
FleetEngineToken signToken(Signer signer, FleetEngineToken token) throws SigningTokenException;
googlemaps/java-fleetengine-auth
src/main/java/com/google/fleetengine/auth/FleetEngineAuthTokenStateManager.java
// Path: src/main/java/com/google/fleetengine/auth/token/FleetEngineToken.java // @AutoValue // public abstract class FleetEngineToken { // /** Token creation timestamp. */ // public abstract Date creationTimestamp(); // // /** Token expiration timestamp. */ // public abstract Date expirationTimestamp(); // // /** Audience (aud claim) of the JWT. */ // public abstract String audience(); // // /** Signed and base64 encoded JWT. */ // @Nullable // public abstract String jwt(); // // /** Scope of the authorization token. */ // public abstract FleetEngineTokenType tokenType(); // // /** Custom authorization claims written to JWT. */ // public abstract FleetEngineTokenClaims authorizationClaims(); // // /** Provides a builder for {@link FleetEngineToken}. */ // public static Builder builder() { // return new AutoValue_FleetEngineToken.Builder() // .setAudience(CommonConstants.DEFAULT_JWT_AUDIENCE); // } // // public abstract FleetEngineToken.Builder toBuilder(); // // /** Builder class for FleetEngineToken. */ // @AutoValue.Builder // public abstract static class Builder { // // /** Setter for token creation timestamp. */ // public abstract Builder setCreationTimestamp(Date creationTimestamp); // // /** Setter for token expiration timestamp. */ // public abstract Builder setExpirationTimestamp(Date expirationTimestamp); // // /** Setter for a signed JWT to be associated with the token object. */ // public abstract Builder setJwt(String token); // // /** Setter for the token type defining the scope of the token. */ // public abstract Builder setTokenType(FleetEngineTokenType type); // // /** Setter for token audience (aud claim). */ // public abstract Builder setAudience(String audience); // // /** Sets custom authorization claims written to JWT. */ // public abstract Builder setAuthorizationClaims(FleetEngineTokenClaims claims); // // /** Builds the token object. */ // public abstract FleetEngineToken build(); // } // } // // Path: src/main/java/com/google/fleetengine/auth/token/factory/signer/Signer.java // public interface Signer { // // /** // * Signs a provided Fleet Engine token. // * // * @param token Fleet Engine token to sign // * @return same value as the {@code token} parameter except with the JWT property set to a valid // * JWT // */ // FleetEngineToken sign(FleetEngineToken token) throws SigningTokenException; // } // // Path: src/main/java/com/google/fleetengine/auth/token/factory/signer/SigningTokenException.java // public class SigningTokenException extends Exception { // /** // * Constructs a {@code SigningTokenException} with the specified detail message. // * // * @param message The detail message (which is saved for later retrieval by the {@link // * #getMessage()} method) // */ // public SigningTokenException(String message) { // this(message, null); // } // // /** // * Constructs a {@code SigningTokenException} with the specified detail message. // * // * @param message The detail message (which is saved for later retrieval by the {@link // * #getMessage()} method) // * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). // * (A null value is permitted, and indicates that the cause is nonexistent or unknown.) // */ // public SigningTokenException(String message, Throwable cause) { // super(message, cause); // } // }
import com.google.fleetengine.auth.token.FleetEngineToken; import com.google.fleetengine.auth.token.factory.signer.Signer; import com.google.fleetengine.auth.token.factory.signer.SigningTokenException; import java.time.Duration;
// Copyright 2021 Google LLC // // 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.fleetengine.auth; /** * Provides non-expired Fleet Engine tokens. * * <p>Tokens can be freshly minted each time or reused. * * <p>Tokens are guaranteed to not expire for a duration of {@link * FleetEngineAuthTokenStateManager#EXPIRATION_WINDOW_DURATION} (currently 5 minutes.) */ public interface FleetEngineAuthTokenStateManager { /** * Tokens returned from any of the {@code findOrCreateToken} methods are guaranteed to be valid * for the given expiration window (currently 5 minutes.) */ Duration EXPIRATION_WINDOW_DURATION = Duration.ofMinutes(5); /** * Either signs {@code token} or reuses an existing non-expired token. * * @param signer signer used to sign the token * @param token unsigned token * @return Signed Fleet Engine token that is guaranteed not to expire for the next {@link * FleetEngineAuthTokenStateManager#EXPIRATION_WINDOW_DURATION} */
// Path: src/main/java/com/google/fleetengine/auth/token/FleetEngineToken.java // @AutoValue // public abstract class FleetEngineToken { // /** Token creation timestamp. */ // public abstract Date creationTimestamp(); // // /** Token expiration timestamp. */ // public abstract Date expirationTimestamp(); // // /** Audience (aud claim) of the JWT. */ // public abstract String audience(); // // /** Signed and base64 encoded JWT. */ // @Nullable // public abstract String jwt(); // // /** Scope of the authorization token. */ // public abstract FleetEngineTokenType tokenType(); // // /** Custom authorization claims written to JWT. */ // public abstract FleetEngineTokenClaims authorizationClaims(); // // /** Provides a builder for {@link FleetEngineToken}. */ // public static Builder builder() { // return new AutoValue_FleetEngineToken.Builder() // .setAudience(CommonConstants.DEFAULT_JWT_AUDIENCE); // } // // public abstract FleetEngineToken.Builder toBuilder(); // // /** Builder class for FleetEngineToken. */ // @AutoValue.Builder // public abstract static class Builder { // // /** Setter for token creation timestamp. */ // public abstract Builder setCreationTimestamp(Date creationTimestamp); // // /** Setter for token expiration timestamp. */ // public abstract Builder setExpirationTimestamp(Date expirationTimestamp); // // /** Setter for a signed JWT to be associated with the token object. */ // public abstract Builder setJwt(String token); // // /** Setter for the token type defining the scope of the token. */ // public abstract Builder setTokenType(FleetEngineTokenType type); // // /** Setter for token audience (aud claim). */ // public abstract Builder setAudience(String audience); // // /** Sets custom authorization claims written to JWT. */ // public abstract Builder setAuthorizationClaims(FleetEngineTokenClaims claims); // // /** Builds the token object. */ // public abstract FleetEngineToken build(); // } // } // // Path: src/main/java/com/google/fleetengine/auth/token/factory/signer/Signer.java // public interface Signer { // // /** // * Signs a provided Fleet Engine token. // * // * @param token Fleet Engine token to sign // * @return same value as the {@code token} parameter except with the JWT property set to a valid // * JWT // */ // FleetEngineToken sign(FleetEngineToken token) throws SigningTokenException; // } // // Path: src/main/java/com/google/fleetengine/auth/token/factory/signer/SigningTokenException.java // public class SigningTokenException extends Exception { // /** // * Constructs a {@code SigningTokenException} with the specified detail message. // * // * @param message The detail message (which is saved for later retrieval by the {@link // * #getMessage()} method) // */ // public SigningTokenException(String message) { // this(message, null); // } // // /** // * Constructs a {@code SigningTokenException} with the specified detail message. // * // * @param message The detail message (which is saved for later retrieval by the {@link // * #getMessage()} method) // * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). // * (A null value is permitted, and indicates that the cause is nonexistent or unknown.) // */ // public SigningTokenException(String message, Throwable cause) { // super(message, cause); // } // } // Path: src/main/java/com/google/fleetengine/auth/FleetEngineAuthTokenStateManager.java import com.google.fleetengine.auth.token.FleetEngineToken; import com.google.fleetengine.auth.token.factory.signer.Signer; import com.google.fleetengine.auth.token.factory.signer.SigningTokenException; import java.time.Duration; // Copyright 2021 Google LLC // // 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.fleetengine.auth; /** * Provides non-expired Fleet Engine tokens. * * <p>Tokens can be freshly minted each time or reused. * * <p>Tokens are guaranteed to not expire for a duration of {@link * FleetEngineAuthTokenStateManager#EXPIRATION_WINDOW_DURATION} (currently 5 minutes.) */ public interface FleetEngineAuthTokenStateManager { /** * Tokens returned from any of the {@code findOrCreateToken} methods are guaranteed to be valid * for the given expiration window (currently 5 minutes.) */ Duration EXPIRATION_WINDOW_DURATION = Duration.ofMinutes(5); /** * Either signs {@code token} or reuses an existing non-expired token. * * @param signer signer used to sign the token * @param token unsigned token * @return Signed Fleet Engine token that is guaranteed not to expire for the next {@link * FleetEngineAuthTokenStateManager#EXPIRATION_WINDOW_DURATION} */
FleetEngineToken signToken(Signer signer, FleetEngineToken token) throws SigningTokenException;
googlemaps/java-fleetengine-auth
src/main/java/com/google/fleetengine/auth/FleetEngineAuthTokenStateManager.java
// Path: src/main/java/com/google/fleetengine/auth/token/FleetEngineToken.java // @AutoValue // public abstract class FleetEngineToken { // /** Token creation timestamp. */ // public abstract Date creationTimestamp(); // // /** Token expiration timestamp. */ // public abstract Date expirationTimestamp(); // // /** Audience (aud claim) of the JWT. */ // public abstract String audience(); // // /** Signed and base64 encoded JWT. */ // @Nullable // public abstract String jwt(); // // /** Scope of the authorization token. */ // public abstract FleetEngineTokenType tokenType(); // // /** Custom authorization claims written to JWT. */ // public abstract FleetEngineTokenClaims authorizationClaims(); // // /** Provides a builder for {@link FleetEngineToken}. */ // public static Builder builder() { // return new AutoValue_FleetEngineToken.Builder() // .setAudience(CommonConstants.DEFAULT_JWT_AUDIENCE); // } // // public abstract FleetEngineToken.Builder toBuilder(); // // /** Builder class for FleetEngineToken. */ // @AutoValue.Builder // public abstract static class Builder { // // /** Setter for token creation timestamp. */ // public abstract Builder setCreationTimestamp(Date creationTimestamp); // // /** Setter for token expiration timestamp. */ // public abstract Builder setExpirationTimestamp(Date expirationTimestamp); // // /** Setter for a signed JWT to be associated with the token object. */ // public abstract Builder setJwt(String token); // // /** Setter for the token type defining the scope of the token. */ // public abstract Builder setTokenType(FleetEngineTokenType type); // // /** Setter for token audience (aud claim). */ // public abstract Builder setAudience(String audience); // // /** Sets custom authorization claims written to JWT. */ // public abstract Builder setAuthorizationClaims(FleetEngineTokenClaims claims); // // /** Builds the token object. */ // public abstract FleetEngineToken build(); // } // } // // Path: src/main/java/com/google/fleetengine/auth/token/factory/signer/Signer.java // public interface Signer { // // /** // * Signs a provided Fleet Engine token. // * // * @param token Fleet Engine token to sign // * @return same value as the {@code token} parameter except with the JWT property set to a valid // * JWT // */ // FleetEngineToken sign(FleetEngineToken token) throws SigningTokenException; // } // // Path: src/main/java/com/google/fleetengine/auth/token/factory/signer/SigningTokenException.java // public class SigningTokenException extends Exception { // /** // * Constructs a {@code SigningTokenException} with the specified detail message. // * // * @param message The detail message (which is saved for later retrieval by the {@link // * #getMessage()} method) // */ // public SigningTokenException(String message) { // this(message, null); // } // // /** // * Constructs a {@code SigningTokenException} with the specified detail message. // * // * @param message The detail message (which is saved for later retrieval by the {@link // * #getMessage()} method) // * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). // * (A null value is permitted, and indicates that the cause is nonexistent or unknown.) // */ // public SigningTokenException(String message, Throwable cause) { // super(message, cause); // } // }
import com.google.fleetengine.auth.token.FleetEngineToken; import com.google.fleetengine.auth.token.factory.signer.Signer; import com.google.fleetengine.auth.token.factory.signer.SigningTokenException; import java.time.Duration;
// Copyright 2021 Google LLC // // 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.fleetengine.auth; /** * Provides non-expired Fleet Engine tokens. * * <p>Tokens can be freshly minted each time or reused. * * <p>Tokens are guaranteed to not expire for a duration of {@link * FleetEngineAuthTokenStateManager#EXPIRATION_WINDOW_DURATION} (currently 5 minutes.) */ public interface FleetEngineAuthTokenStateManager { /** * Tokens returned from any of the {@code findOrCreateToken} methods are guaranteed to be valid * for the given expiration window (currently 5 minutes.) */ Duration EXPIRATION_WINDOW_DURATION = Duration.ofMinutes(5); /** * Either signs {@code token} or reuses an existing non-expired token. * * @param signer signer used to sign the token * @param token unsigned token * @return Signed Fleet Engine token that is guaranteed not to expire for the next {@link * FleetEngineAuthTokenStateManager#EXPIRATION_WINDOW_DURATION} */
// Path: src/main/java/com/google/fleetengine/auth/token/FleetEngineToken.java // @AutoValue // public abstract class FleetEngineToken { // /** Token creation timestamp. */ // public abstract Date creationTimestamp(); // // /** Token expiration timestamp. */ // public abstract Date expirationTimestamp(); // // /** Audience (aud claim) of the JWT. */ // public abstract String audience(); // // /** Signed and base64 encoded JWT. */ // @Nullable // public abstract String jwt(); // // /** Scope of the authorization token. */ // public abstract FleetEngineTokenType tokenType(); // // /** Custom authorization claims written to JWT. */ // public abstract FleetEngineTokenClaims authorizationClaims(); // // /** Provides a builder for {@link FleetEngineToken}. */ // public static Builder builder() { // return new AutoValue_FleetEngineToken.Builder() // .setAudience(CommonConstants.DEFAULT_JWT_AUDIENCE); // } // // public abstract FleetEngineToken.Builder toBuilder(); // // /** Builder class for FleetEngineToken. */ // @AutoValue.Builder // public abstract static class Builder { // // /** Setter for token creation timestamp. */ // public abstract Builder setCreationTimestamp(Date creationTimestamp); // // /** Setter for token expiration timestamp. */ // public abstract Builder setExpirationTimestamp(Date expirationTimestamp); // // /** Setter for a signed JWT to be associated with the token object. */ // public abstract Builder setJwt(String token); // // /** Setter for the token type defining the scope of the token. */ // public abstract Builder setTokenType(FleetEngineTokenType type); // // /** Setter for token audience (aud claim). */ // public abstract Builder setAudience(String audience); // // /** Sets custom authorization claims written to JWT. */ // public abstract Builder setAuthorizationClaims(FleetEngineTokenClaims claims); // // /** Builds the token object. */ // public abstract FleetEngineToken build(); // } // } // // Path: src/main/java/com/google/fleetengine/auth/token/factory/signer/Signer.java // public interface Signer { // // /** // * Signs a provided Fleet Engine token. // * // * @param token Fleet Engine token to sign // * @return same value as the {@code token} parameter except with the JWT property set to a valid // * JWT // */ // FleetEngineToken sign(FleetEngineToken token) throws SigningTokenException; // } // // Path: src/main/java/com/google/fleetengine/auth/token/factory/signer/SigningTokenException.java // public class SigningTokenException extends Exception { // /** // * Constructs a {@code SigningTokenException} with the specified detail message. // * // * @param message The detail message (which is saved for later retrieval by the {@link // * #getMessage()} method) // */ // public SigningTokenException(String message) { // this(message, null); // } // // /** // * Constructs a {@code SigningTokenException} with the specified detail message. // * // * @param message The detail message (which is saved for later retrieval by the {@link // * #getMessage()} method) // * @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). // * (A null value is permitted, and indicates that the cause is nonexistent or unknown.) // */ // public SigningTokenException(String message, Throwable cause) { // super(message, cause); // } // } // Path: src/main/java/com/google/fleetengine/auth/FleetEngineAuthTokenStateManager.java import com.google.fleetengine.auth.token.FleetEngineToken; import com.google.fleetengine.auth.token.factory.signer.Signer; import com.google.fleetengine.auth.token.factory.signer.SigningTokenException; import java.time.Duration; // Copyright 2021 Google LLC // // 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.fleetengine.auth; /** * Provides non-expired Fleet Engine tokens. * * <p>Tokens can be freshly minted each time or reused. * * <p>Tokens are guaranteed to not expire for a duration of {@link * FleetEngineAuthTokenStateManager#EXPIRATION_WINDOW_DURATION} (currently 5 minutes.) */ public interface FleetEngineAuthTokenStateManager { /** * Tokens returned from any of the {@code findOrCreateToken} methods are guaranteed to be valid * for the given expiration window (currently 5 minutes.) */ Duration EXPIRATION_WINDOW_DURATION = Duration.ofMinutes(5); /** * Either signs {@code token} or reuses an existing non-expired token. * * @param signer signer used to sign the token * @param token unsigned token * @return Signed Fleet Engine token that is guaranteed not to expire for the next {@link * FleetEngineAuthTokenStateManager#EXPIRATION_WINDOW_DURATION} */
FleetEngineToken signToken(Signer signer, FleetEngineToken token) throws SigningTokenException;
acromusashi/acromusashi-stream-example
src/main/java/acromusashi/stream/example/topology/Snmp2TrashTopology.java
// Path: src/main/java/acromusashi/stream/example/bolt/BlackHoleBolt.java // public class BlackHoleBolt extends AmBaseBolt // { // /** serialVersionUID */ // private static final long serialVersionUID = 4824580284119159163L; // // /** // * パラメータを指定せずにインスタンスを生成する。 // */ // public BlackHoleBolt() // {} // // /** // * {@inheritDoc} // */ // @SuppressWarnings("rawtypes") // @Override // public void onPrepare(Map config, TopologyContext context) // { // // Do nothing. // } // // /** // * {@inheritDoc} // */ // @Override // public void onExecute(StreamMessage message) // { // // Do nothing. // } // }
import java.util.List; import acromusashi.stream.bolt.MessageConvertBolt; import acromusashi.stream.component.kestrel.spout.KestrelSpout; import acromusashi.stream.component.snmp.converter.SnmpConverter; import acromusashi.stream.config.StormConfigGenerator; import acromusashi.stream.config.StormConfigUtil; import acromusashi.stream.entity.Message; import acromusashi.stream.example.bolt.BlackHoleBolt; import acromusashi.stream.topology.BaseTopology; import backtype.storm.Config; import backtype.storm.scheme.StringScheme; import backtype.storm.spout.SchemeAsMultiScheme;
topology.buildTopology(); topology.submitTopology(isLocal); } @Override public void buildTopology() throws Exception { // Get setting from StormConfig Object List<String> kestrelHosts = StormConfigUtil.getStringListValue(getConfig(), "Kestrel.Hosts"); String kestrelQueueName = StormConfigUtil.getStringValue(getConfig(), "Kestrel.QueueName", "MessageQueue"); int kestrelSpoutPara = StormConfigUtil.getIntValue(getConfig(), "KestrelSpout.Parallelism", 1); int msgConvertPara = StormConfigUtil.getIntValue(getConfig(), "ConvertBolt.Parallelism", 1); int blackholeBoltPara = StormConfigUtil.getIntValue(getConfig(), "BlackHoleBolt.Parallelism", 1); // Topology Setting // Add Spout(KestrelSpout) KestrelSpout kestrelSpout = new KestrelSpout(kestrelHosts, kestrelQueueName, new SchemeAsMultiScheme(new StringScheme())); getBuilder().setSpout("KestrelSpout", kestrelSpout, kestrelSpoutPara); // Add Bolt(KestrelSpout -> MessageConvertBolt) MessageConvertBolt convertBolt = new MessageConvertBolt(); convertBolt.setConverter(new SnmpConverter()); getBuilder().setBolt("ConvertBolt", convertBolt, msgConvertPara).localOrShuffleGrouping( "KestrelSpout"); // Add Bolt(MessageConvertBolt -> HdfsStoreBolt)
// Path: src/main/java/acromusashi/stream/example/bolt/BlackHoleBolt.java // public class BlackHoleBolt extends AmBaseBolt // { // /** serialVersionUID */ // private static final long serialVersionUID = 4824580284119159163L; // // /** // * パラメータを指定せずにインスタンスを生成する。 // */ // public BlackHoleBolt() // {} // // /** // * {@inheritDoc} // */ // @SuppressWarnings("rawtypes") // @Override // public void onPrepare(Map config, TopologyContext context) // { // // Do nothing. // } // // /** // * {@inheritDoc} // */ // @Override // public void onExecute(StreamMessage message) // { // // Do nothing. // } // } // Path: src/main/java/acromusashi/stream/example/topology/Snmp2TrashTopology.java import java.util.List; import acromusashi.stream.bolt.MessageConvertBolt; import acromusashi.stream.component.kestrel.spout.KestrelSpout; import acromusashi.stream.component.snmp.converter.SnmpConverter; import acromusashi.stream.config.StormConfigGenerator; import acromusashi.stream.config.StormConfigUtil; import acromusashi.stream.entity.Message; import acromusashi.stream.example.bolt.BlackHoleBolt; import acromusashi.stream.topology.BaseTopology; import backtype.storm.Config; import backtype.storm.scheme.StringScheme; import backtype.storm.spout.SchemeAsMultiScheme; topology.buildTopology(); topology.submitTopology(isLocal); } @Override public void buildTopology() throws Exception { // Get setting from StormConfig Object List<String> kestrelHosts = StormConfigUtil.getStringListValue(getConfig(), "Kestrel.Hosts"); String kestrelQueueName = StormConfigUtil.getStringValue(getConfig(), "Kestrel.QueueName", "MessageQueue"); int kestrelSpoutPara = StormConfigUtil.getIntValue(getConfig(), "KestrelSpout.Parallelism", 1); int msgConvertPara = StormConfigUtil.getIntValue(getConfig(), "ConvertBolt.Parallelism", 1); int blackholeBoltPara = StormConfigUtil.getIntValue(getConfig(), "BlackHoleBolt.Parallelism", 1); // Topology Setting // Add Spout(KestrelSpout) KestrelSpout kestrelSpout = new KestrelSpout(kestrelHosts, kestrelQueueName, new SchemeAsMultiScheme(new StringScheme())); getBuilder().setSpout("KestrelSpout", kestrelSpout, kestrelSpoutPara); // Add Bolt(KestrelSpout -> MessageConvertBolt) MessageConvertBolt convertBolt = new MessageConvertBolt(); convertBolt.setConverter(new SnmpConverter()); getBuilder().setBolt("ConvertBolt", convertBolt, msgConvertPara).localOrShuffleGrouping( "KestrelSpout"); // Add Bolt(MessageConvertBolt -> HdfsStoreBolt)
BlackHoleBolt bolt = new BlackHoleBolt();
acromusashi/acromusashi-stream-example
src/main/java/acromusashi/stream/example/ml/topology/ChangeFindTopology.java
// Path: src/main/java/acromusashi/stream/example/ml/trident/ResultPrintFunction.java // public class ResultPrintFunction extends BaseFunction // { // /** serialVersionUID */ // private static final long serialVersionUID = -6332711183777478101L; // // /** Logger */ // private static final Logger logger = LoggerFactory.getLogger(ResultPrintFunction.class); // // /** // * パラメータを指定せずにインスタンスを生成する。 // */ // public ResultPrintFunction() // {} // // /** // * {@inheritDoc} // */ // @SuppressWarnings("rawtypes") // @Override // public void prepare(Map conf, TridentOperationContext context) // { // // Do nothing. // } // // /** // * {@inheritDoc} // */ // @Override // public void execute(TridentTuple tuple, TridentCollector collector) // { // ApacheLog statistics = (ApacheLog) tuple.getValueByField("average"); // String logFormat = "Statistics Result: Host={0}, DataCount={1}, MaxChangeFindScore={2}, ResponseTimeSum={3}, SizeSum={4}"; // logger.info(MessageFormat.format(logFormat, statistics.getKey(), statistics.getCount(), // statistics.getAnomalyScore(), statistics.getTimeSum(), statistics.getSizeSum())); // } // }
import storm.kafka.StringScheme; import storm.kafka.ZkHosts; import storm.kafka.trident.OpaqueTridentKafkaSpout; import storm.kafka.trident.TridentKafkaConfig; import storm.trident.TridentTopology; import storm.trident.operation.impl.CombinerAggregatorCombineImpl; import acromusashi.stream.config.StormConfigGenerator; import acromusashi.stream.config.StormConfigUtil; import acromusashi.stream.example.ml.trident.ResultPrintFunction; import acromusashi.stream.ml.loganalyze.ApacheLog; import acromusashi.stream.ml.loganalyze.ApacheLogAggregator; import acromusashi.stream.ml.loganalyze.ApacheLogSplitFunction; import acromusashi.stream.ml.loganalyze.ChangeFindFunction; import acromusashi.stream.topology.BaseTridentTopology; import backtype.storm.Config; import backtype.storm.generated.StormTopology; import backtype.storm.spout.SchemeAsMultiScheme; import backtype.storm.tuple.Fields;
cfFunction.setForgetability(forgetability); cfFunction.setSmoothingWindow(smoothingWindow); cfFunction.setScoreThreshold(scoreThreshold); TridentTopology topology = new TridentTopology(); // 以下の順でTridentTopologyにSpout/Functionを登録する。 // 1.TridentKafkaSpout:KafkaからApacheログ(JSON形式)を取得 // // ※全体並列度を「topology.parallelismHint」の設定値に併せて設定 // // >(each:各メッセージに対して実行) // 2.ApacheLogSplitFunction:受信したApacheログ(JSON形式)をエンティティに変換し、送信 // // ※エンティティを「IPaddress」の値毎にグルーピング // // >(each:各メッセージに対して実行) // 3.ChangeFindFunction:受信したApacheログのレスポンスタイムを用いて変化点スコアを算出 // // >(partitionAggregate:グルーピングしたエンティティを統合) // 4.ApacheLogAggregator:受信したApacheログの統計値を算出 // // >(each:各メッセージに対して実行) // 5.ResultPrintFunction:受信した統計値をログ出力 // @formatter:off topology.newStream("TridentKafkaSpout", tridentKafkaSpout).parallelismHint(parallelism) .each(new Fields("str"), apacheLogSplitFunction, new Fields("IPaddress", "responseTime")) .groupBy(new Fields("IPaddress")) .each(new Fields("IPaddress", "responseTime"), cfFunction, new Fields("webResponse")) .partitionAggregate(new Fields("webResponse"), new CombinerAggregatorCombineImpl(new ApacheLogAggregator()), new Fields("average"))
// Path: src/main/java/acromusashi/stream/example/ml/trident/ResultPrintFunction.java // public class ResultPrintFunction extends BaseFunction // { // /** serialVersionUID */ // private static final long serialVersionUID = -6332711183777478101L; // // /** Logger */ // private static final Logger logger = LoggerFactory.getLogger(ResultPrintFunction.class); // // /** // * パラメータを指定せずにインスタンスを生成する。 // */ // public ResultPrintFunction() // {} // // /** // * {@inheritDoc} // */ // @SuppressWarnings("rawtypes") // @Override // public void prepare(Map conf, TridentOperationContext context) // { // // Do nothing. // } // // /** // * {@inheritDoc} // */ // @Override // public void execute(TridentTuple tuple, TridentCollector collector) // { // ApacheLog statistics = (ApacheLog) tuple.getValueByField("average"); // String logFormat = "Statistics Result: Host={0}, DataCount={1}, MaxChangeFindScore={2}, ResponseTimeSum={3}, SizeSum={4}"; // logger.info(MessageFormat.format(logFormat, statistics.getKey(), statistics.getCount(), // statistics.getAnomalyScore(), statistics.getTimeSum(), statistics.getSizeSum())); // } // } // Path: src/main/java/acromusashi/stream/example/ml/topology/ChangeFindTopology.java import storm.kafka.StringScheme; import storm.kafka.ZkHosts; import storm.kafka.trident.OpaqueTridentKafkaSpout; import storm.kafka.trident.TridentKafkaConfig; import storm.trident.TridentTopology; import storm.trident.operation.impl.CombinerAggregatorCombineImpl; import acromusashi.stream.config.StormConfigGenerator; import acromusashi.stream.config.StormConfigUtil; import acromusashi.stream.example.ml.trident.ResultPrintFunction; import acromusashi.stream.ml.loganalyze.ApacheLog; import acromusashi.stream.ml.loganalyze.ApacheLogAggregator; import acromusashi.stream.ml.loganalyze.ApacheLogSplitFunction; import acromusashi.stream.ml.loganalyze.ChangeFindFunction; import acromusashi.stream.topology.BaseTridentTopology; import backtype.storm.Config; import backtype.storm.generated.StormTopology; import backtype.storm.spout.SchemeAsMultiScheme; import backtype.storm.tuple.Fields; cfFunction.setForgetability(forgetability); cfFunction.setSmoothingWindow(smoothingWindow); cfFunction.setScoreThreshold(scoreThreshold); TridentTopology topology = new TridentTopology(); // 以下の順でTridentTopologyにSpout/Functionを登録する。 // 1.TridentKafkaSpout:KafkaからApacheログ(JSON形式)を取得 // // ※全体並列度を「topology.parallelismHint」の設定値に併せて設定 // // >(each:各メッセージに対して実行) // 2.ApacheLogSplitFunction:受信したApacheログ(JSON形式)をエンティティに変換し、送信 // // ※エンティティを「IPaddress」の値毎にグルーピング // // >(each:各メッセージに対して実行) // 3.ChangeFindFunction:受信したApacheログのレスポンスタイムを用いて変化点スコアを算出 // // >(partitionAggregate:グルーピングしたエンティティを統合) // 4.ApacheLogAggregator:受信したApacheログの統計値を算出 // // >(each:各メッセージに対して実行) // 5.ResultPrintFunction:受信した統計値をログ出力 // @formatter:off topology.newStream("TridentKafkaSpout", tridentKafkaSpout).parallelismHint(parallelism) .each(new Fields("str"), apacheLogSplitFunction, new Fields("IPaddress", "responseTime")) .groupBy(new Fields("IPaddress")) .each(new Fields("IPaddress", "responseTime"), cfFunction, new Fields("webResponse")) .partitionAggregate(new Fields("webResponse"), new CombinerAggregatorCombineImpl(new ApacheLogAggregator()), new Fields("average"))
.each(new Fields("average"), new ResultPrintFunction(), new Fields("count"));
acromusashi/acromusashi-stream-example
src/main/java/acromusashi/stream/example/topology/HbaseStoreTopology.java
// Path: src/main/java/acromusashi/stream/example/spout/PeriodicalMessageGenSpout.java // public class PeriodicalMessageGenSpout extends BaseConfigurationSpout // { // /** serialVersionUID */ // private static final long serialVersionUID = -237111294339742815L; // // /** logger */ // private static final Logger logger = LoggerFactory.getLogger(PeriodicalMessageGenSpout.class); // // /** 送信カウンタ */ // private int counter = 0; // // /** // * パラメータを指定せずにインスタンスを生成する。 // */ // public PeriodicalMessageGenSpout() // {} // // /** // * 一定間隔ごとにデータをBoltに送信する // */ // @Override // public void nextTuple() // { // this.counter++; // Header header = new Header(); // header.setMessageId(UUID.randomUUID().toString()); // header.setTimestamp(System.currentTimeMillis()); // header.setSource("192.168.0.1"); // header.setType("message"); // Message message = new Message(); // message.setHeader(header); // // List<Object> list = new ArrayList<Object>(); // list.add("Counter:"); // list.add(this.counter); // message.setBody(list); // // getCollector().emit(new Values(message)); // // try // { // TimeUnit.SECONDS.sleep(1); // } // catch (InterruptedException iex) // { // if (logger.isDebugEnabled() == true) // { // logger.debug("Occur interrupt. Ignore interrupt.", iex); // } // } // } // // /** // * {@inheritDoc} // */ // @Override // public void declareOutputFields(OutputFieldsDeclarer declarer) // { // declarer.declare(new Fields("message")); // } // }
import java.util.ArrayList; import java.util.List; import org.apache.commons.lang.StringUtils; import acromusashi.stream.bolt.hbase.CamelHbaseStoreBolt; import acromusashi.stream.bolt.hbase.CellDefine; import acromusashi.stream.component.snmp.converter.SnmpConverter; import acromusashi.stream.config.StormConfigGenerator; import acromusashi.stream.config.StormConfigUtil; import acromusashi.stream.entity.Message; import acromusashi.stream.example.spout.PeriodicalMessageGenSpout; import acromusashi.stream.topology.BaseTopology; import backtype.storm.Config;
return; } // 起動引数として使用したパスからStorm設定オブジェクトを生成 Config conf = StormConfigGenerator.loadStormConfig(args[0]); // プログラム引数から設定値を取得(ローカル環境or分散環境) boolean isLocal = Boolean.valueOf(args[1]); // Topologyを起動する BaseTopology topology = new HbaseStoreTopology("HbaseStoreTopology", conf); topology.buildTopology(); topology.submitTopology(isLocal); } @Override public void buildTopology() throws Exception { // Get setting from StormConfig Object int msgGenSpoutPara = StormConfigUtil.getIntValue(getConfig(), "MessageGenSpout.Parallelism", 1); int hbaseBoltPara = StormConfigUtil.getIntValue(getConfig(), "CamelHBaseBolt.Parallelism", 1); String contextUri = StormConfigUtil.getStringValue(getConfig(), "CamelContext.Path", "file:/opt/storm/conf/camel-context-example-hbase.xml"); List<String> cellDefineList = StormConfigUtil.getStringListValue(getConfig(), "HBaseSchema.Define"); // Topology Setting // Add Spout(PeriodicalMessageGenSpout)
// Path: src/main/java/acromusashi/stream/example/spout/PeriodicalMessageGenSpout.java // public class PeriodicalMessageGenSpout extends BaseConfigurationSpout // { // /** serialVersionUID */ // private static final long serialVersionUID = -237111294339742815L; // // /** logger */ // private static final Logger logger = LoggerFactory.getLogger(PeriodicalMessageGenSpout.class); // // /** 送信カウンタ */ // private int counter = 0; // // /** // * パラメータを指定せずにインスタンスを生成する。 // */ // public PeriodicalMessageGenSpout() // {} // // /** // * 一定間隔ごとにデータをBoltに送信する // */ // @Override // public void nextTuple() // { // this.counter++; // Header header = new Header(); // header.setMessageId(UUID.randomUUID().toString()); // header.setTimestamp(System.currentTimeMillis()); // header.setSource("192.168.0.1"); // header.setType("message"); // Message message = new Message(); // message.setHeader(header); // // List<Object> list = new ArrayList<Object>(); // list.add("Counter:"); // list.add(this.counter); // message.setBody(list); // // getCollector().emit(new Values(message)); // // try // { // TimeUnit.SECONDS.sleep(1); // } // catch (InterruptedException iex) // { // if (logger.isDebugEnabled() == true) // { // logger.debug("Occur interrupt. Ignore interrupt.", iex); // } // } // } // // /** // * {@inheritDoc} // */ // @Override // public void declareOutputFields(OutputFieldsDeclarer declarer) // { // declarer.declare(new Fields("message")); // } // } // Path: src/main/java/acromusashi/stream/example/topology/HbaseStoreTopology.java import java.util.ArrayList; import java.util.List; import org.apache.commons.lang.StringUtils; import acromusashi.stream.bolt.hbase.CamelHbaseStoreBolt; import acromusashi.stream.bolt.hbase.CellDefine; import acromusashi.stream.component.snmp.converter.SnmpConverter; import acromusashi.stream.config.StormConfigGenerator; import acromusashi.stream.config.StormConfigUtil; import acromusashi.stream.entity.Message; import acromusashi.stream.example.spout.PeriodicalMessageGenSpout; import acromusashi.stream.topology.BaseTopology; import backtype.storm.Config; return; } // 起動引数として使用したパスからStorm設定オブジェクトを生成 Config conf = StormConfigGenerator.loadStormConfig(args[0]); // プログラム引数から設定値を取得(ローカル環境or分散環境) boolean isLocal = Boolean.valueOf(args[1]); // Topologyを起動する BaseTopology topology = new HbaseStoreTopology("HbaseStoreTopology", conf); topology.buildTopology(); topology.submitTopology(isLocal); } @Override public void buildTopology() throws Exception { // Get setting from StormConfig Object int msgGenSpoutPara = StormConfigUtil.getIntValue(getConfig(), "MessageGenSpout.Parallelism", 1); int hbaseBoltPara = StormConfigUtil.getIntValue(getConfig(), "CamelHBaseBolt.Parallelism", 1); String contextUri = StormConfigUtil.getStringValue(getConfig(), "CamelContext.Path", "file:/opt/storm/conf/camel-context-example-hbase.xml"); List<String> cellDefineList = StormConfigUtil.getStringListValue(getConfig(), "HBaseSchema.Define"); // Topology Setting // Add Spout(PeriodicalMessageGenSpout)
PeriodicalMessageGenSpout messageGenSpout = new PeriodicalMessageGenSpout();
acromusashi/acromusashi-stream-example
src/main/java/acromusashi/stream/example/topology/LocalConsolePrintTopology.java
// Path: src/main/java/acromusashi/stream/example/bolt/ConsolePrintBolt.java // public class ConsolePrintBolt extends AmBaseBolt // { // /** serialVersionUID */ // private static final long serialVersionUID = 5100460578090478268L; // // /** // * パラメータを指定せずにインスタンスを生成する。 // */ // public ConsolePrintBolt() // {} // // /** // * {@inheritDoc} // */ // @SuppressWarnings("rawtypes") // @Override // public void onPrepare(Map config, TopologyContext context) // { // // TODO Auto-generated method stub // // } // // /** // * {@inheritDoc} // */ // @Override // public void onExecute(StreamMessage message) // { // System.out.println(message.toString()); // } // }
import java.util.List; import acromusashi.stream.component.kestrel.spout.KestrelSpout; import acromusashi.stream.config.StormConfigGenerator; import acromusashi.stream.config.StormConfigUtil; import acromusashi.stream.entity.Message; import acromusashi.stream.example.bolt.ConsolePrintBolt; import acromusashi.stream.topology.BaseTopology; import backtype.storm.Config; import backtype.storm.scheme.StringScheme; import backtype.storm.spout.SchemeAsMultiScheme;
Config conf = StormConfigGenerator.loadStormConfig(args[0]); // プログラム引数から設定値を取得(ローカル環境or分散環境) boolean isLocal = Boolean.valueOf(args[1]); // Topologyを起動する BaseTopology topology = new LocalConsolePrintTopology("LocalConsolePrintTopology", conf); topology.buildTopology(); topology.submitTopology(isLocal); } @Override public void buildTopology() throws Exception { // Get setting from StormConfig Object List<String> kestrelHosts = StormConfigUtil.getStringListValue(getConfig(), "Kestrel.Hosts"); String kestrelQueueName = StormConfigUtil.getStringValue(getConfig(), "Kestrel.QueueName", "MessageQueue"); int kestrelSpoutPara = StormConfigUtil.getIntValue(getConfig(), "KestrelSpout.Parallelism", 1); int consoleBoltPara = StormConfigUtil.getIntValue(getConfig(), "ConsolePrintBolt.Parallelism", 2); // Topology Setting // Add Spout(KestrelSpout) KestrelSpout kestrelSpout = new KestrelSpout(kestrelHosts, kestrelQueueName, new SchemeAsMultiScheme(new StringScheme())); getBuilder().setSpout("KestrelSpout", kestrelSpout, kestrelSpoutPara); // Add Bolt(KestrelSpout -> ConsolePrintBolt)
// Path: src/main/java/acromusashi/stream/example/bolt/ConsolePrintBolt.java // public class ConsolePrintBolt extends AmBaseBolt // { // /** serialVersionUID */ // private static final long serialVersionUID = 5100460578090478268L; // // /** // * パラメータを指定せずにインスタンスを生成する。 // */ // public ConsolePrintBolt() // {} // // /** // * {@inheritDoc} // */ // @SuppressWarnings("rawtypes") // @Override // public void onPrepare(Map config, TopologyContext context) // { // // TODO Auto-generated method stub // // } // // /** // * {@inheritDoc} // */ // @Override // public void onExecute(StreamMessage message) // { // System.out.println(message.toString()); // } // } // Path: src/main/java/acromusashi/stream/example/topology/LocalConsolePrintTopology.java import java.util.List; import acromusashi.stream.component.kestrel.spout.KestrelSpout; import acromusashi.stream.config.StormConfigGenerator; import acromusashi.stream.config.StormConfigUtil; import acromusashi.stream.entity.Message; import acromusashi.stream.example.bolt.ConsolePrintBolt; import acromusashi.stream.topology.BaseTopology; import backtype.storm.Config; import backtype.storm.scheme.StringScheme; import backtype.storm.spout.SchemeAsMultiScheme; Config conf = StormConfigGenerator.loadStormConfig(args[0]); // プログラム引数から設定値を取得(ローカル環境or分散環境) boolean isLocal = Boolean.valueOf(args[1]); // Topologyを起動する BaseTopology topology = new LocalConsolePrintTopology("LocalConsolePrintTopology", conf); topology.buildTopology(); topology.submitTopology(isLocal); } @Override public void buildTopology() throws Exception { // Get setting from StormConfig Object List<String> kestrelHosts = StormConfigUtil.getStringListValue(getConfig(), "Kestrel.Hosts"); String kestrelQueueName = StormConfigUtil.getStringValue(getConfig(), "Kestrel.QueueName", "MessageQueue"); int kestrelSpoutPara = StormConfigUtil.getIntValue(getConfig(), "KestrelSpout.Parallelism", 1); int consoleBoltPara = StormConfigUtil.getIntValue(getConfig(), "ConsolePrintBolt.Parallelism", 2); // Topology Setting // Add Spout(KestrelSpout) KestrelSpout kestrelSpout = new KestrelSpout(kestrelHosts, kestrelQueueName, new SchemeAsMultiScheme(new StringScheme())); getBuilder().setSpout("KestrelSpout", kestrelSpout, kestrelSpoutPara); // Add Bolt(KestrelSpout -> ConsolePrintBolt)
ConsolePrintBolt printBolt = new ConsolePrintBolt();
acromusashi/acromusashi-stream-example
src/main/java/acromusashi/stream/example/topology/TwitterJsonConsolePrintTopology.java
// Path: src/main/java/acromusashi/stream/example/bolt/ConsolePrintBolt.java // public class ConsolePrintBolt extends AmBaseBolt // { // /** serialVersionUID */ // private static final long serialVersionUID = 5100460578090478268L; // // /** // * パラメータを指定せずにインスタンスを生成する。 // */ // public ConsolePrintBolt() // {} // // /** // * {@inheritDoc} // */ // @SuppressWarnings("rawtypes") // @Override // public void onPrepare(Map config, TopologyContext context) // { // // TODO Auto-generated method stub // // } // // /** // * {@inheritDoc} // */ // @Override // public void onExecute(StreamMessage message) // { // System.out.println(message.toString()); // } // }
import java.util.List; import acromusashi.stream.bolt.MessageConvertBolt; import acromusashi.stream.component.kestrel.spout.KestrelSpout; import acromusashi.stream.component.twitter.converter.TwitterJsonConverter; import acromusashi.stream.config.StormConfigGenerator; import acromusashi.stream.config.StormConfigUtil; import acromusashi.stream.entity.Message; import acromusashi.stream.example.bolt.ConsolePrintBolt; import acromusashi.stream.topology.BaseTopology; import backtype.storm.Config; import backtype.storm.scheme.StringScheme; import backtype.storm.spout.SchemeAsMultiScheme;
topology.buildTopology(); topology.submitTopology(isLocal); } @Override public void buildTopology() throws Exception { // Get setting from StormConfig Object List<String> kestrelHosts = StormConfigUtil.getStringListValue(getConfig(), "Kestrel.Hosts"); String kestrelQueueName = StormConfigUtil.getStringValue(getConfig(), "Kestrel.QueueName", "MessageQueue"); int kestrelSpoutPara = StormConfigUtil.getIntValue(getConfig(), "KestrelSpout.Parallelism", 1); int msgConvertPara = StormConfigUtil.getIntValue(getConfig(), "ConvertBolt.Parallelism", 1); int consoleBoltPara = StormConfigUtil.getIntValue(getConfig(), "ConsolePrintBolt.Parallelism", 1); // Topology Setting // Add Spout(KestrelSpout) KestrelSpout kestrelSpout = new KestrelSpout(kestrelHosts, kestrelQueueName, new SchemeAsMultiScheme(new StringScheme())); getBuilder().setSpout("KestrelSpout", kestrelSpout, kestrelSpoutPara); // Add Bolt(KestrelSpout -> MessageConvertBolt) MessageConvertBolt convertBolt = new MessageConvertBolt(); convertBolt.setConverter(new TwitterJsonConverter()); getBuilder().setBolt("ConvertBolt", convertBolt, msgConvertPara).localOrShuffleGrouping( "KestrelSpout"); // Add Bolt(MessageConvertBolt -> ConsolePrintBolt)
// Path: src/main/java/acromusashi/stream/example/bolt/ConsolePrintBolt.java // public class ConsolePrintBolt extends AmBaseBolt // { // /** serialVersionUID */ // private static final long serialVersionUID = 5100460578090478268L; // // /** // * パラメータを指定せずにインスタンスを生成する。 // */ // public ConsolePrintBolt() // {} // // /** // * {@inheritDoc} // */ // @SuppressWarnings("rawtypes") // @Override // public void onPrepare(Map config, TopologyContext context) // { // // TODO Auto-generated method stub // // } // // /** // * {@inheritDoc} // */ // @Override // public void onExecute(StreamMessage message) // { // System.out.println(message.toString()); // } // } // Path: src/main/java/acromusashi/stream/example/topology/TwitterJsonConsolePrintTopology.java import java.util.List; import acromusashi.stream.bolt.MessageConvertBolt; import acromusashi.stream.component.kestrel.spout.KestrelSpout; import acromusashi.stream.component.twitter.converter.TwitterJsonConverter; import acromusashi.stream.config.StormConfigGenerator; import acromusashi.stream.config.StormConfigUtil; import acromusashi.stream.entity.Message; import acromusashi.stream.example.bolt.ConsolePrintBolt; import acromusashi.stream.topology.BaseTopology; import backtype.storm.Config; import backtype.storm.scheme.StringScheme; import backtype.storm.spout.SchemeAsMultiScheme; topology.buildTopology(); topology.submitTopology(isLocal); } @Override public void buildTopology() throws Exception { // Get setting from StormConfig Object List<String> kestrelHosts = StormConfigUtil.getStringListValue(getConfig(), "Kestrel.Hosts"); String kestrelQueueName = StormConfigUtil.getStringValue(getConfig(), "Kestrel.QueueName", "MessageQueue"); int kestrelSpoutPara = StormConfigUtil.getIntValue(getConfig(), "KestrelSpout.Parallelism", 1); int msgConvertPara = StormConfigUtil.getIntValue(getConfig(), "ConvertBolt.Parallelism", 1); int consoleBoltPara = StormConfigUtil.getIntValue(getConfig(), "ConsolePrintBolt.Parallelism", 1); // Topology Setting // Add Spout(KestrelSpout) KestrelSpout kestrelSpout = new KestrelSpout(kestrelHosts, kestrelQueueName, new SchemeAsMultiScheme(new StringScheme())); getBuilder().setSpout("KestrelSpout", kestrelSpout, kestrelSpoutPara); // Add Bolt(KestrelSpout -> MessageConvertBolt) MessageConvertBolt convertBolt = new MessageConvertBolt(); convertBolt.setConverter(new TwitterJsonConverter()); getBuilder().setBolt("ConvertBolt", convertBolt, msgConvertPara).localOrShuffleGrouping( "KestrelSpout"); // Add Bolt(MessageConvertBolt -> ConsolePrintBolt)
ConsolePrintBolt bolt = new ConsolePrintBolt();
acromusashi/acromusashi-stream-example
src/main/java/acromusashi/stream/example/topology/Snmp2RedisTopology.java
// Path: src/main/java/acromusashi/stream/example/bolt/RedisBolt.java // public class RedisBolt extends MessageBolt // { // /** serialVersionUID */ // private static final long serialVersionUID = 7742873990972648063L; // // /** redishost */ // private String redisHost; // // /** Redisにアクセスするプールオブジェクト */ // private transient JedisPool jedisPool; // // /** Redisにアクセスするクライアントオブジェクト */ // private transient Jedis jedisClient; // // /** // * コンストラクタ // * // * @param redisHost Redis投入先ホスト // */ // public RedisBolt(String redisHost) // { // this.redisHost = redisHost; // } // // /** // * {@inheritDoc} // */ // @SuppressWarnings("rawtypes") // @Override // public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) // { // super.prepare(stormConf, context, collector); // this.jedisPool = new JedisPool(this.redisHost); // } // // /** // * {@inheritDoc} // */ // @Override // public void onMessage(Message message) throws Exception // { // if (this.jedisClient == null) // { // this.jedisClient = this.jedisPool.getResource(); // } // // this.jedisClient.set(message.getHeader().getMessageId(), message.getBody().toString()); // } // }
import java.util.List; import acromusashi.stream.bolt.MessageConvertBolt; import acromusashi.stream.component.kestrel.spout.KestrelSpout; import acromusashi.stream.component.snmp.converter.SnmpConverter; import acromusashi.stream.config.StormConfigGenerator; import acromusashi.stream.config.StormConfigUtil; import acromusashi.stream.entity.Message; import acromusashi.stream.example.bolt.RedisBolt; import acromusashi.stream.topology.BaseTopology; import backtype.storm.Config; import backtype.storm.scheme.StringScheme; import backtype.storm.spout.SchemeAsMultiScheme;
topology.submitTopology(isLocal); } @Override public void buildTopology() throws Exception { // Get setting from StormConfig Object List<String> kestrelHosts = StormConfigUtil.getStringListValue(getConfig(), "Kestrel.Hosts"); String kestrelQueueName = StormConfigUtil.getStringValue(getConfig(), "Kestrel.QueueName", "MessageQueue"); int kestrelSpoutPara = StormConfigUtil.getIntValue(getConfig(), "KestrelSpout.Parallelism", 1); int msgConvertPara = StormConfigUtil.getIntValue(getConfig(), "ConvertBolt.Parallelism", 1); String redisHost = StormConfigUtil.getStringValue(getConfig(), "RedisBolt.RedisHost", "localhost"); int redisBoltPara = StormConfigUtil.getIntValue(getConfig(), "RedisBolt.Parallelism", 1); // Topology Setting // Add Spout(KestrelSpout) KestrelSpout kestrelSpout = new KestrelSpout(kestrelHosts, kestrelQueueName, new SchemeAsMultiScheme(new StringScheme())); getBuilder().setSpout("KestrelSpout", kestrelSpout, kestrelSpoutPara); // Add Bolt(KestrelSpout -> MessageConvertBolt) MessageConvertBolt convertBolt = new MessageConvertBolt(); convertBolt.setConverter(new SnmpConverter()); getBuilder().setBolt("ConvertBolt", convertBolt, msgConvertPara).localOrShuffleGrouping( "KestrelSpout"); // Add Bolt(MessageConvertBolt -> RedisBolt)
// Path: src/main/java/acromusashi/stream/example/bolt/RedisBolt.java // public class RedisBolt extends MessageBolt // { // /** serialVersionUID */ // private static final long serialVersionUID = 7742873990972648063L; // // /** redishost */ // private String redisHost; // // /** Redisにアクセスするプールオブジェクト */ // private transient JedisPool jedisPool; // // /** Redisにアクセスするクライアントオブジェクト */ // private transient Jedis jedisClient; // // /** // * コンストラクタ // * // * @param redisHost Redis投入先ホスト // */ // public RedisBolt(String redisHost) // { // this.redisHost = redisHost; // } // // /** // * {@inheritDoc} // */ // @SuppressWarnings("rawtypes") // @Override // public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) // { // super.prepare(stormConf, context, collector); // this.jedisPool = new JedisPool(this.redisHost); // } // // /** // * {@inheritDoc} // */ // @Override // public void onMessage(Message message) throws Exception // { // if (this.jedisClient == null) // { // this.jedisClient = this.jedisPool.getResource(); // } // // this.jedisClient.set(message.getHeader().getMessageId(), message.getBody().toString()); // } // } // Path: src/main/java/acromusashi/stream/example/topology/Snmp2RedisTopology.java import java.util.List; import acromusashi.stream.bolt.MessageConvertBolt; import acromusashi.stream.component.kestrel.spout.KestrelSpout; import acromusashi.stream.component.snmp.converter.SnmpConverter; import acromusashi.stream.config.StormConfigGenerator; import acromusashi.stream.config.StormConfigUtil; import acromusashi.stream.entity.Message; import acromusashi.stream.example.bolt.RedisBolt; import acromusashi.stream.topology.BaseTopology; import backtype.storm.Config; import backtype.storm.scheme.StringScheme; import backtype.storm.spout.SchemeAsMultiScheme; topology.submitTopology(isLocal); } @Override public void buildTopology() throws Exception { // Get setting from StormConfig Object List<String> kestrelHosts = StormConfigUtil.getStringListValue(getConfig(), "Kestrel.Hosts"); String kestrelQueueName = StormConfigUtil.getStringValue(getConfig(), "Kestrel.QueueName", "MessageQueue"); int kestrelSpoutPara = StormConfigUtil.getIntValue(getConfig(), "KestrelSpout.Parallelism", 1); int msgConvertPara = StormConfigUtil.getIntValue(getConfig(), "ConvertBolt.Parallelism", 1); String redisHost = StormConfigUtil.getStringValue(getConfig(), "RedisBolt.RedisHost", "localhost"); int redisBoltPara = StormConfigUtil.getIntValue(getConfig(), "RedisBolt.Parallelism", 1); // Topology Setting // Add Spout(KestrelSpout) KestrelSpout kestrelSpout = new KestrelSpout(kestrelHosts, kestrelQueueName, new SchemeAsMultiScheme(new StringScheme())); getBuilder().setSpout("KestrelSpout", kestrelSpout, kestrelSpoutPara); // Add Bolt(KestrelSpout -> MessageConvertBolt) MessageConvertBolt convertBolt = new MessageConvertBolt(); convertBolt.setConverter(new SnmpConverter()); getBuilder().setBolt("ConvertBolt", convertBolt, msgConvertPara).localOrShuffleGrouping( "KestrelSpout"); // Add Bolt(MessageConvertBolt -> RedisBolt)
RedisBolt bolt = new RedisBolt(redisHost);