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 |
|---|---|---|---|---|---|---|
mlk/AssortmentOfJUnitRules | src/test/java/com/github/mlk/junit/rules/LocalDynamoDbRuleTest.java | // Path: src/test/java/com/github/mlk/junit/rules/helpers/dynamodb/DynamoExample.java
// public class DynamoExample {
// private final AmazonDynamoDB client;
//
// private final AttributeDefinition sequenceNumber = new AttributeDefinition("sequence_number", ScalarAttributeType.N);
// private final AttributeDefinition valueAttribute = new AttributeDefinition("value", ScalarAttributeType.S);
//
// public DynamoExample(AmazonDynamoDB client) {
// this.client = client;
// }
//
// public void createTable() {
// List<KeySchemaElement> keySchema = new ArrayList<>();
//
// keySchema.add(
// new KeySchemaElement()
// .withAttributeName(sequenceNumber.getAttributeName())
// .withKeyType(KeyType.HASH)
// );
//
// ProvisionedThroughput provisionedThroughput = new ProvisionedThroughput();
// provisionedThroughput.setReadCapacityUnits(10L);
// provisionedThroughput.setWriteCapacityUnits(10L);
//
// CreateTableRequest request = new CreateTableRequest()
// .withTableName("example_table")
// .withKeySchema(keySchema)
// .withAttributeDefinitions(singleton(sequenceNumber))
// .withProvisionedThroughput(provisionedThroughput);
//
// client.createTable(request);
// }
//
// public void setValue(long key, String value) {
// Map<String, AttributeValue> firstId = new HashMap<>();
// firstId.put(sequenceNumber.getAttributeName(), new AttributeValue().withN(Long.toString(key)));
// firstId.put(valueAttribute.getAttributeName(), new AttributeValue().withS(value));
//
//
// client.putItem(new PutItemRequest()
// .withTableName("example_table")
// .withItem(firstId));
// }
//
// public String getValue(long key) {
// Map<String, AttributeValue> result = client.getItem(new GetItemRequest()
// .withTableName("example_table")
// .withKey(Collections.singletonMap(sequenceNumber.getAttributeName(), new AttributeValue().withN(Long.toString(key))))).getItem();
//
// return result.get(valueAttribute.getAttributeName()).getS();
// }
// }
| import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import com.github.mlk.junit.rules.helpers.dynamodb.DynamoExample;
import java.util.UUID;
import org.junit.Rule;
import org.junit.Test; | package com.github.mlk.junit.rules;
public class LocalDynamoDbRuleTest {
@Rule
public LocalDynamoDbRule subject = new LocalDynamoDbRule();
@Test
public void getterSetterTest() {
String randomValue = UUID.randomUUID().toString();
| // Path: src/test/java/com/github/mlk/junit/rules/helpers/dynamodb/DynamoExample.java
// public class DynamoExample {
// private final AmazonDynamoDB client;
//
// private final AttributeDefinition sequenceNumber = new AttributeDefinition("sequence_number", ScalarAttributeType.N);
// private final AttributeDefinition valueAttribute = new AttributeDefinition("value", ScalarAttributeType.S);
//
// public DynamoExample(AmazonDynamoDB client) {
// this.client = client;
// }
//
// public void createTable() {
// List<KeySchemaElement> keySchema = new ArrayList<>();
//
// keySchema.add(
// new KeySchemaElement()
// .withAttributeName(sequenceNumber.getAttributeName())
// .withKeyType(KeyType.HASH)
// );
//
// ProvisionedThroughput provisionedThroughput = new ProvisionedThroughput();
// provisionedThroughput.setReadCapacityUnits(10L);
// provisionedThroughput.setWriteCapacityUnits(10L);
//
// CreateTableRequest request = new CreateTableRequest()
// .withTableName("example_table")
// .withKeySchema(keySchema)
// .withAttributeDefinitions(singleton(sequenceNumber))
// .withProvisionedThroughput(provisionedThroughput);
//
// client.createTable(request);
// }
//
// public void setValue(long key, String value) {
// Map<String, AttributeValue> firstId = new HashMap<>();
// firstId.put(sequenceNumber.getAttributeName(), new AttributeValue().withN(Long.toString(key)));
// firstId.put(valueAttribute.getAttributeName(), new AttributeValue().withS(value));
//
//
// client.putItem(new PutItemRequest()
// .withTableName("example_table")
// .withItem(firstId));
// }
//
// public String getValue(long key) {
// Map<String, AttributeValue> result = client.getItem(new GetItemRequest()
// .withTableName("example_table")
// .withKey(Collections.singletonMap(sequenceNumber.getAttributeName(), new AttributeValue().withN(Long.toString(key))))).getItem();
//
// return result.get(valueAttribute.getAttributeName()).getS();
// }
// }
// Path: src/test/java/com/github/mlk/junit/rules/LocalDynamoDbRuleTest.java
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import com.github.mlk.junit.rules.helpers.dynamodb.DynamoExample;
import java.util.UUID;
import org.junit.Rule;
import org.junit.Test;
package com.github.mlk.junit.rules;
public class LocalDynamoDbRuleTest {
@Rule
public LocalDynamoDbRule subject = new LocalDynamoDbRule();
@Test
public void getterSetterTest() {
String randomValue = UUID.randomUUID().toString();
| DynamoExample exampleClient = new DynamoExample(subject.getClient()); |
mlk/AssortmentOfJUnitRules | src/main/java/com/github/mlk/junit/rules/SftpRule.java | // Path: src/main/java/com/github/mlk/junit/rules/Helper.java
// public static int findRandomOpenPortOnAllLocalInterfaces() throws IOException {
// try (ServerSocket socket = new ServerSocket(0)) {
// return socket.getLocalPort();
// }
// }
| import static com.github.mlk.junit.rules.Helper.findRandomOpenPortOnAllLocalInterfaces;
import java.io.File;
import java.io.IOException;
import java.security.PublicKey;
import java.util.Collections;
import java.util.function.Supplier;
import org.apache.sshd.common.file.virtualfs.VirtualFileSystemFactory;
import org.apache.sshd.common.keyprovider.ClassLoadableResourceKeyPairProvider;
import org.apache.sshd.server.SshServer;
import org.apache.sshd.server.auth.hostbased.StaticHostBasedAuthenticator;
import org.apache.sshd.server.auth.pubkey.AcceptAllPublickeyAuthenticator;
import org.apache.sshd.server.auth.pubkey.UserAuthPublicKeyFactory;
import org.apache.sshd.server.scp.ScpCommandFactory;
import org.apache.sshd.server.subsystem.sftp.SftpSubsystemFactory;
import org.junit.rules.ExternalResource; | package com.github.mlk.junit.rules;
/**
* Create an SFTP server running on a random port. This server runs in a promiscuous mode, accepting
* any connection with a private key.
* TODO:
* - Allow both public key or username/password auth.
* - Allow for custom server key
*/
public class SftpRule extends ExternalResource {
private final Supplier<File> currentFolder;
private SshServer sshd;
/**
* SFTP Server
*
* @param currentFolder The user home folder for the SFTP server.
*/
public SftpRule(Supplier<File> currentFolder) {
this.currentFolder = currentFolder;
}
@Override
protected void before() throws Throwable {
sshd = SshServer.setUpDefaultServer(); | // Path: src/main/java/com/github/mlk/junit/rules/Helper.java
// public static int findRandomOpenPortOnAllLocalInterfaces() throws IOException {
// try (ServerSocket socket = new ServerSocket(0)) {
// return socket.getLocalPort();
// }
// }
// Path: src/main/java/com/github/mlk/junit/rules/SftpRule.java
import static com.github.mlk.junit.rules.Helper.findRandomOpenPortOnAllLocalInterfaces;
import java.io.File;
import java.io.IOException;
import java.security.PublicKey;
import java.util.Collections;
import java.util.function.Supplier;
import org.apache.sshd.common.file.virtualfs.VirtualFileSystemFactory;
import org.apache.sshd.common.keyprovider.ClassLoadableResourceKeyPairProvider;
import org.apache.sshd.server.SshServer;
import org.apache.sshd.server.auth.hostbased.StaticHostBasedAuthenticator;
import org.apache.sshd.server.auth.pubkey.AcceptAllPublickeyAuthenticator;
import org.apache.sshd.server.auth.pubkey.UserAuthPublicKeyFactory;
import org.apache.sshd.server.scp.ScpCommandFactory;
import org.apache.sshd.server.subsystem.sftp.SftpSubsystemFactory;
import org.junit.rules.ExternalResource;
package com.github.mlk.junit.rules;
/**
* Create an SFTP server running on a random port. This server runs in a promiscuous mode, accepting
* any connection with a private key.
* TODO:
* - Allow both public key or username/password auth.
* - Allow for custom server key
*/
public class SftpRule extends ExternalResource {
private final Supplier<File> currentFolder;
private SshServer sshd;
/**
* SFTP Server
*
* @param currentFolder The user home folder for the SFTP server.
*/
public SftpRule(Supplier<File> currentFolder) {
this.currentFolder = currentFolder;
}
@Override
protected void before() throws Throwable {
sshd = SshServer.setUpDefaultServer(); | sshd.setPort(findRandomOpenPortOnAllLocalInterfaces()); |
mlk/AssortmentOfJUnitRules | src/test/java/com/github/mlk/junit/matchers/HadoopMatchersTest.java | // Path: src/main/java/com/github/mlk/junit/matchers/HadoopMatchers.java
// public static Matcher<HadoopDFSRule> exists(String file) {
// return new HadoopPathExists(file);
// }
//
// Path: src/main/java/com/github/mlk/junit/rules/HadoopDFSRule.java
// public class HadoopDFSRule extends ExternalResource {
//
// private HdfsConfiguration conf;
// private MiniDFSCluster cluster;
//
// private FileSystem mfs;
// private FileContext mfc;
//
// protected HdfsConfiguration createConfiguration() {
// return new HdfsConfiguration();
// }
//
// public HdfsConfiguration getConfiguration() {
// return conf;
// }
//
// @Override
// protected void before() throws Throwable {
// conf = createConfiguration();
// cluster = new MiniDFSCluster.Builder(conf).numDataNodes(3).build();
// cluster.waitActive();
// mfs = cluster.getFileSystem();
// mfc = FileContext.getFileContext();
// }
//
// @Override
// protected void after() {
// cluster.shutdown(true);
// }
//
// /**
// * @return Returns the file system on the Hadoop mini-cluster.
// */
// public FileSystem getMfs() {
// return mfs;
// }
//
// /**
// * @return Returns the port of the name node in the mini-cluster.
// */
// public int getNameNodePort() {
// return cluster.getNameNodePort();
// }
//
// /**
// * Writes the following content to the Hadoop cluster.
// *
// * @param filename File to be created
// * @param content The content to write
// * @throws IOException Anything.
// */
// public void write(String filename, String content) throws IOException {
// FSDataOutputStream s = getMfs().create(new Path(filename));
// s.writeBytes(content);
// s.close();
// }
//
// /**
// * Copies the content of the given resource into Hadoop.
// *
// * @param filename File to be created
// * @param resource Resource to copy
// * @throws IOException Anything
// */
// public void copyResource(String filename, String resource) throws IOException {
// write(filename, IOUtils.toByteArray(getClass().getResource(resource)));
// }
//
// /**
// * Writes the following content to the Hadoop cluster.
// *
// * @param filename File to be created
// * @param content The content to write
// * @throws IOException Anything
// */
// public void write(String filename, byte[] content) throws IOException {
// FSDataOutputStream s = getMfs().create(new Path(filename));
// s.write(content);
// s.close();
// }
//
// /**
// * Fully reads the content of the given file.
// *
// * @param filename File to read
// * @return Content of the file
// * @throws IOException Anything
// */
// public String read(String filename) throws IOException {
// Path p = new Path(filename);
// int size = (int) getMfs().getFileStatus(p).getLen();
// FSDataInputStream is = getMfs().open(p);
// byte[] content = new byte[size];
// is.readFully(content);
// return new String(content);
// }
//
// /**
// * Checks if the given path exists on Hadoop.
// *
// * @param filename Filename to check
// * @return true if the file exists
// * @throws IOException Anything
// * @deprecated Badly named, use exists instead
// */
// @Deprecated
// public boolean exist(String filename) throws IOException {
// return exists(filename);
// }
//
// /**
// * Checks if the given path exists on Hadoop.
// *
// * @param filename Filename to check
// * @throws IOException Anything
// * @return true if the file exists
// */
// public boolean exists(String filename) throws IOException {
// return exists(new Path(filename));
// }
//
// /**
// * Checks if the given path exists on Hadoop.
// *
// * @param filename Filename to check
// * @throws IOException Anything
// * @return true if the file exists
// */
// public boolean exists(Path filename) throws IOException {
// try {
// return getMfs().listFiles(filename, true).hasNext();
// } catch (FileNotFoundException e) {
// return false;
// }
// }
// }
| import static com.github.mlk.junit.matchers.HadoopMatchers.exists;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertThat;
import com.github.mlk.junit.rules.HadoopDFSRule;
import java.io.IOException;
import org.junit.Rule;
import org.junit.Test; | package com.github.mlk.junit.matchers;
public class HadoopMatchersTest {
@Rule | // Path: src/main/java/com/github/mlk/junit/matchers/HadoopMatchers.java
// public static Matcher<HadoopDFSRule> exists(String file) {
// return new HadoopPathExists(file);
// }
//
// Path: src/main/java/com/github/mlk/junit/rules/HadoopDFSRule.java
// public class HadoopDFSRule extends ExternalResource {
//
// private HdfsConfiguration conf;
// private MiniDFSCluster cluster;
//
// private FileSystem mfs;
// private FileContext mfc;
//
// protected HdfsConfiguration createConfiguration() {
// return new HdfsConfiguration();
// }
//
// public HdfsConfiguration getConfiguration() {
// return conf;
// }
//
// @Override
// protected void before() throws Throwable {
// conf = createConfiguration();
// cluster = new MiniDFSCluster.Builder(conf).numDataNodes(3).build();
// cluster.waitActive();
// mfs = cluster.getFileSystem();
// mfc = FileContext.getFileContext();
// }
//
// @Override
// protected void after() {
// cluster.shutdown(true);
// }
//
// /**
// * @return Returns the file system on the Hadoop mini-cluster.
// */
// public FileSystem getMfs() {
// return mfs;
// }
//
// /**
// * @return Returns the port of the name node in the mini-cluster.
// */
// public int getNameNodePort() {
// return cluster.getNameNodePort();
// }
//
// /**
// * Writes the following content to the Hadoop cluster.
// *
// * @param filename File to be created
// * @param content The content to write
// * @throws IOException Anything.
// */
// public void write(String filename, String content) throws IOException {
// FSDataOutputStream s = getMfs().create(new Path(filename));
// s.writeBytes(content);
// s.close();
// }
//
// /**
// * Copies the content of the given resource into Hadoop.
// *
// * @param filename File to be created
// * @param resource Resource to copy
// * @throws IOException Anything
// */
// public void copyResource(String filename, String resource) throws IOException {
// write(filename, IOUtils.toByteArray(getClass().getResource(resource)));
// }
//
// /**
// * Writes the following content to the Hadoop cluster.
// *
// * @param filename File to be created
// * @param content The content to write
// * @throws IOException Anything
// */
// public void write(String filename, byte[] content) throws IOException {
// FSDataOutputStream s = getMfs().create(new Path(filename));
// s.write(content);
// s.close();
// }
//
// /**
// * Fully reads the content of the given file.
// *
// * @param filename File to read
// * @return Content of the file
// * @throws IOException Anything
// */
// public String read(String filename) throws IOException {
// Path p = new Path(filename);
// int size = (int) getMfs().getFileStatus(p).getLen();
// FSDataInputStream is = getMfs().open(p);
// byte[] content = new byte[size];
// is.readFully(content);
// return new String(content);
// }
//
// /**
// * Checks if the given path exists on Hadoop.
// *
// * @param filename Filename to check
// * @return true if the file exists
// * @throws IOException Anything
// * @deprecated Badly named, use exists instead
// */
// @Deprecated
// public boolean exist(String filename) throws IOException {
// return exists(filename);
// }
//
// /**
// * Checks if the given path exists on Hadoop.
// *
// * @param filename Filename to check
// * @throws IOException Anything
// * @return true if the file exists
// */
// public boolean exists(String filename) throws IOException {
// return exists(new Path(filename));
// }
//
// /**
// * Checks if the given path exists on Hadoop.
// *
// * @param filename Filename to check
// * @throws IOException Anything
// * @return true if the file exists
// */
// public boolean exists(Path filename) throws IOException {
// try {
// return getMfs().listFiles(filename, true).hasNext();
// } catch (FileNotFoundException e) {
// return false;
// }
// }
// }
// Path: src/test/java/com/github/mlk/junit/matchers/HadoopMatchersTest.java
import static com.github.mlk.junit.matchers.HadoopMatchers.exists;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertThat;
import com.github.mlk.junit.rules.HadoopDFSRule;
import java.io.IOException;
import org.junit.Rule;
import org.junit.Test;
package com.github.mlk.junit.matchers;
public class HadoopMatchersTest {
@Rule | public HadoopDFSRule hadoop = new HadoopDFSRule(); |
mlk/AssortmentOfJUnitRules | src/test/java/com/github/mlk/junit/matchers/HadoopMatchersTest.java | // Path: src/main/java/com/github/mlk/junit/matchers/HadoopMatchers.java
// public static Matcher<HadoopDFSRule> exists(String file) {
// return new HadoopPathExists(file);
// }
//
// Path: src/main/java/com/github/mlk/junit/rules/HadoopDFSRule.java
// public class HadoopDFSRule extends ExternalResource {
//
// private HdfsConfiguration conf;
// private MiniDFSCluster cluster;
//
// private FileSystem mfs;
// private FileContext mfc;
//
// protected HdfsConfiguration createConfiguration() {
// return new HdfsConfiguration();
// }
//
// public HdfsConfiguration getConfiguration() {
// return conf;
// }
//
// @Override
// protected void before() throws Throwable {
// conf = createConfiguration();
// cluster = new MiniDFSCluster.Builder(conf).numDataNodes(3).build();
// cluster.waitActive();
// mfs = cluster.getFileSystem();
// mfc = FileContext.getFileContext();
// }
//
// @Override
// protected void after() {
// cluster.shutdown(true);
// }
//
// /**
// * @return Returns the file system on the Hadoop mini-cluster.
// */
// public FileSystem getMfs() {
// return mfs;
// }
//
// /**
// * @return Returns the port of the name node in the mini-cluster.
// */
// public int getNameNodePort() {
// return cluster.getNameNodePort();
// }
//
// /**
// * Writes the following content to the Hadoop cluster.
// *
// * @param filename File to be created
// * @param content The content to write
// * @throws IOException Anything.
// */
// public void write(String filename, String content) throws IOException {
// FSDataOutputStream s = getMfs().create(new Path(filename));
// s.writeBytes(content);
// s.close();
// }
//
// /**
// * Copies the content of the given resource into Hadoop.
// *
// * @param filename File to be created
// * @param resource Resource to copy
// * @throws IOException Anything
// */
// public void copyResource(String filename, String resource) throws IOException {
// write(filename, IOUtils.toByteArray(getClass().getResource(resource)));
// }
//
// /**
// * Writes the following content to the Hadoop cluster.
// *
// * @param filename File to be created
// * @param content The content to write
// * @throws IOException Anything
// */
// public void write(String filename, byte[] content) throws IOException {
// FSDataOutputStream s = getMfs().create(new Path(filename));
// s.write(content);
// s.close();
// }
//
// /**
// * Fully reads the content of the given file.
// *
// * @param filename File to read
// * @return Content of the file
// * @throws IOException Anything
// */
// public String read(String filename) throws IOException {
// Path p = new Path(filename);
// int size = (int) getMfs().getFileStatus(p).getLen();
// FSDataInputStream is = getMfs().open(p);
// byte[] content = new byte[size];
// is.readFully(content);
// return new String(content);
// }
//
// /**
// * Checks if the given path exists on Hadoop.
// *
// * @param filename Filename to check
// * @return true if the file exists
// * @throws IOException Anything
// * @deprecated Badly named, use exists instead
// */
// @Deprecated
// public boolean exist(String filename) throws IOException {
// return exists(filename);
// }
//
// /**
// * Checks if the given path exists on Hadoop.
// *
// * @param filename Filename to check
// * @throws IOException Anything
// * @return true if the file exists
// */
// public boolean exists(String filename) throws IOException {
// return exists(new Path(filename));
// }
//
// /**
// * Checks if the given path exists on Hadoop.
// *
// * @param filename Filename to check
// * @throws IOException Anything
// * @return true if the file exists
// */
// public boolean exists(Path filename) throws IOException {
// try {
// return getMfs().listFiles(filename, true).hasNext();
// } catch (FileNotFoundException e) {
// return false;
// }
// }
// }
| import static com.github.mlk.junit.matchers.HadoopMatchers.exists;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertThat;
import com.github.mlk.junit.rules.HadoopDFSRule;
import java.io.IOException;
import org.junit.Rule;
import org.junit.Test; | package com.github.mlk.junit.matchers;
public class HadoopMatchersTest {
@Rule
public HadoopDFSRule hadoop = new HadoopDFSRule();
@Test
public void whenFileExistsReturnTrue() throws IOException {
hadoop.write("/hello.txt", "content");
| // Path: src/main/java/com/github/mlk/junit/matchers/HadoopMatchers.java
// public static Matcher<HadoopDFSRule> exists(String file) {
// return new HadoopPathExists(file);
// }
//
// Path: src/main/java/com/github/mlk/junit/rules/HadoopDFSRule.java
// public class HadoopDFSRule extends ExternalResource {
//
// private HdfsConfiguration conf;
// private MiniDFSCluster cluster;
//
// private FileSystem mfs;
// private FileContext mfc;
//
// protected HdfsConfiguration createConfiguration() {
// return new HdfsConfiguration();
// }
//
// public HdfsConfiguration getConfiguration() {
// return conf;
// }
//
// @Override
// protected void before() throws Throwable {
// conf = createConfiguration();
// cluster = new MiniDFSCluster.Builder(conf).numDataNodes(3).build();
// cluster.waitActive();
// mfs = cluster.getFileSystem();
// mfc = FileContext.getFileContext();
// }
//
// @Override
// protected void after() {
// cluster.shutdown(true);
// }
//
// /**
// * @return Returns the file system on the Hadoop mini-cluster.
// */
// public FileSystem getMfs() {
// return mfs;
// }
//
// /**
// * @return Returns the port of the name node in the mini-cluster.
// */
// public int getNameNodePort() {
// return cluster.getNameNodePort();
// }
//
// /**
// * Writes the following content to the Hadoop cluster.
// *
// * @param filename File to be created
// * @param content The content to write
// * @throws IOException Anything.
// */
// public void write(String filename, String content) throws IOException {
// FSDataOutputStream s = getMfs().create(new Path(filename));
// s.writeBytes(content);
// s.close();
// }
//
// /**
// * Copies the content of the given resource into Hadoop.
// *
// * @param filename File to be created
// * @param resource Resource to copy
// * @throws IOException Anything
// */
// public void copyResource(String filename, String resource) throws IOException {
// write(filename, IOUtils.toByteArray(getClass().getResource(resource)));
// }
//
// /**
// * Writes the following content to the Hadoop cluster.
// *
// * @param filename File to be created
// * @param content The content to write
// * @throws IOException Anything
// */
// public void write(String filename, byte[] content) throws IOException {
// FSDataOutputStream s = getMfs().create(new Path(filename));
// s.write(content);
// s.close();
// }
//
// /**
// * Fully reads the content of the given file.
// *
// * @param filename File to read
// * @return Content of the file
// * @throws IOException Anything
// */
// public String read(String filename) throws IOException {
// Path p = new Path(filename);
// int size = (int) getMfs().getFileStatus(p).getLen();
// FSDataInputStream is = getMfs().open(p);
// byte[] content = new byte[size];
// is.readFully(content);
// return new String(content);
// }
//
// /**
// * Checks if the given path exists on Hadoop.
// *
// * @param filename Filename to check
// * @return true if the file exists
// * @throws IOException Anything
// * @deprecated Badly named, use exists instead
// */
// @Deprecated
// public boolean exist(String filename) throws IOException {
// return exists(filename);
// }
//
// /**
// * Checks if the given path exists on Hadoop.
// *
// * @param filename Filename to check
// * @throws IOException Anything
// * @return true if the file exists
// */
// public boolean exists(String filename) throws IOException {
// return exists(new Path(filename));
// }
//
// /**
// * Checks if the given path exists on Hadoop.
// *
// * @param filename Filename to check
// * @throws IOException Anything
// * @return true if the file exists
// */
// public boolean exists(Path filename) throws IOException {
// try {
// return getMfs().listFiles(filename, true).hasNext();
// } catch (FileNotFoundException e) {
// return false;
// }
// }
// }
// Path: src/test/java/com/github/mlk/junit/matchers/HadoopMatchersTest.java
import static com.github.mlk.junit.matchers.HadoopMatchers.exists;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertThat;
import com.github.mlk.junit.rules.HadoopDFSRule;
import java.io.IOException;
import org.junit.Rule;
import org.junit.Test;
package com.github.mlk.junit.matchers;
public class HadoopMatchersTest {
@Rule
public HadoopDFSRule hadoop = new HadoopDFSRule();
@Test
public void whenFileExistsReturnTrue() throws IOException {
hadoop.write("/hello.txt", "content");
| assertThat(hadoop, exists("/hello.txt")); |
mlk/AssortmentOfJUnitRules | src/test/java/com/github/mlk/junit/rules/HttpDynamoDbRuleTest.java | // Path: src/test/java/com/github/mlk/junit/rules/helpers/dynamodb/DynamoExample.java
// public class DynamoExample {
// private final AmazonDynamoDB client;
//
// private final AttributeDefinition sequenceNumber = new AttributeDefinition("sequence_number", ScalarAttributeType.N);
// private final AttributeDefinition valueAttribute = new AttributeDefinition("value", ScalarAttributeType.S);
//
// public DynamoExample(AmazonDynamoDB client) {
// this.client = client;
// }
//
// public void createTable() {
// List<KeySchemaElement> keySchema = new ArrayList<>();
//
// keySchema.add(
// new KeySchemaElement()
// .withAttributeName(sequenceNumber.getAttributeName())
// .withKeyType(KeyType.HASH)
// );
//
// ProvisionedThroughput provisionedThroughput = new ProvisionedThroughput();
// provisionedThroughput.setReadCapacityUnits(10L);
// provisionedThroughput.setWriteCapacityUnits(10L);
//
// CreateTableRequest request = new CreateTableRequest()
// .withTableName("example_table")
// .withKeySchema(keySchema)
// .withAttributeDefinitions(singleton(sequenceNumber))
// .withProvisionedThroughput(provisionedThroughput);
//
// client.createTable(request);
// }
//
// public void setValue(long key, String value) {
// Map<String, AttributeValue> firstId = new HashMap<>();
// firstId.put(sequenceNumber.getAttributeName(), new AttributeValue().withN(Long.toString(key)));
// firstId.put(valueAttribute.getAttributeName(), new AttributeValue().withS(value));
//
//
// client.putItem(new PutItemRequest()
// .withTableName("example_table")
// .withItem(firstId));
// }
//
// public String getValue(long key) {
// Map<String, AttributeValue> result = client.getItem(new GetItemRequest()
// .withTableName("example_table")
// .withKey(Collections.singletonMap(sequenceNumber.getAttributeName(), new AttributeValue().withN(Long.toString(key))))).getItem();
//
// return result.get(valueAttribute.getAttributeName()).getS();
// }
// }
| import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.github.mlk.junit.rules.helpers.dynamodb.DynamoExample;
import java.util.UUID;
import org.junit.Rule;
import org.junit.Test; | package com.github.mlk.junit.rules;
public class HttpDynamoDbRuleTest {
@Rule
public HttpDynamoDbRule subject = new HttpDynamoDbRule();
@Test
public void getterSetterTest() {
String randomValue = UUID.randomUUID().toString();
| // Path: src/test/java/com/github/mlk/junit/rules/helpers/dynamodb/DynamoExample.java
// public class DynamoExample {
// private final AmazonDynamoDB client;
//
// private final AttributeDefinition sequenceNumber = new AttributeDefinition("sequence_number", ScalarAttributeType.N);
// private final AttributeDefinition valueAttribute = new AttributeDefinition("value", ScalarAttributeType.S);
//
// public DynamoExample(AmazonDynamoDB client) {
// this.client = client;
// }
//
// public void createTable() {
// List<KeySchemaElement> keySchema = new ArrayList<>();
//
// keySchema.add(
// new KeySchemaElement()
// .withAttributeName(sequenceNumber.getAttributeName())
// .withKeyType(KeyType.HASH)
// );
//
// ProvisionedThroughput provisionedThroughput = new ProvisionedThroughput();
// provisionedThroughput.setReadCapacityUnits(10L);
// provisionedThroughput.setWriteCapacityUnits(10L);
//
// CreateTableRequest request = new CreateTableRequest()
// .withTableName("example_table")
// .withKeySchema(keySchema)
// .withAttributeDefinitions(singleton(sequenceNumber))
// .withProvisionedThroughput(provisionedThroughput);
//
// client.createTable(request);
// }
//
// public void setValue(long key, String value) {
// Map<String, AttributeValue> firstId = new HashMap<>();
// firstId.put(sequenceNumber.getAttributeName(), new AttributeValue().withN(Long.toString(key)));
// firstId.put(valueAttribute.getAttributeName(), new AttributeValue().withS(value));
//
//
// client.putItem(new PutItemRequest()
// .withTableName("example_table")
// .withItem(firstId));
// }
//
// public String getValue(long key) {
// Map<String, AttributeValue> result = client.getItem(new GetItemRequest()
// .withTableName("example_table")
// .withKey(Collections.singletonMap(sequenceNumber.getAttributeName(), new AttributeValue().withN(Long.toString(key))))).getItem();
//
// return result.get(valueAttribute.getAttributeName()).getS();
// }
// }
// Path: src/test/java/com/github/mlk/junit/rules/HttpDynamoDbRuleTest.java
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.github.mlk.junit.rules.helpers.dynamodb.DynamoExample;
import java.util.UUID;
import org.junit.Rule;
import org.junit.Test;
package com.github.mlk.junit.rules;
public class HttpDynamoDbRuleTest {
@Rule
public HttpDynamoDbRule subject = new HttpDynamoDbRule();
@Test
public void getterSetterTest() {
String randomValue = UUID.randomUUID().toString();
| DynamoExample exampleClient = new DynamoExample(AmazonDynamoDBClientBuilder |
mlk/AssortmentOfJUnitRules | src/test/java/com/github/mlk/junit/rules/TestHadoopYarnRule.java | // Path: src/test/java/com/github/mlk/junit/rules/helpers/hadoop/BasicTestJob.java
// public class BasicTestJob extends Configured implements Tool {
//
// @Override
// public int run(String... args) throws Exception {
// Job job = Job.getInstance(getConf(), "BasicTestJob");
// TextInputFormat.addInputPath(job, new Path(args[0]));
// job.setInputFormatClass(TextInputFormat.class);
//
// job.setMapperClass(WordCounterMapper.class);
// job.setCombinerClass(WordCounterReducer.class);
// job.setReducerClass(WordCounterReducer.class);
//
// TextOutputFormat.setOutputPath(job, new Path(args[1]));
// job.setOutputFormatClass(TextOutputFormat.class);
// job.setOutputKeyClass(Text.class);
// job.setOutputValueClass(IntWritable.class);
//
// return job.waitForCompletion(true) ? 0 : 1;
// }
// }
| import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import com.github.mlk.junit.rules.helpers.hadoop.BasicTestJob;
import java.util.HashMap;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test; | package com.github.mlk.junit.rules;
public class TestHadoopYarnRule {
@Rule
public HadoopYarnRule subject = new HadoopYarnRule("test-hadoop");
/**
* "Hello World" YARN job that counts the number of each word in a text file.
*/
@Test
public void helloWorld() throws Exception {
subject.copyResource("/hello.txt", "/testfile.txt");
| // Path: src/test/java/com/github/mlk/junit/rules/helpers/hadoop/BasicTestJob.java
// public class BasicTestJob extends Configured implements Tool {
//
// @Override
// public int run(String... args) throws Exception {
// Job job = Job.getInstance(getConf(), "BasicTestJob");
// TextInputFormat.addInputPath(job, new Path(args[0]));
// job.setInputFormatClass(TextInputFormat.class);
//
// job.setMapperClass(WordCounterMapper.class);
// job.setCombinerClass(WordCounterReducer.class);
// job.setReducerClass(WordCounterReducer.class);
//
// TextOutputFormat.setOutputPath(job, new Path(args[1]));
// job.setOutputFormatClass(TextOutputFormat.class);
// job.setOutputKeyClass(Text.class);
// job.setOutputValueClass(IntWritable.class);
//
// return job.waitForCompletion(true) ? 0 : 1;
// }
// }
// Path: src/test/java/com/github/mlk/junit/rules/TestHadoopYarnRule.java
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import com.github.mlk.junit.rules.helpers.hadoop.BasicTestJob;
import java.util.HashMap;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
package com.github.mlk.junit.rules;
public class TestHadoopYarnRule {
@Rule
public HadoopYarnRule subject = new HadoopYarnRule("test-hadoop");
/**
* "Hello World" YARN job that counts the number of each word in a text file.
*/
@Test
public void helloWorld() throws Exception {
subject.copyResource("/hello.txt", "/testfile.txt");
| BasicTestJob job = new BasicTestJob(); |
mlk/AssortmentOfJUnitRules | src/test/java/com/github/mlk/junit/rules/TestHadoopRule.java | // Path: src/test/java/com/github/mlk/junit/rules/helpers/hadoop/NoAccessToHadoopRule.java
// public class NoAccessToHadoopRule {
//
// private final String hadoopUrl;
//
// public NoAccessToHadoopRule(String hadoopUrl) {
// this.hadoopUrl = hadoopUrl;
// }
//
//
// public List<String> content() throws IOException {
// Configuration confHadoop = new Configuration();
// confHadoop.set("fs.hdfs.impl", org.apache.hadoop.hdfs.DistributedFileSystem.class.getName());
// confHadoop.set("fs.file.impl", org.apache.hadoop.fs.LocalFileSystem.class.getName());
// try (FileSystem hdfs = FileSystem.get(URI.create(hadoopUrl), confHadoop)) {
// return IOUtils.readLines(hdfs.open(new Path("/new_file.txt")));
// }
// }
// }
| import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import com.github.mlk.junit.rules.helpers.hadoop.NoAccessToHadoopRule;
import java.io.IOException;
import java.util.List;
import org.junit.Rule;
import org.junit.Test; | package com.github.mlk.junit.rules;
public class TestHadoopRule {
@Rule
public HadoopDFSRule subject = new HadoopDFSRule();
/**
* "Hello World" example that reads in a text file using a class that has no knowledge of the
* JUnit rule.
*/
@Test
public void helloWorld() throws IOException {
subject.copyResource("/new_file.txt", "/testfile.txt");
| // Path: src/test/java/com/github/mlk/junit/rules/helpers/hadoop/NoAccessToHadoopRule.java
// public class NoAccessToHadoopRule {
//
// private final String hadoopUrl;
//
// public NoAccessToHadoopRule(String hadoopUrl) {
// this.hadoopUrl = hadoopUrl;
// }
//
//
// public List<String> content() throws IOException {
// Configuration confHadoop = new Configuration();
// confHadoop.set("fs.hdfs.impl", org.apache.hadoop.hdfs.DistributedFileSystem.class.getName());
// confHadoop.set("fs.file.impl", org.apache.hadoop.fs.LocalFileSystem.class.getName());
// try (FileSystem hdfs = FileSystem.get(URI.create(hadoopUrl), confHadoop)) {
// return IOUtils.readLines(hdfs.open(new Path("/new_file.txt")));
// }
// }
// }
// Path: src/test/java/com/github/mlk/junit/rules/TestHadoopRule.java
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import com.github.mlk.junit.rules.helpers.hadoop.NoAccessToHadoopRule;
import java.io.IOException;
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
package com.github.mlk.junit.rules;
public class TestHadoopRule {
@Rule
public HadoopDFSRule subject = new HadoopDFSRule();
/**
* "Hello World" example that reads in a text file using a class that has no knowledge of the
* JUnit rule.
*/
@Test
public void helloWorld() throws IOException {
subject.copyResource("/new_file.txt", "/testfile.txt");
| List<String> content = new NoAccessToHadoopRule("hdfs://localhost:" + subject.getNameNodePort()) |
anqit/spanqit | src/main/java/com/anqit/spanqit/core/query/DeleteDataQuery.java | // Path: src/main/java/com/anqit/spanqit/core/TriplesTemplate.java
// public class TriplesTemplate extends QueryElementCollection<TriplePattern> {
// TriplesTemplate(TriplePattern... triples) {
// super(" .\n");
// and(triples);
// }
//
// /**
// * add triples to this template
// *
// * @param triples the triples to add
// *
// * @return this TriplesTemplate instance
// */
// public TriplesTemplate and(TriplePattern... triples) {
// Collections.addAll(elements, triples);
//
// return this;
// }
//
// @Override
// public String getQueryString() {
// return SpanqitUtils.getBracedString(super.getQueryString());
// }
//
// }
//
// Path: src/main/java/com/anqit/spanqit/graphpattern/GraphName.java
// public interface GraphName extends QueryElement { }
//
// Path: src/main/java/com/anqit/spanqit/graphpattern/TriplePattern.java
// public interface TriplePattern extends GraphPattern {
// @SuppressWarnings("javadoc")
// static String SUFFIX = " .";
//
// /**
// * Add predicate-object lists describing this triple pattern's subject
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default public TriplePattern andHas(RdfPredicate predicate, RdfObject... objects) {
// return andHas(Rdf.predicateObjectList(predicate, objects));
// }
//
// /**
// * Add predicate-object lists describing this triple pattern's subject
// *
// * @param lists
// * the {@link RdfPredicateObjectList}(s) to add
// *
// * @return this triple pattern
// */
// public TriplePattern andHas(RdfPredicateObjectList... lists);
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Strings
// * and converts them to StringLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, String... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Boolean
// * and converts them to BooleanLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, Boolean... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Numbers
// * and converts them to NumberLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, Number... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Use the built-in RDF shortcut {@code a} for {@code rdf:type} to specify the subject's type
// *
// * @param object the object describing this triple pattern's subject's {@code rdf:type}
// *
// * @return this triple pattern
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#abbrevRdfType">
// * RDF Type abbreviation</a>
// */
// default TriplePattern andIsA(RdfObject object) {
// return andHas(RdfPredicate.a, object);
// }
// }
| import com.anqit.spanqit.core.TriplesTemplate;
import com.anqit.spanqit.graphpattern.GraphName;
import com.anqit.spanqit.graphpattern.TriplePattern; | package com.anqit.spanqit.core.query;
/**
* The SPARQL Delete Data Query
*
* @see <a href="https://www.w3.org/TR/sparql11-update/#deleteData"> SPARQL
* DELETE DATA Query</a>
*
*/
public class DeleteDataQuery extends UpdateDataQuery<DeleteDataQuery> {
private static final String DELETE_DATA = "DELETE DATA";
/**
* Add triples to be deleted
*
* @param triples the triples to add to this delete data query
*
* @return this Delete Data query instance
*/ | // Path: src/main/java/com/anqit/spanqit/core/TriplesTemplate.java
// public class TriplesTemplate extends QueryElementCollection<TriplePattern> {
// TriplesTemplate(TriplePattern... triples) {
// super(" .\n");
// and(triples);
// }
//
// /**
// * add triples to this template
// *
// * @param triples the triples to add
// *
// * @return this TriplesTemplate instance
// */
// public TriplesTemplate and(TriplePattern... triples) {
// Collections.addAll(elements, triples);
//
// return this;
// }
//
// @Override
// public String getQueryString() {
// return SpanqitUtils.getBracedString(super.getQueryString());
// }
//
// }
//
// Path: src/main/java/com/anqit/spanqit/graphpattern/GraphName.java
// public interface GraphName extends QueryElement { }
//
// Path: src/main/java/com/anqit/spanqit/graphpattern/TriplePattern.java
// public interface TriplePattern extends GraphPattern {
// @SuppressWarnings("javadoc")
// static String SUFFIX = " .";
//
// /**
// * Add predicate-object lists describing this triple pattern's subject
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default public TriplePattern andHas(RdfPredicate predicate, RdfObject... objects) {
// return andHas(Rdf.predicateObjectList(predicate, objects));
// }
//
// /**
// * Add predicate-object lists describing this triple pattern's subject
// *
// * @param lists
// * the {@link RdfPredicateObjectList}(s) to add
// *
// * @return this triple pattern
// */
// public TriplePattern andHas(RdfPredicateObjectList... lists);
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Strings
// * and converts them to StringLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, String... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Boolean
// * and converts them to BooleanLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, Boolean... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Numbers
// * and converts them to NumberLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, Number... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Use the built-in RDF shortcut {@code a} for {@code rdf:type} to specify the subject's type
// *
// * @param object the object describing this triple pattern's subject's {@code rdf:type}
// *
// * @return this triple pattern
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#abbrevRdfType">
// * RDF Type abbreviation</a>
// */
// default TriplePattern andIsA(RdfObject object) {
// return andHas(RdfPredicate.a, object);
// }
// }
// Path: src/main/java/com/anqit/spanqit/core/query/DeleteDataQuery.java
import com.anqit.spanqit.core.TriplesTemplate;
import com.anqit.spanqit.graphpattern.GraphName;
import com.anqit.spanqit.graphpattern.TriplePattern;
package com.anqit.spanqit.core.query;
/**
* The SPARQL Delete Data Query
*
* @see <a href="https://www.w3.org/TR/sparql11-update/#deleteData"> SPARQL
* DELETE DATA Query</a>
*
*/
public class DeleteDataQuery extends UpdateDataQuery<DeleteDataQuery> {
private static final String DELETE_DATA = "DELETE DATA";
/**
* Add triples to be deleted
*
* @param triples the triples to add to this delete data query
*
* @return this Delete Data query instance
*/ | public DeleteDataQuery deleteData(TriplePattern... triples) { |
anqit/spanqit | src/main/java/com/anqit/spanqit/core/query/DeleteDataQuery.java | // Path: src/main/java/com/anqit/spanqit/core/TriplesTemplate.java
// public class TriplesTemplate extends QueryElementCollection<TriplePattern> {
// TriplesTemplate(TriplePattern... triples) {
// super(" .\n");
// and(triples);
// }
//
// /**
// * add triples to this template
// *
// * @param triples the triples to add
// *
// * @return this TriplesTemplate instance
// */
// public TriplesTemplate and(TriplePattern... triples) {
// Collections.addAll(elements, triples);
//
// return this;
// }
//
// @Override
// public String getQueryString() {
// return SpanqitUtils.getBracedString(super.getQueryString());
// }
//
// }
//
// Path: src/main/java/com/anqit/spanqit/graphpattern/GraphName.java
// public interface GraphName extends QueryElement { }
//
// Path: src/main/java/com/anqit/spanqit/graphpattern/TriplePattern.java
// public interface TriplePattern extends GraphPattern {
// @SuppressWarnings("javadoc")
// static String SUFFIX = " .";
//
// /**
// * Add predicate-object lists describing this triple pattern's subject
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default public TriplePattern andHas(RdfPredicate predicate, RdfObject... objects) {
// return andHas(Rdf.predicateObjectList(predicate, objects));
// }
//
// /**
// * Add predicate-object lists describing this triple pattern's subject
// *
// * @param lists
// * the {@link RdfPredicateObjectList}(s) to add
// *
// * @return this triple pattern
// */
// public TriplePattern andHas(RdfPredicateObjectList... lists);
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Strings
// * and converts them to StringLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, String... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Boolean
// * and converts them to BooleanLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, Boolean... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Numbers
// * and converts them to NumberLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, Number... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Use the built-in RDF shortcut {@code a} for {@code rdf:type} to specify the subject's type
// *
// * @param object the object describing this triple pattern's subject's {@code rdf:type}
// *
// * @return this triple pattern
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#abbrevRdfType">
// * RDF Type abbreviation</a>
// */
// default TriplePattern andIsA(RdfObject object) {
// return andHas(RdfPredicate.a, object);
// }
// }
| import com.anqit.spanqit.core.TriplesTemplate;
import com.anqit.spanqit.graphpattern.GraphName;
import com.anqit.spanqit.graphpattern.TriplePattern; | package com.anqit.spanqit.core.query;
/**
* The SPARQL Delete Data Query
*
* @see <a href="https://www.w3.org/TR/sparql11-update/#deleteData"> SPARQL
* DELETE DATA Query</a>
*
*/
public class DeleteDataQuery extends UpdateDataQuery<DeleteDataQuery> {
private static final String DELETE_DATA = "DELETE DATA";
/**
* Add triples to be deleted
*
* @param triples the triples to add to this delete data query
*
* @return this Delete Data query instance
*/
public DeleteDataQuery deleteData(TriplePattern... triples) {
return addTriples(triples);
}
/**
* Set this query's triples template
*
* @param triplesTemplate
* the {@link TriplesTemplate} instance to set
*
* @return this instance
*/ | // Path: src/main/java/com/anqit/spanqit/core/TriplesTemplate.java
// public class TriplesTemplate extends QueryElementCollection<TriplePattern> {
// TriplesTemplate(TriplePattern... triples) {
// super(" .\n");
// and(triples);
// }
//
// /**
// * add triples to this template
// *
// * @param triples the triples to add
// *
// * @return this TriplesTemplate instance
// */
// public TriplesTemplate and(TriplePattern... triples) {
// Collections.addAll(elements, triples);
//
// return this;
// }
//
// @Override
// public String getQueryString() {
// return SpanqitUtils.getBracedString(super.getQueryString());
// }
//
// }
//
// Path: src/main/java/com/anqit/spanqit/graphpattern/GraphName.java
// public interface GraphName extends QueryElement { }
//
// Path: src/main/java/com/anqit/spanqit/graphpattern/TriplePattern.java
// public interface TriplePattern extends GraphPattern {
// @SuppressWarnings("javadoc")
// static String SUFFIX = " .";
//
// /**
// * Add predicate-object lists describing this triple pattern's subject
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default public TriplePattern andHas(RdfPredicate predicate, RdfObject... objects) {
// return andHas(Rdf.predicateObjectList(predicate, objects));
// }
//
// /**
// * Add predicate-object lists describing this triple pattern's subject
// *
// * @param lists
// * the {@link RdfPredicateObjectList}(s) to add
// *
// * @return this triple pattern
// */
// public TriplePattern andHas(RdfPredicateObjectList... lists);
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Strings
// * and converts them to StringLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, String... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Boolean
// * and converts them to BooleanLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, Boolean... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Numbers
// * and converts them to NumberLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, Number... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Use the built-in RDF shortcut {@code a} for {@code rdf:type} to specify the subject's type
// *
// * @param object the object describing this triple pattern's subject's {@code rdf:type}
// *
// * @return this triple pattern
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#abbrevRdfType">
// * RDF Type abbreviation</a>
// */
// default TriplePattern andIsA(RdfObject object) {
// return andHas(RdfPredicate.a, object);
// }
// }
// Path: src/main/java/com/anqit/spanqit/core/query/DeleteDataQuery.java
import com.anqit.spanqit.core.TriplesTemplate;
import com.anqit.spanqit.graphpattern.GraphName;
import com.anqit.spanqit.graphpattern.TriplePattern;
package com.anqit.spanqit.core.query;
/**
* The SPARQL Delete Data Query
*
* @see <a href="https://www.w3.org/TR/sparql11-update/#deleteData"> SPARQL
* DELETE DATA Query</a>
*
*/
public class DeleteDataQuery extends UpdateDataQuery<DeleteDataQuery> {
private static final String DELETE_DATA = "DELETE DATA";
/**
* Add triples to be deleted
*
* @param triples the triples to add to this delete data query
*
* @return this Delete Data query instance
*/
public DeleteDataQuery deleteData(TriplePattern... triples) {
return addTriples(triples);
}
/**
* Set this query's triples template
*
* @param triplesTemplate
* the {@link TriplesTemplate} instance to set
*
* @return this instance
*/ | public DeleteDataQuery deleteData(TriplesTemplate triplesTemplate) { |
anqit/spanqit | src/main/java/com/anqit/spanqit/core/query/DeleteDataQuery.java | // Path: src/main/java/com/anqit/spanqit/core/TriplesTemplate.java
// public class TriplesTemplate extends QueryElementCollection<TriplePattern> {
// TriplesTemplate(TriplePattern... triples) {
// super(" .\n");
// and(triples);
// }
//
// /**
// * add triples to this template
// *
// * @param triples the triples to add
// *
// * @return this TriplesTemplate instance
// */
// public TriplesTemplate and(TriplePattern... triples) {
// Collections.addAll(elements, triples);
//
// return this;
// }
//
// @Override
// public String getQueryString() {
// return SpanqitUtils.getBracedString(super.getQueryString());
// }
//
// }
//
// Path: src/main/java/com/anqit/spanqit/graphpattern/GraphName.java
// public interface GraphName extends QueryElement { }
//
// Path: src/main/java/com/anqit/spanqit/graphpattern/TriplePattern.java
// public interface TriplePattern extends GraphPattern {
// @SuppressWarnings("javadoc")
// static String SUFFIX = " .";
//
// /**
// * Add predicate-object lists describing this triple pattern's subject
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default public TriplePattern andHas(RdfPredicate predicate, RdfObject... objects) {
// return andHas(Rdf.predicateObjectList(predicate, objects));
// }
//
// /**
// * Add predicate-object lists describing this triple pattern's subject
// *
// * @param lists
// * the {@link RdfPredicateObjectList}(s) to add
// *
// * @return this triple pattern
// */
// public TriplePattern andHas(RdfPredicateObjectList... lists);
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Strings
// * and converts them to StringLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, String... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Boolean
// * and converts them to BooleanLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, Boolean... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Numbers
// * and converts them to NumberLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, Number... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Use the built-in RDF shortcut {@code a} for {@code rdf:type} to specify the subject's type
// *
// * @param object the object describing this triple pattern's subject's {@code rdf:type}
// *
// * @return this triple pattern
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#abbrevRdfType">
// * RDF Type abbreviation</a>
// */
// default TriplePattern andIsA(RdfObject object) {
// return andHas(RdfPredicate.a, object);
// }
// }
| import com.anqit.spanqit.core.TriplesTemplate;
import com.anqit.spanqit.graphpattern.GraphName;
import com.anqit.spanqit.graphpattern.TriplePattern; | package com.anqit.spanqit.core.query;
/**
* The SPARQL Delete Data Query
*
* @see <a href="https://www.w3.org/TR/sparql11-update/#deleteData"> SPARQL
* DELETE DATA Query</a>
*
*/
public class DeleteDataQuery extends UpdateDataQuery<DeleteDataQuery> {
private static final String DELETE_DATA = "DELETE DATA";
/**
* Add triples to be deleted
*
* @param triples the triples to add to this delete data query
*
* @return this Delete Data query instance
*/
public DeleteDataQuery deleteData(TriplePattern... triples) {
return addTriples(triples);
}
/**
* Set this query's triples template
*
* @param triplesTemplate
* the {@link TriplesTemplate} instance to set
*
* @return this instance
*/
public DeleteDataQuery deleteData(TriplesTemplate triplesTemplate) {
return setTriplesTemplate(triplesTemplate);
}
/**
* Specify a graph to delete the data from
*
* @param graph the identifier of the graph
*
* @return this Delete Data query instance
*/ | // Path: src/main/java/com/anqit/spanqit/core/TriplesTemplate.java
// public class TriplesTemplate extends QueryElementCollection<TriplePattern> {
// TriplesTemplate(TriplePattern... triples) {
// super(" .\n");
// and(triples);
// }
//
// /**
// * add triples to this template
// *
// * @param triples the triples to add
// *
// * @return this TriplesTemplate instance
// */
// public TriplesTemplate and(TriplePattern... triples) {
// Collections.addAll(elements, triples);
//
// return this;
// }
//
// @Override
// public String getQueryString() {
// return SpanqitUtils.getBracedString(super.getQueryString());
// }
//
// }
//
// Path: src/main/java/com/anqit/spanqit/graphpattern/GraphName.java
// public interface GraphName extends QueryElement { }
//
// Path: src/main/java/com/anqit/spanqit/graphpattern/TriplePattern.java
// public interface TriplePattern extends GraphPattern {
// @SuppressWarnings("javadoc")
// static String SUFFIX = " .";
//
// /**
// * Add predicate-object lists describing this triple pattern's subject
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default public TriplePattern andHas(RdfPredicate predicate, RdfObject... objects) {
// return andHas(Rdf.predicateObjectList(predicate, objects));
// }
//
// /**
// * Add predicate-object lists describing this triple pattern's subject
// *
// * @param lists
// * the {@link RdfPredicateObjectList}(s) to add
// *
// * @return this triple pattern
// */
// public TriplePattern andHas(RdfPredicateObjectList... lists);
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Strings
// * and converts them to StringLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, String... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Boolean
// * and converts them to BooleanLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, Boolean... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Numbers
// * and converts them to NumberLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, Number... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Use the built-in RDF shortcut {@code a} for {@code rdf:type} to specify the subject's type
// *
// * @param object the object describing this triple pattern's subject's {@code rdf:type}
// *
// * @return this triple pattern
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#abbrevRdfType">
// * RDF Type abbreviation</a>
// */
// default TriplePattern andIsA(RdfObject object) {
// return andHas(RdfPredicate.a, object);
// }
// }
// Path: src/main/java/com/anqit/spanqit/core/query/DeleteDataQuery.java
import com.anqit.spanqit.core.TriplesTemplate;
import com.anqit.spanqit.graphpattern.GraphName;
import com.anqit.spanqit.graphpattern.TriplePattern;
package com.anqit.spanqit.core.query;
/**
* The SPARQL Delete Data Query
*
* @see <a href="https://www.w3.org/TR/sparql11-update/#deleteData"> SPARQL
* DELETE DATA Query</a>
*
*/
public class DeleteDataQuery extends UpdateDataQuery<DeleteDataQuery> {
private static final String DELETE_DATA = "DELETE DATA";
/**
* Add triples to be deleted
*
* @param triples the triples to add to this delete data query
*
* @return this Delete Data query instance
*/
public DeleteDataQuery deleteData(TriplePattern... triples) {
return addTriples(triples);
}
/**
* Set this query's triples template
*
* @param triplesTemplate
* the {@link TriplesTemplate} instance to set
*
* @return this instance
*/
public DeleteDataQuery deleteData(TriplesTemplate triplesTemplate) {
return setTriplesTemplate(triplesTemplate);
}
/**
* Specify a graph to delete the data from
*
* @param graph the identifier of the graph
*
* @return this Delete Data query instance
*/ | public DeleteDataQuery from(GraphName graph) { |
anqit/spanqit | src/main/java/com/anqit/spanqit/core/query/DestinationSourceManagementQuery.java | // Path: src/main/java/com/anqit/spanqit/rdf/Iri.java
// public interface Iri extends RdfResource, RdfPredicate, GraphName { }
| import java.util.Optional;
import com.anqit.spanqit.rdf.Iri; | package com.anqit.spanqit.core.query;
/**
* A SPARQL Update Query that has a source and a destination
*
* @param <T> the type of the query; used to support fluency
*/
public abstract class DestinationSourceManagementQuery<T extends DestinationSourceManagementQuery<T>> extends GraphManagementQuery<DestinationSourceManagementQuery<T>> {
private static String DEFAULT = "DEFAULT";
private static String TO = "TO";
| // Path: src/main/java/com/anqit/spanqit/rdf/Iri.java
// public interface Iri extends RdfResource, RdfPredicate, GraphName { }
// Path: src/main/java/com/anqit/spanqit/core/query/DestinationSourceManagementQuery.java
import java.util.Optional;
import com.anqit.spanqit.rdf.Iri;
package com.anqit.spanqit.core.query;
/**
* A SPARQL Update Query that has a source and a destination
*
* @param <T> the type of the query; used to support fluency
*/
public abstract class DestinationSourceManagementQuery<T extends DestinationSourceManagementQuery<T>> extends GraphManagementQuery<DestinationSourceManagementQuery<T>> {
private static String DEFAULT = "DEFAULT";
private static String TO = "TO";
| private Optional<Iri> from = Optional.empty(); |
anqit/spanqit | src/main/java/com/anqit/spanqit/constraint/Aggregate.java | // Path: src/main/java/com/anqit/spanqit/core/SpanqitUtils.java
// @SuppressWarnings("javadoc")
// public class SpanqitUtils {
// private static final String PAD = " ";
//
// public static <O> Optional<O> getOrCreateAndModifyOptional(Optional<O> optional, Supplier<O> getter, UnaryOperator<O> operator) {
// return Optional.of(operator.apply(optional.orElseGet(getter)));
// }
//
// public static void appendAndNewlineIfPresent(Optional<? extends QueryElement> elementOptional, StringBuilder builder) {
// appendQueryElementIfPresent(elementOptional, builder, null, "\n");
// }
//
// public static void appendQueryElementIfPresent(Optional<? extends QueryElement> queryElementOptional, StringBuilder builder, String prefix, String suffix) {
// appendStringIfPresent(queryElementOptional.map(QueryElement::getQueryString), builder, prefix, suffix);
// }
//
// public static void appendStringIfPresent(Optional<String> stringOptional, StringBuilder builder, String prefix, String suffix) {
// Optional<String> preOpt = Optional.ofNullable(prefix);
// Optional<String> sufOpt = Optional.ofNullable(suffix);
//
// stringOptional.ifPresent(string -> {
// preOpt.ifPresent(p -> builder.append(p));
// builder.append(string);
// sufOpt.ifPresent(s -> builder.append(s));
// });
// }
//
// public static String getBracedString(String contents) {
// return getEnclosedString("{", "}", contents);
// }
//
// public static String getBracketedString(String contents) {
// return getEnclosedString("[", "]", contents);
// }
//
// public static String getParenthesizedString(String contents) {
// return getEnclosedString("(", ")", contents);
// }
//
// public static String getQuotedString(String contents) {
// return getEnclosedString("\"", "\"", contents, false);
// }
//
// /**
// * For string literals that contain single- or double-quotes
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#QSynLiterals">
// * RDF Literal Syntax</a>
// * @param contents
// * @return a "long quoted" string
// */
// public static String getLongQuotedString(String contents) {
// return getEnclosedString("'''", "'''", contents, false);
// }
//
// private static String getEnclosedString(String open, String close,
// String contents) {
// return getEnclosedString(open, close, contents, true);
// }
//
// private static String getEnclosedString(String open, String close,
// String contents, boolean pad) {
// StringBuilder es = new StringBuilder();
//
// es.append(open);
// if (contents != null && !contents.isEmpty()) {
// es.append(contents);
// if (pad) {
// es.insert(open.length(), PAD).append(PAD);
// }
// } else {
// es.append(PAD);
// }
// es.append(close);
//
// return es.toString();
// }
// }
| import com.anqit.spanqit.core.SpanqitUtils; | public Aggregate separator(String separator) {
this.separator = separator;
return this;
}
@Override
public String getQueryString() {
StringBuilder aggregate = new StringBuilder();
StringBuilder params = new StringBuilder();
aggregate.append(operator.getQueryString());
if(isDistinct) {
params.append(DISTINCT).append(" ");
}
// Yeah. I know...
if(operator == SparqlAggregate.COUNT && countAll) {
params.append("*");
} else {
params.append(super.getQueryString());
}
// Yep, I still know...
if(operator == SparqlAggregate.GROUP_CONCAT && separator != null) {
params.append(" ").append(";").append(" ").append(SEPARATOR)
.append(" ").append("=").append(" ").append(separator);
}
| // Path: src/main/java/com/anqit/spanqit/core/SpanqitUtils.java
// @SuppressWarnings("javadoc")
// public class SpanqitUtils {
// private static final String PAD = " ";
//
// public static <O> Optional<O> getOrCreateAndModifyOptional(Optional<O> optional, Supplier<O> getter, UnaryOperator<O> operator) {
// return Optional.of(operator.apply(optional.orElseGet(getter)));
// }
//
// public static void appendAndNewlineIfPresent(Optional<? extends QueryElement> elementOptional, StringBuilder builder) {
// appendQueryElementIfPresent(elementOptional, builder, null, "\n");
// }
//
// public static void appendQueryElementIfPresent(Optional<? extends QueryElement> queryElementOptional, StringBuilder builder, String prefix, String suffix) {
// appendStringIfPresent(queryElementOptional.map(QueryElement::getQueryString), builder, prefix, suffix);
// }
//
// public static void appendStringIfPresent(Optional<String> stringOptional, StringBuilder builder, String prefix, String suffix) {
// Optional<String> preOpt = Optional.ofNullable(prefix);
// Optional<String> sufOpt = Optional.ofNullable(suffix);
//
// stringOptional.ifPresent(string -> {
// preOpt.ifPresent(p -> builder.append(p));
// builder.append(string);
// sufOpt.ifPresent(s -> builder.append(s));
// });
// }
//
// public static String getBracedString(String contents) {
// return getEnclosedString("{", "}", contents);
// }
//
// public static String getBracketedString(String contents) {
// return getEnclosedString("[", "]", contents);
// }
//
// public static String getParenthesizedString(String contents) {
// return getEnclosedString("(", ")", contents);
// }
//
// public static String getQuotedString(String contents) {
// return getEnclosedString("\"", "\"", contents, false);
// }
//
// /**
// * For string literals that contain single- or double-quotes
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#QSynLiterals">
// * RDF Literal Syntax</a>
// * @param contents
// * @return a "long quoted" string
// */
// public static String getLongQuotedString(String contents) {
// return getEnclosedString("'''", "'''", contents, false);
// }
//
// private static String getEnclosedString(String open, String close,
// String contents) {
// return getEnclosedString(open, close, contents, true);
// }
//
// private static String getEnclosedString(String open, String close,
// String contents, boolean pad) {
// StringBuilder es = new StringBuilder();
//
// es.append(open);
// if (contents != null && !contents.isEmpty()) {
// es.append(contents);
// if (pad) {
// es.insert(open.length(), PAD).append(PAD);
// }
// } else {
// es.append(PAD);
// }
// es.append(close);
//
// return es.toString();
// }
// }
// Path: src/main/java/com/anqit/spanqit/constraint/Aggregate.java
import com.anqit.spanqit.core.SpanqitUtils;
public Aggregate separator(String separator) {
this.separator = separator;
return this;
}
@Override
public String getQueryString() {
StringBuilder aggregate = new StringBuilder();
StringBuilder params = new StringBuilder();
aggregate.append(operator.getQueryString());
if(isDistinct) {
params.append(DISTINCT).append(" ");
}
// Yeah. I know...
if(operator == SparqlAggregate.COUNT && countAll) {
params.append("*");
} else {
params.append(super.getQueryString());
}
// Yep, I still know...
if(operator == SparqlAggregate.GROUP_CONCAT && separator != null) {
params.append(" ").append(";").append(" ").append(SEPARATOR)
.append(" ").append("=").append(" ").append(separator);
}
| return aggregate.append(SpanqitUtils.getParenthesizedString(params.toString())).toString(); |
anqit/spanqit | src/main/java/com/anqit/spanqit/core/Prefix.java | // Path: src/main/java/com/anqit/spanqit/rdf/Iri.java
// public interface Iri extends RdfResource, RdfPredicate, GraphName { }
| import com.anqit.spanqit.rdf.Iri; | package com.anqit.spanqit.core;
/**
* A SPARQL Prefix declaration
*
* @see <a
* href="http://www.w3.org/TR/2013/REC-sparql11-query-20130321/#prefNames">
* SPARQL Prefix</a>
*/
public class Prefix implements QueryElement {
private static final String PREFIX = "PREFIX";
private String label; | // Path: src/main/java/com/anqit/spanqit/rdf/Iri.java
// public interface Iri extends RdfResource, RdfPredicate, GraphName { }
// Path: src/main/java/com/anqit/spanqit/core/Prefix.java
import com.anqit.spanqit.rdf.Iri;
package com.anqit.spanqit.core;
/**
* A SPARQL Prefix declaration
*
* @see <a
* href="http://www.w3.org/TR/2013/REC-sparql11-query-20130321/#prefNames">
* SPARQL Prefix</a>
*/
public class Prefix implements QueryElement {
private static final String PREFIX = "PREFIX";
private String label; | private Iri iri; |
anqit/spanqit | src/main/java/com/anqit/spanqit/core/query/TargetedGraphManagementQuery.java | // Path: src/main/java/com/anqit/spanqit/rdf/Iri.java
// public interface Iri extends RdfResource, RdfPredicate, GraphName { }
| import java.util.Optional;
import com.anqit.spanqit.rdf.Iri; | package com.anqit.spanqit.core.query;
@SuppressWarnings("javadoc")
public abstract class TargetedGraphManagementQuery<T extends TargetedGraphManagementQuery<T>> extends GraphManagementQuery<TargetedGraphManagementQuery<T>> {
private static final String GRAPH = "GRAPH";
private static final String DEFAULT = "DEFAULT";
private static final String NAMED = "NAMED";
private static final String ALL = "ALL";
private String target = DEFAULT; | // Path: src/main/java/com/anqit/spanqit/rdf/Iri.java
// public interface Iri extends RdfResource, RdfPredicate, GraphName { }
// Path: src/main/java/com/anqit/spanqit/core/query/TargetedGraphManagementQuery.java
import java.util.Optional;
import com.anqit.spanqit.rdf.Iri;
package com.anqit.spanqit.core.query;
@SuppressWarnings("javadoc")
public abstract class TargetedGraphManagementQuery<T extends TargetedGraphManagementQuery<T>> extends GraphManagementQuery<TargetedGraphManagementQuery<T>> {
private static final String GRAPH = "GRAPH";
private static final String DEFAULT = "DEFAULT";
private static final String NAMED = "NAMED";
private static final String ALL = "ALL";
private String target = DEFAULT; | private Optional<Iri> graph = Optional.empty(); |
anqit/spanqit | src/main/java/com/anqit/spanqit/constraint/UnaryOperation.java | // Path: src/main/java/com/anqit/spanqit/core/SpanqitUtils.java
// @SuppressWarnings("javadoc")
// public class SpanqitUtils {
// private static final String PAD = " ";
//
// public static <O> Optional<O> getOrCreateAndModifyOptional(Optional<O> optional, Supplier<O> getter, UnaryOperator<O> operator) {
// return Optional.of(operator.apply(optional.orElseGet(getter)));
// }
//
// public static void appendAndNewlineIfPresent(Optional<? extends QueryElement> elementOptional, StringBuilder builder) {
// appendQueryElementIfPresent(elementOptional, builder, null, "\n");
// }
//
// public static void appendQueryElementIfPresent(Optional<? extends QueryElement> queryElementOptional, StringBuilder builder, String prefix, String suffix) {
// appendStringIfPresent(queryElementOptional.map(QueryElement::getQueryString), builder, prefix, suffix);
// }
//
// public static void appendStringIfPresent(Optional<String> stringOptional, StringBuilder builder, String prefix, String suffix) {
// Optional<String> preOpt = Optional.ofNullable(prefix);
// Optional<String> sufOpt = Optional.ofNullable(suffix);
//
// stringOptional.ifPresent(string -> {
// preOpt.ifPresent(p -> builder.append(p));
// builder.append(string);
// sufOpt.ifPresent(s -> builder.append(s));
// });
// }
//
// public static String getBracedString(String contents) {
// return getEnclosedString("{", "}", contents);
// }
//
// public static String getBracketedString(String contents) {
// return getEnclosedString("[", "]", contents);
// }
//
// public static String getParenthesizedString(String contents) {
// return getEnclosedString("(", ")", contents);
// }
//
// public static String getQuotedString(String contents) {
// return getEnclosedString("\"", "\"", contents, false);
// }
//
// /**
// * For string literals that contain single- or double-quotes
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#QSynLiterals">
// * RDF Literal Syntax</a>
// * @param contents
// * @return a "long quoted" string
// */
// public static String getLongQuotedString(String contents) {
// return getEnclosedString("'''", "'''", contents, false);
// }
//
// private static String getEnclosedString(String open, String close,
// String contents) {
// return getEnclosedString(open, close, contents, true);
// }
//
// private static String getEnclosedString(String open, String close,
// String contents, boolean pad) {
// StringBuilder es = new StringBuilder();
//
// es.append(open);
// if (contents != null && !contents.isEmpty()) {
// es.append(contents);
// if (pad) {
// es.insert(open.length(), PAD).append(PAD);
// }
// } else {
// es.append(PAD);
// }
// es.append(close);
//
// return es.toString();
// }
// }
| import com.anqit.spanqit.core.SpanqitUtils; | package com.anqit.spanqit.constraint;
/**
* Represents a SPARQL operation that takes exactly 1 argument
*/
class UnaryOperation extends Operation<UnaryOperation> {
UnaryOperation(UnaryOperator operator) {
super(operator, 1);
}
@Override
public String getQueryString() {
if(isAtOperatorLimit()) {
StringBuilder expression = new StringBuilder();
expression.append(operator.getQueryString());
String op = getOperand(0).getQueryString(); | // Path: src/main/java/com/anqit/spanqit/core/SpanqitUtils.java
// @SuppressWarnings("javadoc")
// public class SpanqitUtils {
// private static final String PAD = " ";
//
// public static <O> Optional<O> getOrCreateAndModifyOptional(Optional<O> optional, Supplier<O> getter, UnaryOperator<O> operator) {
// return Optional.of(operator.apply(optional.orElseGet(getter)));
// }
//
// public static void appendAndNewlineIfPresent(Optional<? extends QueryElement> elementOptional, StringBuilder builder) {
// appendQueryElementIfPresent(elementOptional, builder, null, "\n");
// }
//
// public static void appendQueryElementIfPresent(Optional<? extends QueryElement> queryElementOptional, StringBuilder builder, String prefix, String suffix) {
// appendStringIfPresent(queryElementOptional.map(QueryElement::getQueryString), builder, prefix, suffix);
// }
//
// public static void appendStringIfPresent(Optional<String> stringOptional, StringBuilder builder, String prefix, String suffix) {
// Optional<String> preOpt = Optional.ofNullable(prefix);
// Optional<String> sufOpt = Optional.ofNullable(suffix);
//
// stringOptional.ifPresent(string -> {
// preOpt.ifPresent(p -> builder.append(p));
// builder.append(string);
// sufOpt.ifPresent(s -> builder.append(s));
// });
// }
//
// public static String getBracedString(String contents) {
// return getEnclosedString("{", "}", contents);
// }
//
// public static String getBracketedString(String contents) {
// return getEnclosedString("[", "]", contents);
// }
//
// public static String getParenthesizedString(String contents) {
// return getEnclosedString("(", ")", contents);
// }
//
// public static String getQuotedString(String contents) {
// return getEnclosedString("\"", "\"", contents, false);
// }
//
// /**
// * For string literals that contain single- or double-quotes
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#QSynLiterals">
// * RDF Literal Syntax</a>
// * @param contents
// * @return a "long quoted" string
// */
// public static String getLongQuotedString(String contents) {
// return getEnclosedString("'''", "'''", contents, false);
// }
//
// private static String getEnclosedString(String open, String close,
// String contents) {
// return getEnclosedString(open, close, contents, true);
// }
//
// private static String getEnclosedString(String open, String close,
// String contents, boolean pad) {
// StringBuilder es = new StringBuilder();
//
// es.append(open);
// if (contents != null && !contents.isEmpty()) {
// es.append(contents);
// if (pad) {
// es.insert(open.length(), PAD).append(PAD);
// }
// } else {
// es.append(PAD);
// }
// es.append(close);
//
// return es.toString();
// }
// }
// Path: src/main/java/com/anqit/spanqit/constraint/UnaryOperation.java
import com.anqit.spanqit.core.SpanqitUtils;
package com.anqit.spanqit.constraint;
/**
* Represents a SPARQL operation that takes exactly 1 argument
*/
class UnaryOperation extends Operation<UnaryOperation> {
UnaryOperation(UnaryOperator operator) {
super(operator, 1);
}
@Override
public String getQueryString() {
if(isAtOperatorLimit()) {
StringBuilder expression = new StringBuilder();
expression.append(operator.getQueryString());
String op = getOperand(0).getQueryString(); | expression.append(SpanqitUtils.getParenthesizedString(op)); |
anqit/spanqit | src/main/java/com/anqit/spanqit/core/Dataset.java | // Path: src/main/java/com/anqit/spanqit/rdf/Iri.java
// public interface Iri extends RdfResource, RdfPredicate, GraphName { }
| import java.util.Arrays;
import com.anqit.spanqit.rdf.Iri; | package com.anqit.spanqit.core;
/**
* A SPARQL dataset specification
*
* @see <a
* href="http://www.w3.org/TR/2013/REC-sparql11-query-20130321/#rdfDataset">
* RDF Datasets</a>
*/
public class Dataset extends StandardQueryElementCollection<Dataset, From> {
/**
* Add graph references to this dataset
*
* @param graphs
* the datasets to add
* @return this object
*/
public Dataset from(From... graphs) {
return addElements(graphs);
}
/**
* Add unnamed graph references to this dataset
*
* @param iris the IRI's of the graphs to add
* @return this
*/ | // Path: src/main/java/com/anqit/spanqit/rdf/Iri.java
// public interface Iri extends RdfResource, RdfPredicate, GraphName { }
// Path: src/main/java/com/anqit/spanqit/core/Dataset.java
import java.util.Arrays;
import com.anqit.spanqit.rdf.Iri;
package com.anqit.spanqit.core;
/**
* A SPARQL dataset specification
*
* @see <a
* href="http://www.w3.org/TR/2013/REC-sparql11-query-20130321/#rdfDataset">
* RDF Datasets</a>
*/
public class Dataset extends StandardQueryElementCollection<Dataset, From> {
/**
* Add graph references to this dataset
*
* @param graphs
* the datasets to add
* @return this object
*/
public Dataset from(From... graphs) {
return addElements(graphs);
}
/**
* Add unnamed graph references to this dataset
*
* @param iris the IRI's of the graphs to add
* @return this
*/ | public Dataset from(Iri... iris) { |
anqit/spanqit | src/main/java/com/anqit/spanqit/core/From.java | // Path: src/main/java/com/anqit/spanqit/rdf/Iri.java
// public interface Iri extends RdfResource, RdfPredicate, GraphName { }
| import com.anqit.spanqit.rdf.Iri; | package com.anqit.spanqit.core;
/**
* A SPARQL Dataset specifier.
*
* @see <a
* href="http://www.w3.org/TR/2013/REC-sparql11-query-20130321/#specifyingDataset">
* Specifying RDF Datasets</a>
*/
public class From implements QueryElement {
private static final String FROM = "FROM";
private static final String NAMED = "NAMED"; | // Path: src/main/java/com/anqit/spanqit/rdf/Iri.java
// public interface Iri extends RdfResource, RdfPredicate, GraphName { }
// Path: src/main/java/com/anqit/spanqit/core/From.java
import com.anqit.spanqit.rdf.Iri;
package com.anqit.spanqit.core;
/**
* A SPARQL Dataset specifier.
*
* @see <a
* href="http://www.w3.org/TR/2013/REC-sparql11-query-20130321/#specifyingDataset">
* Specifying RDF Datasets</a>
*/
public class From implements QueryElement {
private static final String FROM = "FROM";
private static final String NAMED = "NAMED"; | private Iri iri; |
anqit/spanqit | src/main/java/com/anqit/spanqit/core/query/InsertDataQuery.java | // Path: src/main/java/com/anqit/spanqit/core/TriplesTemplate.java
// public class TriplesTemplate extends QueryElementCollection<TriplePattern> {
// TriplesTemplate(TriplePattern... triples) {
// super(" .\n");
// and(triples);
// }
//
// /**
// * add triples to this template
// *
// * @param triples the triples to add
// *
// * @return this TriplesTemplate instance
// */
// public TriplesTemplate and(TriplePattern... triples) {
// Collections.addAll(elements, triples);
//
// return this;
// }
//
// @Override
// public String getQueryString() {
// return SpanqitUtils.getBracedString(super.getQueryString());
// }
//
// }
//
// Path: src/main/java/com/anqit/spanqit/graphpattern/GraphName.java
// public interface GraphName extends QueryElement { }
//
// Path: src/main/java/com/anqit/spanqit/graphpattern/TriplePattern.java
// public interface TriplePattern extends GraphPattern {
// @SuppressWarnings("javadoc")
// static String SUFFIX = " .";
//
// /**
// * Add predicate-object lists describing this triple pattern's subject
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default public TriplePattern andHas(RdfPredicate predicate, RdfObject... objects) {
// return andHas(Rdf.predicateObjectList(predicate, objects));
// }
//
// /**
// * Add predicate-object lists describing this triple pattern's subject
// *
// * @param lists
// * the {@link RdfPredicateObjectList}(s) to add
// *
// * @return this triple pattern
// */
// public TriplePattern andHas(RdfPredicateObjectList... lists);
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Strings
// * and converts them to StringLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, String... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Boolean
// * and converts them to BooleanLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, Boolean... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Numbers
// * and converts them to NumberLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, Number... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Use the built-in RDF shortcut {@code a} for {@code rdf:type} to specify the subject's type
// *
// * @param object the object describing this triple pattern's subject's {@code rdf:type}
// *
// * @return this triple pattern
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#abbrevRdfType">
// * RDF Type abbreviation</a>
// */
// default TriplePattern andIsA(RdfObject object) {
// return andHas(RdfPredicate.a, object);
// }
// }
| import com.anqit.spanqit.core.TriplesTemplate;
import com.anqit.spanqit.graphpattern.GraphName;
import com.anqit.spanqit.graphpattern.TriplePattern; | package com.anqit.spanqit.core.query;
/**
* The SPARQL Insert Data Query
*
* @see <a href="https://www.w3.org/TR/sparql11-update/#insertData">
* SPARQL INSERT DATA Query</a>
*
*/
public class InsertDataQuery extends UpdateDataQuery<InsertDataQuery> {
private static final String INSERT_DATA = "INSERT DATA";
/**
* Add triples to be inserted
*
* @param triples the triples to add to this insert data query
*
* @return this Insert Data query instance
*/ | // Path: src/main/java/com/anqit/spanqit/core/TriplesTemplate.java
// public class TriplesTemplate extends QueryElementCollection<TriplePattern> {
// TriplesTemplate(TriplePattern... triples) {
// super(" .\n");
// and(triples);
// }
//
// /**
// * add triples to this template
// *
// * @param triples the triples to add
// *
// * @return this TriplesTemplate instance
// */
// public TriplesTemplate and(TriplePattern... triples) {
// Collections.addAll(elements, triples);
//
// return this;
// }
//
// @Override
// public String getQueryString() {
// return SpanqitUtils.getBracedString(super.getQueryString());
// }
//
// }
//
// Path: src/main/java/com/anqit/spanqit/graphpattern/GraphName.java
// public interface GraphName extends QueryElement { }
//
// Path: src/main/java/com/anqit/spanqit/graphpattern/TriplePattern.java
// public interface TriplePattern extends GraphPattern {
// @SuppressWarnings("javadoc")
// static String SUFFIX = " .";
//
// /**
// * Add predicate-object lists describing this triple pattern's subject
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default public TriplePattern andHas(RdfPredicate predicate, RdfObject... objects) {
// return andHas(Rdf.predicateObjectList(predicate, objects));
// }
//
// /**
// * Add predicate-object lists describing this triple pattern's subject
// *
// * @param lists
// * the {@link RdfPredicateObjectList}(s) to add
// *
// * @return this triple pattern
// */
// public TriplePattern andHas(RdfPredicateObjectList... lists);
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Strings
// * and converts them to StringLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, String... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Boolean
// * and converts them to BooleanLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, Boolean... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Numbers
// * and converts them to NumberLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, Number... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Use the built-in RDF shortcut {@code a} for {@code rdf:type} to specify the subject's type
// *
// * @param object the object describing this triple pattern's subject's {@code rdf:type}
// *
// * @return this triple pattern
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#abbrevRdfType">
// * RDF Type abbreviation</a>
// */
// default TriplePattern andIsA(RdfObject object) {
// return andHas(RdfPredicate.a, object);
// }
// }
// Path: src/main/java/com/anqit/spanqit/core/query/InsertDataQuery.java
import com.anqit.spanqit.core.TriplesTemplate;
import com.anqit.spanqit.graphpattern.GraphName;
import com.anqit.spanqit.graphpattern.TriplePattern;
package com.anqit.spanqit.core.query;
/**
* The SPARQL Insert Data Query
*
* @see <a href="https://www.w3.org/TR/sparql11-update/#insertData">
* SPARQL INSERT DATA Query</a>
*
*/
public class InsertDataQuery extends UpdateDataQuery<InsertDataQuery> {
private static final String INSERT_DATA = "INSERT DATA";
/**
* Add triples to be inserted
*
* @param triples the triples to add to this insert data query
*
* @return this Insert Data query instance
*/ | public InsertDataQuery insertData(TriplePattern... triples) { |
anqit/spanqit | src/main/java/com/anqit/spanqit/core/query/InsertDataQuery.java | // Path: src/main/java/com/anqit/spanqit/core/TriplesTemplate.java
// public class TriplesTemplate extends QueryElementCollection<TriplePattern> {
// TriplesTemplate(TriplePattern... triples) {
// super(" .\n");
// and(triples);
// }
//
// /**
// * add triples to this template
// *
// * @param triples the triples to add
// *
// * @return this TriplesTemplate instance
// */
// public TriplesTemplate and(TriplePattern... triples) {
// Collections.addAll(elements, triples);
//
// return this;
// }
//
// @Override
// public String getQueryString() {
// return SpanqitUtils.getBracedString(super.getQueryString());
// }
//
// }
//
// Path: src/main/java/com/anqit/spanqit/graphpattern/GraphName.java
// public interface GraphName extends QueryElement { }
//
// Path: src/main/java/com/anqit/spanqit/graphpattern/TriplePattern.java
// public interface TriplePattern extends GraphPattern {
// @SuppressWarnings("javadoc")
// static String SUFFIX = " .";
//
// /**
// * Add predicate-object lists describing this triple pattern's subject
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default public TriplePattern andHas(RdfPredicate predicate, RdfObject... objects) {
// return andHas(Rdf.predicateObjectList(predicate, objects));
// }
//
// /**
// * Add predicate-object lists describing this triple pattern's subject
// *
// * @param lists
// * the {@link RdfPredicateObjectList}(s) to add
// *
// * @return this triple pattern
// */
// public TriplePattern andHas(RdfPredicateObjectList... lists);
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Strings
// * and converts them to StringLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, String... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Boolean
// * and converts them to BooleanLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, Boolean... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Numbers
// * and converts them to NumberLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, Number... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Use the built-in RDF shortcut {@code a} for {@code rdf:type} to specify the subject's type
// *
// * @param object the object describing this triple pattern's subject's {@code rdf:type}
// *
// * @return this triple pattern
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#abbrevRdfType">
// * RDF Type abbreviation</a>
// */
// default TriplePattern andIsA(RdfObject object) {
// return andHas(RdfPredicate.a, object);
// }
// }
| import com.anqit.spanqit.core.TriplesTemplate;
import com.anqit.spanqit.graphpattern.GraphName;
import com.anqit.spanqit.graphpattern.TriplePattern; | package com.anqit.spanqit.core.query;
/**
* The SPARQL Insert Data Query
*
* @see <a href="https://www.w3.org/TR/sparql11-update/#insertData">
* SPARQL INSERT DATA Query</a>
*
*/
public class InsertDataQuery extends UpdateDataQuery<InsertDataQuery> {
private static final String INSERT_DATA = "INSERT DATA";
/**
* Add triples to be inserted
*
* @param triples the triples to add to this insert data query
*
* @return this Insert Data query instance
*/
public InsertDataQuery insertData(TriplePattern... triples) {
return addTriples(triples);
}
/**
* Set this query's triples template
*
* @param triplesTemplate
* the {@link TriplesTemplate} instance to set
*
* @return this instance
*/ | // Path: src/main/java/com/anqit/spanqit/core/TriplesTemplate.java
// public class TriplesTemplate extends QueryElementCollection<TriplePattern> {
// TriplesTemplate(TriplePattern... triples) {
// super(" .\n");
// and(triples);
// }
//
// /**
// * add triples to this template
// *
// * @param triples the triples to add
// *
// * @return this TriplesTemplate instance
// */
// public TriplesTemplate and(TriplePattern... triples) {
// Collections.addAll(elements, triples);
//
// return this;
// }
//
// @Override
// public String getQueryString() {
// return SpanqitUtils.getBracedString(super.getQueryString());
// }
//
// }
//
// Path: src/main/java/com/anqit/spanqit/graphpattern/GraphName.java
// public interface GraphName extends QueryElement { }
//
// Path: src/main/java/com/anqit/spanqit/graphpattern/TriplePattern.java
// public interface TriplePattern extends GraphPattern {
// @SuppressWarnings("javadoc")
// static String SUFFIX = " .";
//
// /**
// * Add predicate-object lists describing this triple pattern's subject
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default public TriplePattern andHas(RdfPredicate predicate, RdfObject... objects) {
// return andHas(Rdf.predicateObjectList(predicate, objects));
// }
//
// /**
// * Add predicate-object lists describing this triple pattern's subject
// *
// * @param lists
// * the {@link RdfPredicateObjectList}(s) to add
// *
// * @return this triple pattern
// */
// public TriplePattern andHas(RdfPredicateObjectList... lists);
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Strings
// * and converts them to StringLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, String... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Boolean
// * and converts them to BooleanLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, Boolean... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Numbers
// * and converts them to NumberLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, Number... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Use the built-in RDF shortcut {@code a} for {@code rdf:type} to specify the subject's type
// *
// * @param object the object describing this triple pattern's subject's {@code rdf:type}
// *
// * @return this triple pattern
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#abbrevRdfType">
// * RDF Type abbreviation</a>
// */
// default TriplePattern andIsA(RdfObject object) {
// return andHas(RdfPredicate.a, object);
// }
// }
// Path: src/main/java/com/anqit/spanqit/core/query/InsertDataQuery.java
import com.anqit.spanqit.core.TriplesTemplate;
import com.anqit.spanqit.graphpattern.GraphName;
import com.anqit.spanqit.graphpattern.TriplePattern;
package com.anqit.spanqit.core.query;
/**
* The SPARQL Insert Data Query
*
* @see <a href="https://www.w3.org/TR/sparql11-update/#insertData">
* SPARQL INSERT DATA Query</a>
*
*/
public class InsertDataQuery extends UpdateDataQuery<InsertDataQuery> {
private static final String INSERT_DATA = "INSERT DATA";
/**
* Add triples to be inserted
*
* @param triples the triples to add to this insert data query
*
* @return this Insert Data query instance
*/
public InsertDataQuery insertData(TriplePattern... triples) {
return addTriples(triples);
}
/**
* Set this query's triples template
*
* @param triplesTemplate
* the {@link TriplesTemplate} instance to set
*
* @return this instance
*/ | public InsertDataQuery insertData(TriplesTemplate triplesTemplate) { |
anqit/spanqit | src/main/java/com/anqit/spanqit/core/query/InsertDataQuery.java | // Path: src/main/java/com/anqit/spanqit/core/TriplesTemplate.java
// public class TriplesTemplate extends QueryElementCollection<TriplePattern> {
// TriplesTemplate(TriplePattern... triples) {
// super(" .\n");
// and(triples);
// }
//
// /**
// * add triples to this template
// *
// * @param triples the triples to add
// *
// * @return this TriplesTemplate instance
// */
// public TriplesTemplate and(TriplePattern... triples) {
// Collections.addAll(elements, triples);
//
// return this;
// }
//
// @Override
// public String getQueryString() {
// return SpanqitUtils.getBracedString(super.getQueryString());
// }
//
// }
//
// Path: src/main/java/com/anqit/spanqit/graphpattern/GraphName.java
// public interface GraphName extends QueryElement { }
//
// Path: src/main/java/com/anqit/spanqit/graphpattern/TriplePattern.java
// public interface TriplePattern extends GraphPattern {
// @SuppressWarnings("javadoc")
// static String SUFFIX = " .";
//
// /**
// * Add predicate-object lists describing this triple pattern's subject
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default public TriplePattern andHas(RdfPredicate predicate, RdfObject... objects) {
// return andHas(Rdf.predicateObjectList(predicate, objects));
// }
//
// /**
// * Add predicate-object lists describing this triple pattern's subject
// *
// * @param lists
// * the {@link RdfPredicateObjectList}(s) to add
// *
// * @return this triple pattern
// */
// public TriplePattern andHas(RdfPredicateObjectList... lists);
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Strings
// * and converts them to StringLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, String... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Boolean
// * and converts them to BooleanLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, Boolean... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Numbers
// * and converts them to NumberLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, Number... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Use the built-in RDF shortcut {@code a} for {@code rdf:type} to specify the subject's type
// *
// * @param object the object describing this triple pattern's subject's {@code rdf:type}
// *
// * @return this triple pattern
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#abbrevRdfType">
// * RDF Type abbreviation</a>
// */
// default TriplePattern andIsA(RdfObject object) {
// return andHas(RdfPredicate.a, object);
// }
// }
| import com.anqit.spanqit.core.TriplesTemplate;
import com.anqit.spanqit.graphpattern.GraphName;
import com.anqit.spanqit.graphpattern.TriplePattern; | package com.anqit.spanqit.core.query;
/**
* The SPARQL Insert Data Query
*
* @see <a href="https://www.w3.org/TR/sparql11-update/#insertData">
* SPARQL INSERT DATA Query</a>
*
*/
public class InsertDataQuery extends UpdateDataQuery<InsertDataQuery> {
private static final String INSERT_DATA = "INSERT DATA";
/**
* Add triples to be inserted
*
* @param triples the triples to add to this insert data query
*
* @return this Insert Data query instance
*/
public InsertDataQuery insertData(TriplePattern... triples) {
return addTriples(triples);
}
/**
* Set this query's triples template
*
* @param triplesTemplate
* the {@link TriplesTemplate} instance to set
*
* @return this instance
*/
public InsertDataQuery insertData(TriplesTemplate triplesTemplate) {
return setTriplesTemplate(triplesTemplate);
}
/**
* Specify a graph to insert the data into
*
* @param graph the identifier of the graph
*
* @return this Insert Data query instance
*/ | // Path: src/main/java/com/anqit/spanqit/core/TriplesTemplate.java
// public class TriplesTemplate extends QueryElementCollection<TriplePattern> {
// TriplesTemplate(TriplePattern... triples) {
// super(" .\n");
// and(triples);
// }
//
// /**
// * add triples to this template
// *
// * @param triples the triples to add
// *
// * @return this TriplesTemplate instance
// */
// public TriplesTemplate and(TriplePattern... triples) {
// Collections.addAll(elements, triples);
//
// return this;
// }
//
// @Override
// public String getQueryString() {
// return SpanqitUtils.getBracedString(super.getQueryString());
// }
//
// }
//
// Path: src/main/java/com/anqit/spanqit/graphpattern/GraphName.java
// public interface GraphName extends QueryElement { }
//
// Path: src/main/java/com/anqit/spanqit/graphpattern/TriplePattern.java
// public interface TriplePattern extends GraphPattern {
// @SuppressWarnings("javadoc")
// static String SUFFIX = " .";
//
// /**
// * Add predicate-object lists describing this triple pattern's subject
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default public TriplePattern andHas(RdfPredicate predicate, RdfObject... objects) {
// return andHas(Rdf.predicateObjectList(predicate, objects));
// }
//
// /**
// * Add predicate-object lists describing this triple pattern's subject
// *
// * @param lists
// * the {@link RdfPredicateObjectList}(s) to add
// *
// * @return this triple pattern
// */
// public TriplePattern andHas(RdfPredicateObjectList... lists);
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Strings
// * and converts them to StringLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, String... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Boolean
// * and converts them to BooleanLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, Boolean... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Numbers
// * and converts them to NumberLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, Number... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Use the built-in RDF shortcut {@code a} for {@code rdf:type} to specify the subject's type
// *
// * @param object the object describing this triple pattern's subject's {@code rdf:type}
// *
// * @return this triple pattern
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#abbrevRdfType">
// * RDF Type abbreviation</a>
// */
// default TriplePattern andIsA(RdfObject object) {
// return andHas(RdfPredicate.a, object);
// }
// }
// Path: src/main/java/com/anqit/spanqit/core/query/InsertDataQuery.java
import com.anqit.spanqit.core.TriplesTemplate;
import com.anqit.spanqit.graphpattern.GraphName;
import com.anqit.spanqit.graphpattern.TriplePattern;
package com.anqit.spanqit.core.query;
/**
* The SPARQL Insert Data Query
*
* @see <a href="https://www.w3.org/TR/sparql11-update/#insertData">
* SPARQL INSERT DATA Query</a>
*
*/
public class InsertDataQuery extends UpdateDataQuery<InsertDataQuery> {
private static final String INSERT_DATA = "INSERT DATA";
/**
* Add triples to be inserted
*
* @param triples the triples to add to this insert data query
*
* @return this Insert Data query instance
*/
public InsertDataQuery insertData(TriplePattern... triples) {
return addTriples(triples);
}
/**
* Set this query's triples template
*
* @param triplesTemplate
* the {@link TriplesTemplate} instance to set
*
* @return this instance
*/
public InsertDataQuery insertData(TriplesTemplate triplesTemplate) {
return setTriplesTemplate(triplesTemplate);
}
/**
* Specify a graph to insert the data into
*
* @param graph the identifier of the graph
*
* @return this Insert Data query instance
*/ | public InsertDataQuery into(GraphName graph) { |
anqit/spanqit | src/main/java/com/anqit/spanqit/core/GraphTemplate.java | // Path: src/main/java/com/anqit/spanqit/graphpattern/TriplePattern.java
// public interface TriplePattern extends GraphPattern {
// @SuppressWarnings("javadoc")
// static String SUFFIX = " .";
//
// /**
// * Add predicate-object lists describing this triple pattern's subject
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default public TriplePattern andHas(RdfPredicate predicate, RdfObject... objects) {
// return andHas(Rdf.predicateObjectList(predicate, objects));
// }
//
// /**
// * Add predicate-object lists describing this triple pattern's subject
// *
// * @param lists
// * the {@link RdfPredicateObjectList}(s) to add
// *
// * @return this triple pattern
// */
// public TriplePattern andHas(RdfPredicateObjectList... lists);
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Strings
// * and converts them to StringLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, String... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Boolean
// * and converts them to BooleanLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, Boolean... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Numbers
// * and converts them to NumberLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, Number... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Use the built-in RDF shortcut {@code a} for {@code rdf:type} to specify the subject's type
// *
// * @param object the object describing this triple pattern's subject's {@code rdf:type}
// *
// * @return this triple pattern
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#abbrevRdfType">
// * RDF Type abbreviation</a>
// */
// default TriplePattern andIsA(RdfObject object) {
// return andHas(RdfPredicate.a, object);
// }
// }
| import com.anqit.spanqit.graphpattern.TriplePattern; | package com.anqit.spanqit.core;
/**
* A SPARQL Graph Template, used in Construct queries
*
* @see <a
* href="http://www.w3.org/TR/2013/REC-sparql11-query-20130321/#construct">
* SPARQL CONSTRUCT Query</a>
*/
public class GraphTemplate implements QueryElement {
private static final String CONSTRUCT = "CONSTRUCT";
private TriplesTemplate triplesTemplate = Spanqit.triplesTemplate();
GraphTemplate() { }
/**
* Add triple patterns to this graph template
*
* @param triples
* the patterns to add
* @return this
*/ | // Path: src/main/java/com/anqit/spanqit/graphpattern/TriplePattern.java
// public interface TriplePattern extends GraphPattern {
// @SuppressWarnings("javadoc")
// static String SUFFIX = " .";
//
// /**
// * Add predicate-object lists describing this triple pattern's subject
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default public TriplePattern andHas(RdfPredicate predicate, RdfObject... objects) {
// return andHas(Rdf.predicateObjectList(predicate, objects));
// }
//
// /**
// * Add predicate-object lists describing this triple pattern's subject
// *
// * @param lists
// * the {@link RdfPredicateObjectList}(s) to add
// *
// * @return this triple pattern
// */
// public TriplePattern andHas(RdfPredicateObjectList... lists);
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Strings
// * and converts them to StringLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, String... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Boolean
// * and converts them to BooleanLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, Boolean... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Convenience version of {@link #andHas(RdfPredicate, RdfObject...)} that takes Numbers
// * and converts them to NumberLiterals
// *
// * @param predicate the predicate to use to describe this triple pattern's subject
// * @param objects the corresponding object(s)
// *
// * @return this triple pattern
// */
// default TriplePattern andHas(RdfPredicate predicate, Number... objects) {
// return andHas(predicate, toRdfLiteralArray(objects));
// };
//
// /**
// * Use the built-in RDF shortcut {@code a} for {@code rdf:type} to specify the subject's type
// *
// * @param object the object describing this triple pattern's subject's {@code rdf:type}
// *
// * @return this triple pattern
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#abbrevRdfType">
// * RDF Type abbreviation</a>
// */
// default TriplePattern andIsA(RdfObject object) {
// return andHas(RdfPredicate.a, object);
// }
// }
// Path: src/main/java/com/anqit/spanqit/core/GraphTemplate.java
import com.anqit.spanqit.graphpattern.TriplePattern;
package com.anqit.spanqit.core;
/**
* A SPARQL Graph Template, used in Construct queries
*
* @see <a
* href="http://www.w3.org/TR/2013/REC-sparql11-query-20130321/#construct">
* SPARQL CONSTRUCT Query</a>
*/
public class GraphTemplate implements QueryElement {
private static final String CONSTRUCT = "CONSTRUCT";
private TriplesTemplate triplesTemplate = Spanqit.triplesTemplate();
GraphTemplate() { }
/**
* Add triple patterns to this graph template
*
* @param triples
* the patterns to add
* @return this
*/ | public GraphTemplate construct(TriplePattern... triples) { |
anqit/spanqit | src/main/java/com/anqit/spanqit/core/query/LoadQuery.java | // Path: src/main/java/com/anqit/spanqit/core/SpanqitUtils.java
// @SuppressWarnings("javadoc")
// public class SpanqitUtils {
// private static final String PAD = " ";
//
// public static <O> Optional<O> getOrCreateAndModifyOptional(Optional<O> optional, Supplier<O> getter, UnaryOperator<O> operator) {
// return Optional.of(operator.apply(optional.orElseGet(getter)));
// }
//
// public static void appendAndNewlineIfPresent(Optional<? extends QueryElement> elementOptional, StringBuilder builder) {
// appendQueryElementIfPresent(elementOptional, builder, null, "\n");
// }
//
// public static void appendQueryElementIfPresent(Optional<? extends QueryElement> queryElementOptional, StringBuilder builder, String prefix, String suffix) {
// appendStringIfPresent(queryElementOptional.map(QueryElement::getQueryString), builder, prefix, suffix);
// }
//
// public static void appendStringIfPresent(Optional<String> stringOptional, StringBuilder builder, String prefix, String suffix) {
// Optional<String> preOpt = Optional.ofNullable(prefix);
// Optional<String> sufOpt = Optional.ofNullable(suffix);
//
// stringOptional.ifPresent(string -> {
// preOpt.ifPresent(p -> builder.append(p));
// builder.append(string);
// sufOpt.ifPresent(s -> builder.append(s));
// });
// }
//
// public static String getBracedString(String contents) {
// return getEnclosedString("{", "}", contents);
// }
//
// public static String getBracketedString(String contents) {
// return getEnclosedString("[", "]", contents);
// }
//
// public static String getParenthesizedString(String contents) {
// return getEnclosedString("(", ")", contents);
// }
//
// public static String getQuotedString(String contents) {
// return getEnclosedString("\"", "\"", contents, false);
// }
//
// /**
// * For string literals that contain single- or double-quotes
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#QSynLiterals">
// * RDF Literal Syntax</a>
// * @param contents
// * @return a "long quoted" string
// */
// public static String getLongQuotedString(String contents) {
// return getEnclosedString("'''", "'''", contents, false);
// }
//
// private static String getEnclosedString(String open, String close,
// String contents) {
// return getEnclosedString(open, close, contents, true);
// }
//
// private static String getEnclosedString(String open, String close,
// String contents, boolean pad) {
// StringBuilder es = new StringBuilder();
//
// es.append(open);
// if (contents != null && !contents.isEmpty()) {
// es.append(contents);
// if (pad) {
// es.insert(open.length(), PAD).append(PAD);
// }
// } else {
// es.append(PAD);
// }
// es.append(close);
//
// return es.toString();
// }
// }
//
// Path: src/main/java/com/anqit/spanqit/rdf/Iri.java
// public interface Iri extends RdfResource, RdfPredicate, GraphName { }
| import java.util.Optional;
import com.anqit.spanqit.core.SpanqitUtils;
import com.anqit.spanqit.rdf.Iri; | package com.anqit.spanqit.core.query;
/**
* A SPARQL LOAD Query
*
* @see <a href="https://www.w3.org/TR/sparql11-update/#load">
* SPARQL LOAD Query</a>
*/
public class LoadQuery extends GraphManagementQuery<LoadQuery> {
private static final String LOAD = "LOAD";
private static final String INTO_GRAPH = "INTO GRAPH";
| // Path: src/main/java/com/anqit/spanqit/core/SpanqitUtils.java
// @SuppressWarnings("javadoc")
// public class SpanqitUtils {
// private static final String PAD = " ";
//
// public static <O> Optional<O> getOrCreateAndModifyOptional(Optional<O> optional, Supplier<O> getter, UnaryOperator<O> operator) {
// return Optional.of(operator.apply(optional.orElseGet(getter)));
// }
//
// public static void appendAndNewlineIfPresent(Optional<? extends QueryElement> elementOptional, StringBuilder builder) {
// appendQueryElementIfPresent(elementOptional, builder, null, "\n");
// }
//
// public static void appendQueryElementIfPresent(Optional<? extends QueryElement> queryElementOptional, StringBuilder builder, String prefix, String suffix) {
// appendStringIfPresent(queryElementOptional.map(QueryElement::getQueryString), builder, prefix, suffix);
// }
//
// public static void appendStringIfPresent(Optional<String> stringOptional, StringBuilder builder, String prefix, String suffix) {
// Optional<String> preOpt = Optional.ofNullable(prefix);
// Optional<String> sufOpt = Optional.ofNullable(suffix);
//
// stringOptional.ifPresent(string -> {
// preOpt.ifPresent(p -> builder.append(p));
// builder.append(string);
// sufOpt.ifPresent(s -> builder.append(s));
// });
// }
//
// public static String getBracedString(String contents) {
// return getEnclosedString("{", "}", contents);
// }
//
// public static String getBracketedString(String contents) {
// return getEnclosedString("[", "]", contents);
// }
//
// public static String getParenthesizedString(String contents) {
// return getEnclosedString("(", ")", contents);
// }
//
// public static String getQuotedString(String contents) {
// return getEnclosedString("\"", "\"", contents, false);
// }
//
// /**
// * For string literals that contain single- or double-quotes
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#QSynLiterals">
// * RDF Literal Syntax</a>
// * @param contents
// * @return a "long quoted" string
// */
// public static String getLongQuotedString(String contents) {
// return getEnclosedString("'''", "'''", contents, false);
// }
//
// private static String getEnclosedString(String open, String close,
// String contents) {
// return getEnclosedString(open, close, contents, true);
// }
//
// private static String getEnclosedString(String open, String close,
// String contents, boolean pad) {
// StringBuilder es = new StringBuilder();
//
// es.append(open);
// if (contents != null && !contents.isEmpty()) {
// es.append(contents);
// if (pad) {
// es.insert(open.length(), PAD).append(PAD);
// }
// } else {
// es.append(PAD);
// }
// es.append(close);
//
// return es.toString();
// }
// }
//
// Path: src/main/java/com/anqit/spanqit/rdf/Iri.java
// public interface Iri extends RdfResource, RdfPredicate, GraphName { }
// Path: src/main/java/com/anqit/spanqit/core/query/LoadQuery.java
import java.util.Optional;
import com.anqit.spanqit.core.SpanqitUtils;
import com.anqit.spanqit.rdf.Iri;
package com.anqit.spanqit.core.query;
/**
* A SPARQL LOAD Query
*
* @see <a href="https://www.w3.org/TR/sparql11-update/#load">
* SPARQL LOAD Query</a>
*/
public class LoadQuery extends GraphManagementQuery<LoadQuery> {
private static final String LOAD = "LOAD";
private static final String INTO_GRAPH = "INTO GRAPH";
| private Iri from; |
anqit/spanqit | src/main/java/com/anqit/spanqit/core/query/LoadQuery.java | // Path: src/main/java/com/anqit/spanqit/core/SpanqitUtils.java
// @SuppressWarnings("javadoc")
// public class SpanqitUtils {
// private static final String PAD = " ";
//
// public static <O> Optional<O> getOrCreateAndModifyOptional(Optional<O> optional, Supplier<O> getter, UnaryOperator<O> operator) {
// return Optional.of(operator.apply(optional.orElseGet(getter)));
// }
//
// public static void appendAndNewlineIfPresent(Optional<? extends QueryElement> elementOptional, StringBuilder builder) {
// appendQueryElementIfPresent(elementOptional, builder, null, "\n");
// }
//
// public static void appendQueryElementIfPresent(Optional<? extends QueryElement> queryElementOptional, StringBuilder builder, String prefix, String suffix) {
// appendStringIfPresent(queryElementOptional.map(QueryElement::getQueryString), builder, prefix, suffix);
// }
//
// public static void appendStringIfPresent(Optional<String> stringOptional, StringBuilder builder, String prefix, String suffix) {
// Optional<String> preOpt = Optional.ofNullable(prefix);
// Optional<String> sufOpt = Optional.ofNullable(suffix);
//
// stringOptional.ifPresent(string -> {
// preOpt.ifPresent(p -> builder.append(p));
// builder.append(string);
// sufOpt.ifPresent(s -> builder.append(s));
// });
// }
//
// public static String getBracedString(String contents) {
// return getEnclosedString("{", "}", contents);
// }
//
// public static String getBracketedString(String contents) {
// return getEnclosedString("[", "]", contents);
// }
//
// public static String getParenthesizedString(String contents) {
// return getEnclosedString("(", ")", contents);
// }
//
// public static String getQuotedString(String contents) {
// return getEnclosedString("\"", "\"", contents, false);
// }
//
// /**
// * For string literals that contain single- or double-quotes
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#QSynLiterals">
// * RDF Literal Syntax</a>
// * @param contents
// * @return a "long quoted" string
// */
// public static String getLongQuotedString(String contents) {
// return getEnclosedString("'''", "'''", contents, false);
// }
//
// private static String getEnclosedString(String open, String close,
// String contents) {
// return getEnclosedString(open, close, contents, true);
// }
//
// private static String getEnclosedString(String open, String close,
// String contents, boolean pad) {
// StringBuilder es = new StringBuilder();
//
// es.append(open);
// if (contents != null && !contents.isEmpty()) {
// es.append(contents);
// if (pad) {
// es.insert(open.length(), PAD).append(PAD);
// }
// } else {
// es.append(PAD);
// }
// es.append(close);
//
// return es.toString();
// }
// }
//
// Path: src/main/java/com/anqit/spanqit/rdf/Iri.java
// public interface Iri extends RdfResource, RdfPredicate, GraphName { }
| import java.util.Optional;
import com.anqit.spanqit.core.SpanqitUtils;
import com.anqit.spanqit.rdf.Iri; | package com.anqit.spanqit.core.query;
/**
* A SPARQL LOAD Query
*
* @see <a href="https://www.w3.org/TR/sparql11-update/#load">
* SPARQL LOAD Query</a>
*/
public class LoadQuery extends GraphManagementQuery<LoadQuery> {
private static final String LOAD = "LOAD";
private static final String INTO_GRAPH = "INTO GRAPH";
private Iri from;
private Optional<Iri> to = Optional.empty();
LoadQuery() { }
/**
* Specify which graph to load form
*
* @param from the IRI identifying the graph to load triples from
*
* @return this LoadQuery instance
*/
public LoadQuery from(Iri from) {
this.from = from;
return this;
}
/**
* Specify which graph to load into, if not the default graph
*
* @param to the IRI identifying the graph to load into
*
* @return this LoadQuery instance
*/
public LoadQuery to(Iri to) {
this.to = Optional.ofNullable(to);
return this;
}
@Override
public String getQueryString() {
StringBuilder load = new StringBuilder();
load.append(LOAD).append(" ");
appendSilent(load);
load.append(from.getQueryString());
| // Path: src/main/java/com/anqit/spanqit/core/SpanqitUtils.java
// @SuppressWarnings("javadoc")
// public class SpanqitUtils {
// private static final String PAD = " ";
//
// public static <O> Optional<O> getOrCreateAndModifyOptional(Optional<O> optional, Supplier<O> getter, UnaryOperator<O> operator) {
// return Optional.of(operator.apply(optional.orElseGet(getter)));
// }
//
// public static void appendAndNewlineIfPresent(Optional<? extends QueryElement> elementOptional, StringBuilder builder) {
// appendQueryElementIfPresent(elementOptional, builder, null, "\n");
// }
//
// public static void appendQueryElementIfPresent(Optional<? extends QueryElement> queryElementOptional, StringBuilder builder, String prefix, String suffix) {
// appendStringIfPresent(queryElementOptional.map(QueryElement::getQueryString), builder, prefix, suffix);
// }
//
// public static void appendStringIfPresent(Optional<String> stringOptional, StringBuilder builder, String prefix, String suffix) {
// Optional<String> preOpt = Optional.ofNullable(prefix);
// Optional<String> sufOpt = Optional.ofNullable(suffix);
//
// stringOptional.ifPresent(string -> {
// preOpt.ifPresent(p -> builder.append(p));
// builder.append(string);
// sufOpt.ifPresent(s -> builder.append(s));
// });
// }
//
// public static String getBracedString(String contents) {
// return getEnclosedString("{", "}", contents);
// }
//
// public static String getBracketedString(String contents) {
// return getEnclosedString("[", "]", contents);
// }
//
// public static String getParenthesizedString(String contents) {
// return getEnclosedString("(", ")", contents);
// }
//
// public static String getQuotedString(String contents) {
// return getEnclosedString("\"", "\"", contents, false);
// }
//
// /**
// * For string literals that contain single- or double-quotes
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#QSynLiterals">
// * RDF Literal Syntax</a>
// * @param contents
// * @return a "long quoted" string
// */
// public static String getLongQuotedString(String contents) {
// return getEnclosedString("'''", "'''", contents, false);
// }
//
// private static String getEnclosedString(String open, String close,
// String contents) {
// return getEnclosedString(open, close, contents, true);
// }
//
// private static String getEnclosedString(String open, String close,
// String contents, boolean pad) {
// StringBuilder es = new StringBuilder();
//
// es.append(open);
// if (contents != null && !contents.isEmpty()) {
// es.append(contents);
// if (pad) {
// es.insert(open.length(), PAD).append(PAD);
// }
// } else {
// es.append(PAD);
// }
// es.append(close);
//
// return es.toString();
// }
// }
//
// Path: src/main/java/com/anqit/spanqit/rdf/Iri.java
// public interface Iri extends RdfResource, RdfPredicate, GraphName { }
// Path: src/main/java/com/anqit/spanqit/core/query/LoadQuery.java
import java.util.Optional;
import com.anqit.spanqit.core.SpanqitUtils;
import com.anqit.spanqit.rdf.Iri;
package com.anqit.spanqit.core.query;
/**
* A SPARQL LOAD Query
*
* @see <a href="https://www.w3.org/TR/sparql11-update/#load">
* SPARQL LOAD Query</a>
*/
public class LoadQuery extends GraphManagementQuery<LoadQuery> {
private static final String LOAD = "LOAD";
private static final String INTO_GRAPH = "INTO GRAPH";
private Iri from;
private Optional<Iri> to = Optional.empty();
LoadQuery() { }
/**
* Specify which graph to load form
*
* @param from the IRI identifying the graph to load triples from
*
* @return this LoadQuery instance
*/
public LoadQuery from(Iri from) {
this.from = from;
return this;
}
/**
* Specify which graph to load into, if not the default graph
*
* @param to the IRI identifying the graph to load into
*
* @return this LoadQuery instance
*/
public LoadQuery to(Iri to) {
this.to = Optional.ofNullable(to);
return this;
}
@Override
public String getQueryString() {
StringBuilder load = new StringBuilder();
load.append(LOAD).append(" ");
appendSilent(load);
load.append(from.getQueryString());
| SpanqitUtils.appendQueryElementIfPresent(to, load, " " + INTO_GRAPH + " ", null); |
anqit/spanqit | src/main/java/com/anqit/spanqit/rdf/RdfLiteral.java | // Path: src/main/java/com/anqit/spanqit/core/SpanqitUtils.java
// @SuppressWarnings("javadoc")
// public class SpanqitUtils {
// private static final String PAD = " ";
//
// public static <O> Optional<O> getOrCreateAndModifyOptional(Optional<O> optional, Supplier<O> getter, UnaryOperator<O> operator) {
// return Optional.of(operator.apply(optional.orElseGet(getter)));
// }
//
// public static void appendAndNewlineIfPresent(Optional<? extends QueryElement> elementOptional, StringBuilder builder) {
// appendQueryElementIfPresent(elementOptional, builder, null, "\n");
// }
//
// public static void appendQueryElementIfPresent(Optional<? extends QueryElement> queryElementOptional, StringBuilder builder, String prefix, String suffix) {
// appendStringIfPresent(queryElementOptional.map(QueryElement::getQueryString), builder, prefix, suffix);
// }
//
// public static void appendStringIfPresent(Optional<String> stringOptional, StringBuilder builder, String prefix, String suffix) {
// Optional<String> preOpt = Optional.ofNullable(prefix);
// Optional<String> sufOpt = Optional.ofNullable(suffix);
//
// stringOptional.ifPresent(string -> {
// preOpt.ifPresent(p -> builder.append(p));
// builder.append(string);
// sufOpt.ifPresent(s -> builder.append(s));
// });
// }
//
// public static String getBracedString(String contents) {
// return getEnclosedString("{", "}", contents);
// }
//
// public static String getBracketedString(String contents) {
// return getEnclosedString("[", "]", contents);
// }
//
// public static String getParenthesizedString(String contents) {
// return getEnclosedString("(", ")", contents);
// }
//
// public static String getQuotedString(String contents) {
// return getEnclosedString("\"", "\"", contents, false);
// }
//
// /**
// * For string literals that contain single- or double-quotes
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#QSynLiterals">
// * RDF Literal Syntax</a>
// * @param contents
// * @return a "long quoted" string
// */
// public static String getLongQuotedString(String contents) {
// return getEnclosedString("'''", "'''", contents, false);
// }
//
// private static String getEnclosedString(String open, String close,
// String contents) {
// return getEnclosedString(open, close, contents, true);
// }
//
// private static String getEnclosedString(String open, String close,
// String contents, boolean pad) {
// StringBuilder es = new StringBuilder();
//
// es.append(open);
// if (contents != null && !contents.isEmpty()) {
// es.append(contents);
// if (pad) {
// es.insert(open.length(), PAD).append(PAD);
// }
// } else {
// es.append(PAD);
// }
// es.append(close);
//
// return es.toString();
// }
// }
//
// Path: src/main/java/com/anqit/spanqit/core/SpanqitUtils.java
// public static void appendQueryElementIfPresent(Optional<? extends QueryElement> queryElementOptional, StringBuilder builder, String prefix, String suffix) {
// appendStringIfPresent(queryElementOptional.map(QueryElement::getQueryString), builder, prefix, suffix);
// }
//
// Path: src/main/java/com/anqit/spanqit/core/SpanqitUtils.java
// public static void appendStringIfPresent(Optional<String> stringOptional, StringBuilder builder, String prefix, String suffix) {
// Optional<String> preOpt = Optional.ofNullable(prefix);
// Optional<String> sufOpt = Optional.ofNullable(suffix);
//
// stringOptional.ifPresent(string -> {
// preOpt.ifPresent(p -> builder.append(p));
// builder.append(string);
// sufOpt.ifPresent(s -> builder.append(s));
// });
// }
| import java.util.Optional;
import com.anqit.spanqit.core.SpanqitUtils;
import static com.anqit.spanqit.core.SpanqitUtils.appendQueryElementIfPresent;
import static com.anqit.spanqit.core.SpanqitUtils.appendStringIfPresent; |
/**
* Represents an RDF string literal
*/
public static class StringLiteral extends RdfLiteral<String> {
private static final String DATATYPE_SPECIFIER = "^^";
private static final String LANG_TAG_SPECIFIER = "@";
private Optional<Iri> dataType = Optional.empty();
private Optional<String> languageTag = Optional.empty();
StringLiteral(String stringValue) {
super(stringValue);
}
StringLiteral(String stringValue, Iri dataType) {
super(stringValue);
this.dataType = Optional.ofNullable(dataType);
}
StringLiteral(String stringValue, String languageTag) {
super(stringValue);
this.languageTag = Optional.ofNullable(languageTag);
}
@Override
public String getQueryString() {
StringBuilder literal = new StringBuilder();
if(value.contains("'") || value.contains("\"")) { | // Path: src/main/java/com/anqit/spanqit/core/SpanqitUtils.java
// @SuppressWarnings("javadoc")
// public class SpanqitUtils {
// private static final String PAD = " ";
//
// public static <O> Optional<O> getOrCreateAndModifyOptional(Optional<O> optional, Supplier<O> getter, UnaryOperator<O> operator) {
// return Optional.of(operator.apply(optional.orElseGet(getter)));
// }
//
// public static void appendAndNewlineIfPresent(Optional<? extends QueryElement> elementOptional, StringBuilder builder) {
// appendQueryElementIfPresent(elementOptional, builder, null, "\n");
// }
//
// public static void appendQueryElementIfPresent(Optional<? extends QueryElement> queryElementOptional, StringBuilder builder, String prefix, String suffix) {
// appendStringIfPresent(queryElementOptional.map(QueryElement::getQueryString), builder, prefix, suffix);
// }
//
// public static void appendStringIfPresent(Optional<String> stringOptional, StringBuilder builder, String prefix, String suffix) {
// Optional<String> preOpt = Optional.ofNullable(prefix);
// Optional<String> sufOpt = Optional.ofNullable(suffix);
//
// stringOptional.ifPresent(string -> {
// preOpt.ifPresent(p -> builder.append(p));
// builder.append(string);
// sufOpt.ifPresent(s -> builder.append(s));
// });
// }
//
// public static String getBracedString(String contents) {
// return getEnclosedString("{", "}", contents);
// }
//
// public static String getBracketedString(String contents) {
// return getEnclosedString("[", "]", contents);
// }
//
// public static String getParenthesizedString(String contents) {
// return getEnclosedString("(", ")", contents);
// }
//
// public static String getQuotedString(String contents) {
// return getEnclosedString("\"", "\"", contents, false);
// }
//
// /**
// * For string literals that contain single- or double-quotes
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#QSynLiterals">
// * RDF Literal Syntax</a>
// * @param contents
// * @return a "long quoted" string
// */
// public static String getLongQuotedString(String contents) {
// return getEnclosedString("'''", "'''", contents, false);
// }
//
// private static String getEnclosedString(String open, String close,
// String contents) {
// return getEnclosedString(open, close, contents, true);
// }
//
// private static String getEnclosedString(String open, String close,
// String contents, boolean pad) {
// StringBuilder es = new StringBuilder();
//
// es.append(open);
// if (contents != null && !contents.isEmpty()) {
// es.append(contents);
// if (pad) {
// es.insert(open.length(), PAD).append(PAD);
// }
// } else {
// es.append(PAD);
// }
// es.append(close);
//
// return es.toString();
// }
// }
//
// Path: src/main/java/com/anqit/spanqit/core/SpanqitUtils.java
// public static void appendQueryElementIfPresent(Optional<? extends QueryElement> queryElementOptional, StringBuilder builder, String prefix, String suffix) {
// appendStringIfPresent(queryElementOptional.map(QueryElement::getQueryString), builder, prefix, suffix);
// }
//
// Path: src/main/java/com/anqit/spanqit/core/SpanqitUtils.java
// public static void appendStringIfPresent(Optional<String> stringOptional, StringBuilder builder, String prefix, String suffix) {
// Optional<String> preOpt = Optional.ofNullable(prefix);
// Optional<String> sufOpt = Optional.ofNullable(suffix);
//
// stringOptional.ifPresent(string -> {
// preOpt.ifPresent(p -> builder.append(p));
// builder.append(string);
// sufOpt.ifPresent(s -> builder.append(s));
// });
// }
// Path: src/main/java/com/anqit/spanqit/rdf/RdfLiteral.java
import java.util.Optional;
import com.anqit.spanqit.core.SpanqitUtils;
import static com.anqit.spanqit.core.SpanqitUtils.appendQueryElementIfPresent;
import static com.anqit.spanqit.core.SpanqitUtils.appendStringIfPresent;
/**
* Represents an RDF string literal
*/
public static class StringLiteral extends RdfLiteral<String> {
private static final String DATATYPE_SPECIFIER = "^^";
private static final String LANG_TAG_SPECIFIER = "@";
private Optional<Iri> dataType = Optional.empty();
private Optional<String> languageTag = Optional.empty();
StringLiteral(String stringValue) {
super(stringValue);
}
StringLiteral(String stringValue, Iri dataType) {
super(stringValue);
this.dataType = Optional.ofNullable(dataType);
}
StringLiteral(String stringValue, String languageTag) {
super(stringValue);
this.languageTag = Optional.ofNullable(languageTag);
}
@Override
public String getQueryString() {
StringBuilder literal = new StringBuilder();
if(value.contains("'") || value.contains("\"")) { | literal.append(SpanqitUtils.getLongQuotedString(value)); |
anqit/spanqit | src/main/java/com/anqit/spanqit/rdf/RdfLiteral.java | // Path: src/main/java/com/anqit/spanqit/core/SpanqitUtils.java
// @SuppressWarnings("javadoc")
// public class SpanqitUtils {
// private static final String PAD = " ";
//
// public static <O> Optional<O> getOrCreateAndModifyOptional(Optional<O> optional, Supplier<O> getter, UnaryOperator<O> operator) {
// return Optional.of(operator.apply(optional.orElseGet(getter)));
// }
//
// public static void appendAndNewlineIfPresent(Optional<? extends QueryElement> elementOptional, StringBuilder builder) {
// appendQueryElementIfPresent(elementOptional, builder, null, "\n");
// }
//
// public static void appendQueryElementIfPresent(Optional<? extends QueryElement> queryElementOptional, StringBuilder builder, String prefix, String suffix) {
// appendStringIfPresent(queryElementOptional.map(QueryElement::getQueryString), builder, prefix, suffix);
// }
//
// public static void appendStringIfPresent(Optional<String> stringOptional, StringBuilder builder, String prefix, String suffix) {
// Optional<String> preOpt = Optional.ofNullable(prefix);
// Optional<String> sufOpt = Optional.ofNullable(suffix);
//
// stringOptional.ifPresent(string -> {
// preOpt.ifPresent(p -> builder.append(p));
// builder.append(string);
// sufOpt.ifPresent(s -> builder.append(s));
// });
// }
//
// public static String getBracedString(String contents) {
// return getEnclosedString("{", "}", contents);
// }
//
// public static String getBracketedString(String contents) {
// return getEnclosedString("[", "]", contents);
// }
//
// public static String getParenthesizedString(String contents) {
// return getEnclosedString("(", ")", contents);
// }
//
// public static String getQuotedString(String contents) {
// return getEnclosedString("\"", "\"", contents, false);
// }
//
// /**
// * For string literals that contain single- or double-quotes
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#QSynLiterals">
// * RDF Literal Syntax</a>
// * @param contents
// * @return a "long quoted" string
// */
// public static String getLongQuotedString(String contents) {
// return getEnclosedString("'''", "'''", contents, false);
// }
//
// private static String getEnclosedString(String open, String close,
// String contents) {
// return getEnclosedString(open, close, contents, true);
// }
//
// private static String getEnclosedString(String open, String close,
// String contents, boolean pad) {
// StringBuilder es = new StringBuilder();
//
// es.append(open);
// if (contents != null && !contents.isEmpty()) {
// es.append(contents);
// if (pad) {
// es.insert(open.length(), PAD).append(PAD);
// }
// } else {
// es.append(PAD);
// }
// es.append(close);
//
// return es.toString();
// }
// }
//
// Path: src/main/java/com/anqit/spanqit/core/SpanqitUtils.java
// public static void appendQueryElementIfPresent(Optional<? extends QueryElement> queryElementOptional, StringBuilder builder, String prefix, String suffix) {
// appendStringIfPresent(queryElementOptional.map(QueryElement::getQueryString), builder, prefix, suffix);
// }
//
// Path: src/main/java/com/anqit/spanqit/core/SpanqitUtils.java
// public static void appendStringIfPresent(Optional<String> stringOptional, StringBuilder builder, String prefix, String suffix) {
// Optional<String> preOpt = Optional.ofNullable(prefix);
// Optional<String> sufOpt = Optional.ofNullable(suffix);
//
// stringOptional.ifPresent(string -> {
// preOpt.ifPresent(p -> builder.append(p));
// builder.append(string);
// sufOpt.ifPresent(s -> builder.append(s));
// });
// }
| import java.util.Optional;
import com.anqit.spanqit.core.SpanqitUtils;
import static com.anqit.spanqit.core.SpanqitUtils.appendQueryElementIfPresent;
import static com.anqit.spanqit.core.SpanqitUtils.appendStringIfPresent; | private static final String DATATYPE_SPECIFIER = "^^";
private static final String LANG_TAG_SPECIFIER = "@";
private Optional<Iri> dataType = Optional.empty();
private Optional<String> languageTag = Optional.empty();
StringLiteral(String stringValue) {
super(stringValue);
}
StringLiteral(String stringValue, Iri dataType) {
super(stringValue);
this.dataType = Optional.ofNullable(dataType);
}
StringLiteral(String stringValue, String languageTag) {
super(stringValue);
this.languageTag = Optional.ofNullable(languageTag);
}
@Override
public String getQueryString() {
StringBuilder literal = new StringBuilder();
if(value.contains("'") || value.contains("\"")) {
literal.append(SpanqitUtils.getLongQuotedString(value));
} else {
literal.append(SpanqitUtils.getQuotedString(value));
}
| // Path: src/main/java/com/anqit/spanqit/core/SpanqitUtils.java
// @SuppressWarnings("javadoc")
// public class SpanqitUtils {
// private static final String PAD = " ";
//
// public static <O> Optional<O> getOrCreateAndModifyOptional(Optional<O> optional, Supplier<O> getter, UnaryOperator<O> operator) {
// return Optional.of(operator.apply(optional.orElseGet(getter)));
// }
//
// public static void appendAndNewlineIfPresent(Optional<? extends QueryElement> elementOptional, StringBuilder builder) {
// appendQueryElementIfPresent(elementOptional, builder, null, "\n");
// }
//
// public static void appendQueryElementIfPresent(Optional<? extends QueryElement> queryElementOptional, StringBuilder builder, String prefix, String suffix) {
// appendStringIfPresent(queryElementOptional.map(QueryElement::getQueryString), builder, prefix, suffix);
// }
//
// public static void appendStringIfPresent(Optional<String> stringOptional, StringBuilder builder, String prefix, String suffix) {
// Optional<String> preOpt = Optional.ofNullable(prefix);
// Optional<String> sufOpt = Optional.ofNullable(suffix);
//
// stringOptional.ifPresent(string -> {
// preOpt.ifPresent(p -> builder.append(p));
// builder.append(string);
// sufOpt.ifPresent(s -> builder.append(s));
// });
// }
//
// public static String getBracedString(String contents) {
// return getEnclosedString("{", "}", contents);
// }
//
// public static String getBracketedString(String contents) {
// return getEnclosedString("[", "]", contents);
// }
//
// public static String getParenthesizedString(String contents) {
// return getEnclosedString("(", ")", contents);
// }
//
// public static String getQuotedString(String contents) {
// return getEnclosedString("\"", "\"", contents, false);
// }
//
// /**
// * For string literals that contain single- or double-quotes
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#QSynLiterals">
// * RDF Literal Syntax</a>
// * @param contents
// * @return a "long quoted" string
// */
// public static String getLongQuotedString(String contents) {
// return getEnclosedString("'''", "'''", contents, false);
// }
//
// private static String getEnclosedString(String open, String close,
// String contents) {
// return getEnclosedString(open, close, contents, true);
// }
//
// private static String getEnclosedString(String open, String close,
// String contents, boolean pad) {
// StringBuilder es = new StringBuilder();
//
// es.append(open);
// if (contents != null && !contents.isEmpty()) {
// es.append(contents);
// if (pad) {
// es.insert(open.length(), PAD).append(PAD);
// }
// } else {
// es.append(PAD);
// }
// es.append(close);
//
// return es.toString();
// }
// }
//
// Path: src/main/java/com/anqit/spanqit/core/SpanqitUtils.java
// public static void appendQueryElementIfPresent(Optional<? extends QueryElement> queryElementOptional, StringBuilder builder, String prefix, String suffix) {
// appendStringIfPresent(queryElementOptional.map(QueryElement::getQueryString), builder, prefix, suffix);
// }
//
// Path: src/main/java/com/anqit/spanqit/core/SpanqitUtils.java
// public static void appendStringIfPresent(Optional<String> stringOptional, StringBuilder builder, String prefix, String suffix) {
// Optional<String> preOpt = Optional.ofNullable(prefix);
// Optional<String> sufOpt = Optional.ofNullable(suffix);
//
// stringOptional.ifPresent(string -> {
// preOpt.ifPresent(p -> builder.append(p));
// builder.append(string);
// sufOpt.ifPresent(s -> builder.append(s));
// });
// }
// Path: src/main/java/com/anqit/spanqit/rdf/RdfLiteral.java
import java.util.Optional;
import com.anqit.spanqit.core.SpanqitUtils;
import static com.anqit.spanqit.core.SpanqitUtils.appendQueryElementIfPresent;
import static com.anqit.spanqit.core.SpanqitUtils.appendStringIfPresent;
private static final String DATATYPE_SPECIFIER = "^^";
private static final String LANG_TAG_SPECIFIER = "@";
private Optional<Iri> dataType = Optional.empty();
private Optional<String> languageTag = Optional.empty();
StringLiteral(String stringValue) {
super(stringValue);
}
StringLiteral(String stringValue, Iri dataType) {
super(stringValue);
this.dataType = Optional.ofNullable(dataType);
}
StringLiteral(String stringValue, String languageTag) {
super(stringValue);
this.languageTag = Optional.ofNullable(languageTag);
}
@Override
public String getQueryString() {
StringBuilder literal = new StringBuilder();
if(value.contains("'") || value.contains("\"")) {
literal.append(SpanqitUtils.getLongQuotedString(value));
} else {
literal.append(SpanqitUtils.getQuotedString(value));
}
| appendQueryElementIfPresent(dataType, literal, DATATYPE_SPECIFIER, null); |
anqit/spanqit | src/main/java/com/anqit/spanqit/rdf/RdfLiteral.java | // Path: src/main/java/com/anqit/spanqit/core/SpanqitUtils.java
// @SuppressWarnings("javadoc")
// public class SpanqitUtils {
// private static final String PAD = " ";
//
// public static <O> Optional<O> getOrCreateAndModifyOptional(Optional<O> optional, Supplier<O> getter, UnaryOperator<O> operator) {
// return Optional.of(operator.apply(optional.orElseGet(getter)));
// }
//
// public static void appendAndNewlineIfPresent(Optional<? extends QueryElement> elementOptional, StringBuilder builder) {
// appendQueryElementIfPresent(elementOptional, builder, null, "\n");
// }
//
// public static void appendQueryElementIfPresent(Optional<? extends QueryElement> queryElementOptional, StringBuilder builder, String prefix, String suffix) {
// appendStringIfPresent(queryElementOptional.map(QueryElement::getQueryString), builder, prefix, suffix);
// }
//
// public static void appendStringIfPresent(Optional<String> stringOptional, StringBuilder builder, String prefix, String suffix) {
// Optional<String> preOpt = Optional.ofNullable(prefix);
// Optional<String> sufOpt = Optional.ofNullable(suffix);
//
// stringOptional.ifPresent(string -> {
// preOpt.ifPresent(p -> builder.append(p));
// builder.append(string);
// sufOpt.ifPresent(s -> builder.append(s));
// });
// }
//
// public static String getBracedString(String contents) {
// return getEnclosedString("{", "}", contents);
// }
//
// public static String getBracketedString(String contents) {
// return getEnclosedString("[", "]", contents);
// }
//
// public static String getParenthesizedString(String contents) {
// return getEnclosedString("(", ")", contents);
// }
//
// public static String getQuotedString(String contents) {
// return getEnclosedString("\"", "\"", contents, false);
// }
//
// /**
// * For string literals that contain single- or double-quotes
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#QSynLiterals">
// * RDF Literal Syntax</a>
// * @param contents
// * @return a "long quoted" string
// */
// public static String getLongQuotedString(String contents) {
// return getEnclosedString("'''", "'''", contents, false);
// }
//
// private static String getEnclosedString(String open, String close,
// String contents) {
// return getEnclosedString(open, close, contents, true);
// }
//
// private static String getEnclosedString(String open, String close,
// String contents, boolean pad) {
// StringBuilder es = new StringBuilder();
//
// es.append(open);
// if (contents != null && !contents.isEmpty()) {
// es.append(contents);
// if (pad) {
// es.insert(open.length(), PAD).append(PAD);
// }
// } else {
// es.append(PAD);
// }
// es.append(close);
//
// return es.toString();
// }
// }
//
// Path: src/main/java/com/anqit/spanqit/core/SpanqitUtils.java
// public static void appendQueryElementIfPresent(Optional<? extends QueryElement> queryElementOptional, StringBuilder builder, String prefix, String suffix) {
// appendStringIfPresent(queryElementOptional.map(QueryElement::getQueryString), builder, prefix, suffix);
// }
//
// Path: src/main/java/com/anqit/spanqit/core/SpanqitUtils.java
// public static void appendStringIfPresent(Optional<String> stringOptional, StringBuilder builder, String prefix, String suffix) {
// Optional<String> preOpt = Optional.ofNullable(prefix);
// Optional<String> sufOpt = Optional.ofNullable(suffix);
//
// stringOptional.ifPresent(string -> {
// preOpt.ifPresent(p -> builder.append(p));
// builder.append(string);
// sufOpt.ifPresent(s -> builder.append(s));
// });
// }
| import java.util.Optional;
import com.anqit.spanqit.core.SpanqitUtils;
import static com.anqit.spanqit.core.SpanqitUtils.appendQueryElementIfPresent;
import static com.anqit.spanqit.core.SpanqitUtils.appendStringIfPresent; | private static final String LANG_TAG_SPECIFIER = "@";
private Optional<Iri> dataType = Optional.empty();
private Optional<String> languageTag = Optional.empty();
StringLiteral(String stringValue) {
super(stringValue);
}
StringLiteral(String stringValue, Iri dataType) {
super(stringValue);
this.dataType = Optional.ofNullable(dataType);
}
StringLiteral(String stringValue, String languageTag) {
super(stringValue);
this.languageTag = Optional.ofNullable(languageTag);
}
@Override
public String getQueryString() {
StringBuilder literal = new StringBuilder();
if(value.contains("'") || value.contains("\"")) {
literal.append(SpanqitUtils.getLongQuotedString(value));
} else {
literal.append(SpanqitUtils.getQuotedString(value));
}
appendQueryElementIfPresent(dataType, literal, DATATYPE_SPECIFIER, null); | // Path: src/main/java/com/anqit/spanqit/core/SpanqitUtils.java
// @SuppressWarnings("javadoc")
// public class SpanqitUtils {
// private static final String PAD = " ";
//
// public static <O> Optional<O> getOrCreateAndModifyOptional(Optional<O> optional, Supplier<O> getter, UnaryOperator<O> operator) {
// return Optional.of(operator.apply(optional.orElseGet(getter)));
// }
//
// public static void appendAndNewlineIfPresent(Optional<? extends QueryElement> elementOptional, StringBuilder builder) {
// appendQueryElementIfPresent(elementOptional, builder, null, "\n");
// }
//
// public static void appendQueryElementIfPresent(Optional<? extends QueryElement> queryElementOptional, StringBuilder builder, String prefix, String suffix) {
// appendStringIfPresent(queryElementOptional.map(QueryElement::getQueryString), builder, prefix, suffix);
// }
//
// public static void appendStringIfPresent(Optional<String> stringOptional, StringBuilder builder, String prefix, String suffix) {
// Optional<String> preOpt = Optional.ofNullable(prefix);
// Optional<String> sufOpt = Optional.ofNullable(suffix);
//
// stringOptional.ifPresent(string -> {
// preOpt.ifPresent(p -> builder.append(p));
// builder.append(string);
// sufOpt.ifPresent(s -> builder.append(s));
// });
// }
//
// public static String getBracedString(String contents) {
// return getEnclosedString("{", "}", contents);
// }
//
// public static String getBracketedString(String contents) {
// return getEnclosedString("[", "]", contents);
// }
//
// public static String getParenthesizedString(String contents) {
// return getEnclosedString("(", ")", contents);
// }
//
// public static String getQuotedString(String contents) {
// return getEnclosedString("\"", "\"", contents, false);
// }
//
// /**
// * For string literals that contain single- or double-quotes
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#QSynLiterals">
// * RDF Literal Syntax</a>
// * @param contents
// * @return a "long quoted" string
// */
// public static String getLongQuotedString(String contents) {
// return getEnclosedString("'''", "'''", contents, false);
// }
//
// private static String getEnclosedString(String open, String close,
// String contents) {
// return getEnclosedString(open, close, contents, true);
// }
//
// private static String getEnclosedString(String open, String close,
// String contents, boolean pad) {
// StringBuilder es = new StringBuilder();
//
// es.append(open);
// if (contents != null && !contents.isEmpty()) {
// es.append(contents);
// if (pad) {
// es.insert(open.length(), PAD).append(PAD);
// }
// } else {
// es.append(PAD);
// }
// es.append(close);
//
// return es.toString();
// }
// }
//
// Path: src/main/java/com/anqit/spanqit/core/SpanqitUtils.java
// public static void appendQueryElementIfPresent(Optional<? extends QueryElement> queryElementOptional, StringBuilder builder, String prefix, String suffix) {
// appendStringIfPresent(queryElementOptional.map(QueryElement::getQueryString), builder, prefix, suffix);
// }
//
// Path: src/main/java/com/anqit/spanqit/core/SpanqitUtils.java
// public static void appendStringIfPresent(Optional<String> stringOptional, StringBuilder builder, String prefix, String suffix) {
// Optional<String> preOpt = Optional.ofNullable(prefix);
// Optional<String> sufOpt = Optional.ofNullable(suffix);
//
// stringOptional.ifPresent(string -> {
// preOpt.ifPresent(p -> builder.append(p));
// builder.append(string);
// sufOpt.ifPresent(s -> builder.append(s));
// });
// }
// Path: src/main/java/com/anqit/spanqit/rdf/RdfLiteral.java
import java.util.Optional;
import com.anqit.spanqit.core.SpanqitUtils;
import static com.anqit.spanqit.core.SpanqitUtils.appendQueryElementIfPresent;
import static com.anqit.spanqit.core.SpanqitUtils.appendStringIfPresent;
private static final String LANG_TAG_SPECIFIER = "@";
private Optional<Iri> dataType = Optional.empty();
private Optional<String> languageTag = Optional.empty();
StringLiteral(String stringValue) {
super(stringValue);
}
StringLiteral(String stringValue, Iri dataType) {
super(stringValue);
this.dataType = Optional.ofNullable(dataType);
}
StringLiteral(String stringValue, String languageTag) {
super(stringValue);
this.languageTag = Optional.ofNullable(languageTag);
}
@Override
public String getQueryString() {
StringBuilder literal = new StringBuilder();
if(value.contains("'") || value.contains("\"")) {
literal.append(SpanqitUtils.getLongQuotedString(value));
} else {
literal.append(SpanqitUtils.getQuotedString(value));
}
appendQueryElementIfPresent(dataType, literal, DATATYPE_SPECIFIER, null); | appendStringIfPresent(languageTag, literal, LANG_TAG_SPECIFIER, null); |
anqit/spanqit | src/main/java/com/anqit/spanqit/core/query/CreateQuery.java | // Path: src/main/java/com/anqit/spanqit/rdf/Iri.java
// public interface Iri extends RdfResource, RdfPredicate, GraphName { }
| import com.anqit.spanqit.rdf.Iri; | package com.anqit.spanqit.core.query;
/**
* A SPARQL CREATE Query
*
* @see <a href="https://www.w3.org/TR/sparql11-update/#create">
* SPARQL CREATE Query</a>
*/
public class CreateQuery extends GraphManagementQuery<CreateQuery> {
private static final String CREATE = "CREATE";
private static final String GRAPH = "GRAPH";
| // Path: src/main/java/com/anqit/spanqit/rdf/Iri.java
// public interface Iri extends RdfResource, RdfPredicate, GraphName { }
// Path: src/main/java/com/anqit/spanqit/core/query/CreateQuery.java
import com.anqit.spanqit.rdf.Iri;
package com.anqit.spanqit.core.query;
/**
* A SPARQL CREATE Query
*
* @see <a href="https://www.w3.org/TR/sparql11-update/#create">
* SPARQL CREATE Query</a>
*/
public class CreateQuery extends GraphManagementQuery<CreateQuery> {
private static final String CREATE = "CREATE";
private static final String GRAPH = "GRAPH";
| private Iri graph; |
anqit/spanqit | src/main/java/com/anqit/spanqit/graphpattern/Filter.java | // Path: src/main/java/com/anqit/spanqit/constraint/Expression.java
// public abstract class Expression<T extends Expression<T>> extends
// QueryElementCollection<Operand> implements Operand,
// Orderable, Groupable, Assignable {
// protected SparqlOperator operator;
// private boolean parenthesize;
//
// Expression(SparqlOperator operator) {
// this(operator, " " + operator.getQueryString() + " ");
// }
//
// Expression(SparqlOperator operator, String delimeter) {
// super(delimeter, new ArrayList<Operand>());
// this.operator = operator;
// parenthesize(false);
// }
//
// @SuppressWarnings("unchecked")
// T addOperand(Operand... operands) {
// for (Operand operand : operands) {
// elements.add(operand);
// }
//
// return (T) this;
// }
//
// /**
// * Indicate that this expression should be wrapped in parentheses
// * when converted to a query string
// *
// * @return this
// */
// public T parenthesize() {
// return parenthesize(true);
// }
//
// /**
// * Indicate if this expression should be wrapped in parentheses
// * when converted to a query string
// *
// * @param parenthesize
// * @return this
// */
// @SuppressWarnings("unchecked")
// public T parenthesize(boolean parenthesize) {
// this.parenthesize = parenthesize;
//
// return (T) this;
// }
//
// Operand getOperand(int index) {
// return ((ArrayList<Operand>) elements).get(index);
// }
//
// @Override
// public String getQueryString() {
// String queryString = super.getQueryString();
//
// return parenthesize ? SpanqitUtils.getParenthesizedString(queryString) : queryString;
// }
// }
//
// Path: src/main/java/com/anqit/spanqit/core/QueryElement.java
// public interface QueryElement {
// /**
// * @return the String representing the SPARQL syntax of this element
// */
// public String getQueryString();
// }
//
// Path: src/main/java/com/anqit/spanqit/core/SpanqitUtils.java
// @SuppressWarnings("javadoc")
// public class SpanqitUtils {
// private static final String PAD = " ";
//
// public static <O> Optional<O> getOrCreateAndModifyOptional(Optional<O> optional, Supplier<O> getter, UnaryOperator<O> operator) {
// return Optional.of(operator.apply(optional.orElseGet(getter)));
// }
//
// public static void appendAndNewlineIfPresent(Optional<? extends QueryElement> elementOptional, StringBuilder builder) {
// appendQueryElementIfPresent(elementOptional, builder, null, "\n");
// }
//
// public static void appendQueryElementIfPresent(Optional<? extends QueryElement> queryElementOptional, StringBuilder builder, String prefix, String suffix) {
// appendStringIfPresent(queryElementOptional.map(QueryElement::getQueryString), builder, prefix, suffix);
// }
//
// public static void appendStringIfPresent(Optional<String> stringOptional, StringBuilder builder, String prefix, String suffix) {
// Optional<String> preOpt = Optional.ofNullable(prefix);
// Optional<String> sufOpt = Optional.ofNullable(suffix);
//
// stringOptional.ifPresent(string -> {
// preOpt.ifPresent(p -> builder.append(p));
// builder.append(string);
// sufOpt.ifPresent(s -> builder.append(s));
// });
// }
//
// public static String getBracedString(String contents) {
// return getEnclosedString("{", "}", contents);
// }
//
// public static String getBracketedString(String contents) {
// return getEnclosedString("[", "]", contents);
// }
//
// public static String getParenthesizedString(String contents) {
// return getEnclosedString("(", ")", contents);
// }
//
// public static String getQuotedString(String contents) {
// return getEnclosedString("\"", "\"", contents, false);
// }
//
// /**
// * For string literals that contain single- or double-quotes
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#QSynLiterals">
// * RDF Literal Syntax</a>
// * @param contents
// * @return a "long quoted" string
// */
// public static String getLongQuotedString(String contents) {
// return getEnclosedString("'''", "'''", contents, false);
// }
//
// private static String getEnclosedString(String open, String close,
// String contents) {
// return getEnclosedString(open, close, contents, true);
// }
//
// private static String getEnclosedString(String open, String close,
// String contents, boolean pad) {
// StringBuilder es = new StringBuilder();
//
// es.append(open);
// if (contents != null && !contents.isEmpty()) {
// es.append(contents);
// if (pad) {
// es.insert(open.length(), PAD).append(PAD);
// }
// } else {
// es.append(PAD);
// }
// es.append(close);
//
// return es.toString();
// }
// }
| import java.util.Optional;
import com.anqit.spanqit.constraint.Expression;
import com.anqit.spanqit.core.QueryElement;
import com.anqit.spanqit.core.SpanqitUtils; | package com.anqit.spanqit.graphpattern;
/**
* A SPARQL Filter Clause
*
* @see <a href="http://www.w3.org/TR/sparql11-query/#termConstraint"> SPARQL
* Filter</a>
*/
class Filter implements QueryElement {
private static final String FILTER = "FILTER"; | // Path: src/main/java/com/anqit/spanqit/constraint/Expression.java
// public abstract class Expression<T extends Expression<T>> extends
// QueryElementCollection<Operand> implements Operand,
// Orderable, Groupable, Assignable {
// protected SparqlOperator operator;
// private boolean parenthesize;
//
// Expression(SparqlOperator operator) {
// this(operator, " " + operator.getQueryString() + " ");
// }
//
// Expression(SparqlOperator operator, String delimeter) {
// super(delimeter, new ArrayList<Operand>());
// this.operator = operator;
// parenthesize(false);
// }
//
// @SuppressWarnings("unchecked")
// T addOperand(Operand... operands) {
// for (Operand operand : operands) {
// elements.add(operand);
// }
//
// return (T) this;
// }
//
// /**
// * Indicate that this expression should be wrapped in parentheses
// * when converted to a query string
// *
// * @return this
// */
// public T parenthesize() {
// return parenthesize(true);
// }
//
// /**
// * Indicate if this expression should be wrapped in parentheses
// * when converted to a query string
// *
// * @param parenthesize
// * @return this
// */
// @SuppressWarnings("unchecked")
// public T parenthesize(boolean parenthesize) {
// this.parenthesize = parenthesize;
//
// return (T) this;
// }
//
// Operand getOperand(int index) {
// return ((ArrayList<Operand>) elements).get(index);
// }
//
// @Override
// public String getQueryString() {
// String queryString = super.getQueryString();
//
// return parenthesize ? SpanqitUtils.getParenthesizedString(queryString) : queryString;
// }
// }
//
// Path: src/main/java/com/anqit/spanqit/core/QueryElement.java
// public interface QueryElement {
// /**
// * @return the String representing the SPARQL syntax of this element
// */
// public String getQueryString();
// }
//
// Path: src/main/java/com/anqit/spanqit/core/SpanqitUtils.java
// @SuppressWarnings("javadoc")
// public class SpanqitUtils {
// private static final String PAD = " ";
//
// public static <O> Optional<O> getOrCreateAndModifyOptional(Optional<O> optional, Supplier<O> getter, UnaryOperator<O> operator) {
// return Optional.of(operator.apply(optional.orElseGet(getter)));
// }
//
// public static void appendAndNewlineIfPresent(Optional<? extends QueryElement> elementOptional, StringBuilder builder) {
// appendQueryElementIfPresent(elementOptional, builder, null, "\n");
// }
//
// public static void appendQueryElementIfPresent(Optional<? extends QueryElement> queryElementOptional, StringBuilder builder, String prefix, String suffix) {
// appendStringIfPresent(queryElementOptional.map(QueryElement::getQueryString), builder, prefix, suffix);
// }
//
// public static void appendStringIfPresent(Optional<String> stringOptional, StringBuilder builder, String prefix, String suffix) {
// Optional<String> preOpt = Optional.ofNullable(prefix);
// Optional<String> sufOpt = Optional.ofNullable(suffix);
//
// stringOptional.ifPresent(string -> {
// preOpt.ifPresent(p -> builder.append(p));
// builder.append(string);
// sufOpt.ifPresent(s -> builder.append(s));
// });
// }
//
// public static String getBracedString(String contents) {
// return getEnclosedString("{", "}", contents);
// }
//
// public static String getBracketedString(String contents) {
// return getEnclosedString("[", "]", contents);
// }
//
// public static String getParenthesizedString(String contents) {
// return getEnclosedString("(", ")", contents);
// }
//
// public static String getQuotedString(String contents) {
// return getEnclosedString("\"", "\"", contents, false);
// }
//
// /**
// * For string literals that contain single- or double-quotes
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#QSynLiterals">
// * RDF Literal Syntax</a>
// * @param contents
// * @return a "long quoted" string
// */
// public static String getLongQuotedString(String contents) {
// return getEnclosedString("'''", "'''", contents, false);
// }
//
// private static String getEnclosedString(String open, String close,
// String contents) {
// return getEnclosedString(open, close, contents, true);
// }
//
// private static String getEnclosedString(String open, String close,
// String contents, boolean pad) {
// StringBuilder es = new StringBuilder();
//
// es.append(open);
// if (contents != null && !contents.isEmpty()) {
// es.append(contents);
// if (pad) {
// es.insert(open.length(), PAD).append(PAD);
// }
// } else {
// es.append(PAD);
// }
// es.append(close);
//
// return es.toString();
// }
// }
// Path: src/main/java/com/anqit/spanqit/graphpattern/Filter.java
import java.util.Optional;
import com.anqit.spanqit.constraint.Expression;
import com.anqit.spanqit.core.QueryElement;
import com.anqit.spanqit.core.SpanqitUtils;
package com.anqit.spanqit.graphpattern;
/**
* A SPARQL Filter Clause
*
* @see <a href="http://www.w3.org/TR/sparql11-query/#termConstraint"> SPARQL
* Filter</a>
*/
class Filter implements QueryElement {
private static final String FILTER = "FILTER"; | private Optional<Expression<?>> constraint = Optional.empty(); |
anqit/spanqit | src/main/java/com/anqit/spanqit/graphpattern/BNodeTriplePattern.java | // Path: src/main/java/com/anqit/spanqit/rdf/RdfBlankNode.java
// public static class PropertiesBlankNode implements RdfBlankNode {
// private RdfPredicateObjectListCollection predicateObjectLists = Rdf.predicateObjectListCollection();
//
// PropertiesBlankNode(RdfPredicate predicate, RdfObject... objects) {
// andHas(predicate, objects);
// }
//
// /**
// * Using the predicate-object and object list mechanisms, expand this blank node's pattern to include
// * triples consisting of this blank node as the subject, and the given predicate and object(s)
// *
// * @param predicate the predicate of the triple to add
// * @param objects the object or objects of the triple to add
// *
// * @return this blank node
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#predObjLists">
// * Predicate-Object Lists</a>
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#objLists">
// * Object Lists</a>
// */
// public PropertiesBlankNode andHas(RdfPredicate predicate, RdfObject... objects) {
// predicateObjectLists.andHas(predicate, objects);
//
// return this;
// }
//
// /**
// * Add predicate-object lists to this blank node's pattern
// *
// * @param lists
// * the {@link RdfPredicateObjectList}(s) to add
// * @return this blank node
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#predObjLists">
// * Predicate-Object Lists</a>
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#objLists">
// * Object Lists</a>
// */
// public PropertiesBlankNode andHas(RdfPredicateObjectList... lists) {
// predicateObjectLists.andHas(lists);
//
// return this;
// }
// /**
// * convert this blank node to a triple pattern
// *
// * @return the triple pattern identified by this blank node
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#QSynBlankNodes">
// * blank node syntax</a>
// */
// public TriplePattern toTp() {
// return GraphPatterns.tp(this);
// }
//
// @Override
// public String getQueryString() {
// return SpanqitUtils.getBracketedString(predicateObjectLists.getQueryString());
// }
// }
//
// Path: src/main/java/com/anqit/spanqit/rdf/RdfPredicateObjectList.java
// public class RdfPredicateObjectList extends QueryElementCollection<RdfObject> {
// private RdfPredicate predicate;
//
// RdfPredicateObjectList(RdfPredicate predicate, RdfObject... objects) {
// super(", ");
// this.predicate = predicate;
// and(objects);
// }
//
// /**
// * Add {@link RdfObject} instances to this predicate-object list
// *
// * @param objects the objects to add to this list
// *
// * @return this {@link RdfPredicateObjectList} instance
// */
// public RdfPredicateObjectList and(RdfObject... objects) {
// Collections.addAll(elements, objects);
//
// return this;
// }
//
// @Override
// public String getQueryString() {
// return predicate.getQueryString() + " " + super.getQueryString();
// }
// }
| import com.anqit.spanqit.rdf.RdfBlankNode.PropertiesBlankNode;
import com.anqit.spanqit.rdf.RdfPredicateObjectList; | package com.anqit.spanqit.graphpattern;
/**
* A triple pattern formed by a property-list blank node
*
* @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#QSynBlankNodes">
* blank node syntax</a>
*/
class BNodeTriplePattern implements TriplePattern {
private PropertiesBlankNode bnode;
BNodeTriplePattern(PropertiesBlankNode subject) {
this.bnode = subject;
}
@Override | // Path: src/main/java/com/anqit/spanqit/rdf/RdfBlankNode.java
// public static class PropertiesBlankNode implements RdfBlankNode {
// private RdfPredicateObjectListCollection predicateObjectLists = Rdf.predicateObjectListCollection();
//
// PropertiesBlankNode(RdfPredicate predicate, RdfObject... objects) {
// andHas(predicate, objects);
// }
//
// /**
// * Using the predicate-object and object list mechanisms, expand this blank node's pattern to include
// * triples consisting of this blank node as the subject, and the given predicate and object(s)
// *
// * @param predicate the predicate of the triple to add
// * @param objects the object or objects of the triple to add
// *
// * @return this blank node
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#predObjLists">
// * Predicate-Object Lists</a>
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#objLists">
// * Object Lists</a>
// */
// public PropertiesBlankNode andHas(RdfPredicate predicate, RdfObject... objects) {
// predicateObjectLists.andHas(predicate, objects);
//
// return this;
// }
//
// /**
// * Add predicate-object lists to this blank node's pattern
// *
// * @param lists
// * the {@link RdfPredicateObjectList}(s) to add
// * @return this blank node
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#predObjLists">
// * Predicate-Object Lists</a>
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#objLists">
// * Object Lists</a>
// */
// public PropertiesBlankNode andHas(RdfPredicateObjectList... lists) {
// predicateObjectLists.andHas(lists);
//
// return this;
// }
// /**
// * convert this blank node to a triple pattern
// *
// * @return the triple pattern identified by this blank node
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#QSynBlankNodes">
// * blank node syntax</a>
// */
// public TriplePattern toTp() {
// return GraphPatterns.tp(this);
// }
//
// @Override
// public String getQueryString() {
// return SpanqitUtils.getBracketedString(predicateObjectLists.getQueryString());
// }
// }
//
// Path: src/main/java/com/anqit/spanqit/rdf/RdfPredicateObjectList.java
// public class RdfPredicateObjectList extends QueryElementCollection<RdfObject> {
// private RdfPredicate predicate;
//
// RdfPredicateObjectList(RdfPredicate predicate, RdfObject... objects) {
// super(", ");
// this.predicate = predicate;
// and(objects);
// }
//
// /**
// * Add {@link RdfObject} instances to this predicate-object list
// *
// * @param objects the objects to add to this list
// *
// * @return this {@link RdfPredicateObjectList} instance
// */
// public RdfPredicateObjectList and(RdfObject... objects) {
// Collections.addAll(elements, objects);
//
// return this;
// }
//
// @Override
// public String getQueryString() {
// return predicate.getQueryString() + " " + super.getQueryString();
// }
// }
// Path: src/main/java/com/anqit/spanqit/graphpattern/BNodeTriplePattern.java
import com.anqit.spanqit.rdf.RdfBlankNode.PropertiesBlankNode;
import com.anqit.spanqit.rdf.RdfPredicateObjectList;
package com.anqit.spanqit.graphpattern;
/**
* A triple pattern formed by a property-list blank node
*
* @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#QSynBlankNodes">
* blank node syntax</a>
*/
class BNodeTriplePattern implements TriplePattern {
private PropertiesBlankNode bnode;
BNodeTriplePattern(PropertiesBlankNode subject) {
this.bnode = subject;
}
@Override | public BNodeTriplePattern andHas(RdfPredicateObjectList... lists) { |
anqit/spanqit | src/main/java/com/anqit/spanqit/core/Variable.java | // Path: src/main/java/com/anqit/spanqit/constraint/Operand.java
// public interface Operand extends QueryElement { }
//
// Path: src/main/java/com/anqit/spanqit/graphpattern/GraphName.java
// public interface GraphName extends QueryElement { }
//
// Path: src/main/java/com/anqit/spanqit/rdf/RdfObject.java
// public interface RdfObject extends QueryElement { }
//
// Path: src/main/java/com/anqit/spanqit/rdf/RdfPredicate.java
// public interface RdfPredicate extends QueryElement {
// /**
// * The built-in predicate shortcut for <code>rdf:type</code>
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#abbrevRdfType">
// * RDF Type abbreviation</a>
// */
// public static RdfPredicate a = () -> "a";
// }
//
// Path: src/main/java/com/anqit/spanqit/rdf/RdfSubject.java
// public interface RdfSubject extends QueryElement {
// /**
// * Create a triple pattern from this subject and the given predicate and
// * object
// *
// * @param predicate
// * the predicate of the triple pattern
// * @param objects
// * the object(s) of the triple pattern
// * @return a new {@link TriplePattern} with this subject, and the given predicate and object(s)
// *
// * @see <a
// * href="http://www.w3.org/TR/2013/REC-sparql11-query-20130321/#QSynTriples">
// * Triple pattern syntax</a>
// */
// default public TriplePattern has(RdfPredicate predicate, RdfObject... objects) {
// return GraphPatterns.tp(this, predicate, objects);
// }
//
// /**
// * Create a triple pattern from this subject and the given predicate-object list(s)
// * @param lists
// * the {@link RdfPredicateObjectList}(s) to describing this subject
// * @return a new {@link TriplePattern} with this subject, and the given predicate-object list(s)
// */
// default public TriplePattern has(RdfPredicateObjectList... lists) {
// return GraphPatterns.tp(this, lists);
// }
//
// /**
// * Wrapper for {@link #has(RdfPredicate, RdfObject...)} that converts String objects into RdfLiteral instances
// *
// * @param predicate
// * the predicate of the triple pattern
// * @param objects
// * the String object(s) of the triple pattern
// * @return a new {@link TriplePattern} with this subject, and the given predicate and object(s)
// */
// default public TriplePattern has(RdfPredicate predicate, String... objects) {
// return GraphPatterns.tp(this, predicate, toRdfLiteralArray(objects));
// }
//
// /**
// * Wrapper for {@link #has(RdfPredicate, RdfObject...)} that converts Number objects into RdfLiteral instances
// *
// * @param predicate
// * the predicate of the triple pattern
// * @param objects
// * the Number object(s) of the triple pattern
// * @return a new {@link TriplePattern} with this subject, and the given predicate and object(s)
// */
// default public TriplePattern has(RdfPredicate predicate, Number... objects) {
// return GraphPatterns.tp(this, predicate, toRdfLiteralArray(objects));
// }
//
// /**
// * Wrapper for {@link #has(RdfPredicate, RdfObject...)} that converts Boolean objects into RdfLiteral instances
// *
// * @param predicate
// * the predicate of the triple pattern
// * @param objects
// * the Boolean object(s) of the triple pattern
// * @return a new {@link TriplePattern} with this subject, and the given predicate and object(s)
// */
// default public TriplePattern has(RdfPredicate predicate, Boolean... objects) {
// return GraphPatterns.tp(this, predicate, toRdfLiteralArray(objects));
// }
//
// /**
// * Use the built-in shortcut "a" for <code>rdf:type</code> to build a triple with this subject and the given objects
// * @param objects the objects to use to describe the <code>rdf:type</code> of this subject
// *
// * @return a {@link TriplePattern} object with this subject, the "a" shortcut predicate, and the given objects
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#abbrevRdfType">
// * RDF Type abbreviation</a>
// */
// default public TriplePattern isA(RdfObject... objects) {
// return has(RdfPredicate.a, objects);
// }
// }
| import com.anqit.spanqit.constraint.Operand;
import com.anqit.spanqit.graphpattern.GraphName;
import com.anqit.spanqit.rdf.RdfObject;
import com.anqit.spanqit.rdf.RdfPredicate;
import com.anqit.spanqit.rdf.RdfSubject;
| package com.anqit.spanqit.core;
/**
* A SPARQL query variable
*
* @see <a
* href="http://www.w3.org/TR/2013/REC-sparql11-query-20130321/#QSynVariables">
* SPARQL Variable Syntax</a>
*/
public class Variable implements Projectable, RdfSubject,
RdfPredicate, RdfObject, Operand, Orderable,
| // Path: src/main/java/com/anqit/spanqit/constraint/Operand.java
// public interface Operand extends QueryElement { }
//
// Path: src/main/java/com/anqit/spanqit/graphpattern/GraphName.java
// public interface GraphName extends QueryElement { }
//
// Path: src/main/java/com/anqit/spanqit/rdf/RdfObject.java
// public interface RdfObject extends QueryElement { }
//
// Path: src/main/java/com/anqit/spanqit/rdf/RdfPredicate.java
// public interface RdfPredicate extends QueryElement {
// /**
// * The built-in predicate shortcut for <code>rdf:type</code>
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#abbrevRdfType">
// * RDF Type abbreviation</a>
// */
// public static RdfPredicate a = () -> "a";
// }
//
// Path: src/main/java/com/anqit/spanqit/rdf/RdfSubject.java
// public interface RdfSubject extends QueryElement {
// /**
// * Create a triple pattern from this subject and the given predicate and
// * object
// *
// * @param predicate
// * the predicate of the triple pattern
// * @param objects
// * the object(s) of the triple pattern
// * @return a new {@link TriplePattern} with this subject, and the given predicate and object(s)
// *
// * @see <a
// * href="http://www.w3.org/TR/2013/REC-sparql11-query-20130321/#QSynTriples">
// * Triple pattern syntax</a>
// */
// default public TriplePattern has(RdfPredicate predicate, RdfObject... objects) {
// return GraphPatterns.tp(this, predicate, objects);
// }
//
// /**
// * Create a triple pattern from this subject and the given predicate-object list(s)
// * @param lists
// * the {@link RdfPredicateObjectList}(s) to describing this subject
// * @return a new {@link TriplePattern} with this subject, and the given predicate-object list(s)
// */
// default public TriplePattern has(RdfPredicateObjectList... lists) {
// return GraphPatterns.tp(this, lists);
// }
//
// /**
// * Wrapper for {@link #has(RdfPredicate, RdfObject...)} that converts String objects into RdfLiteral instances
// *
// * @param predicate
// * the predicate of the triple pattern
// * @param objects
// * the String object(s) of the triple pattern
// * @return a new {@link TriplePattern} with this subject, and the given predicate and object(s)
// */
// default public TriplePattern has(RdfPredicate predicate, String... objects) {
// return GraphPatterns.tp(this, predicate, toRdfLiteralArray(objects));
// }
//
// /**
// * Wrapper for {@link #has(RdfPredicate, RdfObject...)} that converts Number objects into RdfLiteral instances
// *
// * @param predicate
// * the predicate of the triple pattern
// * @param objects
// * the Number object(s) of the triple pattern
// * @return a new {@link TriplePattern} with this subject, and the given predicate and object(s)
// */
// default public TriplePattern has(RdfPredicate predicate, Number... objects) {
// return GraphPatterns.tp(this, predicate, toRdfLiteralArray(objects));
// }
//
// /**
// * Wrapper for {@link #has(RdfPredicate, RdfObject...)} that converts Boolean objects into RdfLiteral instances
// *
// * @param predicate
// * the predicate of the triple pattern
// * @param objects
// * the Boolean object(s) of the triple pattern
// * @return a new {@link TriplePattern} with this subject, and the given predicate and object(s)
// */
// default public TriplePattern has(RdfPredicate predicate, Boolean... objects) {
// return GraphPatterns.tp(this, predicate, toRdfLiteralArray(objects));
// }
//
// /**
// * Use the built-in shortcut "a" for <code>rdf:type</code> to build a triple with this subject and the given objects
// * @param objects the objects to use to describe the <code>rdf:type</code> of this subject
// *
// * @return a {@link TriplePattern} object with this subject, the "a" shortcut predicate, and the given objects
// *
// * @see <a href="https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#abbrevRdfType">
// * RDF Type abbreviation</a>
// */
// default public TriplePattern isA(RdfObject... objects) {
// return has(RdfPredicate.a, objects);
// }
// }
// Path: src/main/java/com/anqit/spanqit/core/Variable.java
import com.anqit.spanqit.constraint.Operand;
import com.anqit.spanqit.graphpattern.GraphName;
import com.anqit.spanqit.rdf.RdfObject;
import com.anqit.spanqit.rdf.RdfPredicate;
import com.anqit.spanqit.rdf.RdfSubject;
package com.anqit.spanqit.core;
/**
* A SPARQL query variable
*
* @see <a
* href="http://www.w3.org/TR/2013/REC-sparql11-query-20130321/#QSynVariables">
* SPARQL Variable Syntax</a>
*/
public class Variable implements Projectable, RdfSubject,
RdfPredicate, RdfObject, Operand, Orderable,
| Groupable, GraphName, Assignable {
|
anqit/spanqit | src/main/java/com/anqit/spanqit/core/Base.java | // Path: src/main/java/com/anqit/spanqit/rdf/Iri.java
// public interface Iri extends RdfResource, RdfPredicate, GraphName { }
| import com.anqit.spanqit.rdf.Iri; | package com.anqit.spanqit.core;
/**
* A SPARQL Base declaration
*
* @see <a
* href="http://www.w3.org/TR/2013/REC-sparql11-query-20130321/#relIRIs">
* SPARQL Relative IRIs</a>
*/
public class Base implements QueryElement {
private static final String BASE = "BASE ";
| // Path: src/main/java/com/anqit/spanqit/rdf/Iri.java
// public interface Iri extends RdfResource, RdfPredicate, GraphName { }
// Path: src/main/java/com/anqit/spanqit/core/Base.java
import com.anqit.spanqit.rdf.Iri;
package com.anqit.spanqit.core;
/**
* A SPARQL Base declaration
*
* @see <a
* href="http://www.w3.org/TR/2013/REC-sparql11-query-20130321/#relIRIs">
* SPARQL Relative IRIs</a>
*/
public class Base implements QueryElement {
private static final String BASE = "BASE ";
| private Iri iri; |
WeMakeBetterApps/MortarLib | sample/src/main/java/mortar/lib/sample/screen/SampleScreen2.java | // Path: lib/src/main/java/mortar/lib/presenter/ResumeAndPausePresenter.java
// public abstract class ResumeAndPausePresenter<V extends View> extends ViewPresenter<V>
// implements ResumesAndPauses {
//
// private ResumeAndPauseOwner mResumeAndPauseOwner = null;
// private boolean mIsRunning = false;
//
// @Override protected void onEnterScope(MortarScope scope) {
// super.onEnterScope(scope);
//
// Activity activity = MortarUtil.getActivity(getView().getContext());
// if (activity instanceof ResumeAndPauseActivity) {
// mResumeAndPauseOwner = ((ResumeAndPauseActivity) activity).getResumeAndPausePresenter();
// } else {
// throw new RuntimeException(String.format("Cannot use %s inside an activity that doesn't " +
// "implement %s.", ResumeAndPausePresenter.class.getSimpleName(),
// ResumeAndPauseActivity.class.getSimpleName()));
// }
//
// mResumeAndPauseOwner.register(scope, this);
// }
//
// @Override public void onResume() {
// mIsRunning = true;
// }
//
// @Override public void onPause() {
// mIsRunning = false;
// }
//
// @Override protected void onExitScope() {
// if (mIsRunning) {
// // Mortar keeps it's scoped in a HashMap which doesn't keep order.
// // Without this sometimes onPause would run after onExitScope, and other times before.
// onPause();
// }
// super.onExitScope();
// }
//
// @Override public boolean isRunning() {
// return mIsRunning;
// }
// }
//
// Path: sample/src/main/java/view/SampleView2.java
// public class SampleView2 extends MortarLinearLayout {
//
// @Inject SampleScreen2.Presenter2 mPresenter;
//
// public SampleView2(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// @Override protected ViewPresenter getPresenter() {
// return mPresenter;
// }
//
// @OnClick(R.id.toScreen1) public void onToScreen1Click() {
// mPresenter.goToScreen1();
// }
//
// }
| import android.os.Bundle;
import android.util.Log;
import javax.inject.Inject;
import javax.inject.Singleton;
import flow.Flow;
import flow.Layout;
import mortar.Blueprint;
import mortar.MortarScope;
import mortar.lib.presenter.ResumeAndPausePresenter;
import mortar.lib.sample.R;
import view.SampleView2; | package mortar.lib.sample.screen;
@Layout(R.layout.screen_sample2)
public class SampleScreen2 implements Blueprint {
@Override public String getMortarScopeName() {
return SampleScreen2.class.getName();
}
@Override public Object getDaggerModule() {
return new Module();
}
@dagger.Module(
addsTo = ActivityScreen.Module.class,
injects = {
Presenter2.class, | // Path: lib/src/main/java/mortar/lib/presenter/ResumeAndPausePresenter.java
// public abstract class ResumeAndPausePresenter<V extends View> extends ViewPresenter<V>
// implements ResumesAndPauses {
//
// private ResumeAndPauseOwner mResumeAndPauseOwner = null;
// private boolean mIsRunning = false;
//
// @Override protected void onEnterScope(MortarScope scope) {
// super.onEnterScope(scope);
//
// Activity activity = MortarUtil.getActivity(getView().getContext());
// if (activity instanceof ResumeAndPauseActivity) {
// mResumeAndPauseOwner = ((ResumeAndPauseActivity) activity).getResumeAndPausePresenter();
// } else {
// throw new RuntimeException(String.format("Cannot use %s inside an activity that doesn't " +
// "implement %s.", ResumeAndPausePresenter.class.getSimpleName(),
// ResumeAndPauseActivity.class.getSimpleName()));
// }
//
// mResumeAndPauseOwner.register(scope, this);
// }
//
// @Override public void onResume() {
// mIsRunning = true;
// }
//
// @Override public void onPause() {
// mIsRunning = false;
// }
//
// @Override protected void onExitScope() {
// if (mIsRunning) {
// // Mortar keeps it's scoped in a HashMap which doesn't keep order.
// // Without this sometimes onPause would run after onExitScope, and other times before.
// onPause();
// }
// super.onExitScope();
// }
//
// @Override public boolean isRunning() {
// return mIsRunning;
// }
// }
//
// Path: sample/src/main/java/view/SampleView2.java
// public class SampleView2 extends MortarLinearLayout {
//
// @Inject SampleScreen2.Presenter2 mPresenter;
//
// public SampleView2(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// @Override protected ViewPresenter getPresenter() {
// return mPresenter;
// }
//
// @OnClick(R.id.toScreen1) public void onToScreen1Click() {
// mPresenter.goToScreen1();
// }
//
// }
// Path: sample/src/main/java/mortar/lib/sample/screen/SampleScreen2.java
import android.os.Bundle;
import android.util.Log;
import javax.inject.Inject;
import javax.inject.Singleton;
import flow.Flow;
import flow.Layout;
import mortar.Blueprint;
import mortar.MortarScope;
import mortar.lib.presenter.ResumeAndPausePresenter;
import mortar.lib.sample.R;
import view.SampleView2;
package mortar.lib.sample.screen;
@Layout(R.layout.screen_sample2)
public class SampleScreen2 implements Blueprint {
@Override public String getMortarScopeName() {
return SampleScreen2.class.getName();
}
@Override public Object getDaggerModule() {
return new Module();
}
@dagger.Module(
addsTo = ActivityScreen.Module.class,
injects = {
Presenter2.class, | SampleView2.class |
WeMakeBetterApps/MortarLib | sample/src/main/java/mortar/lib/sample/screen/SampleScreen2.java | // Path: lib/src/main/java/mortar/lib/presenter/ResumeAndPausePresenter.java
// public abstract class ResumeAndPausePresenter<V extends View> extends ViewPresenter<V>
// implements ResumesAndPauses {
//
// private ResumeAndPauseOwner mResumeAndPauseOwner = null;
// private boolean mIsRunning = false;
//
// @Override protected void onEnterScope(MortarScope scope) {
// super.onEnterScope(scope);
//
// Activity activity = MortarUtil.getActivity(getView().getContext());
// if (activity instanceof ResumeAndPauseActivity) {
// mResumeAndPauseOwner = ((ResumeAndPauseActivity) activity).getResumeAndPausePresenter();
// } else {
// throw new RuntimeException(String.format("Cannot use %s inside an activity that doesn't " +
// "implement %s.", ResumeAndPausePresenter.class.getSimpleName(),
// ResumeAndPauseActivity.class.getSimpleName()));
// }
//
// mResumeAndPauseOwner.register(scope, this);
// }
//
// @Override public void onResume() {
// mIsRunning = true;
// }
//
// @Override public void onPause() {
// mIsRunning = false;
// }
//
// @Override protected void onExitScope() {
// if (mIsRunning) {
// // Mortar keeps it's scoped in a HashMap which doesn't keep order.
// // Without this sometimes onPause would run after onExitScope, and other times before.
// onPause();
// }
// super.onExitScope();
// }
//
// @Override public boolean isRunning() {
// return mIsRunning;
// }
// }
//
// Path: sample/src/main/java/view/SampleView2.java
// public class SampleView2 extends MortarLinearLayout {
//
// @Inject SampleScreen2.Presenter2 mPresenter;
//
// public SampleView2(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// @Override protected ViewPresenter getPresenter() {
// return mPresenter;
// }
//
// @OnClick(R.id.toScreen1) public void onToScreen1Click() {
// mPresenter.goToScreen1();
// }
//
// }
| import android.os.Bundle;
import android.util.Log;
import javax.inject.Inject;
import javax.inject.Singleton;
import flow.Flow;
import flow.Layout;
import mortar.Blueprint;
import mortar.MortarScope;
import mortar.lib.presenter.ResumeAndPausePresenter;
import mortar.lib.sample.R;
import view.SampleView2; | package mortar.lib.sample.screen;
@Layout(R.layout.screen_sample2)
public class SampleScreen2 implements Blueprint {
@Override public String getMortarScopeName() {
return SampleScreen2.class.getName();
}
@Override public Object getDaggerModule() {
return new Module();
}
@dagger.Module(
addsTo = ActivityScreen.Module.class,
injects = {
Presenter2.class,
SampleView2.class
},
library = true
)
class Module {
}
| // Path: lib/src/main/java/mortar/lib/presenter/ResumeAndPausePresenter.java
// public abstract class ResumeAndPausePresenter<V extends View> extends ViewPresenter<V>
// implements ResumesAndPauses {
//
// private ResumeAndPauseOwner mResumeAndPauseOwner = null;
// private boolean mIsRunning = false;
//
// @Override protected void onEnterScope(MortarScope scope) {
// super.onEnterScope(scope);
//
// Activity activity = MortarUtil.getActivity(getView().getContext());
// if (activity instanceof ResumeAndPauseActivity) {
// mResumeAndPauseOwner = ((ResumeAndPauseActivity) activity).getResumeAndPausePresenter();
// } else {
// throw new RuntimeException(String.format("Cannot use %s inside an activity that doesn't " +
// "implement %s.", ResumeAndPausePresenter.class.getSimpleName(),
// ResumeAndPauseActivity.class.getSimpleName()));
// }
//
// mResumeAndPauseOwner.register(scope, this);
// }
//
// @Override public void onResume() {
// mIsRunning = true;
// }
//
// @Override public void onPause() {
// mIsRunning = false;
// }
//
// @Override protected void onExitScope() {
// if (mIsRunning) {
// // Mortar keeps it's scoped in a HashMap which doesn't keep order.
// // Without this sometimes onPause would run after onExitScope, and other times before.
// onPause();
// }
// super.onExitScope();
// }
//
// @Override public boolean isRunning() {
// return mIsRunning;
// }
// }
//
// Path: sample/src/main/java/view/SampleView2.java
// public class SampleView2 extends MortarLinearLayout {
//
// @Inject SampleScreen2.Presenter2 mPresenter;
//
// public SampleView2(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// @Override protected ViewPresenter getPresenter() {
// return mPresenter;
// }
//
// @OnClick(R.id.toScreen1) public void onToScreen1Click() {
// mPresenter.goToScreen1();
// }
//
// }
// Path: sample/src/main/java/mortar/lib/sample/screen/SampleScreen2.java
import android.os.Bundle;
import android.util.Log;
import javax.inject.Inject;
import javax.inject.Singleton;
import flow.Flow;
import flow.Layout;
import mortar.Blueprint;
import mortar.MortarScope;
import mortar.lib.presenter.ResumeAndPausePresenter;
import mortar.lib.sample.R;
import view.SampleView2;
package mortar.lib.sample.screen;
@Layout(R.layout.screen_sample2)
public class SampleScreen2 implements Blueprint {
@Override public String getMortarScopeName() {
return SampleScreen2.class.getName();
}
@Override public Object getDaggerModule() {
return new Module();
}
@dagger.Module(
addsTo = ActivityScreen.Module.class,
injects = {
Presenter2.class,
SampleView2.class
},
library = true
)
class Module {
}
| @Singleton public static class Presenter2 extends ResumeAndPausePresenter<SampleView2> { |
WeMakeBetterApps/MortarLib | lib/src/main/java/mortar/lib/activity/MortarActivity.java | // Path: lib/src/main/java/mortar/lib/application/MortarApplication.java
// public abstract class MortarApplication extends Application {
//
// private MortarScope rootScope;
//
// @Override public void onCreate() {
// super.onCreate();
//
// ObjectGraph applicationGraph = ObjectGraph.create(getRootScopeModules());
// Injector.setApplicationGraph(applicationGraph);
// rootScope = Mortar.createRootScope(isBuildConfigDebug(), applicationGraph);
// }
//
// protected abstract Object[] getRootScopeModules();
//
// public abstract boolean isBuildConfigDebug();
//
// public MortarScope getRootScope() {
// return rootScope;
// }
//
// }
//
// Path: lib/src/main/java/mortar/lib/view/FlowOwnerView.java
// public abstract class FlowOwnerView extends FrameLayout implements CanShowScreen<Blueprint> {
//
// private AbstractScreenConductor<Blueprint> mScreenConductor;
//
// public FlowOwnerView(Context context, AttributeSet attrs) {
// super(context, attrs);
// Mortar.inject(context, this);
// }
//
// @Override protected void onFinishInflate() {
// super.onFinishInflate();
// ButterKnifeWrapper.get().inject(this);
// //noinspection unchecked
// mScreenConductor = createScreenConductor(getContext());
// }
//
// public Flow getFlow() {
// return getPresenter().getFlow();
// }
//
// protected abstract FlowOwner getPresenter();
//
// @Override
// public void showScreen(Blueprint screen, Flow.Direction direction) {
// mScreenConductor.showScreen(screen, direction);
// }
//
// protected AbstractScreenConductor createScreenConductor(Context context) {
// return new AnimatedScreenConductor(context, this);
// }
//
// @Override protected void onAttachedToWindow() {
// super.onAttachedToWindow();
// //noinspection unchecked
// getPresenter().takeView(this);
// }
//
// @Override protected void onDetachedFromWindow() {
// super.onDetachedFromWindow();
// //noinspection unchecked
// getPresenter().dropView(this);
// }
//
// }
| import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.ViewGroup;
import mortar.Blueprint;
import mortar.Mortar;
import mortar.MortarActivityScope;
import mortar.MortarScope;
import mortar.lib.application.MortarApplication;
import mortar.lib.view.FlowOwnerView;
import static android.content.Intent.ACTION_MAIN;
import static android.content.Intent.CATEGORY_LAUNCHER; | package mortar.lib.activity;
/**
* Hooks up the {@link mortar.MortarActivityScope}. Loads the main view
* and lets it know about up button and back button presses.
*/
public abstract class MortarActivity extends Activity implements ResumeAndPauseActivity {
private MortarActivityScope mActivityScope;
private final ResumeAndPauseOwner mResumeAndPauseOwner = new ResumeAndPauseOwner();
private boolean mIsRunning = false;
protected abstract Blueprint getNewActivityScreen();
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Application application = getApplication(); | // Path: lib/src/main/java/mortar/lib/application/MortarApplication.java
// public abstract class MortarApplication extends Application {
//
// private MortarScope rootScope;
//
// @Override public void onCreate() {
// super.onCreate();
//
// ObjectGraph applicationGraph = ObjectGraph.create(getRootScopeModules());
// Injector.setApplicationGraph(applicationGraph);
// rootScope = Mortar.createRootScope(isBuildConfigDebug(), applicationGraph);
// }
//
// protected abstract Object[] getRootScopeModules();
//
// public abstract boolean isBuildConfigDebug();
//
// public MortarScope getRootScope() {
// return rootScope;
// }
//
// }
//
// Path: lib/src/main/java/mortar/lib/view/FlowOwnerView.java
// public abstract class FlowOwnerView extends FrameLayout implements CanShowScreen<Blueprint> {
//
// private AbstractScreenConductor<Blueprint> mScreenConductor;
//
// public FlowOwnerView(Context context, AttributeSet attrs) {
// super(context, attrs);
// Mortar.inject(context, this);
// }
//
// @Override protected void onFinishInflate() {
// super.onFinishInflate();
// ButterKnifeWrapper.get().inject(this);
// //noinspection unchecked
// mScreenConductor = createScreenConductor(getContext());
// }
//
// public Flow getFlow() {
// return getPresenter().getFlow();
// }
//
// protected abstract FlowOwner getPresenter();
//
// @Override
// public void showScreen(Blueprint screen, Flow.Direction direction) {
// mScreenConductor.showScreen(screen, direction);
// }
//
// protected AbstractScreenConductor createScreenConductor(Context context) {
// return new AnimatedScreenConductor(context, this);
// }
//
// @Override protected void onAttachedToWindow() {
// super.onAttachedToWindow();
// //noinspection unchecked
// getPresenter().takeView(this);
// }
//
// @Override protected void onDetachedFromWindow() {
// super.onDetachedFromWindow();
// //noinspection unchecked
// getPresenter().dropView(this);
// }
//
// }
// Path: lib/src/main/java/mortar/lib/activity/MortarActivity.java
import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.ViewGroup;
import mortar.Blueprint;
import mortar.Mortar;
import mortar.MortarActivityScope;
import mortar.MortarScope;
import mortar.lib.application.MortarApplication;
import mortar.lib.view.FlowOwnerView;
import static android.content.Intent.ACTION_MAIN;
import static android.content.Intent.CATEGORY_LAUNCHER;
package mortar.lib.activity;
/**
* Hooks up the {@link mortar.MortarActivityScope}. Loads the main view
* and lets it know about up button and back button presses.
*/
public abstract class MortarActivity extends Activity implements ResumeAndPauseActivity {
private MortarActivityScope mActivityScope;
private final ResumeAndPauseOwner mResumeAndPauseOwner = new ResumeAndPauseOwner();
private boolean mIsRunning = false;
protected abstract Blueprint getNewActivityScreen();
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Application application = getApplication(); | if ( !(application instanceof MortarApplication) ) { |
WeMakeBetterApps/MortarLib | lib/src/main/java/mortar/lib/activity/MortarActivity.java | // Path: lib/src/main/java/mortar/lib/application/MortarApplication.java
// public abstract class MortarApplication extends Application {
//
// private MortarScope rootScope;
//
// @Override public void onCreate() {
// super.onCreate();
//
// ObjectGraph applicationGraph = ObjectGraph.create(getRootScopeModules());
// Injector.setApplicationGraph(applicationGraph);
// rootScope = Mortar.createRootScope(isBuildConfigDebug(), applicationGraph);
// }
//
// protected abstract Object[] getRootScopeModules();
//
// public abstract boolean isBuildConfigDebug();
//
// public MortarScope getRootScope() {
// return rootScope;
// }
//
// }
//
// Path: lib/src/main/java/mortar/lib/view/FlowOwnerView.java
// public abstract class FlowOwnerView extends FrameLayout implements CanShowScreen<Blueprint> {
//
// private AbstractScreenConductor<Blueprint> mScreenConductor;
//
// public FlowOwnerView(Context context, AttributeSet attrs) {
// super(context, attrs);
// Mortar.inject(context, this);
// }
//
// @Override protected void onFinishInflate() {
// super.onFinishInflate();
// ButterKnifeWrapper.get().inject(this);
// //noinspection unchecked
// mScreenConductor = createScreenConductor(getContext());
// }
//
// public Flow getFlow() {
// return getPresenter().getFlow();
// }
//
// protected abstract FlowOwner getPresenter();
//
// @Override
// public void showScreen(Blueprint screen, Flow.Direction direction) {
// mScreenConductor.showScreen(screen, direction);
// }
//
// protected AbstractScreenConductor createScreenConductor(Context context) {
// return new AnimatedScreenConductor(context, this);
// }
//
// @Override protected void onAttachedToWindow() {
// super.onAttachedToWindow();
// //noinspection unchecked
// getPresenter().takeView(this);
// }
//
// @Override protected void onDetachedFromWindow() {
// super.onDetachedFromWindow();
// //noinspection unchecked
// getPresenter().dropView(this);
// }
//
// }
| import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.ViewGroup;
import mortar.Blueprint;
import mortar.Mortar;
import mortar.MortarActivityScope;
import mortar.MortarScope;
import mortar.lib.application.MortarApplication;
import mortar.lib.view.FlowOwnerView;
import static android.content.Intent.ACTION_MAIN;
import static android.content.Intent.CATEGORY_LAUNCHER; | return mActivityScope;
}
return super.getSystemService(name);
}
@SuppressWarnings("NullableProblems")
@Override protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mActivityScope.onSaveInstanceState(outState);
}
public MortarActivityScope getMortarScope() {
return mActivityScope;
}
/**
* Dev tools and the play store (and others?) launch with a different intent, and so
* lead to a redundant instance of this activity being spawned. <a
* href="http://stackoverflow.com/questions/17702202/find-out-whether-the-current-activity-will-be-task-root-eventually-after-pendin"
* >Details</a>.
*/
protected boolean isWrongInstance() {
if (!isTaskRoot()) {
Intent intent = getIntent();
boolean isMainAction = intent.getAction() != null && intent.getAction().equals(ACTION_MAIN);
return intent.hasCategory(CATEGORY_LAUNCHER) && isMainAction;
}
return false;
}
| // Path: lib/src/main/java/mortar/lib/application/MortarApplication.java
// public abstract class MortarApplication extends Application {
//
// private MortarScope rootScope;
//
// @Override public void onCreate() {
// super.onCreate();
//
// ObjectGraph applicationGraph = ObjectGraph.create(getRootScopeModules());
// Injector.setApplicationGraph(applicationGraph);
// rootScope = Mortar.createRootScope(isBuildConfigDebug(), applicationGraph);
// }
//
// protected abstract Object[] getRootScopeModules();
//
// public abstract boolean isBuildConfigDebug();
//
// public MortarScope getRootScope() {
// return rootScope;
// }
//
// }
//
// Path: lib/src/main/java/mortar/lib/view/FlowOwnerView.java
// public abstract class FlowOwnerView extends FrameLayout implements CanShowScreen<Blueprint> {
//
// private AbstractScreenConductor<Blueprint> mScreenConductor;
//
// public FlowOwnerView(Context context, AttributeSet attrs) {
// super(context, attrs);
// Mortar.inject(context, this);
// }
//
// @Override protected void onFinishInflate() {
// super.onFinishInflate();
// ButterKnifeWrapper.get().inject(this);
// //noinspection unchecked
// mScreenConductor = createScreenConductor(getContext());
// }
//
// public Flow getFlow() {
// return getPresenter().getFlow();
// }
//
// protected abstract FlowOwner getPresenter();
//
// @Override
// public void showScreen(Blueprint screen, Flow.Direction direction) {
// mScreenConductor.showScreen(screen, direction);
// }
//
// protected AbstractScreenConductor createScreenConductor(Context context) {
// return new AnimatedScreenConductor(context, this);
// }
//
// @Override protected void onAttachedToWindow() {
// super.onAttachedToWindow();
// //noinspection unchecked
// getPresenter().takeView(this);
// }
//
// @Override protected void onDetachedFromWindow() {
// super.onDetachedFromWindow();
// //noinspection unchecked
// getPresenter().dropView(this);
// }
//
// }
// Path: lib/src/main/java/mortar/lib/activity/MortarActivity.java
import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.ViewGroup;
import mortar.Blueprint;
import mortar.Mortar;
import mortar.MortarActivityScope;
import mortar.MortarScope;
import mortar.lib.application.MortarApplication;
import mortar.lib.view.FlowOwnerView;
import static android.content.Intent.ACTION_MAIN;
import static android.content.Intent.CATEGORY_LAUNCHER;
return mActivityScope;
}
return super.getSystemService(name);
}
@SuppressWarnings("NullableProblems")
@Override protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mActivityScope.onSaveInstanceState(outState);
}
public MortarActivityScope getMortarScope() {
return mActivityScope;
}
/**
* Dev tools and the play store (and others?) launch with a different intent, and so
* lead to a redundant instance of this activity being spawned. <a
* href="http://stackoverflow.com/questions/17702202/find-out-whether-the-current-activity-will-be-task-root-eventually-after-pendin"
* >Details</a>.
*/
protected boolean isWrongInstance() {
if (!isTaskRoot()) {
Intent intent = getIntent();
boolean isMainAction = intent.getAction() != null && intent.getAction().equals(ACTION_MAIN);
return intent.hasCategory(CATEGORY_LAUNCHER) && isMainAction;
}
return false;
}
| protected FlowOwnerView getMainView() { |
WeMakeBetterApps/MortarLib | sample/src/main/java/mortar/lib/sample/application/SampleModule.java | // Path: sample/src/main/java/mortar/lib/sample/activity/MainActivity.java
// public class MainActivity extends MortarActivity {
//
// @Override protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// }
//
// @Override protected Blueprint getNewActivityScreen() {
// return new ActivityScreen();
// }
//
// }
//
// Path: lib/src/main/java/mortar/lib/util/GsonParcer.java
// public class GsonParcer<T> implements Parcer<T> {
//
// private final Gson gson;
//
// public GsonParcer() {
// this(new Gson());
// }
//
// public GsonParcer(Gson gson) {
// this.gson = gson;
// }
//
// @Override public Parcelable wrap(T instance) {
// try {
// String json = encode(instance);
// return new Wrapper(json);
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// @Override public T unwrap(Parcelable parcelable) {
// Wrapper wrapper = (Wrapper) parcelable;
// try {
// return decode(wrapper.json);
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// private String encode(T instance) throws IOException {
// StringWriter stringWriter = new StringWriter();
// JsonWriter writer = new JsonWriter(stringWriter);
//
// try {
// Class<?> type = instance.getClass();
//
// writer.beginObject();
// writer.name(type.getName());
// gson.toJson(instance, type, writer);
// writer.endObject();
//
// return stringWriter.toString();
// } finally {
// writer.close();
// }
// }
//
// private T decode(String json) throws IOException {
// JsonReader reader = new JsonReader(new StringReader(json));
//
// try {
// reader.beginObject();
//
// Class<?> type = Class.forName(reader.nextName());
// return gson.fromJson(reader, type);
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// } finally {
// reader.close();
// }
// }
//
// private static class Wrapper implements Parcelable {
// final String json;
//
// Wrapper(String json) {
// this.json = json;
// }
//
// @Override public int describeContents() {
// return 0;
// }
//
// @Override public void writeToParcel(Parcel out, int flags) {
// out.writeString(json);
// }
//
// @SuppressWarnings("UnusedDeclaration")
// public static final Parcelable.Creator<Wrapper> CREATOR = new Parcelable.Creator<Wrapper>() {
// @Override public Wrapper createFromParcel(Parcel in) {
// String json = in.readString();
// return new Wrapper(json);
// }
//
// @Override public Wrapper[] newArray(int size) {
// return new Wrapper[size];
// }
// };
// }
// }
| import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import flow.Parcer;
import mortar.lib.sample.activity.MainActivity;
import mortar.lib.util.GsonParcer; | package mortar.lib.sample.application;
@Module(
injects = { | // Path: sample/src/main/java/mortar/lib/sample/activity/MainActivity.java
// public class MainActivity extends MortarActivity {
//
// @Override protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// }
//
// @Override protected Blueprint getNewActivityScreen() {
// return new ActivityScreen();
// }
//
// }
//
// Path: lib/src/main/java/mortar/lib/util/GsonParcer.java
// public class GsonParcer<T> implements Parcer<T> {
//
// private final Gson gson;
//
// public GsonParcer() {
// this(new Gson());
// }
//
// public GsonParcer(Gson gson) {
// this.gson = gson;
// }
//
// @Override public Parcelable wrap(T instance) {
// try {
// String json = encode(instance);
// return new Wrapper(json);
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// @Override public T unwrap(Parcelable parcelable) {
// Wrapper wrapper = (Wrapper) parcelable;
// try {
// return decode(wrapper.json);
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// private String encode(T instance) throws IOException {
// StringWriter stringWriter = new StringWriter();
// JsonWriter writer = new JsonWriter(stringWriter);
//
// try {
// Class<?> type = instance.getClass();
//
// writer.beginObject();
// writer.name(type.getName());
// gson.toJson(instance, type, writer);
// writer.endObject();
//
// return stringWriter.toString();
// } finally {
// writer.close();
// }
// }
//
// private T decode(String json) throws IOException {
// JsonReader reader = new JsonReader(new StringReader(json));
//
// try {
// reader.beginObject();
//
// Class<?> type = Class.forName(reader.nextName());
// return gson.fromJson(reader, type);
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// } finally {
// reader.close();
// }
// }
//
// private static class Wrapper implements Parcelable {
// final String json;
//
// Wrapper(String json) {
// this.json = json;
// }
//
// @Override public int describeContents() {
// return 0;
// }
//
// @Override public void writeToParcel(Parcel out, int flags) {
// out.writeString(json);
// }
//
// @SuppressWarnings("UnusedDeclaration")
// public static final Parcelable.Creator<Wrapper> CREATOR = new Parcelable.Creator<Wrapper>() {
// @Override public Wrapper createFromParcel(Parcel in) {
// String json = in.readString();
// return new Wrapper(json);
// }
//
// @Override public Wrapper[] newArray(int size) {
// return new Wrapper[size];
// }
// };
// }
// }
// Path: sample/src/main/java/mortar/lib/sample/application/SampleModule.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import flow.Parcer;
import mortar.lib.sample.activity.MainActivity;
import mortar.lib.util.GsonParcer;
package mortar.lib.sample.application;
@Module(
injects = { | MainActivity.class |
WeMakeBetterApps/MortarLib | sample/src/main/java/mortar/lib/sample/application/SampleModule.java | // Path: sample/src/main/java/mortar/lib/sample/activity/MainActivity.java
// public class MainActivity extends MortarActivity {
//
// @Override protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// }
//
// @Override protected Blueprint getNewActivityScreen() {
// return new ActivityScreen();
// }
//
// }
//
// Path: lib/src/main/java/mortar/lib/util/GsonParcer.java
// public class GsonParcer<T> implements Parcer<T> {
//
// private final Gson gson;
//
// public GsonParcer() {
// this(new Gson());
// }
//
// public GsonParcer(Gson gson) {
// this.gson = gson;
// }
//
// @Override public Parcelable wrap(T instance) {
// try {
// String json = encode(instance);
// return new Wrapper(json);
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// @Override public T unwrap(Parcelable parcelable) {
// Wrapper wrapper = (Wrapper) parcelable;
// try {
// return decode(wrapper.json);
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// private String encode(T instance) throws IOException {
// StringWriter stringWriter = new StringWriter();
// JsonWriter writer = new JsonWriter(stringWriter);
//
// try {
// Class<?> type = instance.getClass();
//
// writer.beginObject();
// writer.name(type.getName());
// gson.toJson(instance, type, writer);
// writer.endObject();
//
// return stringWriter.toString();
// } finally {
// writer.close();
// }
// }
//
// private T decode(String json) throws IOException {
// JsonReader reader = new JsonReader(new StringReader(json));
//
// try {
// reader.beginObject();
//
// Class<?> type = Class.forName(reader.nextName());
// return gson.fromJson(reader, type);
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// } finally {
// reader.close();
// }
// }
//
// private static class Wrapper implements Parcelable {
// final String json;
//
// Wrapper(String json) {
// this.json = json;
// }
//
// @Override public int describeContents() {
// return 0;
// }
//
// @Override public void writeToParcel(Parcel out, int flags) {
// out.writeString(json);
// }
//
// @SuppressWarnings("UnusedDeclaration")
// public static final Parcelable.Creator<Wrapper> CREATOR = new Parcelable.Creator<Wrapper>() {
// @Override public Wrapper createFromParcel(Parcel in) {
// String json = in.readString();
// return new Wrapper(json);
// }
//
// @Override public Wrapper[] newArray(int size) {
// return new Wrapper[size];
// }
// };
// }
// }
| import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import flow.Parcer;
import mortar.lib.sample.activity.MainActivity;
import mortar.lib.util.GsonParcer; | package mortar.lib.sample.application;
@Module(
injects = {
MainActivity.class
},
library = true
)
public class SampleModule {
private SampleApplication mApplication;
public SampleModule(SampleApplication application) {
mApplication = application;
}
@Provides @Singleton Gson provideGson() {
return new GsonBuilder()
.create();
}
@Provides @Singleton Parcer<Object> provideParcer(Gson gson) { | // Path: sample/src/main/java/mortar/lib/sample/activity/MainActivity.java
// public class MainActivity extends MortarActivity {
//
// @Override protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// }
//
// @Override protected Blueprint getNewActivityScreen() {
// return new ActivityScreen();
// }
//
// }
//
// Path: lib/src/main/java/mortar/lib/util/GsonParcer.java
// public class GsonParcer<T> implements Parcer<T> {
//
// private final Gson gson;
//
// public GsonParcer() {
// this(new Gson());
// }
//
// public GsonParcer(Gson gson) {
// this.gson = gson;
// }
//
// @Override public Parcelable wrap(T instance) {
// try {
// String json = encode(instance);
// return new Wrapper(json);
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// @Override public T unwrap(Parcelable parcelable) {
// Wrapper wrapper = (Wrapper) parcelable;
// try {
// return decode(wrapper.json);
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// private String encode(T instance) throws IOException {
// StringWriter stringWriter = new StringWriter();
// JsonWriter writer = new JsonWriter(stringWriter);
//
// try {
// Class<?> type = instance.getClass();
//
// writer.beginObject();
// writer.name(type.getName());
// gson.toJson(instance, type, writer);
// writer.endObject();
//
// return stringWriter.toString();
// } finally {
// writer.close();
// }
// }
//
// private T decode(String json) throws IOException {
// JsonReader reader = new JsonReader(new StringReader(json));
//
// try {
// reader.beginObject();
//
// Class<?> type = Class.forName(reader.nextName());
// return gson.fromJson(reader, type);
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// } finally {
// reader.close();
// }
// }
//
// private static class Wrapper implements Parcelable {
// final String json;
//
// Wrapper(String json) {
// this.json = json;
// }
//
// @Override public int describeContents() {
// return 0;
// }
//
// @Override public void writeToParcel(Parcel out, int flags) {
// out.writeString(json);
// }
//
// @SuppressWarnings("UnusedDeclaration")
// public static final Parcelable.Creator<Wrapper> CREATOR = new Parcelable.Creator<Wrapper>() {
// @Override public Wrapper createFromParcel(Parcel in) {
// String json = in.readString();
// return new Wrapper(json);
// }
//
// @Override public Wrapper[] newArray(int size) {
// return new Wrapper[size];
// }
// };
// }
// }
// Path: sample/src/main/java/mortar/lib/sample/application/SampleModule.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import flow.Parcer;
import mortar.lib.sample.activity.MainActivity;
import mortar.lib.util.GsonParcer;
package mortar.lib.sample.application;
@Module(
injects = {
MainActivity.class
},
library = true
)
public class SampleModule {
private SampleApplication mApplication;
public SampleModule(SampleApplication application) {
mApplication = application;
}
@Provides @Singleton Gson provideGson() {
return new GsonBuilder()
.create();
}
@Provides @Singleton Parcer<Object> provideParcer(Gson gson) { | return new GsonParcer<Object>(gson); |
WeMakeBetterApps/MortarLib | sample/src/main/java/mortar/lib/sample/screen/InnerScreen.java | // Path: lib/src/main/java/mortar/lib/presenter/ResumeAndPausePresenter.java
// public abstract class ResumeAndPausePresenter<V extends View> extends ViewPresenter<V>
// implements ResumesAndPauses {
//
// private ResumeAndPauseOwner mResumeAndPauseOwner = null;
// private boolean mIsRunning = false;
//
// @Override protected void onEnterScope(MortarScope scope) {
// super.onEnterScope(scope);
//
// Activity activity = MortarUtil.getActivity(getView().getContext());
// if (activity instanceof ResumeAndPauseActivity) {
// mResumeAndPauseOwner = ((ResumeAndPauseActivity) activity).getResumeAndPausePresenter();
// } else {
// throw new RuntimeException(String.format("Cannot use %s inside an activity that doesn't " +
// "implement %s.", ResumeAndPausePresenter.class.getSimpleName(),
// ResumeAndPauseActivity.class.getSimpleName()));
// }
//
// mResumeAndPauseOwner.register(scope, this);
// }
//
// @Override public void onResume() {
// mIsRunning = true;
// }
//
// @Override public void onPause() {
// mIsRunning = false;
// }
//
// @Override protected void onExitScope() {
// if (mIsRunning) {
// // Mortar keeps it's scoped in a HashMap which doesn't keep order.
// // Without this sometimes onPause would run after onExitScope, and other times before.
// onPause();
// }
// super.onExitScope();
// }
//
// @Override public boolean isRunning() {
// return mIsRunning;
// }
// }
//
// Path: sample/src/main/java/view/InnerView.java
// public class InnerView extends MortarLinearLayout {
//
// @Inject InnerScreen.InnerPresenter mPresenter;
//
// public InnerView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// @Override protected ViewPresenter getPresenter() {
// return mPresenter;
// }
//
// }
//
// Path: sample/src/main/java/view/SampleView1.java
// public class SampleView1 extends MortarLinearLayout {
//
// @Inject SampleScreen1.Presenter1 mPresenter;
//
// private View innerView;
//
// public SampleView1(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// @Override protected ViewPresenter getPresenter() {
// return mPresenter;
// }
//
// @Override protected void onAttachedToWindow() {
// super.onAttachedToWindow();
// innerView = MortarUtil.createScreen(getContext(), new InnerScreen());
// addView(innerView);
// }
//
// @Override protected void onDetachedFromWindow() {
// super.onDetachedFromWindow();
// removeView(innerView);
// MortarUtil.destroyScreen(getContext(), innerView);
// innerView = null;
// }
//
// @OnClick(R.id.toScreen2) public void onToScreen2Click() {
// mPresenter.goToScreen2();
// }
//
// }
| import android.os.Bundle;
import android.util.Log;
import javax.inject.Inject;
import javax.inject.Singleton;
import flow.Flow;
import flow.Layout;
import mortar.Blueprint;
import mortar.MortarScope;
import mortar.lib.presenter.ResumeAndPausePresenter;
import mortar.lib.sample.R;
import view.InnerView;
import view.SampleView1; | package mortar.lib.sample.screen;
@Layout(R.layout.screen_inner)
public class InnerScreen implements Blueprint {
@Override public String getMortarScopeName() {
return InnerScreen.class.getName();
}
@Override public Object getDaggerModule() {
return new Module();
}
@dagger.Module(
addsTo = SampleScreen1.Module.class,
injects = {
InnerPresenter.class, | // Path: lib/src/main/java/mortar/lib/presenter/ResumeAndPausePresenter.java
// public abstract class ResumeAndPausePresenter<V extends View> extends ViewPresenter<V>
// implements ResumesAndPauses {
//
// private ResumeAndPauseOwner mResumeAndPauseOwner = null;
// private boolean mIsRunning = false;
//
// @Override protected void onEnterScope(MortarScope scope) {
// super.onEnterScope(scope);
//
// Activity activity = MortarUtil.getActivity(getView().getContext());
// if (activity instanceof ResumeAndPauseActivity) {
// mResumeAndPauseOwner = ((ResumeAndPauseActivity) activity).getResumeAndPausePresenter();
// } else {
// throw new RuntimeException(String.format("Cannot use %s inside an activity that doesn't " +
// "implement %s.", ResumeAndPausePresenter.class.getSimpleName(),
// ResumeAndPauseActivity.class.getSimpleName()));
// }
//
// mResumeAndPauseOwner.register(scope, this);
// }
//
// @Override public void onResume() {
// mIsRunning = true;
// }
//
// @Override public void onPause() {
// mIsRunning = false;
// }
//
// @Override protected void onExitScope() {
// if (mIsRunning) {
// // Mortar keeps it's scoped in a HashMap which doesn't keep order.
// // Without this sometimes onPause would run after onExitScope, and other times before.
// onPause();
// }
// super.onExitScope();
// }
//
// @Override public boolean isRunning() {
// return mIsRunning;
// }
// }
//
// Path: sample/src/main/java/view/InnerView.java
// public class InnerView extends MortarLinearLayout {
//
// @Inject InnerScreen.InnerPresenter mPresenter;
//
// public InnerView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// @Override protected ViewPresenter getPresenter() {
// return mPresenter;
// }
//
// }
//
// Path: sample/src/main/java/view/SampleView1.java
// public class SampleView1 extends MortarLinearLayout {
//
// @Inject SampleScreen1.Presenter1 mPresenter;
//
// private View innerView;
//
// public SampleView1(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// @Override protected ViewPresenter getPresenter() {
// return mPresenter;
// }
//
// @Override protected void onAttachedToWindow() {
// super.onAttachedToWindow();
// innerView = MortarUtil.createScreen(getContext(), new InnerScreen());
// addView(innerView);
// }
//
// @Override protected void onDetachedFromWindow() {
// super.onDetachedFromWindow();
// removeView(innerView);
// MortarUtil.destroyScreen(getContext(), innerView);
// innerView = null;
// }
//
// @OnClick(R.id.toScreen2) public void onToScreen2Click() {
// mPresenter.goToScreen2();
// }
//
// }
// Path: sample/src/main/java/mortar/lib/sample/screen/InnerScreen.java
import android.os.Bundle;
import android.util.Log;
import javax.inject.Inject;
import javax.inject.Singleton;
import flow.Flow;
import flow.Layout;
import mortar.Blueprint;
import mortar.MortarScope;
import mortar.lib.presenter.ResumeAndPausePresenter;
import mortar.lib.sample.R;
import view.InnerView;
import view.SampleView1;
package mortar.lib.sample.screen;
@Layout(R.layout.screen_inner)
public class InnerScreen implements Blueprint {
@Override public String getMortarScopeName() {
return InnerScreen.class.getName();
}
@Override public Object getDaggerModule() {
return new Module();
}
@dagger.Module(
addsTo = SampleScreen1.Module.class,
injects = {
InnerPresenter.class, | InnerView.class |
WeMakeBetterApps/MortarLib | sample/src/main/java/mortar/lib/sample/screen/InnerScreen.java | // Path: lib/src/main/java/mortar/lib/presenter/ResumeAndPausePresenter.java
// public abstract class ResumeAndPausePresenter<V extends View> extends ViewPresenter<V>
// implements ResumesAndPauses {
//
// private ResumeAndPauseOwner mResumeAndPauseOwner = null;
// private boolean mIsRunning = false;
//
// @Override protected void onEnterScope(MortarScope scope) {
// super.onEnterScope(scope);
//
// Activity activity = MortarUtil.getActivity(getView().getContext());
// if (activity instanceof ResumeAndPauseActivity) {
// mResumeAndPauseOwner = ((ResumeAndPauseActivity) activity).getResumeAndPausePresenter();
// } else {
// throw new RuntimeException(String.format("Cannot use %s inside an activity that doesn't " +
// "implement %s.", ResumeAndPausePresenter.class.getSimpleName(),
// ResumeAndPauseActivity.class.getSimpleName()));
// }
//
// mResumeAndPauseOwner.register(scope, this);
// }
//
// @Override public void onResume() {
// mIsRunning = true;
// }
//
// @Override public void onPause() {
// mIsRunning = false;
// }
//
// @Override protected void onExitScope() {
// if (mIsRunning) {
// // Mortar keeps it's scoped in a HashMap which doesn't keep order.
// // Without this sometimes onPause would run after onExitScope, and other times before.
// onPause();
// }
// super.onExitScope();
// }
//
// @Override public boolean isRunning() {
// return mIsRunning;
// }
// }
//
// Path: sample/src/main/java/view/InnerView.java
// public class InnerView extends MortarLinearLayout {
//
// @Inject InnerScreen.InnerPresenter mPresenter;
//
// public InnerView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// @Override protected ViewPresenter getPresenter() {
// return mPresenter;
// }
//
// }
//
// Path: sample/src/main/java/view/SampleView1.java
// public class SampleView1 extends MortarLinearLayout {
//
// @Inject SampleScreen1.Presenter1 mPresenter;
//
// private View innerView;
//
// public SampleView1(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// @Override protected ViewPresenter getPresenter() {
// return mPresenter;
// }
//
// @Override protected void onAttachedToWindow() {
// super.onAttachedToWindow();
// innerView = MortarUtil.createScreen(getContext(), new InnerScreen());
// addView(innerView);
// }
//
// @Override protected void onDetachedFromWindow() {
// super.onDetachedFromWindow();
// removeView(innerView);
// MortarUtil.destroyScreen(getContext(), innerView);
// innerView = null;
// }
//
// @OnClick(R.id.toScreen2) public void onToScreen2Click() {
// mPresenter.goToScreen2();
// }
//
// }
| import android.os.Bundle;
import android.util.Log;
import javax.inject.Inject;
import javax.inject.Singleton;
import flow.Flow;
import flow.Layout;
import mortar.Blueprint;
import mortar.MortarScope;
import mortar.lib.presenter.ResumeAndPausePresenter;
import mortar.lib.sample.R;
import view.InnerView;
import view.SampleView1; | package mortar.lib.sample.screen;
@Layout(R.layout.screen_inner)
public class InnerScreen implements Blueprint {
@Override public String getMortarScopeName() {
return InnerScreen.class.getName();
}
@Override public Object getDaggerModule() {
return new Module();
}
@dagger.Module(
addsTo = SampleScreen1.Module.class,
injects = {
InnerPresenter.class,
InnerView.class
},
library = true
)
class Module {
}
| // Path: lib/src/main/java/mortar/lib/presenter/ResumeAndPausePresenter.java
// public abstract class ResumeAndPausePresenter<V extends View> extends ViewPresenter<V>
// implements ResumesAndPauses {
//
// private ResumeAndPauseOwner mResumeAndPauseOwner = null;
// private boolean mIsRunning = false;
//
// @Override protected void onEnterScope(MortarScope scope) {
// super.onEnterScope(scope);
//
// Activity activity = MortarUtil.getActivity(getView().getContext());
// if (activity instanceof ResumeAndPauseActivity) {
// mResumeAndPauseOwner = ((ResumeAndPauseActivity) activity).getResumeAndPausePresenter();
// } else {
// throw new RuntimeException(String.format("Cannot use %s inside an activity that doesn't " +
// "implement %s.", ResumeAndPausePresenter.class.getSimpleName(),
// ResumeAndPauseActivity.class.getSimpleName()));
// }
//
// mResumeAndPauseOwner.register(scope, this);
// }
//
// @Override public void onResume() {
// mIsRunning = true;
// }
//
// @Override public void onPause() {
// mIsRunning = false;
// }
//
// @Override protected void onExitScope() {
// if (mIsRunning) {
// // Mortar keeps it's scoped in a HashMap which doesn't keep order.
// // Without this sometimes onPause would run after onExitScope, and other times before.
// onPause();
// }
// super.onExitScope();
// }
//
// @Override public boolean isRunning() {
// return mIsRunning;
// }
// }
//
// Path: sample/src/main/java/view/InnerView.java
// public class InnerView extends MortarLinearLayout {
//
// @Inject InnerScreen.InnerPresenter mPresenter;
//
// public InnerView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// @Override protected ViewPresenter getPresenter() {
// return mPresenter;
// }
//
// }
//
// Path: sample/src/main/java/view/SampleView1.java
// public class SampleView1 extends MortarLinearLayout {
//
// @Inject SampleScreen1.Presenter1 mPresenter;
//
// private View innerView;
//
// public SampleView1(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// @Override protected ViewPresenter getPresenter() {
// return mPresenter;
// }
//
// @Override protected void onAttachedToWindow() {
// super.onAttachedToWindow();
// innerView = MortarUtil.createScreen(getContext(), new InnerScreen());
// addView(innerView);
// }
//
// @Override protected void onDetachedFromWindow() {
// super.onDetachedFromWindow();
// removeView(innerView);
// MortarUtil.destroyScreen(getContext(), innerView);
// innerView = null;
// }
//
// @OnClick(R.id.toScreen2) public void onToScreen2Click() {
// mPresenter.goToScreen2();
// }
//
// }
// Path: sample/src/main/java/mortar/lib/sample/screen/InnerScreen.java
import android.os.Bundle;
import android.util.Log;
import javax.inject.Inject;
import javax.inject.Singleton;
import flow.Flow;
import flow.Layout;
import mortar.Blueprint;
import mortar.MortarScope;
import mortar.lib.presenter.ResumeAndPausePresenter;
import mortar.lib.sample.R;
import view.InnerView;
import view.SampleView1;
package mortar.lib.sample.screen;
@Layout(R.layout.screen_inner)
public class InnerScreen implements Blueprint {
@Override public String getMortarScopeName() {
return InnerScreen.class.getName();
}
@Override public Object getDaggerModule() {
return new Module();
}
@dagger.Module(
addsTo = SampleScreen1.Module.class,
injects = {
InnerPresenter.class,
InnerView.class
},
library = true
)
class Module {
}
| @Singleton public static class InnerPresenter extends ResumeAndPausePresenter<SampleView1> { |
WeMakeBetterApps/MortarLib | sample/src/main/java/mortar/lib/sample/screen/InnerScreen.java | // Path: lib/src/main/java/mortar/lib/presenter/ResumeAndPausePresenter.java
// public abstract class ResumeAndPausePresenter<V extends View> extends ViewPresenter<V>
// implements ResumesAndPauses {
//
// private ResumeAndPauseOwner mResumeAndPauseOwner = null;
// private boolean mIsRunning = false;
//
// @Override protected void onEnterScope(MortarScope scope) {
// super.onEnterScope(scope);
//
// Activity activity = MortarUtil.getActivity(getView().getContext());
// if (activity instanceof ResumeAndPauseActivity) {
// mResumeAndPauseOwner = ((ResumeAndPauseActivity) activity).getResumeAndPausePresenter();
// } else {
// throw new RuntimeException(String.format("Cannot use %s inside an activity that doesn't " +
// "implement %s.", ResumeAndPausePresenter.class.getSimpleName(),
// ResumeAndPauseActivity.class.getSimpleName()));
// }
//
// mResumeAndPauseOwner.register(scope, this);
// }
//
// @Override public void onResume() {
// mIsRunning = true;
// }
//
// @Override public void onPause() {
// mIsRunning = false;
// }
//
// @Override protected void onExitScope() {
// if (mIsRunning) {
// // Mortar keeps it's scoped in a HashMap which doesn't keep order.
// // Without this sometimes onPause would run after onExitScope, and other times before.
// onPause();
// }
// super.onExitScope();
// }
//
// @Override public boolean isRunning() {
// return mIsRunning;
// }
// }
//
// Path: sample/src/main/java/view/InnerView.java
// public class InnerView extends MortarLinearLayout {
//
// @Inject InnerScreen.InnerPresenter mPresenter;
//
// public InnerView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// @Override protected ViewPresenter getPresenter() {
// return mPresenter;
// }
//
// }
//
// Path: sample/src/main/java/view/SampleView1.java
// public class SampleView1 extends MortarLinearLayout {
//
// @Inject SampleScreen1.Presenter1 mPresenter;
//
// private View innerView;
//
// public SampleView1(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// @Override protected ViewPresenter getPresenter() {
// return mPresenter;
// }
//
// @Override protected void onAttachedToWindow() {
// super.onAttachedToWindow();
// innerView = MortarUtil.createScreen(getContext(), new InnerScreen());
// addView(innerView);
// }
//
// @Override protected void onDetachedFromWindow() {
// super.onDetachedFromWindow();
// removeView(innerView);
// MortarUtil.destroyScreen(getContext(), innerView);
// innerView = null;
// }
//
// @OnClick(R.id.toScreen2) public void onToScreen2Click() {
// mPresenter.goToScreen2();
// }
//
// }
| import android.os.Bundle;
import android.util.Log;
import javax.inject.Inject;
import javax.inject.Singleton;
import flow.Flow;
import flow.Layout;
import mortar.Blueprint;
import mortar.MortarScope;
import mortar.lib.presenter.ResumeAndPausePresenter;
import mortar.lib.sample.R;
import view.InnerView;
import view.SampleView1; | package mortar.lib.sample.screen;
@Layout(R.layout.screen_inner)
public class InnerScreen implements Blueprint {
@Override public String getMortarScopeName() {
return InnerScreen.class.getName();
}
@Override public Object getDaggerModule() {
return new Module();
}
@dagger.Module(
addsTo = SampleScreen1.Module.class,
injects = {
InnerPresenter.class,
InnerView.class
},
library = true
)
class Module {
}
| // Path: lib/src/main/java/mortar/lib/presenter/ResumeAndPausePresenter.java
// public abstract class ResumeAndPausePresenter<V extends View> extends ViewPresenter<V>
// implements ResumesAndPauses {
//
// private ResumeAndPauseOwner mResumeAndPauseOwner = null;
// private boolean mIsRunning = false;
//
// @Override protected void onEnterScope(MortarScope scope) {
// super.onEnterScope(scope);
//
// Activity activity = MortarUtil.getActivity(getView().getContext());
// if (activity instanceof ResumeAndPauseActivity) {
// mResumeAndPauseOwner = ((ResumeAndPauseActivity) activity).getResumeAndPausePresenter();
// } else {
// throw new RuntimeException(String.format("Cannot use %s inside an activity that doesn't " +
// "implement %s.", ResumeAndPausePresenter.class.getSimpleName(),
// ResumeAndPauseActivity.class.getSimpleName()));
// }
//
// mResumeAndPauseOwner.register(scope, this);
// }
//
// @Override public void onResume() {
// mIsRunning = true;
// }
//
// @Override public void onPause() {
// mIsRunning = false;
// }
//
// @Override protected void onExitScope() {
// if (mIsRunning) {
// // Mortar keeps it's scoped in a HashMap which doesn't keep order.
// // Without this sometimes onPause would run after onExitScope, and other times before.
// onPause();
// }
// super.onExitScope();
// }
//
// @Override public boolean isRunning() {
// return mIsRunning;
// }
// }
//
// Path: sample/src/main/java/view/InnerView.java
// public class InnerView extends MortarLinearLayout {
//
// @Inject InnerScreen.InnerPresenter mPresenter;
//
// public InnerView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// @Override protected ViewPresenter getPresenter() {
// return mPresenter;
// }
//
// }
//
// Path: sample/src/main/java/view/SampleView1.java
// public class SampleView1 extends MortarLinearLayout {
//
// @Inject SampleScreen1.Presenter1 mPresenter;
//
// private View innerView;
//
// public SampleView1(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// @Override protected ViewPresenter getPresenter() {
// return mPresenter;
// }
//
// @Override protected void onAttachedToWindow() {
// super.onAttachedToWindow();
// innerView = MortarUtil.createScreen(getContext(), new InnerScreen());
// addView(innerView);
// }
//
// @Override protected void onDetachedFromWindow() {
// super.onDetachedFromWindow();
// removeView(innerView);
// MortarUtil.destroyScreen(getContext(), innerView);
// innerView = null;
// }
//
// @OnClick(R.id.toScreen2) public void onToScreen2Click() {
// mPresenter.goToScreen2();
// }
//
// }
// Path: sample/src/main/java/mortar/lib/sample/screen/InnerScreen.java
import android.os.Bundle;
import android.util.Log;
import javax.inject.Inject;
import javax.inject.Singleton;
import flow.Flow;
import flow.Layout;
import mortar.Blueprint;
import mortar.MortarScope;
import mortar.lib.presenter.ResumeAndPausePresenter;
import mortar.lib.sample.R;
import view.InnerView;
import view.SampleView1;
package mortar.lib.sample.screen;
@Layout(R.layout.screen_inner)
public class InnerScreen implements Blueprint {
@Override public String getMortarScopeName() {
return InnerScreen.class.getName();
}
@Override public Object getDaggerModule() {
return new Module();
}
@dagger.Module(
addsTo = SampleScreen1.Module.class,
injects = {
InnerPresenter.class,
InnerView.class
},
library = true
)
class Module {
}
| @Singleton public static class InnerPresenter extends ResumeAndPausePresenter<SampleView1> { |
WeMakeBetterApps/MortarLib | sample/src/main/java/mortar/lib/sample/screen/SampleScreen1.java | // Path: lib/src/main/java/mortar/lib/presenter/ResumeAndPausePresenter.java
// public abstract class ResumeAndPausePresenter<V extends View> extends ViewPresenter<V>
// implements ResumesAndPauses {
//
// private ResumeAndPauseOwner mResumeAndPauseOwner = null;
// private boolean mIsRunning = false;
//
// @Override protected void onEnterScope(MortarScope scope) {
// super.onEnterScope(scope);
//
// Activity activity = MortarUtil.getActivity(getView().getContext());
// if (activity instanceof ResumeAndPauseActivity) {
// mResumeAndPauseOwner = ((ResumeAndPauseActivity) activity).getResumeAndPausePresenter();
// } else {
// throw new RuntimeException(String.format("Cannot use %s inside an activity that doesn't " +
// "implement %s.", ResumeAndPausePresenter.class.getSimpleName(),
// ResumeAndPauseActivity.class.getSimpleName()));
// }
//
// mResumeAndPauseOwner.register(scope, this);
// }
//
// @Override public void onResume() {
// mIsRunning = true;
// }
//
// @Override public void onPause() {
// mIsRunning = false;
// }
//
// @Override protected void onExitScope() {
// if (mIsRunning) {
// // Mortar keeps it's scoped in a HashMap which doesn't keep order.
// // Without this sometimes onPause would run after onExitScope, and other times before.
// onPause();
// }
// super.onExitScope();
// }
//
// @Override public boolean isRunning() {
// return mIsRunning;
// }
// }
//
// Path: sample/src/main/java/view/SampleView1.java
// public class SampleView1 extends MortarLinearLayout {
//
// @Inject SampleScreen1.Presenter1 mPresenter;
//
// private View innerView;
//
// public SampleView1(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// @Override protected ViewPresenter getPresenter() {
// return mPresenter;
// }
//
// @Override protected void onAttachedToWindow() {
// super.onAttachedToWindow();
// innerView = MortarUtil.createScreen(getContext(), new InnerScreen());
// addView(innerView);
// }
//
// @Override protected void onDetachedFromWindow() {
// super.onDetachedFromWindow();
// removeView(innerView);
// MortarUtil.destroyScreen(getContext(), innerView);
// innerView = null;
// }
//
// @OnClick(R.id.toScreen2) public void onToScreen2Click() {
// mPresenter.goToScreen2();
// }
//
// }
| import android.os.Bundle;
import android.util.Log;
import javax.inject.Inject;
import javax.inject.Singleton;
import flow.Flow;
import flow.Layout;
import mortar.Blueprint;
import mortar.MortarScope;
import mortar.lib.presenter.ResumeAndPausePresenter;
import mortar.lib.sample.R;
import view.SampleView1; | package mortar.lib.sample.screen;
@Layout(R.layout.screen_sample1)
public class SampleScreen1 implements Blueprint {
@Override public String getMortarScopeName() {
return SampleScreen1.class.getName();
}
@Override public Object getDaggerModule() {
return new Module();
}
@dagger.Module(
addsTo = ActivityScreen.Module.class,
injects = {
Presenter1.class, | // Path: lib/src/main/java/mortar/lib/presenter/ResumeAndPausePresenter.java
// public abstract class ResumeAndPausePresenter<V extends View> extends ViewPresenter<V>
// implements ResumesAndPauses {
//
// private ResumeAndPauseOwner mResumeAndPauseOwner = null;
// private boolean mIsRunning = false;
//
// @Override protected void onEnterScope(MortarScope scope) {
// super.onEnterScope(scope);
//
// Activity activity = MortarUtil.getActivity(getView().getContext());
// if (activity instanceof ResumeAndPauseActivity) {
// mResumeAndPauseOwner = ((ResumeAndPauseActivity) activity).getResumeAndPausePresenter();
// } else {
// throw new RuntimeException(String.format("Cannot use %s inside an activity that doesn't " +
// "implement %s.", ResumeAndPausePresenter.class.getSimpleName(),
// ResumeAndPauseActivity.class.getSimpleName()));
// }
//
// mResumeAndPauseOwner.register(scope, this);
// }
//
// @Override public void onResume() {
// mIsRunning = true;
// }
//
// @Override public void onPause() {
// mIsRunning = false;
// }
//
// @Override protected void onExitScope() {
// if (mIsRunning) {
// // Mortar keeps it's scoped in a HashMap which doesn't keep order.
// // Without this sometimes onPause would run after onExitScope, and other times before.
// onPause();
// }
// super.onExitScope();
// }
//
// @Override public boolean isRunning() {
// return mIsRunning;
// }
// }
//
// Path: sample/src/main/java/view/SampleView1.java
// public class SampleView1 extends MortarLinearLayout {
//
// @Inject SampleScreen1.Presenter1 mPresenter;
//
// private View innerView;
//
// public SampleView1(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// @Override protected ViewPresenter getPresenter() {
// return mPresenter;
// }
//
// @Override protected void onAttachedToWindow() {
// super.onAttachedToWindow();
// innerView = MortarUtil.createScreen(getContext(), new InnerScreen());
// addView(innerView);
// }
//
// @Override protected void onDetachedFromWindow() {
// super.onDetachedFromWindow();
// removeView(innerView);
// MortarUtil.destroyScreen(getContext(), innerView);
// innerView = null;
// }
//
// @OnClick(R.id.toScreen2) public void onToScreen2Click() {
// mPresenter.goToScreen2();
// }
//
// }
// Path: sample/src/main/java/mortar/lib/sample/screen/SampleScreen1.java
import android.os.Bundle;
import android.util.Log;
import javax.inject.Inject;
import javax.inject.Singleton;
import flow.Flow;
import flow.Layout;
import mortar.Blueprint;
import mortar.MortarScope;
import mortar.lib.presenter.ResumeAndPausePresenter;
import mortar.lib.sample.R;
import view.SampleView1;
package mortar.lib.sample.screen;
@Layout(R.layout.screen_sample1)
public class SampleScreen1 implements Blueprint {
@Override public String getMortarScopeName() {
return SampleScreen1.class.getName();
}
@Override public Object getDaggerModule() {
return new Module();
}
@dagger.Module(
addsTo = ActivityScreen.Module.class,
injects = {
Presenter1.class, | SampleView1.class |
WeMakeBetterApps/MortarLib | sample/src/main/java/mortar/lib/sample/screen/SampleScreen1.java | // Path: lib/src/main/java/mortar/lib/presenter/ResumeAndPausePresenter.java
// public abstract class ResumeAndPausePresenter<V extends View> extends ViewPresenter<V>
// implements ResumesAndPauses {
//
// private ResumeAndPauseOwner mResumeAndPauseOwner = null;
// private boolean mIsRunning = false;
//
// @Override protected void onEnterScope(MortarScope scope) {
// super.onEnterScope(scope);
//
// Activity activity = MortarUtil.getActivity(getView().getContext());
// if (activity instanceof ResumeAndPauseActivity) {
// mResumeAndPauseOwner = ((ResumeAndPauseActivity) activity).getResumeAndPausePresenter();
// } else {
// throw new RuntimeException(String.format("Cannot use %s inside an activity that doesn't " +
// "implement %s.", ResumeAndPausePresenter.class.getSimpleName(),
// ResumeAndPauseActivity.class.getSimpleName()));
// }
//
// mResumeAndPauseOwner.register(scope, this);
// }
//
// @Override public void onResume() {
// mIsRunning = true;
// }
//
// @Override public void onPause() {
// mIsRunning = false;
// }
//
// @Override protected void onExitScope() {
// if (mIsRunning) {
// // Mortar keeps it's scoped in a HashMap which doesn't keep order.
// // Without this sometimes onPause would run after onExitScope, and other times before.
// onPause();
// }
// super.onExitScope();
// }
//
// @Override public boolean isRunning() {
// return mIsRunning;
// }
// }
//
// Path: sample/src/main/java/view/SampleView1.java
// public class SampleView1 extends MortarLinearLayout {
//
// @Inject SampleScreen1.Presenter1 mPresenter;
//
// private View innerView;
//
// public SampleView1(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// @Override protected ViewPresenter getPresenter() {
// return mPresenter;
// }
//
// @Override protected void onAttachedToWindow() {
// super.onAttachedToWindow();
// innerView = MortarUtil.createScreen(getContext(), new InnerScreen());
// addView(innerView);
// }
//
// @Override protected void onDetachedFromWindow() {
// super.onDetachedFromWindow();
// removeView(innerView);
// MortarUtil.destroyScreen(getContext(), innerView);
// innerView = null;
// }
//
// @OnClick(R.id.toScreen2) public void onToScreen2Click() {
// mPresenter.goToScreen2();
// }
//
// }
| import android.os.Bundle;
import android.util.Log;
import javax.inject.Inject;
import javax.inject.Singleton;
import flow.Flow;
import flow.Layout;
import mortar.Blueprint;
import mortar.MortarScope;
import mortar.lib.presenter.ResumeAndPausePresenter;
import mortar.lib.sample.R;
import view.SampleView1; | package mortar.lib.sample.screen;
@Layout(R.layout.screen_sample1)
public class SampleScreen1 implements Blueprint {
@Override public String getMortarScopeName() {
return SampleScreen1.class.getName();
}
@Override public Object getDaggerModule() {
return new Module();
}
@dagger.Module(
addsTo = ActivityScreen.Module.class,
injects = {
Presenter1.class,
SampleView1.class
},
library = true
)
class Module {
}
| // Path: lib/src/main/java/mortar/lib/presenter/ResumeAndPausePresenter.java
// public abstract class ResumeAndPausePresenter<V extends View> extends ViewPresenter<V>
// implements ResumesAndPauses {
//
// private ResumeAndPauseOwner mResumeAndPauseOwner = null;
// private boolean mIsRunning = false;
//
// @Override protected void onEnterScope(MortarScope scope) {
// super.onEnterScope(scope);
//
// Activity activity = MortarUtil.getActivity(getView().getContext());
// if (activity instanceof ResumeAndPauseActivity) {
// mResumeAndPauseOwner = ((ResumeAndPauseActivity) activity).getResumeAndPausePresenter();
// } else {
// throw new RuntimeException(String.format("Cannot use %s inside an activity that doesn't " +
// "implement %s.", ResumeAndPausePresenter.class.getSimpleName(),
// ResumeAndPauseActivity.class.getSimpleName()));
// }
//
// mResumeAndPauseOwner.register(scope, this);
// }
//
// @Override public void onResume() {
// mIsRunning = true;
// }
//
// @Override public void onPause() {
// mIsRunning = false;
// }
//
// @Override protected void onExitScope() {
// if (mIsRunning) {
// // Mortar keeps it's scoped in a HashMap which doesn't keep order.
// // Without this sometimes onPause would run after onExitScope, and other times before.
// onPause();
// }
// super.onExitScope();
// }
//
// @Override public boolean isRunning() {
// return mIsRunning;
// }
// }
//
// Path: sample/src/main/java/view/SampleView1.java
// public class SampleView1 extends MortarLinearLayout {
//
// @Inject SampleScreen1.Presenter1 mPresenter;
//
// private View innerView;
//
// public SampleView1(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// @Override protected ViewPresenter getPresenter() {
// return mPresenter;
// }
//
// @Override protected void onAttachedToWindow() {
// super.onAttachedToWindow();
// innerView = MortarUtil.createScreen(getContext(), new InnerScreen());
// addView(innerView);
// }
//
// @Override protected void onDetachedFromWindow() {
// super.onDetachedFromWindow();
// removeView(innerView);
// MortarUtil.destroyScreen(getContext(), innerView);
// innerView = null;
// }
//
// @OnClick(R.id.toScreen2) public void onToScreen2Click() {
// mPresenter.goToScreen2();
// }
//
// }
// Path: sample/src/main/java/mortar/lib/sample/screen/SampleScreen1.java
import android.os.Bundle;
import android.util.Log;
import javax.inject.Inject;
import javax.inject.Singleton;
import flow.Flow;
import flow.Layout;
import mortar.Blueprint;
import mortar.MortarScope;
import mortar.lib.presenter.ResumeAndPausePresenter;
import mortar.lib.sample.R;
import view.SampleView1;
package mortar.lib.sample.screen;
@Layout(R.layout.screen_sample1)
public class SampleScreen1 implements Blueprint {
@Override public String getMortarScopeName() {
return SampleScreen1.class.getName();
}
@Override public Object getDaggerModule() {
return new Module();
}
@dagger.Module(
addsTo = ActivityScreen.Module.class,
injects = {
Presenter1.class,
SampleView1.class
},
library = true
)
class Module {
}
| @Singleton public static class Presenter1 extends ResumeAndPausePresenter<SampleView1> { |
WeMakeBetterApps/MortarLib | sample/src/main/java/mortar/lib/sample/screen/ActivityScreen.java | // Path: sample/src/main/java/mortar/lib/sample/activity/MainActivity.java
// public class MainActivity extends MortarActivity {
//
// @Override protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// }
//
// @Override protected Blueprint getNewActivityScreen() {
// return new ActivityScreen();
// }
//
// }
//
// Path: sample/src/main/java/mortar/lib/sample/application/SampleModule.java
// @Module(
// injects = {
// MainActivity.class
// },
// library = true
// )
// public class SampleModule {
//
// private SampleApplication mApplication;
//
// public SampleModule(SampleApplication application) {
// mApplication = application;
// }
//
// @Provides @Singleton Gson provideGson() {
// return new GsonBuilder()
// .create();
// }
//
// @Provides @Singleton Parcer<Object> provideParcer(Gson gson) {
// return new GsonParcer<Object>(gson);
// }
// }
//
// Path: lib/src/main/java/mortar/lib/screen/FlowOwner.java
// public abstract class FlowOwner<S extends Blueprint, V extends View & CanShowScreen<S>>
// extends ViewPresenter<V> implements Flow.Listener {
//
// private static final String FLOW_KEY = "FLOW_KEY";
//
// private final Parcer<Object> parcer;
//
// private Flow flow;
//
// protected FlowOwner(Parcer<Object> parcer) {
// this.parcer = parcer;
// }
//
// @Override public void onLoad(Bundle savedInstanceState) {
// super.onLoad(savedInstanceState);
// if (flow == null) {
// Backstack backstack;
//
// if (savedInstanceState != null) {
// backstack = Backstack.from(savedInstanceState.getParcelable(FLOW_KEY), parcer);
// } else {
// backstack = Backstack.fromUpChain(getFirstScreen());
// }
//
// flow = new Flow(backstack, this);
// }
//
// //noinspection unchecked
// showScreen((S) flow.getBackstack().current().getScreen(), null);
// }
//
// @Override public void onSave(Bundle outState) {
// super.onSave(outState);
// outState.putParcelable(FLOW_KEY, flow.getBackstack().getParcelable(parcer));
// }
//
// @Override public void go(Backstack backstack, Flow.Direction flowDirection) {
// //noinspection unchecked
// S newScreen = (S) backstack.current().getScreen();
// showScreen(newScreen, flowDirection);
// }
//
// public boolean onRetreatSelected() {
// return getFlow().goBack();
// }
//
// public boolean onUpSelected() {
// return getFlow().goUp();
// }
//
// protected void showScreen(S newScreen, Flow.Direction flowDirection) {
// V view = getView();
// if (view == null) return;
//
// view.showScreen(newScreen, flowDirection);
// }
//
// public final Flow getFlow() {
// return flow;
// }
//
// /** Returns the first screen shown by this presenter. */
// protected abstract S getFirstScreen();
//
// }
//
// Path: sample/src/main/java/view/ActivityView.java
// public class ActivityView extends FlowOwnerView implements CanShowScreen<Blueprint> {
//
// @Inject ActivityScreen.Presenter mPresenter;
//
// public ActivityView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// @Override protected FlowOwner getPresenter() {
// return mPresenter;
// }
//
// @Override public void showScreen(Blueprint screen, Flow.Direction direction) {
// super.showScreen(screen, direction);
// }
//
// @Override protected AbstractScreenConductor createScreenConductor(Context context) {
// return new AnimatedScreenConductor(context, ActivityView.this);
// }
//
// }
| import javax.inject.Inject;
import javax.inject.Singleton;
import dagger.Provides;
import flow.Flow;
import flow.Parcer;
import mortar.Blueprint;
import mortar.lib.sample.activity.MainActivity;
import mortar.lib.sample.application.SampleModule;
import mortar.lib.screen.FlowOwner;
import view.ActivityView; | package mortar.lib.sample.screen;
public class ActivityScreen implements Blueprint {
public ActivityScreen() {
}
@Override public String getMortarScopeName() {
return ActivityScreen.class.getName();
}
@Override public Object getDaggerModule() {
return new Module();
}
@dagger.Module( | // Path: sample/src/main/java/mortar/lib/sample/activity/MainActivity.java
// public class MainActivity extends MortarActivity {
//
// @Override protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// }
//
// @Override protected Blueprint getNewActivityScreen() {
// return new ActivityScreen();
// }
//
// }
//
// Path: sample/src/main/java/mortar/lib/sample/application/SampleModule.java
// @Module(
// injects = {
// MainActivity.class
// },
// library = true
// )
// public class SampleModule {
//
// private SampleApplication mApplication;
//
// public SampleModule(SampleApplication application) {
// mApplication = application;
// }
//
// @Provides @Singleton Gson provideGson() {
// return new GsonBuilder()
// .create();
// }
//
// @Provides @Singleton Parcer<Object> provideParcer(Gson gson) {
// return new GsonParcer<Object>(gson);
// }
// }
//
// Path: lib/src/main/java/mortar/lib/screen/FlowOwner.java
// public abstract class FlowOwner<S extends Blueprint, V extends View & CanShowScreen<S>>
// extends ViewPresenter<V> implements Flow.Listener {
//
// private static final String FLOW_KEY = "FLOW_KEY";
//
// private final Parcer<Object> parcer;
//
// private Flow flow;
//
// protected FlowOwner(Parcer<Object> parcer) {
// this.parcer = parcer;
// }
//
// @Override public void onLoad(Bundle savedInstanceState) {
// super.onLoad(savedInstanceState);
// if (flow == null) {
// Backstack backstack;
//
// if (savedInstanceState != null) {
// backstack = Backstack.from(savedInstanceState.getParcelable(FLOW_KEY), parcer);
// } else {
// backstack = Backstack.fromUpChain(getFirstScreen());
// }
//
// flow = new Flow(backstack, this);
// }
//
// //noinspection unchecked
// showScreen((S) flow.getBackstack().current().getScreen(), null);
// }
//
// @Override public void onSave(Bundle outState) {
// super.onSave(outState);
// outState.putParcelable(FLOW_KEY, flow.getBackstack().getParcelable(parcer));
// }
//
// @Override public void go(Backstack backstack, Flow.Direction flowDirection) {
// //noinspection unchecked
// S newScreen = (S) backstack.current().getScreen();
// showScreen(newScreen, flowDirection);
// }
//
// public boolean onRetreatSelected() {
// return getFlow().goBack();
// }
//
// public boolean onUpSelected() {
// return getFlow().goUp();
// }
//
// protected void showScreen(S newScreen, Flow.Direction flowDirection) {
// V view = getView();
// if (view == null) return;
//
// view.showScreen(newScreen, flowDirection);
// }
//
// public final Flow getFlow() {
// return flow;
// }
//
// /** Returns the first screen shown by this presenter. */
// protected abstract S getFirstScreen();
//
// }
//
// Path: sample/src/main/java/view/ActivityView.java
// public class ActivityView extends FlowOwnerView implements CanShowScreen<Blueprint> {
//
// @Inject ActivityScreen.Presenter mPresenter;
//
// public ActivityView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// @Override protected FlowOwner getPresenter() {
// return mPresenter;
// }
//
// @Override public void showScreen(Blueprint screen, Flow.Direction direction) {
// super.showScreen(screen, direction);
// }
//
// @Override protected AbstractScreenConductor createScreenConductor(Context context) {
// return new AnimatedScreenConductor(context, ActivityView.this);
// }
//
// }
// Path: sample/src/main/java/mortar/lib/sample/screen/ActivityScreen.java
import javax.inject.Inject;
import javax.inject.Singleton;
import dagger.Provides;
import flow.Flow;
import flow.Parcer;
import mortar.Blueprint;
import mortar.lib.sample.activity.MainActivity;
import mortar.lib.sample.application.SampleModule;
import mortar.lib.screen.FlowOwner;
import view.ActivityView;
package mortar.lib.sample.screen;
public class ActivityScreen implements Blueprint {
public ActivityScreen() {
}
@Override public String getMortarScopeName() {
return ActivityScreen.class.getName();
}
@Override public Object getDaggerModule() {
return new Module();
}
@dagger.Module( | addsTo = SampleModule.class, |
WeMakeBetterApps/MortarLib | sample/src/main/java/mortar/lib/sample/screen/ActivityScreen.java | // Path: sample/src/main/java/mortar/lib/sample/activity/MainActivity.java
// public class MainActivity extends MortarActivity {
//
// @Override protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// }
//
// @Override protected Blueprint getNewActivityScreen() {
// return new ActivityScreen();
// }
//
// }
//
// Path: sample/src/main/java/mortar/lib/sample/application/SampleModule.java
// @Module(
// injects = {
// MainActivity.class
// },
// library = true
// )
// public class SampleModule {
//
// private SampleApplication mApplication;
//
// public SampleModule(SampleApplication application) {
// mApplication = application;
// }
//
// @Provides @Singleton Gson provideGson() {
// return new GsonBuilder()
// .create();
// }
//
// @Provides @Singleton Parcer<Object> provideParcer(Gson gson) {
// return new GsonParcer<Object>(gson);
// }
// }
//
// Path: lib/src/main/java/mortar/lib/screen/FlowOwner.java
// public abstract class FlowOwner<S extends Blueprint, V extends View & CanShowScreen<S>>
// extends ViewPresenter<V> implements Flow.Listener {
//
// private static final String FLOW_KEY = "FLOW_KEY";
//
// private final Parcer<Object> parcer;
//
// private Flow flow;
//
// protected FlowOwner(Parcer<Object> parcer) {
// this.parcer = parcer;
// }
//
// @Override public void onLoad(Bundle savedInstanceState) {
// super.onLoad(savedInstanceState);
// if (flow == null) {
// Backstack backstack;
//
// if (savedInstanceState != null) {
// backstack = Backstack.from(savedInstanceState.getParcelable(FLOW_KEY), parcer);
// } else {
// backstack = Backstack.fromUpChain(getFirstScreen());
// }
//
// flow = new Flow(backstack, this);
// }
//
// //noinspection unchecked
// showScreen((S) flow.getBackstack().current().getScreen(), null);
// }
//
// @Override public void onSave(Bundle outState) {
// super.onSave(outState);
// outState.putParcelable(FLOW_KEY, flow.getBackstack().getParcelable(parcer));
// }
//
// @Override public void go(Backstack backstack, Flow.Direction flowDirection) {
// //noinspection unchecked
// S newScreen = (S) backstack.current().getScreen();
// showScreen(newScreen, flowDirection);
// }
//
// public boolean onRetreatSelected() {
// return getFlow().goBack();
// }
//
// public boolean onUpSelected() {
// return getFlow().goUp();
// }
//
// protected void showScreen(S newScreen, Flow.Direction flowDirection) {
// V view = getView();
// if (view == null) return;
//
// view.showScreen(newScreen, flowDirection);
// }
//
// public final Flow getFlow() {
// return flow;
// }
//
// /** Returns the first screen shown by this presenter. */
// protected abstract S getFirstScreen();
//
// }
//
// Path: sample/src/main/java/view/ActivityView.java
// public class ActivityView extends FlowOwnerView implements CanShowScreen<Blueprint> {
//
// @Inject ActivityScreen.Presenter mPresenter;
//
// public ActivityView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// @Override protected FlowOwner getPresenter() {
// return mPresenter;
// }
//
// @Override public void showScreen(Blueprint screen, Flow.Direction direction) {
// super.showScreen(screen, direction);
// }
//
// @Override protected AbstractScreenConductor createScreenConductor(Context context) {
// return new AnimatedScreenConductor(context, ActivityView.this);
// }
//
// }
| import javax.inject.Inject;
import javax.inject.Singleton;
import dagger.Provides;
import flow.Flow;
import flow.Parcer;
import mortar.Blueprint;
import mortar.lib.sample.activity.MainActivity;
import mortar.lib.sample.application.SampleModule;
import mortar.lib.screen.FlowOwner;
import view.ActivityView; | package mortar.lib.sample.screen;
public class ActivityScreen implements Blueprint {
public ActivityScreen() {
}
@Override public String getMortarScopeName() {
return ActivityScreen.class.getName();
}
@Override public Object getDaggerModule() {
return new Module();
}
@dagger.Module(
addsTo = SampleModule.class,
injects = { | // Path: sample/src/main/java/mortar/lib/sample/activity/MainActivity.java
// public class MainActivity extends MortarActivity {
//
// @Override protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// }
//
// @Override protected Blueprint getNewActivityScreen() {
// return new ActivityScreen();
// }
//
// }
//
// Path: sample/src/main/java/mortar/lib/sample/application/SampleModule.java
// @Module(
// injects = {
// MainActivity.class
// },
// library = true
// )
// public class SampleModule {
//
// private SampleApplication mApplication;
//
// public SampleModule(SampleApplication application) {
// mApplication = application;
// }
//
// @Provides @Singleton Gson provideGson() {
// return new GsonBuilder()
// .create();
// }
//
// @Provides @Singleton Parcer<Object> provideParcer(Gson gson) {
// return new GsonParcer<Object>(gson);
// }
// }
//
// Path: lib/src/main/java/mortar/lib/screen/FlowOwner.java
// public abstract class FlowOwner<S extends Blueprint, V extends View & CanShowScreen<S>>
// extends ViewPresenter<V> implements Flow.Listener {
//
// private static final String FLOW_KEY = "FLOW_KEY";
//
// private final Parcer<Object> parcer;
//
// private Flow flow;
//
// protected FlowOwner(Parcer<Object> parcer) {
// this.parcer = parcer;
// }
//
// @Override public void onLoad(Bundle savedInstanceState) {
// super.onLoad(savedInstanceState);
// if (flow == null) {
// Backstack backstack;
//
// if (savedInstanceState != null) {
// backstack = Backstack.from(savedInstanceState.getParcelable(FLOW_KEY), parcer);
// } else {
// backstack = Backstack.fromUpChain(getFirstScreen());
// }
//
// flow = new Flow(backstack, this);
// }
//
// //noinspection unchecked
// showScreen((S) flow.getBackstack().current().getScreen(), null);
// }
//
// @Override public void onSave(Bundle outState) {
// super.onSave(outState);
// outState.putParcelable(FLOW_KEY, flow.getBackstack().getParcelable(parcer));
// }
//
// @Override public void go(Backstack backstack, Flow.Direction flowDirection) {
// //noinspection unchecked
// S newScreen = (S) backstack.current().getScreen();
// showScreen(newScreen, flowDirection);
// }
//
// public boolean onRetreatSelected() {
// return getFlow().goBack();
// }
//
// public boolean onUpSelected() {
// return getFlow().goUp();
// }
//
// protected void showScreen(S newScreen, Flow.Direction flowDirection) {
// V view = getView();
// if (view == null) return;
//
// view.showScreen(newScreen, flowDirection);
// }
//
// public final Flow getFlow() {
// return flow;
// }
//
// /** Returns the first screen shown by this presenter. */
// protected abstract S getFirstScreen();
//
// }
//
// Path: sample/src/main/java/view/ActivityView.java
// public class ActivityView extends FlowOwnerView implements CanShowScreen<Blueprint> {
//
// @Inject ActivityScreen.Presenter mPresenter;
//
// public ActivityView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// @Override protected FlowOwner getPresenter() {
// return mPresenter;
// }
//
// @Override public void showScreen(Blueprint screen, Flow.Direction direction) {
// super.showScreen(screen, direction);
// }
//
// @Override protected AbstractScreenConductor createScreenConductor(Context context) {
// return new AnimatedScreenConductor(context, ActivityView.this);
// }
//
// }
// Path: sample/src/main/java/mortar/lib/sample/screen/ActivityScreen.java
import javax.inject.Inject;
import javax.inject.Singleton;
import dagger.Provides;
import flow.Flow;
import flow.Parcer;
import mortar.Blueprint;
import mortar.lib.sample.activity.MainActivity;
import mortar.lib.sample.application.SampleModule;
import mortar.lib.screen.FlowOwner;
import view.ActivityView;
package mortar.lib.sample.screen;
public class ActivityScreen implements Blueprint {
public ActivityScreen() {
}
@Override public String getMortarScopeName() {
return ActivityScreen.class.getName();
}
@Override public Object getDaggerModule() {
return new Module();
}
@dagger.Module(
addsTo = SampleModule.class,
injects = { | MainActivity.class, |
WeMakeBetterApps/MortarLib | sample/src/main/java/mortar/lib/sample/screen/ActivityScreen.java | // Path: sample/src/main/java/mortar/lib/sample/activity/MainActivity.java
// public class MainActivity extends MortarActivity {
//
// @Override protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// }
//
// @Override protected Blueprint getNewActivityScreen() {
// return new ActivityScreen();
// }
//
// }
//
// Path: sample/src/main/java/mortar/lib/sample/application/SampleModule.java
// @Module(
// injects = {
// MainActivity.class
// },
// library = true
// )
// public class SampleModule {
//
// private SampleApplication mApplication;
//
// public SampleModule(SampleApplication application) {
// mApplication = application;
// }
//
// @Provides @Singleton Gson provideGson() {
// return new GsonBuilder()
// .create();
// }
//
// @Provides @Singleton Parcer<Object> provideParcer(Gson gson) {
// return new GsonParcer<Object>(gson);
// }
// }
//
// Path: lib/src/main/java/mortar/lib/screen/FlowOwner.java
// public abstract class FlowOwner<S extends Blueprint, V extends View & CanShowScreen<S>>
// extends ViewPresenter<V> implements Flow.Listener {
//
// private static final String FLOW_KEY = "FLOW_KEY";
//
// private final Parcer<Object> parcer;
//
// private Flow flow;
//
// protected FlowOwner(Parcer<Object> parcer) {
// this.parcer = parcer;
// }
//
// @Override public void onLoad(Bundle savedInstanceState) {
// super.onLoad(savedInstanceState);
// if (flow == null) {
// Backstack backstack;
//
// if (savedInstanceState != null) {
// backstack = Backstack.from(savedInstanceState.getParcelable(FLOW_KEY), parcer);
// } else {
// backstack = Backstack.fromUpChain(getFirstScreen());
// }
//
// flow = new Flow(backstack, this);
// }
//
// //noinspection unchecked
// showScreen((S) flow.getBackstack().current().getScreen(), null);
// }
//
// @Override public void onSave(Bundle outState) {
// super.onSave(outState);
// outState.putParcelable(FLOW_KEY, flow.getBackstack().getParcelable(parcer));
// }
//
// @Override public void go(Backstack backstack, Flow.Direction flowDirection) {
// //noinspection unchecked
// S newScreen = (S) backstack.current().getScreen();
// showScreen(newScreen, flowDirection);
// }
//
// public boolean onRetreatSelected() {
// return getFlow().goBack();
// }
//
// public boolean onUpSelected() {
// return getFlow().goUp();
// }
//
// protected void showScreen(S newScreen, Flow.Direction flowDirection) {
// V view = getView();
// if (view == null) return;
//
// view.showScreen(newScreen, flowDirection);
// }
//
// public final Flow getFlow() {
// return flow;
// }
//
// /** Returns the first screen shown by this presenter. */
// protected abstract S getFirstScreen();
//
// }
//
// Path: sample/src/main/java/view/ActivityView.java
// public class ActivityView extends FlowOwnerView implements CanShowScreen<Blueprint> {
//
// @Inject ActivityScreen.Presenter mPresenter;
//
// public ActivityView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// @Override protected FlowOwner getPresenter() {
// return mPresenter;
// }
//
// @Override public void showScreen(Blueprint screen, Flow.Direction direction) {
// super.showScreen(screen, direction);
// }
//
// @Override protected AbstractScreenConductor createScreenConductor(Context context) {
// return new AnimatedScreenConductor(context, ActivityView.this);
// }
//
// }
| import javax.inject.Inject;
import javax.inject.Singleton;
import dagger.Provides;
import flow.Flow;
import flow.Parcer;
import mortar.Blueprint;
import mortar.lib.sample.activity.MainActivity;
import mortar.lib.sample.application.SampleModule;
import mortar.lib.screen.FlowOwner;
import view.ActivityView; | package mortar.lib.sample.screen;
public class ActivityScreen implements Blueprint {
public ActivityScreen() {
}
@Override public String getMortarScopeName() {
return ActivityScreen.class.getName();
}
@Override public Object getDaggerModule() {
return new Module();
}
@dagger.Module(
addsTo = SampleModule.class,
injects = {
MainActivity.class, | // Path: sample/src/main/java/mortar/lib/sample/activity/MainActivity.java
// public class MainActivity extends MortarActivity {
//
// @Override protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// }
//
// @Override protected Blueprint getNewActivityScreen() {
// return new ActivityScreen();
// }
//
// }
//
// Path: sample/src/main/java/mortar/lib/sample/application/SampleModule.java
// @Module(
// injects = {
// MainActivity.class
// },
// library = true
// )
// public class SampleModule {
//
// private SampleApplication mApplication;
//
// public SampleModule(SampleApplication application) {
// mApplication = application;
// }
//
// @Provides @Singleton Gson provideGson() {
// return new GsonBuilder()
// .create();
// }
//
// @Provides @Singleton Parcer<Object> provideParcer(Gson gson) {
// return new GsonParcer<Object>(gson);
// }
// }
//
// Path: lib/src/main/java/mortar/lib/screen/FlowOwner.java
// public abstract class FlowOwner<S extends Blueprint, V extends View & CanShowScreen<S>>
// extends ViewPresenter<V> implements Flow.Listener {
//
// private static final String FLOW_KEY = "FLOW_KEY";
//
// private final Parcer<Object> parcer;
//
// private Flow flow;
//
// protected FlowOwner(Parcer<Object> parcer) {
// this.parcer = parcer;
// }
//
// @Override public void onLoad(Bundle savedInstanceState) {
// super.onLoad(savedInstanceState);
// if (flow == null) {
// Backstack backstack;
//
// if (savedInstanceState != null) {
// backstack = Backstack.from(savedInstanceState.getParcelable(FLOW_KEY), parcer);
// } else {
// backstack = Backstack.fromUpChain(getFirstScreen());
// }
//
// flow = new Flow(backstack, this);
// }
//
// //noinspection unchecked
// showScreen((S) flow.getBackstack().current().getScreen(), null);
// }
//
// @Override public void onSave(Bundle outState) {
// super.onSave(outState);
// outState.putParcelable(FLOW_KEY, flow.getBackstack().getParcelable(parcer));
// }
//
// @Override public void go(Backstack backstack, Flow.Direction flowDirection) {
// //noinspection unchecked
// S newScreen = (S) backstack.current().getScreen();
// showScreen(newScreen, flowDirection);
// }
//
// public boolean onRetreatSelected() {
// return getFlow().goBack();
// }
//
// public boolean onUpSelected() {
// return getFlow().goUp();
// }
//
// protected void showScreen(S newScreen, Flow.Direction flowDirection) {
// V view = getView();
// if (view == null) return;
//
// view.showScreen(newScreen, flowDirection);
// }
//
// public final Flow getFlow() {
// return flow;
// }
//
// /** Returns the first screen shown by this presenter. */
// protected abstract S getFirstScreen();
//
// }
//
// Path: sample/src/main/java/view/ActivityView.java
// public class ActivityView extends FlowOwnerView implements CanShowScreen<Blueprint> {
//
// @Inject ActivityScreen.Presenter mPresenter;
//
// public ActivityView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// @Override protected FlowOwner getPresenter() {
// return mPresenter;
// }
//
// @Override public void showScreen(Blueprint screen, Flow.Direction direction) {
// super.showScreen(screen, direction);
// }
//
// @Override protected AbstractScreenConductor createScreenConductor(Context context) {
// return new AnimatedScreenConductor(context, ActivityView.this);
// }
//
// }
// Path: sample/src/main/java/mortar/lib/sample/screen/ActivityScreen.java
import javax.inject.Inject;
import javax.inject.Singleton;
import dagger.Provides;
import flow.Flow;
import flow.Parcer;
import mortar.Blueprint;
import mortar.lib.sample.activity.MainActivity;
import mortar.lib.sample.application.SampleModule;
import mortar.lib.screen.FlowOwner;
import view.ActivityView;
package mortar.lib.sample.screen;
public class ActivityScreen implements Blueprint {
public ActivityScreen() {
}
@Override public String getMortarScopeName() {
return ActivityScreen.class.getName();
}
@Override public Object getDaggerModule() {
return new Module();
}
@dagger.Module(
addsTo = SampleModule.class,
injects = {
MainActivity.class, | ActivityView.class, |
WeMakeBetterApps/MortarLib | sample/src/main/java/mortar/lib/sample/screen/ActivityScreen.java | // Path: sample/src/main/java/mortar/lib/sample/activity/MainActivity.java
// public class MainActivity extends MortarActivity {
//
// @Override protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// }
//
// @Override protected Blueprint getNewActivityScreen() {
// return new ActivityScreen();
// }
//
// }
//
// Path: sample/src/main/java/mortar/lib/sample/application/SampleModule.java
// @Module(
// injects = {
// MainActivity.class
// },
// library = true
// )
// public class SampleModule {
//
// private SampleApplication mApplication;
//
// public SampleModule(SampleApplication application) {
// mApplication = application;
// }
//
// @Provides @Singleton Gson provideGson() {
// return new GsonBuilder()
// .create();
// }
//
// @Provides @Singleton Parcer<Object> provideParcer(Gson gson) {
// return new GsonParcer<Object>(gson);
// }
// }
//
// Path: lib/src/main/java/mortar/lib/screen/FlowOwner.java
// public abstract class FlowOwner<S extends Blueprint, V extends View & CanShowScreen<S>>
// extends ViewPresenter<V> implements Flow.Listener {
//
// private static final String FLOW_KEY = "FLOW_KEY";
//
// private final Parcer<Object> parcer;
//
// private Flow flow;
//
// protected FlowOwner(Parcer<Object> parcer) {
// this.parcer = parcer;
// }
//
// @Override public void onLoad(Bundle savedInstanceState) {
// super.onLoad(savedInstanceState);
// if (flow == null) {
// Backstack backstack;
//
// if (savedInstanceState != null) {
// backstack = Backstack.from(savedInstanceState.getParcelable(FLOW_KEY), parcer);
// } else {
// backstack = Backstack.fromUpChain(getFirstScreen());
// }
//
// flow = new Flow(backstack, this);
// }
//
// //noinspection unchecked
// showScreen((S) flow.getBackstack().current().getScreen(), null);
// }
//
// @Override public void onSave(Bundle outState) {
// super.onSave(outState);
// outState.putParcelable(FLOW_KEY, flow.getBackstack().getParcelable(parcer));
// }
//
// @Override public void go(Backstack backstack, Flow.Direction flowDirection) {
// //noinspection unchecked
// S newScreen = (S) backstack.current().getScreen();
// showScreen(newScreen, flowDirection);
// }
//
// public boolean onRetreatSelected() {
// return getFlow().goBack();
// }
//
// public boolean onUpSelected() {
// return getFlow().goUp();
// }
//
// protected void showScreen(S newScreen, Flow.Direction flowDirection) {
// V view = getView();
// if (view == null) return;
//
// view.showScreen(newScreen, flowDirection);
// }
//
// public final Flow getFlow() {
// return flow;
// }
//
// /** Returns the first screen shown by this presenter. */
// protected abstract S getFirstScreen();
//
// }
//
// Path: sample/src/main/java/view/ActivityView.java
// public class ActivityView extends FlowOwnerView implements CanShowScreen<Blueprint> {
//
// @Inject ActivityScreen.Presenter mPresenter;
//
// public ActivityView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// @Override protected FlowOwner getPresenter() {
// return mPresenter;
// }
//
// @Override public void showScreen(Blueprint screen, Flow.Direction direction) {
// super.showScreen(screen, direction);
// }
//
// @Override protected AbstractScreenConductor createScreenConductor(Context context) {
// return new AnimatedScreenConductor(context, ActivityView.this);
// }
//
// }
| import javax.inject.Inject;
import javax.inject.Singleton;
import dagger.Provides;
import flow.Flow;
import flow.Parcer;
import mortar.Blueprint;
import mortar.lib.sample.activity.MainActivity;
import mortar.lib.sample.application.SampleModule;
import mortar.lib.screen.FlowOwner;
import view.ActivityView; | package mortar.lib.sample.screen;
public class ActivityScreen implements Blueprint {
public ActivityScreen() {
}
@Override public String getMortarScopeName() {
return ActivityScreen.class.getName();
}
@Override public Object getDaggerModule() {
return new Module();
}
@dagger.Module(
addsTo = SampleModule.class,
injects = {
MainActivity.class,
ActivityView.class,
},
library = true
)
public class Module {
@Provides @Singleton Flow provideFlow(Presenter presenter) {
return presenter.getFlow();
}
}
| // Path: sample/src/main/java/mortar/lib/sample/activity/MainActivity.java
// public class MainActivity extends MortarActivity {
//
// @Override protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// }
//
// @Override protected Blueprint getNewActivityScreen() {
// return new ActivityScreen();
// }
//
// }
//
// Path: sample/src/main/java/mortar/lib/sample/application/SampleModule.java
// @Module(
// injects = {
// MainActivity.class
// },
// library = true
// )
// public class SampleModule {
//
// private SampleApplication mApplication;
//
// public SampleModule(SampleApplication application) {
// mApplication = application;
// }
//
// @Provides @Singleton Gson provideGson() {
// return new GsonBuilder()
// .create();
// }
//
// @Provides @Singleton Parcer<Object> provideParcer(Gson gson) {
// return new GsonParcer<Object>(gson);
// }
// }
//
// Path: lib/src/main/java/mortar/lib/screen/FlowOwner.java
// public abstract class FlowOwner<S extends Blueprint, V extends View & CanShowScreen<S>>
// extends ViewPresenter<V> implements Flow.Listener {
//
// private static final String FLOW_KEY = "FLOW_KEY";
//
// private final Parcer<Object> parcer;
//
// private Flow flow;
//
// protected FlowOwner(Parcer<Object> parcer) {
// this.parcer = parcer;
// }
//
// @Override public void onLoad(Bundle savedInstanceState) {
// super.onLoad(savedInstanceState);
// if (flow == null) {
// Backstack backstack;
//
// if (savedInstanceState != null) {
// backstack = Backstack.from(savedInstanceState.getParcelable(FLOW_KEY), parcer);
// } else {
// backstack = Backstack.fromUpChain(getFirstScreen());
// }
//
// flow = new Flow(backstack, this);
// }
//
// //noinspection unchecked
// showScreen((S) flow.getBackstack().current().getScreen(), null);
// }
//
// @Override public void onSave(Bundle outState) {
// super.onSave(outState);
// outState.putParcelable(FLOW_KEY, flow.getBackstack().getParcelable(parcer));
// }
//
// @Override public void go(Backstack backstack, Flow.Direction flowDirection) {
// //noinspection unchecked
// S newScreen = (S) backstack.current().getScreen();
// showScreen(newScreen, flowDirection);
// }
//
// public boolean onRetreatSelected() {
// return getFlow().goBack();
// }
//
// public boolean onUpSelected() {
// return getFlow().goUp();
// }
//
// protected void showScreen(S newScreen, Flow.Direction flowDirection) {
// V view = getView();
// if (view == null) return;
//
// view.showScreen(newScreen, flowDirection);
// }
//
// public final Flow getFlow() {
// return flow;
// }
//
// /** Returns the first screen shown by this presenter. */
// protected abstract S getFirstScreen();
//
// }
//
// Path: sample/src/main/java/view/ActivityView.java
// public class ActivityView extends FlowOwnerView implements CanShowScreen<Blueprint> {
//
// @Inject ActivityScreen.Presenter mPresenter;
//
// public ActivityView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// @Override protected FlowOwner getPresenter() {
// return mPresenter;
// }
//
// @Override public void showScreen(Blueprint screen, Flow.Direction direction) {
// super.showScreen(screen, direction);
// }
//
// @Override protected AbstractScreenConductor createScreenConductor(Context context) {
// return new AnimatedScreenConductor(context, ActivityView.this);
// }
//
// }
// Path: sample/src/main/java/mortar/lib/sample/screen/ActivityScreen.java
import javax.inject.Inject;
import javax.inject.Singleton;
import dagger.Provides;
import flow.Flow;
import flow.Parcer;
import mortar.Blueprint;
import mortar.lib.sample.activity.MainActivity;
import mortar.lib.sample.application.SampleModule;
import mortar.lib.screen.FlowOwner;
import view.ActivityView;
package mortar.lib.sample.screen;
public class ActivityScreen implements Blueprint {
public ActivityScreen() {
}
@Override public String getMortarScopeName() {
return ActivityScreen.class.getName();
}
@Override public Object getDaggerModule() {
return new Module();
}
@dagger.Module(
addsTo = SampleModule.class,
injects = {
MainActivity.class,
ActivityView.class,
},
library = true
)
public class Module {
@Provides @Singleton Flow provideFlow(Presenter presenter) {
return presenter.getFlow();
}
}
| @Singleton public static class Presenter extends FlowOwner<Blueprint, ActivityView> { |
WeMakeBetterApps/MortarLib | lib/src/main/java/mortar/lib/activity/MortarActionBarActivity.java | // Path: lib/src/main/java/mortar/lib/application/MortarApplication.java
// public abstract class MortarApplication extends Application {
//
// private MortarScope rootScope;
//
// @Override public void onCreate() {
// super.onCreate();
//
// ObjectGraph applicationGraph = ObjectGraph.create(getRootScopeModules());
// Injector.setApplicationGraph(applicationGraph);
// rootScope = Mortar.createRootScope(isBuildConfigDebug(), applicationGraph);
// }
//
// protected abstract Object[] getRootScopeModules();
//
// public abstract boolean isBuildConfigDebug();
//
// public MortarScope getRootScope() {
// return rootScope;
// }
//
// }
//
// Path: lib/src/main/java/mortar/lib/view/FlowOwnerView.java
// public abstract class FlowOwnerView extends FrameLayout implements CanShowScreen<Blueprint> {
//
// private AbstractScreenConductor<Blueprint> mScreenConductor;
//
// public FlowOwnerView(Context context, AttributeSet attrs) {
// super(context, attrs);
// Mortar.inject(context, this);
// }
//
// @Override protected void onFinishInflate() {
// super.onFinishInflate();
// ButterKnifeWrapper.get().inject(this);
// //noinspection unchecked
// mScreenConductor = createScreenConductor(getContext());
// }
//
// public Flow getFlow() {
// return getPresenter().getFlow();
// }
//
// protected abstract FlowOwner getPresenter();
//
// @Override
// public void showScreen(Blueprint screen, Flow.Direction direction) {
// mScreenConductor.showScreen(screen, direction);
// }
//
// protected AbstractScreenConductor createScreenConductor(Context context) {
// return new AnimatedScreenConductor(context, this);
// }
//
// @Override protected void onAttachedToWindow() {
// super.onAttachedToWindow();
// //noinspection unchecked
// getPresenter().takeView(this);
// }
//
// @Override protected void onDetachedFromWindow() {
// super.onDetachedFromWindow();
// //noinspection unchecked
// getPresenter().dropView(this);
// }
//
// }
| import android.app.Application;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.MenuItem;
import android.view.ViewGroup;
import mortar.Blueprint;
import mortar.Mortar;
import mortar.MortarActivityScope;
import mortar.MortarScope;
import mortar.lib.application.MortarApplication;
import mortar.lib.view.FlowOwnerView;
import static android.content.Intent.ACTION_MAIN;
import static android.content.Intent.CATEGORY_LAUNCHER; | package mortar.lib.activity;
/**
* Hooks up the {@link mortar.MortarActivityScope}. Loads the main view
* and lets it know about up button and back button presses.
*/
public abstract class MortarActionBarActivity extends ActionBarActivity
implements ResumeAndPauseActivity {
private MortarActivityScope mActivityScope;
private final ResumeAndPauseOwner mResumeAndPauseOwner = new ResumeAndPauseOwner();
private boolean mIsRunning = false;
protected abstract Blueprint getNewActivityScreen();
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Application application = getApplication(); | // Path: lib/src/main/java/mortar/lib/application/MortarApplication.java
// public abstract class MortarApplication extends Application {
//
// private MortarScope rootScope;
//
// @Override public void onCreate() {
// super.onCreate();
//
// ObjectGraph applicationGraph = ObjectGraph.create(getRootScopeModules());
// Injector.setApplicationGraph(applicationGraph);
// rootScope = Mortar.createRootScope(isBuildConfigDebug(), applicationGraph);
// }
//
// protected abstract Object[] getRootScopeModules();
//
// public abstract boolean isBuildConfigDebug();
//
// public MortarScope getRootScope() {
// return rootScope;
// }
//
// }
//
// Path: lib/src/main/java/mortar/lib/view/FlowOwnerView.java
// public abstract class FlowOwnerView extends FrameLayout implements CanShowScreen<Blueprint> {
//
// private AbstractScreenConductor<Blueprint> mScreenConductor;
//
// public FlowOwnerView(Context context, AttributeSet attrs) {
// super(context, attrs);
// Mortar.inject(context, this);
// }
//
// @Override protected void onFinishInflate() {
// super.onFinishInflate();
// ButterKnifeWrapper.get().inject(this);
// //noinspection unchecked
// mScreenConductor = createScreenConductor(getContext());
// }
//
// public Flow getFlow() {
// return getPresenter().getFlow();
// }
//
// protected abstract FlowOwner getPresenter();
//
// @Override
// public void showScreen(Blueprint screen, Flow.Direction direction) {
// mScreenConductor.showScreen(screen, direction);
// }
//
// protected AbstractScreenConductor createScreenConductor(Context context) {
// return new AnimatedScreenConductor(context, this);
// }
//
// @Override protected void onAttachedToWindow() {
// super.onAttachedToWindow();
// //noinspection unchecked
// getPresenter().takeView(this);
// }
//
// @Override protected void onDetachedFromWindow() {
// super.onDetachedFromWindow();
// //noinspection unchecked
// getPresenter().dropView(this);
// }
//
// }
// Path: lib/src/main/java/mortar/lib/activity/MortarActionBarActivity.java
import android.app.Application;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.MenuItem;
import android.view.ViewGroup;
import mortar.Blueprint;
import mortar.Mortar;
import mortar.MortarActivityScope;
import mortar.MortarScope;
import mortar.lib.application.MortarApplication;
import mortar.lib.view.FlowOwnerView;
import static android.content.Intent.ACTION_MAIN;
import static android.content.Intent.CATEGORY_LAUNCHER;
package mortar.lib.activity;
/**
* Hooks up the {@link mortar.MortarActivityScope}. Loads the main view
* and lets it know about up button and back button presses.
*/
public abstract class MortarActionBarActivity extends ActionBarActivity
implements ResumeAndPauseActivity {
private MortarActivityScope mActivityScope;
private final ResumeAndPauseOwner mResumeAndPauseOwner = new ResumeAndPauseOwner();
private boolean mIsRunning = false;
protected abstract Blueprint getNewActivityScreen();
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Application application = getApplication(); | if ( !(application instanceof MortarApplication) ) { |
WeMakeBetterApps/MortarLib | lib/src/main/java/mortar/lib/activity/MortarActionBarActivity.java | // Path: lib/src/main/java/mortar/lib/application/MortarApplication.java
// public abstract class MortarApplication extends Application {
//
// private MortarScope rootScope;
//
// @Override public void onCreate() {
// super.onCreate();
//
// ObjectGraph applicationGraph = ObjectGraph.create(getRootScopeModules());
// Injector.setApplicationGraph(applicationGraph);
// rootScope = Mortar.createRootScope(isBuildConfigDebug(), applicationGraph);
// }
//
// protected abstract Object[] getRootScopeModules();
//
// public abstract boolean isBuildConfigDebug();
//
// public MortarScope getRootScope() {
// return rootScope;
// }
//
// }
//
// Path: lib/src/main/java/mortar/lib/view/FlowOwnerView.java
// public abstract class FlowOwnerView extends FrameLayout implements CanShowScreen<Blueprint> {
//
// private AbstractScreenConductor<Blueprint> mScreenConductor;
//
// public FlowOwnerView(Context context, AttributeSet attrs) {
// super(context, attrs);
// Mortar.inject(context, this);
// }
//
// @Override protected void onFinishInflate() {
// super.onFinishInflate();
// ButterKnifeWrapper.get().inject(this);
// //noinspection unchecked
// mScreenConductor = createScreenConductor(getContext());
// }
//
// public Flow getFlow() {
// return getPresenter().getFlow();
// }
//
// protected abstract FlowOwner getPresenter();
//
// @Override
// public void showScreen(Blueprint screen, Flow.Direction direction) {
// mScreenConductor.showScreen(screen, direction);
// }
//
// protected AbstractScreenConductor createScreenConductor(Context context) {
// return new AnimatedScreenConductor(context, this);
// }
//
// @Override protected void onAttachedToWindow() {
// super.onAttachedToWindow();
// //noinspection unchecked
// getPresenter().takeView(this);
// }
//
// @Override protected void onDetachedFromWindow() {
// super.onDetachedFromWindow();
// //noinspection unchecked
// getPresenter().dropView(this);
// }
//
// }
| import android.app.Application;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.MenuItem;
import android.view.ViewGroup;
import mortar.Blueprint;
import mortar.Mortar;
import mortar.MortarActivityScope;
import mortar.MortarScope;
import mortar.lib.application.MortarApplication;
import mortar.lib.view.FlowOwnerView;
import static android.content.Intent.ACTION_MAIN;
import static android.content.Intent.CATEGORY_LAUNCHER; | return mActivityScope;
}
return super.getSystemService(name);
}
@SuppressWarnings("NullableProblems")
@Override protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mActivityScope.onSaveInstanceState(outState);
}
public MortarActivityScope getMortarScope() {
return mActivityScope;
}
/**
* Dev tools and the play store (and others?) launch with a different intent, and so
* lead to a redundant instance of this activity being spawned. <a
* href="http://stackoverflow.com/questions/17702202/find-out-whether-the-current-activity-will-be-task-root-eventually-after-pendin"
* >Details</a>.
*/
protected boolean isWrongInstance() {
if (!isTaskRoot()) {
Intent intent = getIntent();
boolean isMainAction = intent.getAction() != null && intent.getAction().equals(ACTION_MAIN);
return intent.hasCategory(CATEGORY_LAUNCHER) && isMainAction;
}
return false;
}
| // Path: lib/src/main/java/mortar/lib/application/MortarApplication.java
// public abstract class MortarApplication extends Application {
//
// private MortarScope rootScope;
//
// @Override public void onCreate() {
// super.onCreate();
//
// ObjectGraph applicationGraph = ObjectGraph.create(getRootScopeModules());
// Injector.setApplicationGraph(applicationGraph);
// rootScope = Mortar.createRootScope(isBuildConfigDebug(), applicationGraph);
// }
//
// protected abstract Object[] getRootScopeModules();
//
// public abstract boolean isBuildConfigDebug();
//
// public MortarScope getRootScope() {
// return rootScope;
// }
//
// }
//
// Path: lib/src/main/java/mortar/lib/view/FlowOwnerView.java
// public abstract class FlowOwnerView extends FrameLayout implements CanShowScreen<Blueprint> {
//
// private AbstractScreenConductor<Blueprint> mScreenConductor;
//
// public FlowOwnerView(Context context, AttributeSet attrs) {
// super(context, attrs);
// Mortar.inject(context, this);
// }
//
// @Override protected void onFinishInflate() {
// super.onFinishInflate();
// ButterKnifeWrapper.get().inject(this);
// //noinspection unchecked
// mScreenConductor = createScreenConductor(getContext());
// }
//
// public Flow getFlow() {
// return getPresenter().getFlow();
// }
//
// protected abstract FlowOwner getPresenter();
//
// @Override
// public void showScreen(Blueprint screen, Flow.Direction direction) {
// mScreenConductor.showScreen(screen, direction);
// }
//
// protected AbstractScreenConductor createScreenConductor(Context context) {
// return new AnimatedScreenConductor(context, this);
// }
//
// @Override protected void onAttachedToWindow() {
// super.onAttachedToWindow();
// //noinspection unchecked
// getPresenter().takeView(this);
// }
//
// @Override protected void onDetachedFromWindow() {
// super.onDetachedFromWindow();
// //noinspection unchecked
// getPresenter().dropView(this);
// }
//
// }
// Path: lib/src/main/java/mortar/lib/activity/MortarActionBarActivity.java
import android.app.Application;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.MenuItem;
import android.view.ViewGroup;
import mortar.Blueprint;
import mortar.Mortar;
import mortar.MortarActivityScope;
import mortar.MortarScope;
import mortar.lib.application.MortarApplication;
import mortar.lib.view.FlowOwnerView;
import static android.content.Intent.ACTION_MAIN;
import static android.content.Intent.CATEGORY_LAUNCHER;
return mActivityScope;
}
return super.getSystemService(name);
}
@SuppressWarnings("NullableProblems")
@Override protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mActivityScope.onSaveInstanceState(outState);
}
public MortarActivityScope getMortarScope() {
return mActivityScope;
}
/**
* Dev tools and the play store (and others?) launch with a different intent, and so
* lead to a redundant instance of this activity being spawned. <a
* href="http://stackoverflow.com/questions/17702202/find-out-whether-the-current-activity-will-be-task-root-eventually-after-pendin"
* >Details</a>.
*/
protected boolean isWrongInstance() {
if (!isTaskRoot()) {
Intent intent = getIntent();
boolean isMainAction = intent.getAction() != null && intent.getAction().equals(ACTION_MAIN);
return intent.hasCategory(CATEGORY_LAUNCHER) && isMainAction;
}
return false;
}
| protected FlowOwnerView getMainView() { |
WeMakeBetterApps/MortarLib | lib/src/main/java/mortar/lib/presenter/ResumeAndPausePresenter.java | // Path: lib/src/main/java/mortar/lib/activity/ResumeAndPauseActivity.java
// public interface ResumeAndPauseActivity {
//
// boolean isRunning();
// MortarScope getMortarScope();
// ResumeAndPauseOwner getResumeAndPausePresenter();
//
// }
//
// Path: lib/src/main/java/mortar/lib/activity/ResumeAndPauseOwner.java
// public class ResumeAndPauseOwner extends Presenter<ResumeAndPauseActivity>
// implements ResumeAndPauseRegistrar {
//
// private final Set<Registration> registrations = new LinkedHashSet<Registration>();
//
// public ResumeAndPauseOwner() {
// }
//
// @Override protected MortarScope extractScope(ResumeAndPauseActivity view) {
// return view.getMortarScope();
// }
//
// @Override public void onExitScope() {
// registrations.clear();
// }
//
// @Override public void register(MortarScope scope, ResumesAndPauses listener) {
// Registration registration = new Registration(listener);
// scope.register(registration);
//
// boolean added = registrations.add(registration);
// if (added && isRunning()) {
// listener.onResume();
// }
// }
//
// @Override public boolean isRunning() {
// return getView() != null && getView().isRunning();
// }
//
// public void activityPaused() {
// for (Registration registration : registrations) {
// registration.registrant.onPause();
// }
// }
//
// public void activityResumed() {
// for (Registration registration : registrations) {
// registration.registrant.onResume();
// }
// }
//
// private class Registration implements Scoped {
// final ResumesAndPauses registrant;
//
// private Registration(ResumesAndPauses registrant) {
// this.registrant = registrant;
// }
//
// @Override public void onEnterScope(MortarScope scope) {
// }
//
// @Override public void onExitScope() {
// if (registrant.isRunning())
// registrant.onPause();
// registrations.remove(this);
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Registration that = (Registration) o;
//
// return registrant.equals(that.registrant);
// }
//
// @Override
// public int hashCode() {
// return registrant.hashCode();
// }
// }
// }
//
// Path: lib/src/main/java/mortar/lib/activity/ResumesAndPauses.java
// public interface ResumesAndPauses {
// void onResume();
// void onPause();
//
// /**
// * @return true if is running, meaning has been resumed, and has not been paused yet; false otherwise
// */
// boolean isRunning();
// }
//
// Path: lib/src/main/java/mortar/lib/util/MortarUtil.java
// public class MortarUtil {
//
// public static View createScreen(Context context, Blueprint screen) {
// MortarScope scope = Mortar.getScope(context);
// MortarScope newChildScope = scope.requireChild(screen);
//
// Context childContext = newChildScope.createContext(context);
// return Layouts.createView(childContext, screen);
// }
//
// public static int getLayoutId(Blueprint screen) {
// Class<? extends Blueprint> screenType = screen.getClass();
// Layout layoutAnnotation = screenType.getAnnotation(Layout.class);
// if (layoutAnnotation == null) {
// throw new IllegalArgumentException(
// String.format("@%s annotation not found on class %s", Layout.class.getSimpleName(),
// screenType.getName()));
// }
//
// return layoutAnnotation.value();
// }
//
// public static void destroyScreen(View view) {
// destroyScreen(view.getContext().getApplicationContext(), view);
// }
//
// public static void destroyScreen(Context parentContext, View view) {
// MortarScope parentScope = Mortar.getScope(parentContext);
// MortarScope oldChildScope = Mortar.getScope(view.getContext());
// parentScope.destroyChild(oldChildScope);
// }
//
// public static Activity getActivity(Context context) {
// Context currentContext = context;
// while (currentContext instanceof ContextWrapper) {
// currentContext = ((ContextWrapper) currentContext).getBaseContext();
//
// if (currentContext instanceof Activity) {
// return (Activity) currentContext;
// } else if (currentContext instanceof Application) {
// return null;
// }
// }
//
// return null;
// }
//
// }
| import android.app.Activity;
import android.view.View;
import mortar.MortarScope;
import mortar.ViewPresenter;
import mortar.lib.activity.ResumeAndPauseActivity;
import mortar.lib.activity.ResumeAndPauseOwner;
import mortar.lib.activity.ResumesAndPauses;
import mortar.lib.util.MortarUtil; | package mortar.lib.presenter;
public abstract class ResumeAndPausePresenter<V extends View> extends ViewPresenter<V>
implements ResumesAndPauses {
| // Path: lib/src/main/java/mortar/lib/activity/ResumeAndPauseActivity.java
// public interface ResumeAndPauseActivity {
//
// boolean isRunning();
// MortarScope getMortarScope();
// ResumeAndPauseOwner getResumeAndPausePresenter();
//
// }
//
// Path: lib/src/main/java/mortar/lib/activity/ResumeAndPauseOwner.java
// public class ResumeAndPauseOwner extends Presenter<ResumeAndPauseActivity>
// implements ResumeAndPauseRegistrar {
//
// private final Set<Registration> registrations = new LinkedHashSet<Registration>();
//
// public ResumeAndPauseOwner() {
// }
//
// @Override protected MortarScope extractScope(ResumeAndPauseActivity view) {
// return view.getMortarScope();
// }
//
// @Override public void onExitScope() {
// registrations.clear();
// }
//
// @Override public void register(MortarScope scope, ResumesAndPauses listener) {
// Registration registration = new Registration(listener);
// scope.register(registration);
//
// boolean added = registrations.add(registration);
// if (added && isRunning()) {
// listener.onResume();
// }
// }
//
// @Override public boolean isRunning() {
// return getView() != null && getView().isRunning();
// }
//
// public void activityPaused() {
// for (Registration registration : registrations) {
// registration.registrant.onPause();
// }
// }
//
// public void activityResumed() {
// for (Registration registration : registrations) {
// registration.registrant.onResume();
// }
// }
//
// private class Registration implements Scoped {
// final ResumesAndPauses registrant;
//
// private Registration(ResumesAndPauses registrant) {
// this.registrant = registrant;
// }
//
// @Override public void onEnterScope(MortarScope scope) {
// }
//
// @Override public void onExitScope() {
// if (registrant.isRunning())
// registrant.onPause();
// registrations.remove(this);
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Registration that = (Registration) o;
//
// return registrant.equals(that.registrant);
// }
//
// @Override
// public int hashCode() {
// return registrant.hashCode();
// }
// }
// }
//
// Path: lib/src/main/java/mortar/lib/activity/ResumesAndPauses.java
// public interface ResumesAndPauses {
// void onResume();
// void onPause();
//
// /**
// * @return true if is running, meaning has been resumed, and has not been paused yet; false otherwise
// */
// boolean isRunning();
// }
//
// Path: lib/src/main/java/mortar/lib/util/MortarUtil.java
// public class MortarUtil {
//
// public static View createScreen(Context context, Blueprint screen) {
// MortarScope scope = Mortar.getScope(context);
// MortarScope newChildScope = scope.requireChild(screen);
//
// Context childContext = newChildScope.createContext(context);
// return Layouts.createView(childContext, screen);
// }
//
// public static int getLayoutId(Blueprint screen) {
// Class<? extends Blueprint> screenType = screen.getClass();
// Layout layoutAnnotation = screenType.getAnnotation(Layout.class);
// if (layoutAnnotation == null) {
// throw new IllegalArgumentException(
// String.format("@%s annotation not found on class %s", Layout.class.getSimpleName(),
// screenType.getName()));
// }
//
// return layoutAnnotation.value();
// }
//
// public static void destroyScreen(View view) {
// destroyScreen(view.getContext().getApplicationContext(), view);
// }
//
// public static void destroyScreen(Context parentContext, View view) {
// MortarScope parentScope = Mortar.getScope(parentContext);
// MortarScope oldChildScope = Mortar.getScope(view.getContext());
// parentScope.destroyChild(oldChildScope);
// }
//
// public static Activity getActivity(Context context) {
// Context currentContext = context;
// while (currentContext instanceof ContextWrapper) {
// currentContext = ((ContextWrapper) currentContext).getBaseContext();
//
// if (currentContext instanceof Activity) {
// return (Activity) currentContext;
// } else if (currentContext instanceof Application) {
// return null;
// }
// }
//
// return null;
// }
//
// }
// Path: lib/src/main/java/mortar/lib/presenter/ResumeAndPausePresenter.java
import android.app.Activity;
import android.view.View;
import mortar.MortarScope;
import mortar.ViewPresenter;
import mortar.lib.activity.ResumeAndPauseActivity;
import mortar.lib.activity.ResumeAndPauseOwner;
import mortar.lib.activity.ResumesAndPauses;
import mortar.lib.util.MortarUtil;
package mortar.lib.presenter;
public abstract class ResumeAndPausePresenter<V extends View> extends ViewPresenter<V>
implements ResumesAndPauses {
| private ResumeAndPauseOwner mResumeAndPauseOwner = null; |
WeMakeBetterApps/MortarLib | lib/src/main/java/mortar/lib/presenter/ResumeAndPausePresenter.java | // Path: lib/src/main/java/mortar/lib/activity/ResumeAndPauseActivity.java
// public interface ResumeAndPauseActivity {
//
// boolean isRunning();
// MortarScope getMortarScope();
// ResumeAndPauseOwner getResumeAndPausePresenter();
//
// }
//
// Path: lib/src/main/java/mortar/lib/activity/ResumeAndPauseOwner.java
// public class ResumeAndPauseOwner extends Presenter<ResumeAndPauseActivity>
// implements ResumeAndPauseRegistrar {
//
// private final Set<Registration> registrations = new LinkedHashSet<Registration>();
//
// public ResumeAndPauseOwner() {
// }
//
// @Override protected MortarScope extractScope(ResumeAndPauseActivity view) {
// return view.getMortarScope();
// }
//
// @Override public void onExitScope() {
// registrations.clear();
// }
//
// @Override public void register(MortarScope scope, ResumesAndPauses listener) {
// Registration registration = new Registration(listener);
// scope.register(registration);
//
// boolean added = registrations.add(registration);
// if (added && isRunning()) {
// listener.onResume();
// }
// }
//
// @Override public boolean isRunning() {
// return getView() != null && getView().isRunning();
// }
//
// public void activityPaused() {
// for (Registration registration : registrations) {
// registration.registrant.onPause();
// }
// }
//
// public void activityResumed() {
// for (Registration registration : registrations) {
// registration.registrant.onResume();
// }
// }
//
// private class Registration implements Scoped {
// final ResumesAndPauses registrant;
//
// private Registration(ResumesAndPauses registrant) {
// this.registrant = registrant;
// }
//
// @Override public void onEnterScope(MortarScope scope) {
// }
//
// @Override public void onExitScope() {
// if (registrant.isRunning())
// registrant.onPause();
// registrations.remove(this);
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Registration that = (Registration) o;
//
// return registrant.equals(that.registrant);
// }
//
// @Override
// public int hashCode() {
// return registrant.hashCode();
// }
// }
// }
//
// Path: lib/src/main/java/mortar/lib/activity/ResumesAndPauses.java
// public interface ResumesAndPauses {
// void onResume();
// void onPause();
//
// /**
// * @return true if is running, meaning has been resumed, and has not been paused yet; false otherwise
// */
// boolean isRunning();
// }
//
// Path: lib/src/main/java/mortar/lib/util/MortarUtil.java
// public class MortarUtil {
//
// public static View createScreen(Context context, Blueprint screen) {
// MortarScope scope = Mortar.getScope(context);
// MortarScope newChildScope = scope.requireChild(screen);
//
// Context childContext = newChildScope.createContext(context);
// return Layouts.createView(childContext, screen);
// }
//
// public static int getLayoutId(Blueprint screen) {
// Class<? extends Blueprint> screenType = screen.getClass();
// Layout layoutAnnotation = screenType.getAnnotation(Layout.class);
// if (layoutAnnotation == null) {
// throw new IllegalArgumentException(
// String.format("@%s annotation not found on class %s", Layout.class.getSimpleName(),
// screenType.getName()));
// }
//
// return layoutAnnotation.value();
// }
//
// public static void destroyScreen(View view) {
// destroyScreen(view.getContext().getApplicationContext(), view);
// }
//
// public static void destroyScreen(Context parentContext, View view) {
// MortarScope parentScope = Mortar.getScope(parentContext);
// MortarScope oldChildScope = Mortar.getScope(view.getContext());
// parentScope.destroyChild(oldChildScope);
// }
//
// public static Activity getActivity(Context context) {
// Context currentContext = context;
// while (currentContext instanceof ContextWrapper) {
// currentContext = ((ContextWrapper) currentContext).getBaseContext();
//
// if (currentContext instanceof Activity) {
// return (Activity) currentContext;
// } else if (currentContext instanceof Application) {
// return null;
// }
// }
//
// return null;
// }
//
// }
| import android.app.Activity;
import android.view.View;
import mortar.MortarScope;
import mortar.ViewPresenter;
import mortar.lib.activity.ResumeAndPauseActivity;
import mortar.lib.activity.ResumeAndPauseOwner;
import mortar.lib.activity.ResumesAndPauses;
import mortar.lib.util.MortarUtil; | package mortar.lib.presenter;
public abstract class ResumeAndPausePresenter<V extends View> extends ViewPresenter<V>
implements ResumesAndPauses {
private ResumeAndPauseOwner mResumeAndPauseOwner = null;
private boolean mIsRunning = false;
@Override protected void onEnterScope(MortarScope scope) {
super.onEnterScope(scope);
| // Path: lib/src/main/java/mortar/lib/activity/ResumeAndPauseActivity.java
// public interface ResumeAndPauseActivity {
//
// boolean isRunning();
// MortarScope getMortarScope();
// ResumeAndPauseOwner getResumeAndPausePresenter();
//
// }
//
// Path: lib/src/main/java/mortar/lib/activity/ResumeAndPauseOwner.java
// public class ResumeAndPauseOwner extends Presenter<ResumeAndPauseActivity>
// implements ResumeAndPauseRegistrar {
//
// private final Set<Registration> registrations = new LinkedHashSet<Registration>();
//
// public ResumeAndPauseOwner() {
// }
//
// @Override protected MortarScope extractScope(ResumeAndPauseActivity view) {
// return view.getMortarScope();
// }
//
// @Override public void onExitScope() {
// registrations.clear();
// }
//
// @Override public void register(MortarScope scope, ResumesAndPauses listener) {
// Registration registration = new Registration(listener);
// scope.register(registration);
//
// boolean added = registrations.add(registration);
// if (added && isRunning()) {
// listener.onResume();
// }
// }
//
// @Override public boolean isRunning() {
// return getView() != null && getView().isRunning();
// }
//
// public void activityPaused() {
// for (Registration registration : registrations) {
// registration.registrant.onPause();
// }
// }
//
// public void activityResumed() {
// for (Registration registration : registrations) {
// registration.registrant.onResume();
// }
// }
//
// private class Registration implements Scoped {
// final ResumesAndPauses registrant;
//
// private Registration(ResumesAndPauses registrant) {
// this.registrant = registrant;
// }
//
// @Override public void onEnterScope(MortarScope scope) {
// }
//
// @Override public void onExitScope() {
// if (registrant.isRunning())
// registrant.onPause();
// registrations.remove(this);
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Registration that = (Registration) o;
//
// return registrant.equals(that.registrant);
// }
//
// @Override
// public int hashCode() {
// return registrant.hashCode();
// }
// }
// }
//
// Path: lib/src/main/java/mortar/lib/activity/ResumesAndPauses.java
// public interface ResumesAndPauses {
// void onResume();
// void onPause();
//
// /**
// * @return true if is running, meaning has been resumed, and has not been paused yet; false otherwise
// */
// boolean isRunning();
// }
//
// Path: lib/src/main/java/mortar/lib/util/MortarUtil.java
// public class MortarUtil {
//
// public static View createScreen(Context context, Blueprint screen) {
// MortarScope scope = Mortar.getScope(context);
// MortarScope newChildScope = scope.requireChild(screen);
//
// Context childContext = newChildScope.createContext(context);
// return Layouts.createView(childContext, screen);
// }
//
// public static int getLayoutId(Blueprint screen) {
// Class<? extends Blueprint> screenType = screen.getClass();
// Layout layoutAnnotation = screenType.getAnnotation(Layout.class);
// if (layoutAnnotation == null) {
// throw new IllegalArgumentException(
// String.format("@%s annotation not found on class %s", Layout.class.getSimpleName(),
// screenType.getName()));
// }
//
// return layoutAnnotation.value();
// }
//
// public static void destroyScreen(View view) {
// destroyScreen(view.getContext().getApplicationContext(), view);
// }
//
// public static void destroyScreen(Context parentContext, View view) {
// MortarScope parentScope = Mortar.getScope(parentContext);
// MortarScope oldChildScope = Mortar.getScope(view.getContext());
// parentScope.destroyChild(oldChildScope);
// }
//
// public static Activity getActivity(Context context) {
// Context currentContext = context;
// while (currentContext instanceof ContextWrapper) {
// currentContext = ((ContextWrapper) currentContext).getBaseContext();
//
// if (currentContext instanceof Activity) {
// return (Activity) currentContext;
// } else if (currentContext instanceof Application) {
// return null;
// }
// }
//
// return null;
// }
//
// }
// Path: lib/src/main/java/mortar/lib/presenter/ResumeAndPausePresenter.java
import android.app.Activity;
import android.view.View;
import mortar.MortarScope;
import mortar.ViewPresenter;
import mortar.lib.activity.ResumeAndPauseActivity;
import mortar.lib.activity.ResumeAndPauseOwner;
import mortar.lib.activity.ResumesAndPauses;
import mortar.lib.util.MortarUtil;
package mortar.lib.presenter;
public abstract class ResumeAndPausePresenter<V extends View> extends ViewPresenter<V>
implements ResumesAndPauses {
private ResumeAndPauseOwner mResumeAndPauseOwner = null;
private boolean mIsRunning = false;
@Override protected void onEnterScope(MortarScope scope) {
super.onEnterScope(scope);
| Activity activity = MortarUtil.getActivity(getView().getContext()); |
WeMakeBetterApps/MortarLib | lib/src/main/java/mortar/lib/presenter/ResumeAndPausePresenter.java | // Path: lib/src/main/java/mortar/lib/activity/ResumeAndPauseActivity.java
// public interface ResumeAndPauseActivity {
//
// boolean isRunning();
// MortarScope getMortarScope();
// ResumeAndPauseOwner getResumeAndPausePresenter();
//
// }
//
// Path: lib/src/main/java/mortar/lib/activity/ResumeAndPauseOwner.java
// public class ResumeAndPauseOwner extends Presenter<ResumeAndPauseActivity>
// implements ResumeAndPauseRegistrar {
//
// private final Set<Registration> registrations = new LinkedHashSet<Registration>();
//
// public ResumeAndPauseOwner() {
// }
//
// @Override protected MortarScope extractScope(ResumeAndPauseActivity view) {
// return view.getMortarScope();
// }
//
// @Override public void onExitScope() {
// registrations.clear();
// }
//
// @Override public void register(MortarScope scope, ResumesAndPauses listener) {
// Registration registration = new Registration(listener);
// scope.register(registration);
//
// boolean added = registrations.add(registration);
// if (added && isRunning()) {
// listener.onResume();
// }
// }
//
// @Override public boolean isRunning() {
// return getView() != null && getView().isRunning();
// }
//
// public void activityPaused() {
// for (Registration registration : registrations) {
// registration.registrant.onPause();
// }
// }
//
// public void activityResumed() {
// for (Registration registration : registrations) {
// registration.registrant.onResume();
// }
// }
//
// private class Registration implements Scoped {
// final ResumesAndPauses registrant;
//
// private Registration(ResumesAndPauses registrant) {
// this.registrant = registrant;
// }
//
// @Override public void onEnterScope(MortarScope scope) {
// }
//
// @Override public void onExitScope() {
// if (registrant.isRunning())
// registrant.onPause();
// registrations.remove(this);
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Registration that = (Registration) o;
//
// return registrant.equals(that.registrant);
// }
//
// @Override
// public int hashCode() {
// return registrant.hashCode();
// }
// }
// }
//
// Path: lib/src/main/java/mortar/lib/activity/ResumesAndPauses.java
// public interface ResumesAndPauses {
// void onResume();
// void onPause();
//
// /**
// * @return true if is running, meaning has been resumed, and has not been paused yet; false otherwise
// */
// boolean isRunning();
// }
//
// Path: lib/src/main/java/mortar/lib/util/MortarUtil.java
// public class MortarUtil {
//
// public static View createScreen(Context context, Blueprint screen) {
// MortarScope scope = Mortar.getScope(context);
// MortarScope newChildScope = scope.requireChild(screen);
//
// Context childContext = newChildScope.createContext(context);
// return Layouts.createView(childContext, screen);
// }
//
// public static int getLayoutId(Blueprint screen) {
// Class<? extends Blueprint> screenType = screen.getClass();
// Layout layoutAnnotation = screenType.getAnnotation(Layout.class);
// if (layoutAnnotation == null) {
// throw new IllegalArgumentException(
// String.format("@%s annotation not found on class %s", Layout.class.getSimpleName(),
// screenType.getName()));
// }
//
// return layoutAnnotation.value();
// }
//
// public static void destroyScreen(View view) {
// destroyScreen(view.getContext().getApplicationContext(), view);
// }
//
// public static void destroyScreen(Context parentContext, View view) {
// MortarScope parentScope = Mortar.getScope(parentContext);
// MortarScope oldChildScope = Mortar.getScope(view.getContext());
// parentScope.destroyChild(oldChildScope);
// }
//
// public static Activity getActivity(Context context) {
// Context currentContext = context;
// while (currentContext instanceof ContextWrapper) {
// currentContext = ((ContextWrapper) currentContext).getBaseContext();
//
// if (currentContext instanceof Activity) {
// return (Activity) currentContext;
// } else if (currentContext instanceof Application) {
// return null;
// }
// }
//
// return null;
// }
//
// }
| import android.app.Activity;
import android.view.View;
import mortar.MortarScope;
import mortar.ViewPresenter;
import mortar.lib.activity.ResumeAndPauseActivity;
import mortar.lib.activity.ResumeAndPauseOwner;
import mortar.lib.activity.ResumesAndPauses;
import mortar.lib.util.MortarUtil; | package mortar.lib.presenter;
public abstract class ResumeAndPausePresenter<V extends View> extends ViewPresenter<V>
implements ResumesAndPauses {
private ResumeAndPauseOwner mResumeAndPauseOwner = null;
private boolean mIsRunning = false;
@Override protected void onEnterScope(MortarScope scope) {
super.onEnterScope(scope);
Activity activity = MortarUtil.getActivity(getView().getContext()); | // Path: lib/src/main/java/mortar/lib/activity/ResumeAndPauseActivity.java
// public interface ResumeAndPauseActivity {
//
// boolean isRunning();
// MortarScope getMortarScope();
// ResumeAndPauseOwner getResumeAndPausePresenter();
//
// }
//
// Path: lib/src/main/java/mortar/lib/activity/ResumeAndPauseOwner.java
// public class ResumeAndPauseOwner extends Presenter<ResumeAndPauseActivity>
// implements ResumeAndPauseRegistrar {
//
// private final Set<Registration> registrations = new LinkedHashSet<Registration>();
//
// public ResumeAndPauseOwner() {
// }
//
// @Override protected MortarScope extractScope(ResumeAndPauseActivity view) {
// return view.getMortarScope();
// }
//
// @Override public void onExitScope() {
// registrations.clear();
// }
//
// @Override public void register(MortarScope scope, ResumesAndPauses listener) {
// Registration registration = new Registration(listener);
// scope.register(registration);
//
// boolean added = registrations.add(registration);
// if (added && isRunning()) {
// listener.onResume();
// }
// }
//
// @Override public boolean isRunning() {
// return getView() != null && getView().isRunning();
// }
//
// public void activityPaused() {
// for (Registration registration : registrations) {
// registration.registrant.onPause();
// }
// }
//
// public void activityResumed() {
// for (Registration registration : registrations) {
// registration.registrant.onResume();
// }
// }
//
// private class Registration implements Scoped {
// final ResumesAndPauses registrant;
//
// private Registration(ResumesAndPauses registrant) {
// this.registrant = registrant;
// }
//
// @Override public void onEnterScope(MortarScope scope) {
// }
//
// @Override public void onExitScope() {
// if (registrant.isRunning())
// registrant.onPause();
// registrations.remove(this);
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Registration that = (Registration) o;
//
// return registrant.equals(that.registrant);
// }
//
// @Override
// public int hashCode() {
// return registrant.hashCode();
// }
// }
// }
//
// Path: lib/src/main/java/mortar/lib/activity/ResumesAndPauses.java
// public interface ResumesAndPauses {
// void onResume();
// void onPause();
//
// /**
// * @return true if is running, meaning has been resumed, and has not been paused yet; false otherwise
// */
// boolean isRunning();
// }
//
// Path: lib/src/main/java/mortar/lib/util/MortarUtil.java
// public class MortarUtil {
//
// public static View createScreen(Context context, Blueprint screen) {
// MortarScope scope = Mortar.getScope(context);
// MortarScope newChildScope = scope.requireChild(screen);
//
// Context childContext = newChildScope.createContext(context);
// return Layouts.createView(childContext, screen);
// }
//
// public static int getLayoutId(Blueprint screen) {
// Class<? extends Blueprint> screenType = screen.getClass();
// Layout layoutAnnotation = screenType.getAnnotation(Layout.class);
// if (layoutAnnotation == null) {
// throw new IllegalArgumentException(
// String.format("@%s annotation not found on class %s", Layout.class.getSimpleName(),
// screenType.getName()));
// }
//
// return layoutAnnotation.value();
// }
//
// public static void destroyScreen(View view) {
// destroyScreen(view.getContext().getApplicationContext(), view);
// }
//
// public static void destroyScreen(Context parentContext, View view) {
// MortarScope parentScope = Mortar.getScope(parentContext);
// MortarScope oldChildScope = Mortar.getScope(view.getContext());
// parentScope.destroyChild(oldChildScope);
// }
//
// public static Activity getActivity(Context context) {
// Context currentContext = context;
// while (currentContext instanceof ContextWrapper) {
// currentContext = ((ContextWrapper) currentContext).getBaseContext();
//
// if (currentContext instanceof Activity) {
// return (Activity) currentContext;
// } else if (currentContext instanceof Application) {
// return null;
// }
// }
//
// return null;
// }
//
// }
// Path: lib/src/main/java/mortar/lib/presenter/ResumeAndPausePresenter.java
import android.app.Activity;
import android.view.View;
import mortar.MortarScope;
import mortar.ViewPresenter;
import mortar.lib.activity.ResumeAndPauseActivity;
import mortar.lib.activity.ResumeAndPauseOwner;
import mortar.lib.activity.ResumesAndPauses;
import mortar.lib.util.MortarUtil;
package mortar.lib.presenter;
public abstract class ResumeAndPausePresenter<V extends View> extends ViewPresenter<V>
implements ResumesAndPauses {
private ResumeAndPauseOwner mResumeAndPauseOwner = null;
private boolean mIsRunning = false;
@Override protected void onEnterScope(MortarScope scope) {
super.onEnterScope(scope);
Activity activity = MortarUtil.getActivity(getView().getContext()); | if (activity instanceof ResumeAndPauseActivity) { |
WeMakeBetterApps/MortarLib | lib/src/main/java/mortar/lib/screen/AbstractScreenConductor.java | // Path: lib/src/main/java/mortar/lib/util/MortarUtil.java
// public class MortarUtil {
//
// public static View createScreen(Context context, Blueprint screen) {
// MortarScope scope = Mortar.getScope(context);
// MortarScope newChildScope = scope.requireChild(screen);
//
// Context childContext = newChildScope.createContext(context);
// return Layouts.createView(childContext, screen);
// }
//
// public static int getLayoutId(Blueprint screen) {
// Class<? extends Blueprint> screenType = screen.getClass();
// Layout layoutAnnotation = screenType.getAnnotation(Layout.class);
// if (layoutAnnotation == null) {
// throw new IllegalArgumentException(
// String.format("@%s annotation not found on class %s", Layout.class.getSimpleName(),
// screenType.getName()));
// }
//
// return layoutAnnotation.value();
// }
//
// public static void destroyScreen(View view) {
// destroyScreen(view.getContext().getApplicationContext(), view);
// }
//
// public static void destroyScreen(Context parentContext, View view) {
// MortarScope parentScope = Mortar.getScope(parentContext);
// MortarScope oldChildScope = Mortar.getScope(view.getContext());
// parentScope.destroyChild(oldChildScope);
// }
//
// public static Activity getActivity(Context context) {
// Context currentContext = context;
// while (currentContext instanceof ContextWrapper) {
// currentContext = ((ContextWrapper) currentContext).getBaseContext();
//
// if (currentContext instanceof Activity) {
// return (Activity) currentContext;
// } else if (currentContext instanceof Application) {
// return null;
// }
// }
//
// return null;
// }
//
// }
| import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import flow.Flow;
import mortar.Blueprint;
import mortar.Mortar;
import mortar.MortarScope;
import mortar.lib.util.MortarUtil; | package mortar.lib.screen;
/**
* A conductor that can swap subviews within a container view.
* <p/>
*
* @param <S> the type of the screens that serve as a {@link Blueprint} for subview. Must
* be annotated with {@link flow.Layout}, suitable for use with {@link flow.Layouts#createView}.
*/
public abstract class AbstractScreenConductor<S extends Blueprint> implements CanShowScreen<S> {
private final Context mContext;
private final ViewGroup mContainer;
/**
* @param container the container used to host child views. Typically this is a {@link
* android.widget.FrameLayout} under the action bar.
*/
public AbstractScreenConductor(Context context, ViewGroup container) {
this.mContext = context;
this.mContainer = container;
}
public void showScreen(S screen, Flow.Direction direction) {
MortarScope parentScope = Mortar.getScope(mContext);
MortarScope newChildScope = parentScope.requireChild(screen);
View oldChild = getChildView();
if (oldChild != null) {
MortarScope oldChildScope = Mortar.getScope(oldChild.getContext());
if (oldChildScope.getName().equals(screen.getMortarScopeName())) {
// If it's already showing, short circuit.
return;
}
parentScope.destroyChild(oldChildScope);
}
// Create the new child.
Context childContext = newChildScope.createContext(mContext);
View newView = inflateScreen(childContext, screen, mContainer);
animateAndAddScreen(childContext, direction, oldChild, newView, mContainer);
}
protected View inflateScreen(Context context, S screen, ViewGroup container) { | // Path: lib/src/main/java/mortar/lib/util/MortarUtil.java
// public class MortarUtil {
//
// public static View createScreen(Context context, Blueprint screen) {
// MortarScope scope = Mortar.getScope(context);
// MortarScope newChildScope = scope.requireChild(screen);
//
// Context childContext = newChildScope.createContext(context);
// return Layouts.createView(childContext, screen);
// }
//
// public static int getLayoutId(Blueprint screen) {
// Class<? extends Blueprint> screenType = screen.getClass();
// Layout layoutAnnotation = screenType.getAnnotation(Layout.class);
// if (layoutAnnotation == null) {
// throw new IllegalArgumentException(
// String.format("@%s annotation not found on class %s", Layout.class.getSimpleName(),
// screenType.getName()));
// }
//
// return layoutAnnotation.value();
// }
//
// public static void destroyScreen(View view) {
// destroyScreen(view.getContext().getApplicationContext(), view);
// }
//
// public static void destroyScreen(Context parentContext, View view) {
// MortarScope parentScope = Mortar.getScope(parentContext);
// MortarScope oldChildScope = Mortar.getScope(view.getContext());
// parentScope.destroyChild(oldChildScope);
// }
//
// public static Activity getActivity(Context context) {
// Context currentContext = context;
// while (currentContext instanceof ContextWrapper) {
// currentContext = ((ContextWrapper) currentContext).getBaseContext();
//
// if (currentContext instanceof Activity) {
// return (Activity) currentContext;
// } else if (currentContext instanceof Application) {
// return null;
// }
// }
//
// return null;
// }
//
// }
// Path: lib/src/main/java/mortar/lib/screen/AbstractScreenConductor.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import flow.Flow;
import mortar.Blueprint;
import mortar.Mortar;
import mortar.MortarScope;
import mortar.lib.util.MortarUtil;
package mortar.lib.screen;
/**
* A conductor that can swap subviews within a container view.
* <p/>
*
* @param <S> the type of the screens that serve as a {@link Blueprint} for subview. Must
* be annotated with {@link flow.Layout}, suitable for use with {@link flow.Layouts#createView}.
*/
public abstract class AbstractScreenConductor<S extends Blueprint> implements CanShowScreen<S> {
private final Context mContext;
private final ViewGroup mContainer;
/**
* @param container the container used to host child views. Typically this is a {@link
* android.widget.FrameLayout} under the action bar.
*/
public AbstractScreenConductor(Context context, ViewGroup container) {
this.mContext = context;
this.mContainer = container;
}
public void showScreen(S screen, Flow.Direction direction) {
MortarScope parentScope = Mortar.getScope(mContext);
MortarScope newChildScope = parentScope.requireChild(screen);
View oldChild = getChildView();
if (oldChild != null) {
MortarScope oldChildScope = Mortar.getScope(oldChild.getContext());
if (oldChildScope.getName().equals(screen.getMortarScopeName())) {
// If it's already showing, short circuit.
return;
}
parentScope.destroyChild(oldChildScope);
}
// Create the new child.
Context childContext = newChildScope.createContext(mContext);
View newView = inflateScreen(childContext, screen, mContainer);
animateAndAddScreen(childContext, direction, oldChild, newView, mContainer);
}
protected View inflateScreen(Context context, S screen, ViewGroup container) { | int layoutId = MortarUtil.getLayoutId(screen); |
WeMakeBetterApps/MortarLib | lib/src/main/java/mortar/lib/view/MortarPagerAdapter.java | // Path: lib/src/main/java/mortar/lib/util/MortarUtil.java
// public class MortarUtil {
//
// public static View createScreen(Context context, Blueprint screen) {
// MortarScope scope = Mortar.getScope(context);
// MortarScope newChildScope = scope.requireChild(screen);
//
// Context childContext = newChildScope.createContext(context);
// return Layouts.createView(childContext, screen);
// }
//
// public static int getLayoutId(Blueprint screen) {
// Class<? extends Blueprint> screenType = screen.getClass();
// Layout layoutAnnotation = screenType.getAnnotation(Layout.class);
// if (layoutAnnotation == null) {
// throw new IllegalArgumentException(
// String.format("@%s annotation not found on class %s", Layout.class.getSimpleName(),
// screenType.getName()));
// }
//
// return layoutAnnotation.value();
// }
//
// public static void destroyScreen(View view) {
// destroyScreen(view.getContext().getApplicationContext(), view);
// }
//
// public static void destroyScreen(Context parentContext, View view) {
// MortarScope parentScope = Mortar.getScope(parentContext);
// MortarScope oldChildScope = Mortar.getScope(view.getContext());
// parentScope.destroyChild(oldChildScope);
// }
//
// public static Activity getActivity(Context context) {
// Context currentContext = context;
// while (currentContext instanceof ContextWrapper) {
// currentContext = ((ContextWrapper) currentContext).getBaseContext();
//
// if (currentContext instanceof Activity) {
// return (Activity) currentContext;
// } else if (currentContext instanceof Application) {
// return null;
// }
// }
//
// return null;
// }
//
// }
| import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import mortar.Blueprint;
import mortar.lib.util.MortarUtil; | package mortar.lib.view;
public abstract class MortarPagerAdapter extends PagerAdapter {
public abstract Blueprint getScreen(int position);
public Context getContext(ViewGroup container) {
return container.getContext();
}
@Override public boolean isViewFromObject(View view, Object o) {
return view == o;
}
@Override public Object instantiateItem(ViewGroup container, int position) {
Blueprint blueprint = getScreen(position); | // Path: lib/src/main/java/mortar/lib/util/MortarUtil.java
// public class MortarUtil {
//
// public static View createScreen(Context context, Blueprint screen) {
// MortarScope scope = Mortar.getScope(context);
// MortarScope newChildScope = scope.requireChild(screen);
//
// Context childContext = newChildScope.createContext(context);
// return Layouts.createView(childContext, screen);
// }
//
// public static int getLayoutId(Blueprint screen) {
// Class<? extends Blueprint> screenType = screen.getClass();
// Layout layoutAnnotation = screenType.getAnnotation(Layout.class);
// if (layoutAnnotation == null) {
// throw new IllegalArgumentException(
// String.format("@%s annotation not found on class %s", Layout.class.getSimpleName(),
// screenType.getName()));
// }
//
// return layoutAnnotation.value();
// }
//
// public static void destroyScreen(View view) {
// destroyScreen(view.getContext().getApplicationContext(), view);
// }
//
// public static void destroyScreen(Context parentContext, View view) {
// MortarScope parentScope = Mortar.getScope(parentContext);
// MortarScope oldChildScope = Mortar.getScope(view.getContext());
// parentScope.destroyChild(oldChildScope);
// }
//
// public static Activity getActivity(Context context) {
// Context currentContext = context;
// while (currentContext instanceof ContextWrapper) {
// currentContext = ((ContextWrapper) currentContext).getBaseContext();
//
// if (currentContext instanceof Activity) {
// return (Activity) currentContext;
// } else if (currentContext instanceof Application) {
// return null;
// }
// }
//
// return null;
// }
//
// }
// Path: lib/src/main/java/mortar/lib/view/MortarPagerAdapter.java
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import mortar.Blueprint;
import mortar.lib.util.MortarUtil;
package mortar.lib.view;
public abstract class MortarPagerAdapter extends PagerAdapter {
public abstract Blueprint getScreen(int position);
public Context getContext(ViewGroup container) {
return container.getContext();
}
@Override public boolean isViewFromObject(View view, Object o) {
return view == o;
}
@Override public Object instantiateItem(ViewGroup container, int position) {
Blueprint blueprint = getScreen(position); | View child = MortarUtil.createScreen(getContext(container), blueprint); |
WeMakeBetterApps/MortarLib | lib/src/main/java/mortar/lib/application/MortarApplication.java | // Path: lib/src/main/java/mortar/lib/inject/Injector.java
// public class Injector {
//
// private static ObjectGraph mApplicationGraph;
//
// public static <T> T get(Class<T> clazz) {
// return mApplicationGraph.get(clazz);
// }
//
// public static void inject(Object obj) {
// mApplicationGraph.inject(obj);
// }
//
// public static <T> T get(Context context, Class<T> clazz) {
// MortarScope scope = Mortar.getScope(context);
// ObjectGraph objectGraph = scope.getObjectGraph();
// return objectGraph.get(clazz);
// }
//
// public static ObjectGraph getApplicationGraph() {
// return mApplicationGraph;
// }
//
// public static void setApplicationGraph(ObjectGraph applicationGraph) {
// mApplicationGraph = applicationGraph;
// }
//
// }
| import android.app.Application;
import dagger.ObjectGraph;
import mortar.Mortar;
import mortar.MortarScope;
import mortar.lib.inject.Injector; | package mortar.lib.application;
public abstract class MortarApplication extends Application {
private MortarScope rootScope;
@Override public void onCreate() {
super.onCreate();
ObjectGraph applicationGraph = ObjectGraph.create(getRootScopeModules()); | // Path: lib/src/main/java/mortar/lib/inject/Injector.java
// public class Injector {
//
// private static ObjectGraph mApplicationGraph;
//
// public static <T> T get(Class<T> clazz) {
// return mApplicationGraph.get(clazz);
// }
//
// public static void inject(Object obj) {
// mApplicationGraph.inject(obj);
// }
//
// public static <T> T get(Context context, Class<T> clazz) {
// MortarScope scope = Mortar.getScope(context);
// ObjectGraph objectGraph = scope.getObjectGraph();
// return objectGraph.get(clazz);
// }
//
// public static ObjectGraph getApplicationGraph() {
// return mApplicationGraph;
// }
//
// public static void setApplicationGraph(ObjectGraph applicationGraph) {
// mApplicationGraph = applicationGraph;
// }
//
// }
// Path: lib/src/main/java/mortar/lib/application/MortarApplication.java
import android.app.Application;
import dagger.ObjectGraph;
import mortar.Mortar;
import mortar.MortarScope;
import mortar.lib.inject.Injector;
package mortar.lib.application;
public abstract class MortarApplication extends Application {
private MortarScope rootScope;
@Override public void onCreate() {
super.onCreate();
ObjectGraph applicationGraph = ObjectGraph.create(getRootScopeModules()); | Injector.setApplicationGraph(applicationGraph); |
WeMakeBetterApps/MortarLib | sample/src/main/java/mortar/lib/sample/activity/MainActivity.java | // Path: lib/src/main/java/mortar/lib/activity/MortarActivity.java
// public abstract class MortarActivity extends Activity implements ResumeAndPauseActivity {
//
// private MortarActivityScope mActivityScope;
// private final ResumeAndPauseOwner mResumeAndPauseOwner = new ResumeAndPauseOwner();
// private boolean mIsRunning = false;
//
// protected abstract Blueprint getNewActivityScreen();
//
// @Override protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// Application application = getApplication();
// if ( !(application instanceof MortarApplication) ) {
// throw new RuntimeException("Application must be an instance of " + MortarApplication.class.getName());
// }
// //noinspection ConstantConditions
// MortarScope parentScope = ((MortarApplication) application).getRootScope();
//
// Blueprint activityScope = getNewActivityScreen();
// if (activityScope == null)
// throw new RuntimeException("Provided activity scope for "
// + MortarActivity.class.getSimpleName() + " cannot be null.");
//
// mActivityScope = Mortar.requireActivityScope(parentScope, activityScope);
// Mortar.inject(this, this);
//
// mActivityScope.onCreate(savedInstanceState);
// mResumeAndPauseOwner.takeView(this);
// }
//
// @Override protected void onResume() {
// super.onResume();
// mIsRunning = true;
// mResumeAndPauseOwner.activityResumed();
// }
//
// @Override protected void onPause() {
// mIsRunning = false;
// mResumeAndPauseOwner.activityPaused();
// super.onPause();
// }
//
// @Override protected void onDestroy() {
// mResumeAndPauseOwner.dropView(this);
// super.onDestroy();
// }
//
// @Override public ResumeAndPauseOwner getResumeAndPausePresenter() {
// return mResumeAndPauseOwner;
// }
//
// @Override public Object getSystemService(String name) {
// if (Mortar.isScopeSystemService(name)) {
// return mActivityScope;
// }
// return super.getSystemService(name);
// }
//
// @SuppressWarnings("NullableProblems")
// @Override protected void onSaveInstanceState(Bundle outState) {
// super.onSaveInstanceState(outState);
// mActivityScope.onSaveInstanceState(outState);
// }
//
// public MortarActivityScope getMortarScope() {
// return mActivityScope;
// }
//
// /**
// * Dev tools and the play store (and others?) launch with a different intent, and so
// * lead to a redundant instance of this activity being spawned. <a
// * href="http://stackoverflow.com/questions/17702202/find-out-whether-the-current-activity-will-be-task-root-eventually-after-pendin"
// * >Details</a>.
// */
// protected boolean isWrongInstance() {
// if (!isTaskRoot()) {
// Intent intent = getIntent();
// boolean isMainAction = intent.getAction() != null && intent.getAction().equals(ACTION_MAIN);
// return intent.hasCategory(CATEGORY_LAUNCHER) && isMainAction;
// }
// return false;
// }
//
// protected FlowOwnerView getMainView() {
// ViewGroup root = (ViewGroup) findViewById(android.R.id.content);
// return (FlowOwnerView) root.getChildAt(0);
// }
//
// /** Inform the view about back events. */
// @Override public void onBackPressed() {
// // Give the view a chance to handle going back. If it declines the honor, let super do its thing.
// FlowOwnerView view = getMainView();
// if (!view.getFlow().goBack()) super.onBackPressed();
// }
//
// /** Inform the view about up events. */
// @Override public boolean onOptionsItemSelected(MenuItem item) {
// if (item.getItemId() == android.R.id.home) {
// FlowOwnerView view = getMainView();
// return view.getFlow().goUp();
// }
//
// return super.onOptionsItemSelected(item);
// }
//
// @Override public boolean isRunning() {
// return mIsRunning;
// }
//
// }
//
// Path: sample/src/main/java/mortar/lib/sample/screen/ActivityScreen.java
// public class ActivityScreen implements Blueprint {
//
// public ActivityScreen() {
// }
//
// @Override public String getMortarScopeName() {
// return ActivityScreen.class.getName();
// }
//
// @Override public Object getDaggerModule() {
// return new Module();
// }
//
// @dagger.Module(
// addsTo = SampleModule.class,
// injects = {
// MainActivity.class,
// ActivityView.class,
// },
// library = true
// )
// public class Module {
// @Provides @Singleton Flow provideFlow(Presenter presenter) {
// return presenter.getFlow();
// }
// }
//
// @Singleton public static class Presenter extends FlowOwner<Blueprint, ActivityView> {
// @Inject Presenter(Parcer<Object> flowParcer) {
// super(flowParcer);
// }
//
// @Override protected Blueprint getFirstScreen() {
// return new SampleScreen1();
// }
// }
//
// }
| import android.os.Bundle;
import mortar.Blueprint;
import mortar.lib.activity.MortarActivity;
import mortar.lib.sample.R;
import mortar.lib.sample.screen.ActivityScreen; | package mortar.lib.sample.activity;
public class MainActivity extends MortarActivity {
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override protected Blueprint getNewActivityScreen() { | // Path: lib/src/main/java/mortar/lib/activity/MortarActivity.java
// public abstract class MortarActivity extends Activity implements ResumeAndPauseActivity {
//
// private MortarActivityScope mActivityScope;
// private final ResumeAndPauseOwner mResumeAndPauseOwner = new ResumeAndPauseOwner();
// private boolean mIsRunning = false;
//
// protected abstract Blueprint getNewActivityScreen();
//
// @Override protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// Application application = getApplication();
// if ( !(application instanceof MortarApplication) ) {
// throw new RuntimeException("Application must be an instance of " + MortarApplication.class.getName());
// }
// //noinspection ConstantConditions
// MortarScope parentScope = ((MortarApplication) application).getRootScope();
//
// Blueprint activityScope = getNewActivityScreen();
// if (activityScope == null)
// throw new RuntimeException("Provided activity scope for "
// + MortarActivity.class.getSimpleName() + " cannot be null.");
//
// mActivityScope = Mortar.requireActivityScope(parentScope, activityScope);
// Mortar.inject(this, this);
//
// mActivityScope.onCreate(savedInstanceState);
// mResumeAndPauseOwner.takeView(this);
// }
//
// @Override protected void onResume() {
// super.onResume();
// mIsRunning = true;
// mResumeAndPauseOwner.activityResumed();
// }
//
// @Override protected void onPause() {
// mIsRunning = false;
// mResumeAndPauseOwner.activityPaused();
// super.onPause();
// }
//
// @Override protected void onDestroy() {
// mResumeAndPauseOwner.dropView(this);
// super.onDestroy();
// }
//
// @Override public ResumeAndPauseOwner getResumeAndPausePresenter() {
// return mResumeAndPauseOwner;
// }
//
// @Override public Object getSystemService(String name) {
// if (Mortar.isScopeSystemService(name)) {
// return mActivityScope;
// }
// return super.getSystemService(name);
// }
//
// @SuppressWarnings("NullableProblems")
// @Override protected void onSaveInstanceState(Bundle outState) {
// super.onSaveInstanceState(outState);
// mActivityScope.onSaveInstanceState(outState);
// }
//
// public MortarActivityScope getMortarScope() {
// return mActivityScope;
// }
//
// /**
// * Dev tools and the play store (and others?) launch with a different intent, and so
// * lead to a redundant instance of this activity being spawned. <a
// * href="http://stackoverflow.com/questions/17702202/find-out-whether-the-current-activity-will-be-task-root-eventually-after-pendin"
// * >Details</a>.
// */
// protected boolean isWrongInstance() {
// if (!isTaskRoot()) {
// Intent intent = getIntent();
// boolean isMainAction = intent.getAction() != null && intent.getAction().equals(ACTION_MAIN);
// return intent.hasCategory(CATEGORY_LAUNCHER) && isMainAction;
// }
// return false;
// }
//
// protected FlowOwnerView getMainView() {
// ViewGroup root = (ViewGroup) findViewById(android.R.id.content);
// return (FlowOwnerView) root.getChildAt(0);
// }
//
// /** Inform the view about back events. */
// @Override public void onBackPressed() {
// // Give the view a chance to handle going back. If it declines the honor, let super do its thing.
// FlowOwnerView view = getMainView();
// if (!view.getFlow().goBack()) super.onBackPressed();
// }
//
// /** Inform the view about up events. */
// @Override public boolean onOptionsItemSelected(MenuItem item) {
// if (item.getItemId() == android.R.id.home) {
// FlowOwnerView view = getMainView();
// return view.getFlow().goUp();
// }
//
// return super.onOptionsItemSelected(item);
// }
//
// @Override public boolean isRunning() {
// return mIsRunning;
// }
//
// }
//
// Path: sample/src/main/java/mortar/lib/sample/screen/ActivityScreen.java
// public class ActivityScreen implements Blueprint {
//
// public ActivityScreen() {
// }
//
// @Override public String getMortarScopeName() {
// return ActivityScreen.class.getName();
// }
//
// @Override public Object getDaggerModule() {
// return new Module();
// }
//
// @dagger.Module(
// addsTo = SampleModule.class,
// injects = {
// MainActivity.class,
// ActivityView.class,
// },
// library = true
// )
// public class Module {
// @Provides @Singleton Flow provideFlow(Presenter presenter) {
// return presenter.getFlow();
// }
// }
//
// @Singleton public static class Presenter extends FlowOwner<Blueprint, ActivityView> {
// @Inject Presenter(Parcer<Object> flowParcer) {
// super(flowParcer);
// }
//
// @Override protected Blueprint getFirstScreen() {
// return new SampleScreen1();
// }
// }
//
// }
// Path: sample/src/main/java/mortar/lib/sample/activity/MainActivity.java
import android.os.Bundle;
import mortar.Blueprint;
import mortar.lib.activity.MortarActivity;
import mortar.lib.sample.R;
import mortar.lib.sample.screen.ActivityScreen;
package mortar.lib.sample.activity;
public class MainActivity extends MortarActivity {
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override protected Blueprint getNewActivityScreen() { | return new ActivityScreen(); |
WeMakeBetterApps/MortarLib | lib/src/main/java/mortar/lib/inject/MortarModule.java | // Path: lib/src/main/java/mortar/lib/util/GsonParcer.java
// public class GsonParcer<T> implements Parcer<T> {
//
// private final Gson gson;
//
// public GsonParcer() {
// this(new Gson());
// }
//
// public GsonParcer(Gson gson) {
// this.gson = gson;
// }
//
// @Override public Parcelable wrap(T instance) {
// try {
// String json = encode(instance);
// return new Wrapper(json);
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// @Override public T unwrap(Parcelable parcelable) {
// Wrapper wrapper = (Wrapper) parcelable;
// try {
// return decode(wrapper.json);
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// private String encode(T instance) throws IOException {
// StringWriter stringWriter = new StringWriter();
// JsonWriter writer = new JsonWriter(stringWriter);
//
// try {
// Class<?> type = instance.getClass();
//
// writer.beginObject();
// writer.name(type.getName());
// gson.toJson(instance, type, writer);
// writer.endObject();
//
// return stringWriter.toString();
// } finally {
// writer.close();
// }
// }
//
// private T decode(String json) throws IOException {
// JsonReader reader = new JsonReader(new StringReader(json));
//
// try {
// reader.beginObject();
//
// Class<?> type = Class.forName(reader.nextName());
// return gson.fromJson(reader, type);
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// } finally {
// reader.close();
// }
// }
//
// private static class Wrapper implements Parcelable {
// final String json;
//
// Wrapper(String json) {
// this.json = json;
// }
//
// @Override public int describeContents() {
// return 0;
// }
//
// @Override public void writeToParcel(Parcel out, int flags) {
// out.writeString(json);
// }
//
// @SuppressWarnings("UnusedDeclaration")
// public static final Parcelable.Creator<Wrapper> CREATOR = new Parcelable.Creator<Wrapper>() {
// @Override public Wrapper createFromParcel(Parcel in) {
// String json = in.readString();
// return new Wrapper(json);
// }
//
// @Override public Wrapper[] newArray(int size) {
// return new Wrapper[size];
// }
// };
// }
// }
| import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import flow.Parcer;
import mortar.lib.util.GsonParcer; | package mortar.lib.inject;
@Module(
library = true
)
public class MortarModule {
@Provides @Singleton Parcer<Object> provideParcer() { | // Path: lib/src/main/java/mortar/lib/util/GsonParcer.java
// public class GsonParcer<T> implements Parcer<T> {
//
// private final Gson gson;
//
// public GsonParcer() {
// this(new Gson());
// }
//
// public GsonParcer(Gson gson) {
// this.gson = gson;
// }
//
// @Override public Parcelable wrap(T instance) {
// try {
// String json = encode(instance);
// return new Wrapper(json);
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// @Override public T unwrap(Parcelable parcelable) {
// Wrapper wrapper = (Wrapper) parcelable;
// try {
// return decode(wrapper.json);
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// private String encode(T instance) throws IOException {
// StringWriter stringWriter = new StringWriter();
// JsonWriter writer = new JsonWriter(stringWriter);
//
// try {
// Class<?> type = instance.getClass();
//
// writer.beginObject();
// writer.name(type.getName());
// gson.toJson(instance, type, writer);
// writer.endObject();
//
// return stringWriter.toString();
// } finally {
// writer.close();
// }
// }
//
// private T decode(String json) throws IOException {
// JsonReader reader = new JsonReader(new StringReader(json));
//
// try {
// reader.beginObject();
//
// Class<?> type = Class.forName(reader.nextName());
// return gson.fromJson(reader, type);
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// } finally {
// reader.close();
// }
// }
//
// private static class Wrapper implements Parcelable {
// final String json;
//
// Wrapper(String json) {
// this.json = json;
// }
//
// @Override public int describeContents() {
// return 0;
// }
//
// @Override public void writeToParcel(Parcel out, int flags) {
// out.writeString(json);
// }
//
// @SuppressWarnings("UnusedDeclaration")
// public static final Parcelable.Creator<Wrapper> CREATOR = new Parcelable.Creator<Wrapper>() {
// @Override public Wrapper createFromParcel(Parcel in) {
// String json = in.readString();
// return new Wrapper(json);
// }
//
// @Override public Wrapper[] newArray(int size) {
// return new Wrapper[size];
// }
// };
// }
// }
// Path: lib/src/main/java/mortar/lib/inject/MortarModule.java
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import flow.Parcer;
import mortar.lib.util.GsonParcer;
package mortar.lib.inject;
@Module(
library = true
)
public class MortarModule {
@Provides @Singleton Parcer<Object> provideParcer() { | return new GsonParcer<Object>(); |
Vedenin/RestAndSpringMVC-CodingChallenge | src/main/java/com/github/vedenin/codingchallenge/restclient/impl/openexchange/OpenExchangeRestClient.java | // Path: src/main/java/com/github/vedenin/codingchallenge/exceptions/RestClientException.java
// public class RestClientException extends RuntimeException {
// public RestClientException() {
// }
//
// public RestClientException(String message) {
// super(message);
// }
//
// public RestClientException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public RestClientException(Throwable cause) {
// super(cause);
// }
//
// public RestClientException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/restclient/RestClient.java
// public interface RestClient {
// BigDecimal getCurrentExchangeRates(CurrencyEnum currecnyFrom, CurrencyEnum currecnyTo);
// BigDecimal getHistoricalExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, Calendar calendar);
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
| import com.github.vedenin.codingchallenge.exceptions.RestClientException;
import com.github.vedenin.codingchallenge.restclient.RestClient;
import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import org.springframework.stereotype.Service;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Response;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.GregorianCalendar;
import static java.math.BigDecimal.ROUND_FLOOR; | package com.github.vedenin.codingchallenge.restclient.impl.openexchange;
/**
* Created by slava on 04.02.17.
*/
@Service("OpenExchange")
public class OpenExchangeRestClient implements RestClient {
private final static String URL_LAST = "https://openexchangerates.org/api/latest.json?";
private final static String URL_HISTORY = "https://openexchangerates.org/api/historical/";
private final static String API_ID = "20b5648a4f504982aba6464b13160704";
private final static String API_ID_PRM = "app_id=";
public static final String ERROR_WHILE_GATHERING_INFORMATION = "Error while gathering information from OpenExchange services";
| // Path: src/main/java/com/github/vedenin/codingchallenge/exceptions/RestClientException.java
// public class RestClientException extends RuntimeException {
// public RestClientException() {
// }
//
// public RestClientException(String message) {
// super(message);
// }
//
// public RestClientException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public RestClientException(Throwable cause) {
// super(cause);
// }
//
// public RestClientException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/restclient/RestClient.java
// public interface RestClient {
// BigDecimal getCurrentExchangeRates(CurrencyEnum currecnyFrom, CurrencyEnum currecnyTo);
// BigDecimal getHistoricalExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, Calendar calendar);
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
// Path: src/main/java/com/github/vedenin/codingchallenge/restclient/impl/openexchange/OpenExchangeRestClient.java
import com.github.vedenin.codingchallenge.exceptions.RestClientException;
import com.github.vedenin.codingchallenge.restclient.RestClient;
import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import org.springframework.stereotype.Service;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Response;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.GregorianCalendar;
import static java.math.BigDecimal.ROUND_FLOOR;
package com.github.vedenin.codingchallenge.restclient.impl.openexchange;
/**
* Created by slava on 04.02.17.
*/
@Service("OpenExchange")
public class OpenExchangeRestClient implements RestClient {
private final static String URL_LAST = "https://openexchangerates.org/api/latest.json?";
private final static String URL_HISTORY = "https://openexchangerates.org/api/historical/";
private final static String API_ID = "20b5648a4f504982aba6464b13160704";
private final static String API_ID_PRM = "app_id=";
public static final String ERROR_WHILE_GATHERING_INFORMATION = "Error while gathering information from OpenExchange services";
| public BigDecimal getCurrentExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo) { |
Vedenin/RestAndSpringMVC-CodingChallenge | src/main/java/com/github/vedenin/codingchallenge/restclient/impl/openexchange/OpenExchangeRestClient.java | // Path: src/main/java/com/github/vedenin/codingchallenge/exceptions/RestClientException.java
// public class RestClientException extends RuntimeException {
// public RestClientException() {
// }
//
// public RestClientException(String message) {
// super(message);
// }
//
// public RestClientException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public RestClientException(Throwable cause) {
// super(cause);
// }
//
// public RestClientException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/restclient/RestClient.java
// public interface RestClient {
// BigDecimal getCurrentExchangeRates(CurrencyEnum currecnyFrom, CurrencyEnum currecnyTo);
// BigDecimal getHistoricalExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, Calendar calendar);
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
| import com.github.vedenin.codingchallenge.exceptions.RestClientException;
import com.github.vedenin.codingchallenge.restclient.RestClient;
import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import org.springframework.stereotype.Service;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Response;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.GregorianCalendar;
import static java.math.BigDecimal.ROUND_FLOOR; | return getExchangeRates(currencyFrom, currencyTo, getCurrentRates());
}
public BigDecimal getHistoricalExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, Calendar calendar) {
return getExchangeRates(currencyFrom, currencyTo, getHistoricalRates(calendar));
}
private BigDecimal getExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, OpenExchangeRatesContainer rates) {
BigDecimal currencyFromRate = getRates(currencyFrom, rates);
BigDecimal currencyToRate = getRates(currencyTo, rates);
return currencyToRate.divide(currencyFromRate, 20, ROUND_FLOOR);
}
public OpenExchangeRatesContainer getCurrentRates() {
return getEntity(URL_LAST, API_ID, OpenExchangeRatesContainer.class);
}
public OpenExchangeRatesContainer getHistoricalRates(Calendar date) {
return getEntity(URL_HISTORY + date.get(Calendar.YEAR) + "-" +
getStringWithLeftPadZero(date.get(Calendar.MONTH) + 1) + "-" +
getStringWithLeftPadZero(date.get(Calendar.DAY_OF_MONTH)) + ".json?"
, API_ID, OpenExchangeRatesContainer.class);
}
private String getStringWithLeftPadZero(int number) {
return String.format("%02d", number);
}
private static BigDecimal getRates(CurrencyEnum currency, OpenExchangeRatesContainer rates) {
if (rates.getRates() == null || rates.getRates().get(currency.getCode()) == null) { | // Path: src/main/java/com/github/vedenin/codingchallenge/exceptions/RestClientException.java
// public class RestClientException extends RuntimeException {
// public RestClientException() {
// }
//
// public RestClientException(String message) {
// super(message);
// }
//
// public RestClientException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public RestClientException(Throwable cause) {
// super(cause);
// }
//
// public RestClientException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/restclient/RestClient.java
// public interface RestClient {
// BigDecimal getCurrentExchangeRates(CurrencyEnum currecnyFrom, CurrencyEnum currecnyTo);
// BigDecimal getHistoricalExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, Calendar calendar);
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
// Path: src/main/java/com/github/vedenin/codingchallenge/restclient/impl/openexchange/OpenExchangeRestClient.java
import com.github.vedenin.codingchallenge.exceptions.RestClientException;
import com.github.vedenin.codingchallenge.restclient.RestClient;
import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import org.springframework.stereotype.Service;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Response;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.GregorianCalendar;
import static java.math.BigDecimal.ROUND_FLOOR;
return getExchangeRates(currencyFrom, currencyTo, getCurrentRates());
}
public BigDecimal getHistoricalExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, Calendar calendar) {
return getExchangeRates(currencyFrom, currencyTo, getHistoricalRates(calendar));
}
private BigDecimal getExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, OpenExchangeRatesContainer rates) {
BigDecimal currencyFromRate = getRates(currencyFrom, rates);
BigDecimal currencyToRate = getRates(currencyTo, rates);
return currencyToRate.divide(currencyFromRate, 20, ROUND_FLOOR);
}
public OpenExchangeRatesContainer getCurrentRates() {
return getEntity(URL_LAST, API_ID, OpenExchangeRatesContainer.class);
}
public OpenExchangeRatesContainer getHistoricalRates(Calendar date) {
return getEntity(URL_HISTORY + date.get(Calendar.YEAR) + "-" +
getStringWithLeftPadZero(date.get(Calendar.MONTH) + 1) + "-" +
getStringWithLeftPadZero(date.get(Calendar.DAY_OF_MONTH)) + ".json?"
, API_ID, OpenExchangeRatesContainer.class);
}
private String getStringWithLeftPadZero(int number) {
return String.format("%02d", number);
}
private static BigDecimal getRates(CurrencyEnum currency, OpenExchangeRatesContainer rates) {
if (rates.getRates() == null || rates.getRates().get(currency.getCode()) == null) { | throw new RestClientException(ERROR_WHILE_GATHERING_INFORMATION + |
Vedenin/RestAndSpringMVC-CodingChallenge | src/main/java/com/github/vedenin/codingchallenge/mvc/controler/MainWebController.java | // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/converter/CurrencyConvector.java
// public interface CurrencyConvector {
// BigDecimal getConvertingValue(Boolean isHistory, BigDecimal amount, CurrencyEnum currencyFrom,
// CurrencyEnum currencyTo, Calendar calendar);
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/converter/DateConverter.java
// public interface DateConverter {
// Calendar getCalendarFromString(String date);
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/model/ConverterFormModel.java
// public class ConverterFormModel {
// @NotNull
// private String to = CurrencyEnum.USD.getCode();
// @NotNull
// private String from = CurrencyEnum.EUR.getCode();
// @Min(0)
// @NotNull
// private BigDecimal amount = new BigDecimal(0.0);
//
// private String type = "current";
//
// private String date = "";
//
// public String getTo() {
// return to;
// }
//
// public void setTo(String to) {
// this.to = to;
// }
//
// public String getFrom() {
// return from;
// }
//
// public void setFrom(String from) {
// this.from = from;
// }
//
// public BigDecimal getAmount() {
// return amount;
// }
//
// public void setAmount(BigDecimal amount) {
// this.amount = amount;
// }
//
// public CurrencyEnum getCurrencyEnumTo() {
// return Enum.valueOf(CurrencyEnum.class, to);
// }
//
// public CurrencyEnum getCurrencyEnumFrom() {
// return Enum.valueOf(CurrencyEnum.class, from);
// }
//
// public String getType() {
// return type;
// }
//
// public Boolean isHistory() {
// return type.equals("history");
// }
// public void setType(String type) {
// this.type = type;
// }
//
// public String getDate() {
// return date;
// }
//
// public void setDate(String date) {
// this.date = date;
// }
//
// @AssertTrue
// public boolean isDataCorrect() {
// return type.equals("current") || !date.isEmpty();
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/model/CountryService.java
// public interface CountryService {
// List<String> getCountriesNames();
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/Consts.java
// public final class Consts {
// public static final String CONVERTER_URL = "converter";
// public static final String LOGIN_URL = "login";
// public static final String REGISTER_URL = "register";
// }
| import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import com.github.vedenin.codingchallenge.converter.CurrencyConvector;
import com.github.vedenin.codingchallenge.converter.DateConverter;
import com.github.vedenin.codingchallenge.mvc.model.ConverterFormModel;
import com.github.vedenin.codingchallenge.mvc.model.CountryService;
import com.github.vedenin.codingchallenge.persistence.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.math.BigDecimal;
import java.util.Date;
import javax.inject.Inject;
import static com.github.vedenin.codingchallenge.mvc.Consts.*; | package com.github.vedenin.codingchallenge.mvc.controler;
/*
* Controller that provide main page of Converter application
*/
@Controller
public class MainWebController extends WebMvcConfigurerAdapter {
private static final String CURRENCY_ENUM = "currencyEnum";
private static final String RESULT = "result";
@Inject | // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/converter/CurrencyConvector.java
// public interface CurrencyConvector {
// BigDecimal getConvertingValue(Boolean isHistory, BigDecimal amount, CurrencyEnum currencyFrom,
// CurrencyEnum currencyTo, Calendar calendar);
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/converter/DateConverter.java
// public interface DateConverter {
// Calendar getCalendarFromString(String date);
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/model/ConverterFormModel.java
// public class ConverterFormModel {
// @NotNull
// private String to = CurrencyEnum.USD.getCode();
// @NotNull
// private String from = CurrencyEnum.EUR.getCode();
// @Min(0)
// @NotNull
// private BigDecimal amount = new BigDecimal(0.0);
//
// private String type = "current";
//
// private String date = "";
//
// public String getTo() {
// return to;
// }
//
// public void setTo(String to) {
// this.to = to;
// }
//
// public String getFrom() {
// return from;
// }
//
// public void setFrom(String from) {
// this.from = from;
// }
//
// public BigDecimal getAmount() {
// return amount;
// }
//
// public void setAmount(BigDecimal amount) {
// this.amount = amount;
// }
//
// public CurrencyEnum getCurrencyEnumTo() {
// return Enum.valueOf(CurrencyEnum.class, to);
// }
//
// public CurrencyEnum getCurrencyEnumFrom() {
// return Enum.valueOf(CurrencyEnum.class, from);
// }
//
// public String getType() {
// return type;
// }
//
// public Boolean isHistory() {
// return type.equals("history");
// }
// public void setType(String type) {
// this.type = type;
// }
//
// public String getDate() {
// return date;
// }
//
// public void setDate(String date) {
// this.date = date;
// }
//
// @AssertTrue
// public boolean isDataCorrect() {
// return type.equals("current") || !date.isEmpty();
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/model/CountryService.java
// public interface CountryService {
// List<String> getCountriesNames();
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/Consts.java
// public final class Consts {
// public static final String CONVERTER_URL = "converter";
// public static final String LOGIN_URL = "login";
// public static final String REGISTER_URL = "register";
// }
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/controler/MainWebController.java
import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import com.github.vedenin.codingchallenge.converter.CurrencyConvector;
import com.github.vedenin.codingchallenge.converter.DateConverter;
import com.github.vedenin.codingchallenge.mvc.model.ConverterFormModel;
import com.github.vedenin.codingchallenge.mvc.model.CountryService;
import com.github.vedenin.codingchallenge.persistence.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.math.BigDecimal;
import java.util.Date;
import javax.inject.Inject;
import static com.github.vedenin.codingchallenge.mvc.Consts.*;
package com.github.vedenin.codingchallenge.mvc.controler;
/*
* Controller that provide main page of Converter application
*/
@Controller
public class MainWebController extends WebMvcConfigurerAdapter {
private static final String CURRENCY_ENUM = "currencyEnum";
private static final String RESULT = "result";
@Inject | CurrencyConvector currencyConvector; |
Vedenin/RestAndSpringMVC-CodingChallenge | src/main/java/com/github/vedenin/codingchallenge/mvc/controler/MainWebController.java | // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/converter/CurrencyConvector.java
// public interface CurrencyConvector {
// BigDecimal getConvertingValue(Boolean isHistory, BigDecimal amount, CurrencyEnum currencyFrom,
// CurrencyEnum currencyTo, Calendar calendar);
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/converter/DateConverter.java
// public interface DateConverter {
// Calendar getCalendarFromString(String date);
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/model/ConverterFormModel.java
// public class ConverterFormModel {
// @NotNull
// private String to = CurrencyEnum.USD.getCode();
// @NotNull
// private String from = CurrencyEnum.EUR.getCode();
// @Min(0)
// @NotNull
// private BigDecimal amount = new BigDecimal(0.0);
//
// private String type = "current";
//
// private String date = "";
//
// public String getTo() {
// return to;
// }
//
// public void setTo(String to) {
// this.to = to;
// }
//
// public String getFrom() {
// return from;
// }
//
// public void setFrom(String from) {
// this.from = from;
// }
//
// public BigDecimal getAmount() {
// return amount;
// }
//
// public void setAmount(BigDecimal amount) {
// this.amount = amount;
// }
//
// public CurrencyEnum getCurrencyEnumTo() {
// return Enum.valueOf(CurrencyEnum.class, to);
// }
//
// public CurrencyEnum getCurrencyEnumFrom() {
// return Enum.valueOf(CurrencyEnum.class, from);
// }
//
// public String getType() {
// return type;
// }
//
// public Boolean isHistory() {
// return type.equals("history");
// }
// public void setType(String type) {
// this.type = type;
// }
//
// public String getDate() {
// return date;
// }
//
// public void setDate(String date) {
// this.date = date;
// }
//
// @AssertTrue
// public boolean isDataCorrect() {
// return type.equals("current") || !date.isEmpty();
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/model/CountryService.java
// public interface CountryService {
// List<String> getCountriesNames();
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/Consts.java
// public final class Consts {
// public static final String CONVERTER_URL = "converter";
// public static final String LOGIN_URL = "login";
// public static final String REGISTER_URL = "register";
// }
| import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import com.github.vedenin.codingchallenge.converter.CurrencyConvector;
import com.github.vedenin.codingchallenge.converter.DateConverter;
import com.github.vedenin.codingchallenge.mvc.model.ConverterFormModel;
import com.github.vedenin.codingchallenge.mvc.model.CountryService;
import com.github.vedenin.codingchallenge.persistence.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.math.BigDecimal;
import java.util.Date;
import javax.inject.Inject;
import static com.github.vedenin.codingchallenge.mvc.Consts.*; | package com.github.vedenin.codingchallenge.mvc.controler;
/*
* Controller that provide main page of Converter application
*/
@Controller
public class MainWebController extends WebMvcConfigurerAdapter {
private static final String CURRENCY_ENUM = "currencyEnum";
private static final String RESULT = "result";
@Inject
CurrencyConvector currencyConvector;
@Inject | // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/converter/CurrencyConvector.java
// public interface CurrencyConvector {
// BigDecimal getConvertingValue(Boolean isHistory, BigDecimal amount, CurrencyEnum currencyFrom,
// CurrencyEnum currencyTo, Calendar calendar);
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/converter/DateConverter.java
// public interface DateConverter {
// Calendar getCalendarFromString(String date);
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/model/ConverterFormModel.java
// public class ConverterFormModel {
// @NotNull
// private String to = CurrencyEnum.USD.getCode();
// @NotNull
// private String from = CurrencyEnum.EUR.getCode();
// @Min(0)
// @NotNull
// private BigDecimal amount = new BigDecimal(0.0);
//
// private String type = "current";
//
// private String date = "";
//
// public String getTo() {
// return to;
// }
//
// public void setTo(String to) {
// this.to = to;
// }
//
// public String getFrom() {
// return from;
// }
//
// public void setFrom(String from) {
// this.from = from;
// }
//
// public BigDecimal getAmount() {
// return amount;
// }
//
// public void setAmount(BigDecimal amount) {
// this.amount = amount;
// }
//
// public CurrencyEnum getCurrencyEnumTo() {
// return Enum.valueOf(CurrencyEnum.class, to);
// }
//
// public CurrencyEnum getCurrencyEnumFrom() {
// return Enum.valueOf(CurrencyEnum.class, from);
// }
//
// public String getType() {
// return type;
// }
//
// public Boolean isHistory() {
// return type.equals("history");
// }
// public void setType(String type) {
// this.type = type;
// }
//
// public String getDate() {
// return date;
// }
//
// public void setDate(String date) {
// this.date = date;
// }
//
// @AssertTrue
// public boolean isDataCorrect() {
// return type.equals("current") || !date.isEmpty();
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/model/CountryService.java
// public interface CountryService {
// List<String> getCountriesNames();
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/Consts.java
// public final class Consts {
// public static final String CONVERTER_URL = "converter";
// public static final String LOGIN_URL = "login";
// public static final String REGISTER_URL = "register";
// }
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/controler/MainWebController.java
import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import com.github.vedenin.codingchallenge.converter.CurrencyConvector;
import com.github.vedenin.codingchallenge.converter.DateConverter;
import com.github.vedenin.codingchallenge.mvc.model.ConverterFormModel;
import com.github.vedenin.codingchallenge.mvc.model.CountryService;
import com.github.vedenin.codingchallenge.persistence.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.math.BigDecimal;
import java.util.Date;
import javax.inject.Inject;
import static com.github.vedenin.codingchallenge.mvc.Consts.*;
package com.github.vedenin.codingchallenge.mvc.controler;
/*
* Controller that provide main page of Converter application
*/
@Controller
public class MainWebController extends WebMvcConfigurerAdapter {
private static final String CURRENCY_ENUM = "currencyEnum";
private static final String RESULT = "result";
@Inject
CurrencyConvector currencyConvector;
@Inject | DateConverter dateConverter; |
Vedenin/RestAndSpringMVC-CodingChallenge | src/main/java/com/github/vedenin/codingchallenge/mvc/controler/MainWebController.java | // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/converter/CurrencyConvector.java
// public interface CurrencyConvector {
// BigDecimal getConvertingValue(Boolean isHistory, BigDecimal amount, CurrencyEnum currencyFrom,
// CurrencyEnum currencyTo, Calendar calendar);
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/converter/DateConverter.java
// public interface DateConverter {
// Calendar getCalendarFromString(String date);
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/model/ConverterFormModel.java
// public class ConverterFormModel {
// @NotNull
// private String to = CurrencyEnum.USD.getCode();
// @NotNull
// private String from = CurrencyEnum.EUR.getCode();
// @Min(0)
// @NotNull
// private BigDecimal amount = new BigDecimal(0.0);
//
// private String type = "current";
//
// private String date = "";
//
// public String getTo() {
// return to;
// }
//
// public void setTo(String to) {
// this.to = to;
// }
//
// public String getFrom() {
// return from;
// }
//
// public void setFrom(String from) {
// this.from = from;
// }
//
// public BigDecimal getAmount() {
// return amount;
// }
//
// public void setAmount(BigDecimal amount) {
// this.amount = amount;
// }
//
// public CurrencyEnum getCurrencyEnumTo() {
// return Enum.valueOf(CurrencyEnum.class, to);
// }
//
// public CurrencyEnum getCurrencyEnumFrom() {
// return Enum.valueOf(CurrencyEnum.class, from);
// }
//
// public String getType() {
// return type;
// }
//
// public Boolean isHistory() {
// return type.equals("history");
// }
// public void setType(String type) {
// this.type = type;
// }
//
// public String getDate() {
// return date;
// }
//
// public void setDate(String date) {
// this.date = date;
// }
//
// @AssertTrue
// public boolean isDataCorrect() {
// return type.equals("current") || !date.isEmpty();
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/model/CountryService.java
// public interface CountryService {
// List<String> getCountriesNames();
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/Consts.java
// public final class Consts {
// public static final String CONVERTER_URL = "converter";
// public static final String LOGIN_URL = "login";
// public static final String REGISTER_URL = "register";
// }
| import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import com.github.vedenin.codingchallenge.converter.CurrencyConvector;
import com.github.vedenin.codingchallenge.converter.DateConverter;
import com.github.vedenin.codingchallenge.mvc.model.ConverterFormModel;
import com.github.vedenin.codingchallenge.mvc.model.CountryService;
import com.github.vedenin.codingchallenge.persistence.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.math.BigDecimal;
import java.util.Date;
import javax.inject.Inject;
import static com.github.vedenin.codingchallenge.mvc.Consts.*; | package com.github.vedenin.codingchallenge.mvc.controler;
/*
* Controller that provide main page of Converter application
*/
@Controller
public class MainWebController extends WebMvcConfigurerAdapter {
private static final String CURRENCY_ENUM = "currencyEnum";
private static final String RESULT = "result";
@Inject
CurrencyConvector currencyConvector;
@Inject
DateConverter dateConverter;
@Inject
HistoryRepository historyRepository;
@Inject
UserRepository userRepository;
@Inject | // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/converter/CurrencyConvector.java
// public interface CurrencyConvector {
// BigDecimal getConvertingValue(Boolean isHistory, BigDecimal amount, CurrencyEnum currencyFrom,
// CurrencyEnum currencyTo, Calendar calendar);
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/converter/DateConverter.java
// public interface DateConverter {
// Calendar getCalendarFromString(String date);
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/model/ConverterFormModel.java
// public class ConverterFormModel {
// @NotNull
// private String to = CurrencyEnum.USD.getCode();
// @NotNull
// private String from = CurrencyEnum.EUR.getCode();
// @Min(0)
// @NotNull
// private BigDecimal amount = new BigDecimal(0.0);
//
// private String type = "current";
//
// private String date = "";
//
// public String getTo() {
// return to;
// }
//
// public void setTo(String to) {
// this.to = to;
// }
//
// public String getFrom() {
// return from;
// }
//
// public void setFrom(String from) {
// this.from = from;
// }
//
// public BigDecimal getAmount() {
// return amount;
// }
//
// public void setAmount(BigDecimal amount) {
// this.amount = amount;
// }
//
// public CurrencyEnum getCurrencyEnumTo() {
// return Enum.valueOf(CurrencyEnum.class, to);
// }
//
// public CurrencyEnum getCurrencyEnumFrom() {
// return Enum.valueOf(CurrencyEnum.class, from);
// }
//
// public String getType() {
// return type;
// }
//
// public Boolean isHistory() {
// return type.equals("history");
// }
// public void setType(String type) {
// this.type = type;
// }
//
// public String getDate() {
// return date;
// }
//
// public void setDate(String date) {
// this.date = date;
// }
//
// @AssertTrue
// public boolean isDataCorrect() {
// return type.equals("current") || !date.isEmpty();
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/model/CountryService.java
// public interface CountryService {
// List<String> getCountriesNames();
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/Consts.java
// public final class Consts {
// public static final String CONVERTER_URL = "converter";
// public static final String LOGIN_URL = "login";
// public static final String REGISTER_URL = "register";
// }
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/controler/MainWebController.java
import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import com.github.vedenin.codingchallenge.converter.CurrencyConvector;
import com.github.vedenin.codingchallenge.converter.DateConverter;
import com.github.vedenin.codingchallenge.mvc.model.ConverterFormModel;
import com.github.vedenin.codingchallenge.mvc.model.CountryService;
import com.github.vedenin.codingchallenge.persistence.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.math.BigDecimal;
import java.util.Date;
import javax.inject.Inject;
import static com.github.vedenin.codingchallenge.mvc.Consts.*;
package com.github.vedenin.codingchallenge.mvc.controler;
/*
* Controller that provide main page of Converter application
*/
@Controller
public class MainWebController extends WebMvcConfigurerAdapter {
private static final String CURRENCY_ENUM = "currencyEnum";
private static final String RESULT = "result";
@Inject
CurrencyConvector currencyConvector;
@Inject
DateConverter dateConverter;
@Inject
HistoryRepository historyRepository;
@Inject
UserRepository userRepository;
@Inject | CountryService countryService; |
Vedenin/RestAndSpringMVC-CodingChallenge | src/main/java/com/github/vedenin/codingchallenge/mvc/controler/MainWebController.java | // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/converter/CurrencyConvector.java
// public interface CurrencyConvector {
// BigDecimal getConvertingValue(Boolean isHistory, BigDecimal amount, CurrencyEnum currencyFrom,
// CurrencyEnum currencyTo, Calendar calendar);
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/converter/DateConverter.java
// public interface DateConverter {
// Calendar getCalendarFromString(String date);
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/model/ConverterFormModel.java
// public class ConverterFormModel {
// @NotNull
// private String to = CurrencyEnum.USD.getCode();
// @NotNull
// private String from = CurrencyEnum.EUR.getCode();
// @Min(0)
// @NotNull
// private BigDecimal amount = new BigDecimal(0.0);
//
// private String type = "current";
//
// private String date = "";
//
// public String getTo() {
// return to;
// }
//
// public void setTo(String to) {
// this.to = to;
// }
//
// public String getFrom() {
// return from;
// }
//
// public void setFrom(String from) {
// this.from = from;
// }
//
// public BigDecimal getAmount() {
// return amount;
// }
//
// public void setAmount(BigDecimal amount) {
// this.amount = amount;
// }
//
// public CurrencyEnum getCurrencyEnumTo() {
// return Enum.valueOf(CurrencyEnum.class, to);
// }
//
// public CurrencyEnum getCurrencyEnumFrom() {
// return Enum.valueOf(CurrencyEnum.class, from);
// }
//
// public String getType() {
// return type;
// }
//
// public Boolean isHistory() {
// return type.equals("history");
// }
// public void setType(String type) {
// this.type = type;
// }
//
// public String getDate() {
// return date;
// }
//
// public void setDate(String date) {
// this.date = date;
// }
//
// @AssertTrue
// public boolean isDataCorrect() {
// return type.equals("current") || !date.isEmpty();
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/model/CountryService.java
// public interface CountryService {
// List<String> getCountriesNames();
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/Consts.java
// public final class Consts {
// public static final String CONVERTER_URL = "converter";
// public static final String LOGIN_URL = "login";
// public static final String REGISTER_URL = "register";
// }
| import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import com.github.vedenin.codingchallenge.converter.CurrencyConvector;
import com.github.vedenin.codingchallenge.converter.DateConverter;
import com.github.vedenin.codingchallenge.mvc.model.ConverterFormModel;
import com.github.vedenin.codingchallenge.mvc.model.CountryService;
import com.github.vedenin.codingchallenge.persistence.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.math.BigDecimal;
import java.util.Date;
import javax.inject.Inject;
import static com.github.vedenin.codingchallenge.mvc.Consts.*; | package com.github.vedenin.codingchallenge.mvc.controler;
/*
* Controller that provide main page of Converter application
*/
@Controller
public class MainWebController extends WebMvcConfigurerAdapter {
private static final String CURRENCY_ENUM = "currencyEnum";
private static final String RESULT = "result";
@Inject
CurrencyConvector currencyConvector;
@Inject
DateConverter dateConverter;
@Inject
HistoryRepository historyRepository;
@Inject
UserRepository userRepository;
@Inject
CountryService countryService;
@Inject
ErrorRepository errorRepository;
@Inject
PropertyService propertyService;
@RequestMapping(CONVERTER_URL) | // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/converter/CurrencyConvector.java
// public interface CurrencyConvector {
// BigDecimal getConvertingValue(Boolean isHistory, BigDecimal amount, CurrencyEnum currencyFrom,
// CurrencyEnum currencyTo, Calendar calendar);
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/converter/DateConverter.java
// public interface DateConverter {
// Calendar getCalendarFromString(String date);
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/model/ConverterFormModel.java
// public class ConverterFormModel {
// @NotNull
// private String to = CurrencyEnum.USD.getCode();
// @NotNull
// private String from = CurrencyEnum.EUR.getCode();
// @Min(0)
// @NotNull
// private BigDecimal amount = new BigDecimal(0.0);
//
// private String type = "current";
//
// private String date = "";
//
// public String getTo() {
// return to;
// }
//
// public void setTo(String to) {
// this.to = to;
// }
//
// public String getFrom() {
// return from;
// }
//
// public void setFrom(String from) {
// this.from = from;
// }
//
// public BigDecimal getAmount() {
// return amount;
// }
//
// public void setAmount(BigDecimal amount) {
// this.amount = amount;
// }
//
// public CurrencyEnum getCurrencyEnumTo() {
// return Enum.valueOf(CurrencyEnum.class, to);
// }
//
// public CurrencyEnum getCurrencyEnumFrom() {
// return Enum.valueOf(CurrencyEnum.class, from);
// }
//
// public String getType() {
// return type;
// }
//
// public Boolean isHistory() {
// return type.equals("history");
// }
// public void setType(String type) {
// this.type = type;
// }
//
// public String getDate() {
// return date;
// }
//
// public void setDate(String date) {
// this.date = date;
// }
//
// @AssertTrue
// public boolean isDataCorrect() {
// return type.equals("current") || !date.isEmpty();
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/model/CountryService.java
// public interface CountryService {
// List<String> getCountriesNames();
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/Consts.java
// public final class Consts {
// public static final String CONVERTER_URL = "converter";
// public static final String LOGIN_URL = "login";
// public static final String REGISTER_URL = "register";
// }
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/controler/MainWebController.java
import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import com.github.vedenin.codingchallenge.converter.CurrencyConvector;
import com.github.vedenin.codingchallenge.converter.DateConverter;
import com.github.vedenin.codingchallenge.mvc.model.ConverterFormModel;
import com.github.vedenin.codingchallenge.mvc.model.CountryService;
import com.github.vedenin.codingchallenge.persistence.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.math.BigDecimal;
import java.util.Date;
import javax.inject.Inject;
import static com.github.vedenin.codingchallenge.mvc.Consts.*;
package com.github.vedenin.codingchallenge.mvc.controler;
/*
* Controller that provide main page of Converter application
*/
@Controller
public class MainWebController extends WebMvcConfigurerAdapter {
private static final String CURRENCY_ENUM = "currencyEnum";
private static final String RESULT = "result";
@Inject
CurrencyConvector currencyConvector;
@Inject
DateConverter dateConverter;
@Inject
HistoryRepository historyRepository;
@Inject
UserRepository userRepository;
@Inject
CountryService countryService;
@Inject
ErrorRepository errorRepository;
@Inject
PropertyService propertyService;
@RequestMapping(CONVERTER_URL) | public String handleConverterForm(ConverterFormModel converterFormModel, Model model, BindingResult bindingResult) { |
Vedenin/RestAndSpringMVC-CodingChallenge | src/main/java/com/github/vedenin/codingchallenge/mvc/controler/MainWebController.java | // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/converter/CurrencyConvector.java
// public interface CurrencyConvector {
// BigDecimal getConvertingValue(Boolean isHistory, BigDecimal amount, CurrencyEnum currencyFrom,
// CurrencyEnum currencyTo, Calendar calendar);
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/converter/DateConverter.java
// public interface DateConverter {
// Calendar getCalendarFromString(String date);
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/model/ConverterFormModel.java
// public class ConverterFormModel {
// @NotNull
// private String to = CurrencyEnum.USD.getCode();
// @NotNull
// private String from = CurrencyEnum.EUR.getCode();
// @Min(0)
// @NotNull
// private BigDecimal amount = new BigDecimal(0.0);
//
// private String type = "current";
//
// private String date = "";
//
// public String getTo() {
// return to;
// }
//
// public void setTo(String to) {
// this.to = to;
// }
//
// public String getFrom() {
// return from;
// }
//
// public void setFrom(String from) {
// this.from = from;
// }
//
// public BigDecimal getAmount() {
// return amount;
// }
//
// public void setAmount(BigDecimal amount) {
// this.amount = amount;
// }
//
// public CurrencyEnum getCurrencyEnumTo() {
// return Enum.valueOf(CurrencyEnum.class, to);
// }
//
// public CurrencyEnum getCurrencyEnumFrom() {
// return Enum.valueOf(CurrencyEnum.class, from);
// }
//
// public String getType() {
// return type;
// }
//
// public Boolean isHistory() {
// return type.equals("history");
// }
// public void setType(String type) {
// this.type = type;
// }
//
// public String getDate() {
// return date;
// }
//
// public void setDate(String date) {
// this.date = date;
// }
//
// @AssertTrue
// public boolean isDataCorrect() {
// return type.equals("current") || !date.isEmpty();
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/model/CountryService.java
// public interface CountryService {
// List<String> getCountriesNames();
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/Consts.java
// public final class Consts {
// public static final String CONVERTER_URL = "converter";
// public static final String LOGIN_URL = "login";
// public static final String REGISTER_URL = "register";
// }
| import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import com.github.vedenin.codingchallenge.converter.CurrencyConvector;
import com.github.vedenin.codingchallenge.converter.DateConverter;
import com.github.vedenin.codingchallenge.mvc.model.ConverterFormModel;
import com.github.vedenin.codingchallenge.mvc.model.CountryService;
import com.github.vedenin.codingchallenge.persistence.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.math.BigDecimal;
import java.util.Date;
import javax.inject.Inject;
import static com.github.vedenin.codingchallenge.mvc.Consts.*; | package com.github.vedenin.codingchallenge.mvc.controler;
/*
* Controller that provide main page of Converter application
*/
@Controller
public class MainWebController extends WebMvcConfigurerAdapter {
private static final String CURRENCY_ENUM = "currencyEnum";
private static final String RESULT = "result";
@Inject
CurrencyConvector currencyConvector;
@Inject
DateConverter dateConverter;
@Inject
HistoryRepository historyRepository;
@Inject
UserRepository userRepository;
@Inject
CountryService countryService;
@Inject
ErrorRepository errorRepository;
@Inject
PropertyService propertyService;
@RequestMapping(CONVERTER_URL)
public String handleConverterForm(ConverterFormModel converterFormModel, Model model, BindingResult bindingResult) {
try { | // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/converter/CurrencyConvector.java
// public interface CurrencyConvector {
// BigDecimal getConvertingValue(Boolean isHistory, BigDecimal amount, CurrencyEnum currencyFrom,
// CurrencyEnum currencyTo, Calendar calendar);
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/converter/DateConverter.java
// public interface DateConverter {
// Calendar getCalendarFromString(String date);
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/model/ConverterFormModel.java
// public class ConverterFormModel {
// @NotNull
// private String to = CurrencyEnum.USD.getCode();
// @NotNull
// private String from = CurrencyEnum.EUR.getCode();
// @Min(0)
// @NotNull
// private BigDecimal amount = new BigDecimal(0.0);
//
// private String type = "current";
//
// private String date = "";
//
// public String getTo() {
// return to;
// }
//
// public void setTo(String to) {
// this.to = to;
// }
//
// public String getFrom() {
// return from;
// }
//
// public void setFrom(String from) {
// this.from = from;
// }
//
// public BigDecimal getAmount() {
// return amount;
// }
//
// public void setAmount(BigDecimal amount) {
// this.amount = amount;
// }
//
// public CurrencyEnum getCurrencyEnumTo() {
// return Enum.valueOf(CurrencyEnum.class, to);
// }
//
// public CurrencyEnum getCurrencyEnumFrom() {
// return Enum.valueOf(CurrencyEnum.class, from);
// }
//
// public String getType() {
// return type;
// }
//
// public Boolean isHistory() {
// return type.equals("history");
// }
// public void setType(String type) {
// this.type = type;
// }
//
// public String getDate() {
// return date;
// }
//
// public void setDate(String date) {
// this.date = date;
// }
//
// @AssertTrue
// public boolean isDataCorrect() {
// return type.equals("current") || !date.isEmpty();
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/model/CountryService.java
// public interface CountryService {
// List<String> getCountriesNames();
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/Consts.java
// public final class Consts {
// public static final String CONVERTER_URL = "converter";
// public static final String LOGIN_URL = "login";
// public static final String REGISTER_URL = "register";
// }
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/controler/MainWebController.java
import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import com.github.vedenin.codingchallenge.converter.CurrencyConvector;
import com.github.vedenin.codingchallenge.converter.DateConverter;
import com.github.vedenin.codingchallenge.mvc.model.ConverterFormModel;
import com.github.vedenin.codingchallenge.mvc.model.CountryService;
import com.github.vedenin.codingchallenge.persistence.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.math.BigDecimal;
import java.util.Date;
import javax.inject.Inject;
import static com.github.vedenin.codingchallenge.mvc.Consts.*;
package com.github.vedenin.codingchallenge.mvc.controler;
/*
* Controller that provide main page of Converter application
*/
@Controller
public class MainWebController extends WebMvcConfigurerAdapter {
private static final String CURRENCY_ENUM = "currencyEnum";
private static final String RESULT = "result";
@Inject
CurrencyConvector currencyConvector;
@Inject
DateConverter dateConverter;
@Inject
HistoryRepository historyRepository;
@Inject
UserRepository userRepository;
@Inject
CountryService countryService;
@Inject
ErrorRepository errorRepository;
@Inject
PropertyService propertyService;
@RequestMapping(CONVERTER_URL)
public String handleConverterForm(ConverterFormModel converterFormModel, Model model, BindingResult bindingResult) {
try { | model.addAttribute(CURRENCY_ENUM, CurrencyEnum.values()); |
Vedenin/RestAndSpringMVC-CodingChallenge | src/main/java/com/github/vedenin/codingchallenge/persistence/DefaultProperty.java | // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
| import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.math.BigDecimal; | package com.github.vedenin.codingchallenge.persistence;
/**
* Created by slava on 16.02.17.
*/
@Entity
public class DefaultProperty {
@Id
private Long id = 1L;
| // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
// Path: src/main/java/com/github/vedenin/codingchallenge/persistence/DefaultProperty.java
import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.math.BigDecimal;
package com.github.vedenin.codingchallenge.persistence;
/**
* Created by slava on 16.02.17.
*/
@Entity
public class DefaultProperty {
@Id
private Long id = 1L;
| private String defaultCurrencyTo = CurrencyEnum.USD.getCode(); |
Vedenin/RestAndSpringMVC-CodingChallenge | src/test/java/com.github.vedenin.codingchallenge/CountryServiceTest.java | // Path: src/main/java/com/github/vedenin/codingchallenge/mvc/model/CountryService.java
// public interface CountryService {
// List<String> getCountriesNames();
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/model/CountryServiceImpl.java
// @Service
// public class CountryServiceImpl implements CountryService {
// @Override
// public List<String> getCountriesNames() {
// return Arrays.stream(Locale.getISOCountries()).
// map((code)->new Locale("en", code)).
// map(Locale::getDisplayCountry).
// sorted().
// collect(Collectors.toList());
// }
// }
| import com.github.vedenin.codingchallenge.mvc.model.CountryService;
import com.github.vedenin.codingchallenge.mvc.model.CountryServiceImpl;
import org.junit.Assert;
import org.junit.Test;
import java.util.List; | package com.github.vedenin.codingchallenge;
/**
* Created by slava on 12.02.17.
*/
public class CountryServiceTest {
@Test
public void testService() { | // Path: src/main/java/com/github/vedenin/codingchallenge/mvc/model/CountryService.java
// public interface CountryService {
// List<String> getCountriesNames();
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/model/CountryServiceImpl.java
// @Service
// public class CountryServiceImpl implements CountryService {
// @Override
// public List<String> getCountriesNames() {
// return Arrays.stream(Locale.getISOCountries()).
// map((code)->new Locale("en", code)).
// map(Locale::getDisplayCountry).
// sorted().
// collect(Collectors.toList());
// }
// }
// Path: src/test/java/com.github.vedenin.codingchallenge/CountryServiceTest.java
import com.github.vedenin.codingchallenge.mvc.model.CountryService;
import com.github.vedenin.codingchallenge.mvc.model.CountryServiceImpl;
import org.junit.Assert;
import org.junit.Test;
import java.util.List;
package com.github.vedenin.codingchallenge;
/**
* Created by slava on 12.02.17.
*/
public class CountryServiceTest {
@Test
public void testService() { | CountryService countryService = new CountryServiceImpl(); |
Vedenin/RestAndSpringMVC-CodingChallenge | src/test/java/com.github.vedenin.codingchallenge/CountryServiceTest.java | // Path: src/main/java/com/github/vedenin/codingchallenge/mvc/model/CountryService.java
// public interface CountryService {
// List<String> getCountriesNames();
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/model/CountryServiceImpl.java
// @Service
// public class CountryServiceImpl implements CountryService {
// @Override
// public List<String> getCountriesNames() {
// return Arrays.stream(Locale.getISOCountries()).
// map((code)->new Locale("en", code)).
// map(Locale::getDisplayCountry).
// sorted().
// collect(Collectors.toList());
// }
// }
| import com.github.vedenin.codingchallenge.mvc.model.CountryService;
import com.github.vedenin.codingchallenge.mvc.model.CountryServiceImpl;
import org.junit.Assert;
import org.junit.Test;
import java.util.List; | package com.github.vedenin.codingchallenge;
/**
* Created by slava on 12.02.17.
*/
public class CountryServiceTest {
@Test
public void testService() { | // Path: src/main/java/com/github/vedenin/codingchallenge/mvc/model/CountryService.java
// public interface CountryService {
// List<String> getCountriesNames();
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/model/CountryServiceImpl.java
// @Service
// public class CountryServiceImpl implements CountryService {
// @Override
// public List<String> getCountriesNames() {
// return Arrays.stream(Locale.getISOCountries()).
// map((code)->new Locale("en", code)).
// map(Locale::getDisplayCountry).
// sorted().
// collect(Collectors.toList());
// }
// }
// Path: src/test/java/com.github.vedenin.codingchallenge/CountryServiceTest.java
import com.github.vedenin.codingchallenge.mvc.model.CountryService;
import com.github.vedenin.codingchallenge.mvc.model.CountryServiceImpl;
import org.junit.Assert;
import org.junit.Test;
import java.util.List;
package com.github.vedenin.codingchallenge;
/**
* Created by slava on 12.02.17.
*/
public class CountryServiceTest {
@Test
public void testService() { | CountryService countryService = new CountryServiceImpl(); |
Vedenin/RestAndSpringMVC-CodingChallenge | src/main/java/com/github/vedenin/codingchallenge/mvc/security/ConverterUserDetailsServices.java | // Path: src/main/java/com/github/vedenin/codingchallenge/persistence/UserEntity.java
// @Entity
// public class UserEntity implements UserDetails {
// @Id
// @GeneratedValue(strategy=GenerationType.AUTO)
// private Long id;
// @NotNull
// private String userName;
// @NotNull
// private String password;
// private String firstName;
// private String lastName;
// @NotNull
// private String email;
// @NotNull
// private String dataOfBirth;
// private String zipCode;
// private String city;
// private String country;
// private Boolean isAccountNonExpired = true;
// private Boolean isAccountNonLocked = true;
// private Boolean isCredentialsNonExpired = true;
// private Boolean isEnabled = true;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getFirstName() {
// return firstName;
// }
//
// public void setFirstName(String firstName) {
// this.firstName = firstName;
// }
//
// public String getLastName() {
// return lastName;
// }
//
// public void setLastName(String lastName) {
// this.lastName = lastName;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getDataOfBirth() {
// return dataOfBirth;
// }
//
// public void setDataOfBirth(String dataOfBirth) {
// this.dataOfBirth = dataOfBirth;
// }
//
// public String getZipCode() {
// return zipCode;
// }
//
// public void setZipCode(String zipCode) {
// this.zipCode = zipCode;
// }
//
// public String getCity() {
// return city;
// }
//
// public void setCity(String city) {
// this.city = city;
// }
//
// public String getCountry() {
// return country;
// }
//
// public void setCountry(String country) {
// this.country = country;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// @Override
// public Collection<? extends GrantedAuthority> getAuthorities() {
// return Collections.singletonList(new SimpleGrantedAuthority("USER"));
// }
//
// public String getPassword() {
// return password;
// }
//
// @Override
// public String getUsername() {
// return userName;
// }
//
// @Override
// public boolean isAccountNonExpired() {
// return isAccountNonExpired;
// }
//
// @Override
// public boolean isAccountNonLocked() {
// return isAccountNonLocked;
// }
//
// @Override
// public boolean isCredentialsNonExpired() {
// return isCredentialsNonExpired;
// }
//
// @Override
// public boolean isEnabled() {
// return isEnabled;
// }
//
// public void setAccountNonExpired(Boolean accountNonExpired) {
// isAccountNonExpired = accountNonExpired;
// }
//
// public void setAccountNonLocked(Boolean accountNonLocked) {
// isAccountNonLocked = accountNonLocked;
// }
//
// public void setCredentialsNonExpired(Boolean credentialsNonExpired) {
// isCredentialsNonExpired = credentialsNonExpired;
// }
//
// public void setEnabled(Boolean enabled) {
// isEnabled = enabled;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/persistence/UserRepository.java
// public interface UserRepository extends CrudRepository<UserEntity, Long> {
// public UserEntity findByUserName(String userName);
// }
| import com.github.vedenin.codingchallenge.persistence.UserEntity;
import com.github.vedenin.codingchallenge.persistence.UserRepository;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import javax.inject.Inject; | package com.github.vedenin.codingchallenge.mvc.security;
/**
* Created by slava on 11.02.17.
*/
@Service
public class ConverterUserDetailsServices implements UserDetailsService {
@Inject | // Path: src/main/java/com/github/vedenin/codingchallenge/persistence/UserEntity.java
// @Entity
// public class UserEntity implements UserDetails {
// @Id
// @GeneratedValue(strategy=GenerationType.AUTO)
// private Long id;
// @NotNull
// private String userName;
// @NotNull
// private String password;
// private String firstName;
// private String lastName;
// @NotNull
// private String email;
// @NotNull
// private String dataOfBirth;
// private String zipCode;
// private String city;
// private String country;
// private Boolean isAccountNonExpired = true;
// private Boolean isAccountNonLocked = true;
// private Boolean isCredentialsNonExpired = true;
// private Boolean isEnabled = true;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getFirstName() {
// return firstName;
// }
//
// public void setFirstName(String firstName) {
// this.firstName = firstName;
// }
//
// public String getLastName() {
// return lastName;
// }
//
// public void setLastName(String lastName) {
// this.lastName = lastName;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getDataOfBirth() {
// return dataOfBirth;
// }
//
// public void setDataOfBirth(String dataOfBirth) {
// this.dataOfBirth = dataOfBirth;
// }
//
// public String getZipCode() {
// return zipCode;
// }
//
// public void setZipCode(String zipCode) {
// this.zipCode = zipCode;
// }
//
// public String getCity() {
// return city;
// }
//
// public void setCity(String city) {
// this.city = city;
// }
//
// public String getCountry() {
// return country;
// }
//
// public void setCountry(String country) {
// this.country = country;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// @Override
// public Collection<? extends GrantedAuthority> getAuthorities() {
// return Collections.singletonList(new SimpleGrantedAuthority("USER"));
// }
//
// public String getPassword() {
// return password;
// }
//
// @Override
// public String getUsername() {
// return userName;
// }
//
// @Override
// public boolean isAccountNonExpired() {
// return isAccountNonExpired;
// }
//
// @Override
// public boolean isAccountNonLocked() {
// return isAccountNonLocked;
// }
//
// @Override
// public boolean isCredentialsNonExpired() {
// return isCredentialsNonExpired;
// }
//
// @Override
// public boolean isEnabled() {
// return isEnabled;
// }
//
// public void setAccountNonExpired(Boolean accountNonExpired) {
// isAccountNonExpired = accountNonExpired;
// }
//
// public void setAccountNonLocked(Boolean accountNonLocked) {
// isAccountNonLocked = accountNonLocked;
// }
//
// public void setCredentialsNonExpired(Boolean credentialsNonExpired) {
// isCredentialsNonExpired = credentialsNonExpired;
// }
//
// public void setEnabled(Boolean enabled) {
// isEnabled = enabled;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/persistence/UserRepository.java
// public interface UserRepository extends CrudRepository<UserEntity, Long> {
// public UserEntity findByUserName(String userName);
// }
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/security/ConverterUserDetailsServices.java
import com.github.vedenin.codingchallenge.persistence.UserEntity;
import com.github.vedenin.codingchallenge.persistence.UserRepository;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
package com.github.vedenin.codingchallenge.mvc.security;
/**
* Created by slava on 11.02.17.
*/
@Service
public class ConverterUserDetailsServices implements UserDetailsService {
@Inject | UserRepository userRepository; |
Vedenin/RestAndSpringMVC-CodingChallenge | src/main/java/com/github/vedenin/codingchallenge/mvc/security/ConverterUserDetailsServices.java | // Path: src/main/java/com/github/vedenin/codingchallenge/persistence/UserEntity.java
// @Entity
// public class UserEntity implements UserDetails {
// @Id
// @GeneratedValue(strategy=GenerationType.AUTO)
// private Long id;
// @NotNull
// private String userName;
// @NotNull
// private String password;
// private String firstName;
// private String lastName;
// @NotNull
// private String email;
// @NotNull
// private String dataOfBirth;
// private String zipCode;
// private String city;
// private String country;
// private Boolean isAccountNonExpired = true;
// private Boolean isAccountNonLocked = true;
// private Boolean isCredentialsNonExpired = true;
// private Boolean isEnabled = true;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getFirstName() {
// return firstName;
// }
//
// public void setFirstName(String firstName) {
// this.firstName = firstName;
// }
//
// public String getLastName() {
// return lastName;
// }
//
// public void setLastName(String lastName) {
// this.lastName = lastName;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getDataOfBirth() {
// return dataOfBirth;
// }
//
// public void setDataOfBirth(String dataOfBirth) {
// this.dataOfBirth = dataOfBirth;
// }
//
// public String getZipCode() {
// return zipCode;
// }
//
// public void setZipCode(String zipCode) {
// this.zipCode = zipCode;
// }
//
// public String getCity() {
// return city;
// }
//
// public void setCity(String city) {
// this.city = city;
// }
//
// public String getCountry() {
// return country;
// }
//
// public void setCountry(String country) {
// this.country = country;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// @Override
// public Collection<? extends GrantedAuthority> getAuthorities() {
// return Collections.singletonList(new SimpleGrantedAuthority("USER"));
// }
//
// public String getPassword() {
// return password;
// }
//
// @Override
// public String getUsername() {
// return userName;
// }
//
// @Override
// public boolean isAccountNonExpired() {
// return isAccountNonExpired;
// }
//
// @Override
// public boolean isAccountNonLocked() {
// return isAccountNonLocked;
// }
//
// @Override
// public boolean isCredentialsNonExpired() {
// return isCredentialsNonExpired;
// }
//
// @Override
// public boolean isEnabled() {
// return isEnabled;
// }
//
// public void setAccountNonExpired(Boolean accountNonExpired) {
// isAccountNonExpired = accountNonExpired;
// }
//
// public void setAccountNonLocked(Boolean accountNonLocked) {
// isAccountNonLocked = accountNonLocked;
// }
//
// public void setCredentialsNonExpired(Boolean credentialsNonExpired) {
// isCredentialsNonExpired = credentialsNonExpired;
// }
//
// public void setEnabled(Boolean enabled) {
// isEnabled = enabled;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/persistence/UserRepository.java
// public interface UserRepository extends CrudRepository<UserEntity, Long> {
// public UserEntity findByUserName(String userName);
// }
| import com.github.vedenin.codingchallenge.persistence.UserEntity;
import com.github.vedenin.codingchallenge.persistence.UserRepository;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import javax.inject.Inject; | package com.github.vedenin.codingchallenge.mvc.security;
/**
* Created by slava on 11.02.17.
*/
@Service
public class ConverterUserDetailsServices implements UserDetailsService {
@Inject
UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { | // Path: src/main/java/com/github/vedenin/codingchallenge/persistence/UserEntity.java
// @Entity
// public class UserEntity implements UserDetails {
// @Id
// @GeneratedValue(strategy=GenerationType.AUTO)
// private Long id;
// @NotNull
// private String userName;
// @NotNull
// private String password;
// private String firstName;
// private String lastName;
// @NotNull
// private String email;
// @NotNull
// private String dataOfBirth;
// private String zipCode;
// private String city;
// private String country;
// private Boolean isAccountNonExpired = true;
// private Boolean isAccountNonLocked = true;
// private Boolean isCredentialsNonExpired = true;
// private Boolean isEnabled = true;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getFirstName() {
// return firstName;
// }
//
// public void setFirstName(String firstName) {
// this.firstName = firstName;
// }
//
// public String getLastName() {
// return lastName;
// }
//
// public void setLastName(String lastName) {
// this.lastName = lastName;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getDataOfBirth() {
// return dataOfBirth;
// }
//
// public void setDataOfBirth(String dataOfBirth) {
// this.dataOfBirth = dataOfBirth;
// }
//
// public String getZipCode() {
// return zipCode;
// }
//
// public void setZipCode(String zipCode) {
// this.zipCode = zipCode;
// }
//
// public String getCity() {
// return city;
// }
//
// public void setCity(String city) {
// this.city = city;
// }
//
// public String getCountry() {
// return country;
// }
//
// public void setCountry(String country) {
// this.country = country;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// @Override
// public Collection<? extends GrantedAuthority> getAuthorities() {
// return Collections.singletonList(new SimpleGrantedAuthority("USER"));
// }
//
// public String getPassword() {
// return password;
// }
//
// @Override
// public String getUsername() {
// return userName;
// }
//
// @Override
// public boolean isAccountNonExpired() {
// return isAccountNonExpired;
// }
//
// @Override
// public boolean isAccountNonLocked() {
// return isAccountNonLocked;
// }
//
// @Override
// public boolean isCredentialsNonExpired() {
// return isCredentialsNonExpired;
// }
//
// @Override
// public boolean isEnabled() {
// return isEnabled;
// }
//
// public void setAccountNonExpired(Boolean accountNonExpired) {
// isAccountNonExpired = accountNonExpired;
// }
//
// public void setAccountNonLocked(Boolean accountNonLocked) {
// isAccountNonLocked = accountNonLocked;
// }
//
// public void setCredentialsNonExpired(Boolean credentialsNonExpired) {
// isCredentialsNonExpired = credentialsNonExpired;
// }
//
// public void setEnabled(Boolean enabled) {
// isEnabled = enabled;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/persistence/UserRepository.java
// public interface UserRepository extends CrudRepository<UserEntity, Long> {
// public UserEntity findByUserName(String userName);
// }
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/security/ConverterUserDetailsServices.java
import com.github.vedenin.codingchallenge.persistence.UserEntity;
import com.github.vedenin.codingchallenge.persistence.UserRepository;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
package com.github.vedenin.codingchallenge.mvc.security;
/**
* Created by slava on 11.02.17.
*/
@Service
public class ConverterUserDetailsServices implements UserDetailsService {
@Inject
UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { | UserEntity userEntity = userRepository.findByUserName(s); |
Vedenin/RestAndSpringMVC-CodingChallenge | src/main/java/com/github/vedenin/codingchallenge/restclient/impl/currencylayer/CurrencyLayerRestClient.java | // Path: src/main/java/com/github/vedenin/codingchallenge/exceptions/RestClientException.java
// public class RestClientException extends RuntimeException {
// public RestClientException() {
// }
//
// public RestClientException(String message) {
// super(message);
// }
//
// public RestClientException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public RestClientException(Throwable cause) {
// super(cause);
// }
//
// public RestClientException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/restclient/RestClient.java
// public interface RestClient {
// BigDecimal getCurrentExchangeRates(CurrencyEnum currecnyFrom, CurrencyEnum currecnyTo);
// BigDecimal getHistoricalExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, Calendar calendar);
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
| import com.github.vedenin.codingchallenge.exceptions.RestClientException;
import com.github.vedenin.codingchallenge.restclient.RestClient;
import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import org.springframework.stereotype.Service;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Response;
import java.math.BigDecimal;
import java.util.Calendar;
import static java.math.BigDecimal.ROUND_FLOOR; | package com.github.vedenin.codingchallenge.restclient.impl.currencylayer;
/**
* Created by slava on 04.02.17.
*/
@Service("CurrencyLayer")
public class CurrencyLayerRestClient implements RestClient {
private final static String URL_LAST = "http://www.apilayer.net/api/live?format=1";
private final static String URL_HISTORY = "http://apilayer.net/api/historical?date=";
private final static String API_ID = "f7e5948888d41713110273b47c682db0";
private final static String API_ID_PRM = "&access_key=";
private static final String ERROR_WHILE_GATHERING_INFORMATION = "Error while gathering information from CurrencyLayer services";
| // Path: src/main/java/com/github/vedenin/codingchallenge/exceptions/RestClientException.java
// public class RestClientException extends RuntimeException {
// public RestClientException() {
// }
//
// public RestClientException(String message) {
// super(message);
// }
//
// public RestClientException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public RestClientException(Throwable cause) {
// super(cause);
// }
//
// public RestClientException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/restclient/RestClient.java
// public interface RestClient {
// BigDecimal getCurrentExchangeRates(CurrencyEnum currecnyFrom, CurrencyEnum currecnyTo);
// BigDecimal getHistoricalExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, Calendar calendar);
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
// Path: src/main/java/com/github/vedenin/codingchallenge/restclient/impl/currencylayer/CurrencyLayerRestClient.java
import com.github.vedenin.codingchallenge.exceptions.RestClientException;
import com.github.vedenin.codingchallenge.restclient.RestClient;
import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import org.springframework.stereotype.Service;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Response;
import java.math.BigDecimal;
import java.util.Calendar;
import static java.math.BigDecimal.ROUND_FLOOR;
package com.github.vedenin.codingchallenge.restclient.impl.currencylayer;
/**
* Created by slava on 04.02.17.
*/
@Service("CurrencyLayer")
public class CurrencyLayerRestClient implements RestClient {
private final static String URL_LAST = "http://www.apilayer.net/api/live?format=1";
private final static String URL_HISTORY = "http://apilayer.net/api/historical?date=";
private final static String API_ID = "f7e5948888d41713110273b47c682db0";
private final static String API_ID_PRM = "&access_key=";
private static final String ERROR_WHILE_GATHERING_INFORMATION = "Error while gathering information from CurrencyLayer services";
| public BigDecimal getCurrentExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo) { |
Vedenin/RestAndSpringMVC-CodingChallenge | src/main/java/com/github/vedenin/codingchallenge/restclient/impl/currencylayer/CurrencyLayerRestClient.java | // Path: src/main/java/com/github/vedenin/codingchallenge/exceptions/RestClientException.java
// public class RestClientException extends RuntimeException {
// public RestClientException() {
// }
//
// public RestClientException(String message) {
// super(message);
// }
//
// public RestClientException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public RestClientException(Throwable cause) {
// super(cause);
// }
//
// public RestClientException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/restclient/RestClient.java
// public interface RestClient {
// BigDecimal getCurrentExchangeRates(CurrencyEnum currecnyFrom, CurrencyEnum currecnyTo);
// BigDecimal getHistoricalExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, Calendar calendar);
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
| import com.github.vedenin.codingchallenge.exceptions.RestClientException;
import com.github.vedenin.codingchallenge.restclient.RestClient;
import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import org.springframework.stereotype.Service;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Response;
import java.math.BigDecimal;
import java.util.Calendar;
import static java.math.BigDecimal.ROUND_FLOOR; | return getExchangeRates(currencyFrom, currencyTo, getCurrentRates());
}
public BigDecimal getHistoricalExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, Calendar calendar) {
return getExchangeRates(currencyFrom, currencyTo, getHistoricalRates(calendar));
}
private BigDecimal getExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, CurrencyLayerRatesContainer rates) {
BigDecimal currencyFromRate = getRates(currencyFrom, rates);
BigDecimal currencyToRate = getRates(currencyTo, rates);
return currencyToRate.divide(currencyFromRate, 20, ROUND_FLOOR);
}
public CurrencyLayerRatesContainer getCurrentRates() {
return getEntity(URL_LAST, API_ID, CurrencyLayerRatesContainer.class);
}
public CurrencyLayerRatesContainer getHistoricalRates(Calendar date) {
return getEntity(URL_HISTORY + date.get(Calendar.YEAR) + "-" +
getStringWithLeftPadZero(date.get(Calendar.MONTH) + 1) + "-" +
getStringWithLeftPadZero(date.get(Calendar.DAY_OF_MONTH))
, API_ID, CurrencyLayerRatesContainer.class);
}
private String getStringWithLeftPadZero(int number) {
return String.format("%02d", number);
}
private static BigDecimal getRates(CurrencyEnum currency, CurrencyLayerRatesContainer rates) {
if (rates.getQuotes() == null) { | // Path: src/main/java/com/github/vedenin/codingchallenge/exceptions/RestClientException.java
// public class RestClientException extends RuntimeException {
// public RestClientException() {
// }
//
// public RestClientException(String message) {
// super(message);
// }
//
// public RestClientException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public RestClientException(Throwable cause) {
// super(cause);
// }
//
// public RestClientException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/restclient/RestClient.java
// public interface RestClient {
// BigDecimal getCurrentExchangeRates(CurrencyEnum currecnyFrom, CurrencyEnum currecnyTo);
// BigDecimal getHistoricalExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, Calendar calendar);
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
// Path: src/main/java/com/github/vedenin/codingchallenge/restclient/impl/currencylayer/CurrencyLayerRestClient.java
import com.github.vedenin.codingchallenge.exceptions.RestClientException;
import com.github.vedenin.codingchallenge.restclient.RestClient;
import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import org.springframework.stereotype.Service;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Response;
import java.math.BigDecimal;
import java.util.Calendar;
import static java.math.BigDecimal.ROUND_FLOOR;
return getExchangeRates(currencyFrom, currencyTo, getCurrentRates());
}
public BigDecimal getHistoricalExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, Calendar calendar) {
return getExchangeRates(currencyFrom, currencyTo, getHistoricalRates(calendar));
}
private BigDecimal getExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, CurrencyLayerRatesContainer rates) {
BigDecimal currencyFromRate = getRates(currencyFrom, rates);
BigDecimal currencyToRate = getRates(currencyTo, rates);
return currencyToRate.divide(currencyFromRate, 20, ROUND_FLOOR);
}
public CurrencyLayerRatesContainer getCurrentRates() {
return getEntity(URL_LAST, API_ID, CurrencyLayerRatesContainer.class);
}
public CurrencyLayerRatesContainer getHistoricalRates(Calendar date) {
return getEntity(URL_HISTORY + date.get(Calendar.YEAR) + "-" +
getStringWithLeftPadZero(date.get(Calendar.MONTH) + 1) + "-" +
getStringWithLeftPadZero(date.get(Calendar.DAY_OF_MONTH))
, API_ID, CurrencyLayerRatesContainer.class);
}
private String getStringWithLeftPadZero(int number) {
return String.format("%02d", number);
}
private static BigDecimal getRates(CurrencyEnum currency, CurrencyLayerRatesContainer rates) {
if (rates.getQuotes() == null) { | throw new RestClientException(ERROR_WHILE_GATHERING_INFORMATION + |
Vedenin/RestAndSpringMVC-CodingChallenge | src/test/java/com.github.vedenin.codingchallenge/CurrencyLayerRestClientTest.java | // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/exceptions/RestClientException.java
// public class RestClientException extends RuntimeException {
// public RestClientException() {
// }
//
// public RestClientException(String message) {
// super(message);
// }
//
// public RestClientException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public RestClientException(Throwable cause) {
// super(cause);
// }
//
// public RestClientException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/restclient/RestClient.java
// public interface RestClient {
// BigDecimal getCurrentExchangeRates(CurrencyEnum currecnyFrom, CurrencyEnum currecnyTo);
// BigDecimal getHistoricalExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, Calendar calendar);
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/restclient/impl/currencylayer/CurrencyLayerRestClient.java
// @Service("CurrencyLayer")
// public class CurrencyLayerRestClient implements RestClient {
// private final static String URL_LAST = "http://www.apilayer.net/api/live?format=1";
// private final static String URL_HISTORY = "http://apilayer.net/api/historical?date=";
// private final static String API_ID = "f7e5948888d41713110273b47c682db0";
// private final static String API_ID_PRM = "&access_key=";
// private static final String ERROR_WHILE_GATHERING_INFORMATION = "Error while gathering information from CurrencyLayer services";
//
//
// public BigDecimal getCurrentExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo) {
// return getExchangeRates(currencyFrom, currencyTo, getCurrentRates());
// }
//
// public BigDecimal getHistoricalExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, Calendar calendar) {
// return getExchangeRates(currencyFrom, currencyTo, getHistoricalRates(calendar));
// }
//
// private BigDecimal getExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, CurrencyLayerRatesContainer rates) {
// BigDecimal currencyFromRate = getRates(currencyFrom, rates);
// BigDecimal currencyToRate = getRates(currencyTo, rates);
// return currencyToRate.divide(currencyFromRate, 20, ROUND_FLOOR);
// }
//
// public CurrencyLayerRatesContainer getCurrentRates() {
// return getEntity(URL_LAST, API_ID, CurrencyLayerRatesContainer.class);
// }
//
// public CurrencyLayerRatesContainer getHistoricalRates(Calendar date) {
// return getEntity(URL_HISTORY + date.get(Calendar.YEAR) + "-" +
// getStringWithLeftPadZero(date.get(Calendar.MONTH) + 1) + "-" +
// getStringWithLeftPadZero(date.get(Calendar.DAY_OF_MONTH))
// , API_ID, CurrencyLayerRatesContainer.class);
// }
//
// private String getStringWithLeftPadZero(int number) {
// return String.format("%02d", number);
// }
//
// private static BigDecimal getRates(CurrencyEnum currency, CurrencyLayerRatesContainer rates) {
// if (rates.getQuotes() == null) {
// throw new RestClientException(ERROR_WHILE_GATHERING_INFORMATION +
// (rates.getError() != null ? ", code:" + rates.getError().getCode() + ", error:" +
// rates.getError().getInfo() : ""));
// } else {
// String rate = rates.getQuotes().get("USD" + currency.getCode());
// return new BigDecimal(rate);
// }
// }
//
// private static <T> T getEntity(String url, String api, Class<T> entityClass) {
// Response response = null;
// try {
// Client client = ClientBuilder.newBuilder().build();
// response = client.target(url + API_ID_PRM + api).request().get();
// return response.readEntity(entityClass);
// } catch (Exception exp) {
// throw new RestClientException(ERROR_WHILE_GATHERING_INFORMATION + ", error: " +
// (response != null? response.getStatusInfo(): exp.getMessage()));
// } finally {
// if (response != null) {
// response.close();
// }
// }
// }
//
//
// }
| import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import com.github.vedenin.codingchallenge.exceptions.RestClientException;
import com.github.vedenin.codingchallenge.restclient.RestClient;
import com.github.vedenin.codingchallenge.restclient.impl.currencylayer.CurrencyLayerRestClient;
import org.junit.Assert;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.GregorianCalendar; | package com.github.vedenin.codingchallenge;
/**
* Created by vvedenin on 2/10/2017.
*/
public class CurrencyLayerRestClientTest {
@Test
public void ExternalTest() { | // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/exceptions/RestClientException.java
// public class RestClientException extends RuntimeException {
// public RestClientException() {
// }
//
// public RestClientException(String message) {
// super(message);
// }
//
// public RestClientException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public RestClientException(Throwable cause) {
// super(cause);
// }
//
// public RestClientException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/restclient/RestClient.java
// public interface RestClient {
// BigDecimal getCurrentExchangeRates(CurrencyEnum currecnyFrom, CurrencyEnum currecnyTo);
// BigDecimal getHistoricalExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, Calendar calendar);
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/restclient/impl/currencylayer/CurrencyLayerRestClient.java
// @Service("CurrencyLayer")
// public class CurrencyLayerRestClient implements RestClient {
// private final static String URL_LAST = "http://www.apilayer.net/api/live?format=1";
// private final static String URL_HISTORY = "http://apilayer.net/api/historical?date=";
// private final static String API_ID = "f7e5948888d41713110273b47c682db0";
// private final static String API_ID_PRM = "&access_key=";
// private static final String ERROR_WHILE_GATHERING_INFORMATION = "Error while gathering information from CurrencyLayer services";
//
//
// public BigDecimal getCurrentExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo) {
// return getExchangeRates(currencyFrom, currencyTo, getCurrentRates());
// }
//
// public BigDecimal getHistoricalExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, Calendar calendar) {
// return getExchangeRates(currencyFrom, currencyTo, getHistoricalRates(calendar));
// }
//
// private BigDecimal getExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, CurrencyLayerRatesContainer rates) {
// BigDecimal currencyFromRate = getRates(currencyFrom, rates);
// BigDecimal currencyToRate = getRates(currencyTo, rates);
// return currencyToRate.divide(currencyFromRate, 20, ROUND_FLOOR);
// }
//
// public CurrencyLayerRatesContainer getCurrentRates() {
// return getEntity(URL_LAST, API_ID, CurrencyLayerRatesContainer.class);
// }
//
// public CurrencyLayerRatesContainer getHistoricalRates(Calendar date) {
// return getEntity(URL_HISTORY + date.get(Calendar.YEAR) + "-" +
// getStringWithLeftPadZero(date.get(Calendar.MONTH) + 1) + "-" +
// getStringWithLeftPadZero(date.get(Calendar.DAY_OF_MONTH))
// , API_ID, CurrencyLayerRatesContainer.class);
// }
//
// private String getStringWithLeftPadZero(int number) {
// return String.format("%02d", number);
// }
//
// private static BigDecimal getRates(CurrencyEnum currency, CurrencyLayerRatesContainer rates) {
// if (rates.getQuotes() == null) {
// throw new RestClientException(ERROR_WHILE_GATHERING_INFORMATION +
// (rates.getError() != null ? ", code:" + rates.getError().getCode() + ", error:" +
// rates.getError().getInfo() : ""));
// } else {
// String rate = rates.getQuotes().get("USD" + currency.getCode());
// return new BigDecimal(rate);
// }
// }
//
// private static <T> T getEntity(String url, String api, Class<T> entityClass) {
// Response response = null;
// try {
// Client client = ClientBuilder.newBuilder().build();
// response = client.target(url + API_ID_PRM + api).request().get();
// return response.readEntity(entityClass);
// } catch (Exception exp) {
// throw new RestClientException(ERROR_WHILE_GATHERING_INFORMATION + ", error: " +
// (response != null? response.getStatusInfo(): exp.getMessage()));
// } finally {
// if (response != null) {
// response.close();
// }
// }
// }
//
//
// }
// Path: src/test/java/com.github.vedenin.codingchallenge/CurrencyLayerRestClientTest.java
import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import com.github.vedenin.codingchallenge.exceptions.RestClientException;
import com.github.vedenin.codingchallenge.restclient.RestClient;
import com.github.vedenin.codingchallenge.restclient.impl.currencylayer.CurrencyLayerRestClient;
import org.junit.Assert;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.GregorianCalendar;
package com.github.vedenin.codingchallenge;
/**
* Created by vvedenin on 2/10/2017.
*/
public class CurrencyLayerRestClientTest {
@Test
public void ExternalTest() { | RestClient restClient = new CurrencyLayerRestClient(); |
Vedenin/RestAndSpringMVC-CodingChallenge | src/test/java/com.github.vedenin.codingchallenge/CurrencyLayerRestClientTest.java | // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/exceptions/RestClientException.java
// public class RestClientException extends RuntimeException {
// public RestClientException() {
// }
//
// public RestClientException(String message) {
// super(message);
// }
//
// public RestClientException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public RestClientException(Throwable cause) {
// super(cause);
// }
//
// public RestClientException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/restclient/RestClient.java
// public interface RestClient {
// BigDecimal getCurrentExchangeRates(CurrencyEnum currecnyFrom, CurrencyEnum currecnyTo);
// BigDecimal getHistoricalExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, Calendar calendar);
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/restclient/impl/currencylayer/CurrencyLayerRestClient.java
// @Service("CurrencyLayer")
// public class CurrencyLayerRestClient implements RestClient {
// private final static String URL_LAST = "http://www.apilayer.net/api/live?format=1";
// private final static String URL_HISTORY = "http://apilayer.net/api/historical?date=";
// private final static String API_ID = "f7e5948888d41713110273b47c682db0";
// private final static String API_ID_PRM = "&access_key=";
// private static final String ERROR_WHILE_GATHERING_INFORMATION = "Error while gathering information from CurrencyLayer services";
//
//
// public BigDecimal getCurrentExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo) {
// return getExchangeRates(currencyFrom, currencyTo, getCurrentRates());
// }
//
// public BigDecimal getHistoricalExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, Calendar calendar) {
// return getExchangeRates(currencyFrom, currencyTo, getHistoricalRates(calendar));
// }
//
// private BigDecimal getExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, CurrencyLayerRatesContainer rates) {
// BigDecimal currencyFromRate = getRates(currencyFrom, rates);
// BigDecimal currencyToRate = getRates(currencyTo, rates);
// return currencyToRate.divide(currencyFromRate, 20, ROUND_FLOOR);
// }
//
// public CurrencyLayerRatesContainer getCurrentRates() {
// return getEntity(URL_LAST, API_ID, CurrencyLayerRatesContainer.class);
// }
//
// public CurrencyLayerRatesContainer getHistoricalRates(Calendar date) {
// return getEntity(URL_HISTORY + date.get(Calendar.YEAR) + "-" +
// getStringWithLeftPadZero(date.get(Calendar.MONTH) + 1) + "-" +
// getStringWithLeftPadZero(date.get(Calendar.DAY_OF_MONTH))
// , API_ID, CurrencyLayerRatesContainer.class);
// }
//
// private String getStringWithLeftPadZero(int number) {
// return String.format("%02d", number);
// }
//
// private static BigDecimal getRates(CurrencyEnum currency, CurrencyLayerRatesContainer rates) {
// if (rates.getQuotes() == null) {
// throw new RestClientException(ERROR_WHILE_GATHERING_INFORMATION +
// (rates.getError() != null ? ", code:" + rates.getError().getCode() + ", error:" +
// rates.getError().getInfo() : ""));
// } else {
// String rate = rates.getQuotes().get("USD" + currency.getCode());
// return new BigDecimal(rate);
// }
// }
//
// private static <T> T getEntity(String url, String api, Class<T> entityClass) {
// Response response = null;
// try {
// Client client = ClientBuilder.newBuilder().build();
// response = client.target(url + API_ID_PRM + api).request().get();
// return response.readEntity(entityClass);
// } catch (Exception exp) {
// throw new RestClientException(ERROR_WHILE_GATHERING_INFORMATION + ", error: " +
// (response != null? response.getStatusInfo(): exp.getMessage()));
// } finally {
// if (response != null) {
// response.close();
// }
// }
// }
//
//
// }
| import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import com.github.vedenin.codingchallenge.exceptions.RestClientException;
import com.github.vedenin.codingchallenge.restclient.RestClient;
import com.github.vedenin.codingchallenge.restclient.impl.currencylayer.CurrencyLayerRestClient;
import org.junit.Assert;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.GregorianCalendar; | package com.github.vedenin.codingchallenge;
/**
* Created by vvedenin on 2/10/2017.
*/
public class CurrencyLayerRestClientTest {
@Test
public void ExternalTest() { | // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/exceptions/RestClientException.java
// public class RestClientException extends RuntimeException {
// public RestClientException() {
// }
//
// public RestClientException(String message) {
// super(message);
// }
//
// public RestClientException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public RestClientException(Throwable cause) {
// super(cause);
// }
//
// public RestClientException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/restclient/RestClient.java
// public interface RestClient {
// BigDecimal getCurrentExchangeRates(CurrencyEnum currecnyFrom, CurrencyEnum currecnyTo);
// BigDecimal getHistoricalExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, Calendar calendar);
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/restclient/impl/currencylayer/CurrencyLayerRestClient.java
// @Service("CurrencyLayer")
// public class CurrencyLayerRestClient implements RestClient {
// private final static String URL_LAST = "http://www.apilayer.net/api/live?format=1";
// private final static String URL_HISTORY = "http://apilayer.net/api/historical?date=";
// private final static String API_ID = "f7e5948888d41713110273b47c682db0";
// private final static String API_ID_PRM = "&access_key=";
// private static final String ERROR_WHILE_GATHERING_INFORMATION = "Error while gathering information from CurrencyLayer services";
//
//
// public BigDecimal getCurrentExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo) {
// return getExchangeRates(currencyFrom, currencyTo, getCurrentRates());
// }
//
// public BigDecimal getHistoricalExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, Calendar calendar) {
// return getExchangeRates(currencyFrom, currencyTo, getHistoricalRates(calendar));
// }
//
// private BigDecimal getExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, CurrencyLayerRatesContainer rates) {
// BigDecimal currencyFromRate = getRates(currencyFrom, rates);
// BigDecimal currencyToRate = getRates(currencyTo, rates);
// return currencyToRate.divide(currencyFromRate, 20, ROUND_FLOOR);
// }
//
// public CurrencyLayerRatesContainer getCurrentRates() {
// return getEntity(URL_LAST, API_ID, CurrencyLayerRatesContainer.class);
// }
//
// public CurrencyLayerRatesContainer getHistoricalRates(Calendar date) {
// return getEntity(URL_HISTORY + date.get(Calendar.YEAR) + "-" +
// getStringWithLeftPadZero(date.get(Calendar.MONTH) + 1) + "-" +
// getStringWithLeftPadZero(date.get(Calendar.DAY_OF_MONTH))
// , API_ID, CurrencyLayerRatesContainer.class);
// }
//
// private String getStringWithLeftPadZero(int number) {
// return String.format("%02d", number);
// }
//
// private static BigDecimal getRates(CurrencyEnum currency, CurrencyLayerRatesContainer rates) {
// if (rates.getQuotes() == null) {
// throw new RestClientException(ERROR_WHILE_GATHERING_INFORMATION +
// (rates.getError() != null ? ", code:" + rates.getError().getCode() + ", error:" +
// rates.getError().getInfo() : ""));
// } else {
// String rate = rates.getQuotes().get("USD" + currency.getCode());
// return new BigDecimal(rate);
// }
// }
//
// private static <T> T getEntity(String url, String api, Class<T> entityClass) {
// Response response = null;
// try {
// Client client = ClientBuilder.newBuilder().build();
// response = client.target(url + API_ID_PRM + api).request().get();
// return response.readEntity(entityClass);
// } catch (Exception exp) {
// throw new RestClientException(ERROR_WHILE_GATHERING_INFORMATION + ", error: " +
// (response != null? response.getStatusInfo(): exp.getMessage()));
// } finally {
// if (response != null) {
// response.close();
// }
// }
// }
//
//
// }
// Path: src/test/java/com.github.vedenin.codingchallenge/CurrencyLayerRestClientTest.java
import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import com.github.vedenin.codingchallenge.exceptions.RestClientException;
import com.github.vedenin.codingchallenge.restclient.RestClient;
import com.github.vedenin.codingchallenge.restclient.impl.currencylayer.CurrencyLayerRestClient;
import org.junit.Assert;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.GregorianCalendar;
package com.github.vedenin.codingchallenge;
/**
* Created by vvedenin on 2/10/2017.
*/
public class CurrencyLayerRestClientTest {
@Test
public void ExternalTest() { | RestClient restClient = new CurrencyLayerRestClient(); |
Vedenin/RestAndSpringMVC-CodingChallenge | src/test/java/com.github.vedenin.codingchallenge/CurrencyLayerRestClientTest.java | // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/exceptions/RestClientException.java
// public class RestClientException extends RuntimeException {
// public RestClientException() {
// }
//
// public RestClientException(String message) {
// super(message);
// }
//
// public RestClientException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public RestClientException(Throwable cause) {
// super(cause);
// }
//
// public RestClientException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/restclient/RestClient.java
// public interface RestClient {
// BigDecimal getCurrentExchangeRates(CurrencyEnum currecnyFrom, CurrencyEnum currecnyTo);
// BigDecimal getHistoricalExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, Calendar calendar);
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/restclient/impl/currencylayer/CurrencyLayerRestClient.java
// @Service("CurrencyLayer")
// public class CurrencyLayerRestClient implements RestClient {
// private final static String URL_LAST = "http://www.apilayer.net/api/live?format=1";
// private final static String URL_HISTORY = "http://apilayer.net/api/historical?date=";
// private final static String API_ID = "f7e5948888d41713110273b47c682db0";
// private final static String API_ID_PRM = "&access_key=";
// private static final String ERROR_WHILE_GATHERING_INFORMATION = "Error while gathering information from CurrencyLayer services";
//
//
// public BigDecimal getCurrentExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo) {
// return getExchangeRates(currencyFrom, currencyTo, getCurrentRates());
// }
//
// public BigDecimal getHistoricalExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, Calendar calendar) {
// return getExchangeRates(currencyFrom, currencyTo, getHistoricalRates(calendar));
// }
//
// private BigDecimal getExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, CurrencyLayerRatesContainer rates) {
// BigDecimal currencyFromRate = getRates(currencyFrom, rates);
// BigDecimal currencyToRate = getRates(currencyTo, rates);
// return currencyToRate.divide(currencyFromRate, 20, ROUND_FLOOR);
// }
//
// public CurrencyLayerRatesContainer getCurrentRates() {
// return getEntity(URL_LAST, API_ID, CurrencyLayerRatesContainer.class);
// }
//
// public CurrencyLayerRatesContainer getHistoricalRates(Calendar date) {
// return getEntity(URL_HISTORY + date.get(Calendar.YEAR) + "-" +
// getStringWithLeftPadZero(date.get(Calendar.MONTH) + 1) + "-" +
// getStringWithLeftPadZero(date.get(Calendar.DAY_OF_MONTH))
// , API_ID, CurrencyLayerRatesContainer.class);
// }
//
// private String getStringWithLeftPadZero(int number) {
// return String.format("%02d", number);
// }
//
// private static BigDecimal getRates(CurrencyEnum currency, CurrencyLayerRatesContainer rates) {
// if (rates.getQuotes() == null) {
// throw new RestClientException(ERROR_WHILE_GATHERING_INFORMATION +
// (rates.getError() != null ? ", code:" + rates.getError().getCode() + ", error:" +
// rates.getError().getInfo() : ""));
// } else {
// String rate = rates.getQuotes().get("USD" + currency.getCode());
// return new BigDecimal(rate);
// }
// }
//
// private static <T> T getEntity(String url, String api, Class<T> entityClass) {
// Response response = null;
// try {
// Client client = ClientBuilder.newBuilder().build();
// response = client.target(url + API_ID_PRM + api).request().get();
// return response.readEntity(entityClass);
// } catch (Exception exp) {
// throw new RestClientException(ERROR_WHILE_GATHERING_INFORMATION + ", error: " +
// (response != null? response.getStatusInfo(): exp.getMessage()));
// } finally {
// if (response != null) {
// response.close();
// }
// }
// }
//
//
// }
| import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import com.github.vedenin.codingchallenge.exceptions.RestClientException;
import com.github.vedenin.codingchallenge.restclient.RestClient;
import com.github.vedenin.codingchallenge.restclient.impl.currencylayer.CurrencyLayerRestClient;
import org.junit.Assert;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.GregorianCalendar; | package com.github.vedenin.codingchallenge;
/**
* Created by vvedenin on 2/10/2017.
*/
public class CurrencyLayerRestClientTest {
@Test
public void ExternalTest() {
RestClient restClient = new CurrencyLayerRestClient(); | // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/exceptions/RestClientException.java
// public class RestClientException extends RuntimeException {
// public RestClientException() {
// }
//
// public RestClientException(String message) {
// super(message);
// }
//
// public RestClientException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public RestClientException(Throwable cause) {
// super(cause);
// }
//
// public RestClientException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/restclient/RestClient.java
// public interface RestClient {
// BigDecimal getCurrentExchangeRates(CurrencyEnum currecnyFrom, CurrencyEnum currecnyTo);
// BigDecimal getHistoricalExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, Calendar calendar);
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/restclient/impl/currencylayer/CurrencyLayerRestClient.java
// @Service("CurrencyLayer")
// public class CurrencyLayerRestClient implements RestClient {
// private final static String URL_LAST = "http://www.apilayer.net/api/live?format=1";
// private final static String URL_HISTORY = "http://apilayer.net/api/historical?date=";
// private final static String API_ID = "f7e5948888d41713110273b47c682db0";
// private final static String API_ID_PRM = "&access_key=";
// private static final String ERROR_WHILE_GATHERING_INFORMATION = "Error while gathering information from CurrencyLayer services";
//
//
// public BigDecimal getCurrentExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo) {
// return getExchangeRates(currencyFrom, currencyTo, getCurrentRates());
// }
//
// public BigDecimal getHistoricalExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, Calendar calendar) {
// return getExchangeRates(currencyFrom, currencyTo, getHistoricalRates(calendar));
// }
//
// private BigDecimal getExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, CurrencyLayerRatesContainer rates) {
// BigDecimal currencyFromRate = getRates(currencyFrom, rates);
// BigDecimal currencyToRate = getRates(currencyTo, rates);
// return currencyToRate.divide(currencyFromRate, 20, ROUND_FLOOR);
// }
//
// public CurrencyLayerRatesContainer getCurrentRates() {
// return getEntity(URL_LAST, API_ID, CurrencyLayerRatesContainer.class);
// }
//
// public CurrencyLayerRatesContainer getHistoricalRates(Calendar date) {
// return getEntity(URL_HISTORY + date.get(Calendar.YEAR) + "-" +
// getStringWithLeftPadZero(date.get(Calendar.MONTH) + 1) + "-" +
// getStringWithLeftPadZero(date.get(Calendar.DAY_OF_MONTH))
// , API_ID, CurrencyLayerRatesContainer.class);
// }
//
// private String getStringWithLeftPadZero(int number) {
// return String.format("%02d", number);
// }
//
// private static BigDecimal getRates(CurrencyEnum currency, CurrencyLayerRatesContainer rates) {
// if (rates.getQuotes() == null) {
// throw new RestClientException(ERROR_WHILE_GATHERING_INFORMATION +
// (rates.getError() != null ? ", code:" + rates.getError().getCode() + ", error:" +
// rates.getError().getInfo() : ""));
// } else {
// String rate = rates.getQuotes().get("USD" + currency.getCode());
// return new BigDecimal(rate);
// }
// }
//
// private static <T> T getEntity(String url, String api, Class<T> entityClass) {
// Response response = null;
// try {
// Client client = ClientBuilder.newBuilder().build();
// response = client.target(url + API_ID_PRM + api).request().get();
// return response.readEntity(entityClass);
// } catch (Exception exp) {
// throw new RestClientException(ERROR_WHILE_GATHERING_INFORMATION + ", error: " +
// (response != null? response.getStatusInfo(): exp.getMessage()));
// } finally {
// if (response != null) {
// response.close();
// }
// }
// }
//
//
// }
// Path: src/test/java/com.github.vedenin.codingchallenge/CurrencyLayerRestClientTest.java
import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import com.github.vedenin.codingchallenge.exceptions.RestClientException;
import com.github.vedenin.codingchallenge.restclient.RestClient;
import com.github.vedenin.codingchallenge.restclient.impl.currencylayer.CurrencyLayerRestClient;
import org.junit.Assert;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.GregorianCalendar;
package com.github.vedenin.codingchallenge;
/**
* Created by vvedenin on 2/10/2017.
*/
public class CurrencyLayerRestClientTest {
@Test
public void ExternalTest() {
RestClient restClient = new CurrencyLayerRestClient(); | BigDecimal convertRates = restClient.getCurrentExchangeRates(CurrencyEnum.EUR, CurrencyEnum.RUB); |
Vedenin/RestAndSpringMVC-CodingChallenge | src/main/java/com/github/vedenin/codingchallenge/converter/CurrencyConvectorDefault.java | // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/exceptions/ConverterException.java
// public class ConverterException extends RuntimeException {
// public ConverterException() {
// }
//
// public ConverterException(String message) {
// super(message);
// }
//
// public ConverterException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ConverterException(Throwable cause) {
// super(cause);
// }
//
// public ConverterException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/restclient/RestClient.java
// public interface RestClient {
// BigDecimal getCurrentExchangeRates(CurrencyEnum currecnyFrom, CurrencyEnum currecnyTo);
// BigDecimal getHistoricalExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, Calendar calendar);
// }
| import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import com.github.vedenin.codingchallenge.exceptions.ConverterException;
import com.github.vedenin.codingchallenge.restclient.RestClient;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
import java.math.BigDecimal;
import java.util.Calendar; | package com.github.vedenin.codingchallenge.converter;
/**
* Created by vvedenin on 2/9/2017.
*/
@Service
public class CurrencyConvectorDefault implements CurrencyConvector {
@Inject
@Qualifier("FaultTolerant") | // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/exceptions/ConverterException.java
// public class ConverterException extends RuntimeException {
// public ConverterException() {
// }
//
// public ConverterException(String message) {
// super(message);
// }
//
// public ConverterException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ConverterException(Throwable cause) {
// super(cause);
// }
//
// public ConverterException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/restclient/RestClient.java
// public interface RestClient {
// BigDecimal getCurrentExchangeRates(CurrencyEnum currecnyFrom, CurrencyEnum currecnyTo);
// BigDecimal getHistoricalExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, Calendar calendar);
// }
// Path: src/main/java/com/github/vedenin/codingchallenge/converter/CurrencyConvectorDefault.java
import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import com.github.vedenin.codingchallenge.exceptions.ConverterException;
import com.github.vedenin.codingchallenge.restclient.RestClient;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
import java.math.BigDecimal;
import java.util.Calendar;
package com.github.vedenin.codingchallenge.converter;
/**
* Created by vvedenin on 2/9/2017.
*/
@Service
public class CurrencyConvectorDefault implements CurrencyConvector {
@Inject
@Qualifier("FaultTolerant") | RestClient restClient; |
Vedenin/RestAndSpringMVC-CodingChallenge | src/main/java/com/github/vedenin/codingchallenge/converter/CurrencyConvectorDefault.java | // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/exceptions/ConverterException.java
// public class ConverterException extends RuntimeException {
// public ConverterException() {
// }
//
// public ConverterException(String message) {
// super(message);
// }
//
// public ConverterException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ConverterException(Throwable cause) {
// super(cause);
// }
//
// public ConverterException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/restclient/RestClient.java
// public interface RestClient {
// BigDecimal getCurrentExchangeRates(CurrencyEnum currecnyFrom, CurrencyEnum currecnyTo);
// BigDecimal getHistoricalExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, Calendar calendar);
// }
| import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import com.github.vedenin.codingchallenge.exceptions.ConverterException;
import com.github.vedenin.codingchallenge.restclient.RestClient;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
import java.math.BigDecimal;
import java.util.Calendar; | package com.github.vedenin.codingchallenge.converter;
/**
* Created by vvedenin on 2/9/2017.
*/
@Service
public class CurrencyConvectorDefault implements CurrencyConvector {
@Inject
@Qualifier("FaultTolerant")
RestClient restClient;
| // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/exceptions/ConverterException.java
// public class ConverterException extends RuntimeException {
// public ConverterException() {
// }
//
// public ConverterException(String message) {
// super(message);
// }
//
// public ConverterException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ConverterException(Throwable cause) {
// super(cause);
// }
//
// public ConverterException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/restclient/RestClient.java
// public interface RestClient {
// BigDecimal getCurrentExchangeRates(CurrencyEnum currecnyFrom, CurrencyEnum currecnyTo);
// BigDecimal getHistoricalExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, Calendar calendar);
// }
// Path: src/main/java/com/github/vedenin/codingchallenge/converter/CurrencyConvectorDefault.java
import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import com.github.vedenin.codingchallenge.exceptions.ConverterException;
import com.github.vedenin.codingchallenge.restclient.RestClient;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
import java.math.BigDecimal;
import java.util.Calendar;
package com.github.vedenin.codingchallenge.converter;
/**
* Created by vvedenin on 2/9/2017.
*/
@Service
public class CurrencyConvectorDefault implements CurrencyConvector {
@Inject
@Qualifier("FaultTolerant")
RestClient restClient;
| private BigDecimal getConvertingCurrentValue(BigDecimal amount, CurrencyEnum currencyFrom, CurrencyEnum currencyTo) { |
Vedenin/RestAndSpringMVC-CodingChallenge | src/main/java/com/github/vedenin/codingchallenge/converter/CurrencyConvectorDefault.java | // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/exceptions/ConverterException.java
// public class ConverterException extends RuntimeException {
// public ConverterException() {
// }
//
// public ConverterException(String message) {
// super(message);
// }
//
// public ConverterException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ConverterException(Throwable cause) {
// super(cause);
// }
//
// public ConverterException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/restclient/RestClient.java
// public interface RestClient {
// BigDecimal getCurrentExchangeRates(CurrencyEnum currecnyFrom, CurrencyEnum currecnyTo);
// BigDecimal getHistoricalExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, Calendar calendar);
// }
| import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import com.github.vedenin.codingchallenge.exceptions.ConverterException;
import com.github.vedenin.codingchallenge.restclient.RestClient;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
import java.math.BigDecimal;
import java.util.Calendar; | package com.github.vedenin.codingchallenge.converter;
/**
* Created by vvedenin on 2/9/2017.
*/
@Service
public class CurrencyConvectorDefault implements CurrencyConvector {
@Inject
@Qualifier("FaultTolerant")
RestClient restClient;
private BigDecimal getConvertingCurrentValue(BigDecimal amount, CurrencyEnum currencyFrom, CurrencyEnum currencyTo) {
return amount.multiply(restClient.getCurrentExchangeRates(currencyFrom, currencyTo));
}
private BigDecimal getConvertingHistoricalValue(BigDecimal amount, CurrencyEnum currencyFrom, CurrencyEnum currencyTo, Calendar calendar) {
return amount.multiply(restClient.getHistoricalExchangeRates(currencyFrom, currencyTo, calendar));
}
@Override
public BigDecimal getConvertingValue(Boolean isHistory, BigDecimal amount, CurrencyEnum currencyFrom,
CurrencyEnum currencyTo, Calendar calendar) {
if(isHistory) {
if(calendar != null) {
return getConvertingHistoricalValue(amount, currencyFrom, currencyTo, calendar);
} else { | // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/exceptions/ConverterException.java
// public class ConverterException extends RuntimeException {
// public ConverterException() {
// }
//
// public ConverterException(String message) {
// super(message);
// }
//
// public ConverterException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ConverterException(Throwable cause) {
// super(cause);
// }
//
// public ConverterException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/restclient/RestClient.java
// public interface RestClient {
// BigDecimal getCurrentExchangeRates(CurrencyEnum currecnyFrom, CurrencyEnum currecnyTo);
// BigDecimal getHistoricalExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo, Calendar calendar);
// }
// Path: src/main/java/com/github/vedenin/codingchallenge/converter/CurrencyConvectorDefault.java
import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import com.github.vedenin.codingchallenge.exceptions.ConverterException;
import com.github.vedenin.codingchallenge.restclient.RestClient;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
import java.math.BigDecimal;
import java.util.Calendar;
package com.github.vedenin.codingchallenge.converter;
/**
* Created by vvedenin on 2/9/2017.
*/
@Service
public class CurrencyConvectorDefault implements CurrencyConvector {
@Inject
@Qualifier("FaultTolerant")
RestClient restClient;
private BigDecimal getConvertingCurrentValue(BigDecimal amount, CurrencyEnum currencyFrom, CurrencyEnum currencyTo) {
return amount.multiply(restClient.getCurrentExchangeRates(currencyFrom, currencyTo));
}
private BigDecimal getConvertingHistoricalValue(BigDecimal amount, CurrencyEnum currencyFrom, CurrencyEnum currencyTo, Calendar calendar) {
return amount.multiply(restClient.getHistoricalExchangeRates(currencyFrom, currencyTo, calendar));
}
@Override
public BigDecimal getConvertingValue(Boolean isHistory, BigDecimal amount, CurrencyEnum currencyFrom,
CurrencyEnum currencyTo, Calendar calendar) {
if(isHistory) {
if(calendar != null) {
return getConvertingHistoricalValue(amount, currencyFrom, currencyTo, calendar);
} else { | throw new ConverterException("'Date' must be filled in historical convection"); |
Vedenin/RestAndSpringMVC-CodingChallenge | src/main/java/com/github/vedenin/codingchallenge/mvc/controler/MainRestController.java | // Path: src/main/java/com/github/vedenin/codingchallenge/mvc/model/ResponseChangeStatus.java
// public class ResponseChangeStatus {
// private String status = "ok";
//
// public String getStatus() {
// return status;
// }
//
// public void setStatus(String status) {
// this.status = status;
// }
// }
| import com.github.vedenin.codingchallenge.mvc.model.ResponseChangeStatus;
import com.github.vedenin.codingchallenge.persistence.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.google.common.collect.Lists;
import javax.inject.Inject;
import java.util.List; | }
@RequestMapping(value = "/rest/history", method = RequestMethod.GET)
public ResponseEntity<List<HistoryEntity>> getHistories(@RequestParam(value="access_key", defaultValue = "") String accessKey) {
if(ACCESS_KEY.equals(accessKey)) {
return ResponseEntity.ok(Lists.newArrayList(historyRepository.findAll()));
} else {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
}
}
@RequestMapping(value = "/rest/error", method = RequestMethod.GET)
public ResponseEntity<List<ErrorEntity>> getErrors(@RequestParam(value="access_key", defaultValue = "") String accessKey) {
if(ACCESS_KEY.equals(accessKey)) {
return ResponseEntity.ok(Lists.newArrayList(errorRepository.findAll()));
} else {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
}
}
@RequestMapping(value = "/rest/property", method = RequestMethod.GET)
public ResponseEntity<DefaultProperty> getProperty(@RequestParam(value="access_key", defaultValue = "") String accessKey) {
if(ACCESS_KEY.equals(accessKey)) {
return ResponseEntity.ok(propertyService.getDefaultProperties());
} else {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
}
}
@RequestMapping(value = "/rest/property", method = RequestMethod.POST) | // Path: src/main/java/com/github/vedenin/codingchallenge/mvc/model/ResponseChangeStatus.java
// public class ResponseChangeStatus {
// private String status = "ok";
//
// public String getStatus() {
// return status;
// }
//
// public void setStatus(String status) {
// this.status = status;
// }
// }
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/controler/MainRestController.java
import com.github.vedenin.codingchallenge.mvc.model.ResponseChangeStatus;
import com.github.vedenin.codingchallenge.persistence.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.google.common.collect.Lists;
import javax.inject.Inject;
import java.util.List;
}
@RequestMapping(value = "/rest/history", method = RequestMethod.GET)
public ResponseEntity<List<HistoryEntity>> getHistories(@RequestParam(value="access_key", defaultValue = "") String accessKey) {
if(ACCESS_KEY.equals(accessKey)) {
return ResponseEntity.ok(Lists.newArrayList(historyRepository.findAll()));
} else {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
}
}
@RequestMapping(value = "/rest/error", method = RequestMethod.GET)
public ResponseEntity<List<ErrorEntity>> getErrors(@RequestParam(value="access_key", defaultValue = "") String accessKey) {
if(ACCESS_KEY.equals(accessKey)) {
return ResponseEntity.ok(Lists.newArrayList(errorRepository.findAll()));
} else {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
}
}
@RequestMapping(value = "/rest/property", method = RequestMethod.GET)
public ResponseEntity<DefaultProperty> getProperty(@RequestParam(value="access_key", defaultValue = "") String accessKey) {
if(ACCESS_KEY.equals(accessKey)) {
return ResponseEntity.ok(propertyService.getDefaultProperties());
} else {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
}
}
@RequestMapping(value = "/rest/property", method = RequestMethod.POST) | public ResponseEntity<ResponseChangeStatus> setProperty( |
Vedenin/RestAndSpringMVC-CodingChallenge | src/main/java/com/github/vedenin/codingchallenge/persistence/HistoryEntity.java | // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
| import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.Date; | package com.github.vedenin.codingchallenge.persistence;
/**
* Created by slava on 11.02.17.
*/
@Entity
public class HistoryEntity {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@Column(precision = 30, scale = 2)
private BigDecimal amount;
| // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
// Path: src/main/java/com/github/vedenin/codingchallenge/persistence/HistoryEntity.java
import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.Date;
package com.github.vedenin.codingchallenge.persistence;
/**
* Created by slava on 11.02.17.
*/
@Entity
public class HistoryEntity {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@Column(precision = 30, scale = 2)
private BigDecimal amount;
| private CurrencyEnum currencyFrom; |
Vedenin/RestAndSpringMVC-CodingChallenge | src/main/java/com/github/vedenin/codingchallenge/restclient/FaultTolerantRestClient.java | // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/persistence/ErrorEntity.java
// @Entity
// public class ErrorEntity {
// @Id
// @GeneratedValue(strategy= GenerationType.AUTO)
// private Long id;
// private String errorMessage;
// private Exception exp;
//
// public ErrorEntity(String errorMessage, Exception exp) {
// this.errorMessage = errorMessage;
// this.exp = exp;
// }
//
// public ErrorEntity() {
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public Exception getExp() {
// return exp;
// }
//
// public void setExp(Exception exp) {
// this.exp = exp;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/persistence/ErrorRepository.java
// public interface ErrorRepository extends CrudRepository<ErrorEntity, Long> {
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/persistence/PropertyService.java
// @Service
// public class PropertyService {
// @Inject
// PropertyRepository repository;
//
// public DefaultProperty getDefaultProperties() {
// DefaultProperty properties = repository.findOne(1L);
// if(properties == null) {
// properties = new DefaultProperty();
// repository.save(properties);
// }
// return properties;
// }
//
// public void setDefaultProperties(DefaultProperty properties) {
// repository.save(properties);
// }
// }
| import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import com.github.vedenin.codingchallenge.persistence.ErrorEntity;
import com.github.vedenin.codingchallenge.persistence.ErrorRepository;
import com.github.vedenin.codingchallenge.persistence.PropertyService;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit; | package com.github.vedenin.codingchallenge.restclient;
/**
* Rest client that used all services before one of services not returns
* correct result
* <p>
* Created by slava on 10.02.17.
*/
@Service("FaultTolerant")
public class FaultTolerantRestClient implements RestClient {
private static final long INIT_DURATION = 60L * 60L;
@Inject
private List<RestClient> list;
@Inject | // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/persistence/ErrorEntity.java
// @Entity
// public class ErrorEntity {
// @Id
// @GeneratedValue(strategy= GenerationType.AUTO)
// private Long id;
// private String errorMessage;
// private Exception exp;
//
// public ErrorEntity(String errorMessage, Exception exp) {
// this.errorMessage = errorMessage;
// this.exp = exp;
// }
//
// public ErrorEntity() {
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public Exception getExp() {
// return exp;
// }
//
// public void setExp(Exception exp) {
// this.exp = exp;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/persistence/ErrorRepository.java
// public interface ErrorRepository extends CrudRepository<ErrorEntity, Long> {
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/persistence/PropertyService.java
// @Service
// public class PropertyService {
// @Inject
// PropertyRepository repository;
//
// public DefaultProperty getDefaultProperties() {
// DefaultProperty properties = repository.findOne(1L);
// if(properties == null) {
// properties = new DefaultProperty();
// repository.save(properties);
// }
// return properties;
// }
//
// public void setDefaultProperties(DefaultProperty properties) {
// repository.save(properties);
// }
// }
// Path: src/main/java/com/github/vedenin/codingchallenge/restclient/FaultTolerantRestClient.java
import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import com.github.vedenin.codingchallenge.persistence.ErrorEntity;
import com.github.vedenin.codingchallenge.persistence.ErrorRepository;
import com.github.vedenin.codingchallenge.persistence.PropertyService;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit;
package com.github.vedenin.codingchallenge.restclient;
/**
* Rest client that used all services before one of services not returns
* correct result
* <p>
* Created by slava on 10.02.17.
*/
@Service("FaultTolerant")
public class FaultTolerantRestClient implements RestClient {
private static final long INIT_DURATION = 60L * 60L;
@Inject
private List<RestClient> list;
@Inject | private ErrorRepository errorRepository; |
Vedenin/RestAndSpringMVC-CodingChallenge | src/main/java/com/github/vedenin/codingchallenge/restclient/FaultTolerantRestClient.java | // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/persistence/ErrorEntity.java
// @Entity
// public class ErrorEntity {
// @Id
// @GeneratedValue(strategy= GenerationType.AUTO)
// private Long id;
// private String errorMessage;
// private Exception exp;
//
// public ErrorEntity(String errorMessage, Exception exp) {
// this.errorMessage = errorMessage;
// this.exp = exp;
// }
//
// public ErrorEntity() {
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public Exception getExp() {
// return exp;
// }
//
// public void setExp(Exception exp) {
// this.exp = exp;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/persistence/ErrorRepository.java
// public interface ErrorRepository extends CrudRepository<ErrorEntity, Long> {
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/persistence/PropertyService.java
// @Service
// public class PropertyService {
// @Inject
// PropertyRepository repository;
//
// public DefaultProperty getDefaultProperties() {
// DefaultProperty properties = repository.findOne(1L);
// if(properties == null) {
// properties = new DefaultProperty();
// repository.save(properties);
// }
// return properties;
// }
//
// public void setDefaultProperties(DefaultProperty properties) {
// repository.save(properties);
// }
// }
| import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import com.github.vedenin.codingchallenge.persistence.ErrorEntity;
import com.github.vedenin.codingchallenge.persistence.ErrorRepository;
import com.github.vedenin.codingchallenge.persistence.PropertyService;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit; | package com.github.vedenin.codingchallenge.restclient;
/**
* Rest client that used all services before one of services not returns
* correct result
* <p>
* Created by slava on 10.02.17.
*/
@Service("FaultTolerant")
public class FaultTolerantRestClient implements RestClient {
private static final long INIT_DURATION = 60L * 60L;
@Inject
private List<RestClient> list;
@Inject
private ErrorRepository errorRepository;
@Inject | // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/persistence/ErrorEntity.java
// @Entity
// public class ErrorEntity {
// @Id
// @GeneratedValue(strategy= GenerationType.AUTO)
// private Long id;
// private String errorMessage;
// private Exception exp;
//
// public ErrorEntity(String errorMessage, Exception exp) {
// this.errorMessage = errorMessage;
// this.exp = exp;
// }
//
// public ErrorEntity() {
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public Exception getExp() {
// return exp;
// }
//
// public void setExp(Exception exp) {
// this.exp = exp;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/persistence/ErrorRepository.java
// public interface ErrorRepository extends CrudRepository<ErrorEntity, Long> {
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/persistence/PropertyService.java
// @Service
// public class PropertyService {
// @Inject
// PropertyRepository repository;
//
// public DefaultProperty getDefaultProperties() {
// DefaultProperty properties = repository.findOne(1L);
// if(properties == null) {
// properties = new DefaultProperty();
// repository.save(properties);
// }
// return properties;
// }
//
// public void setDefaultProperties(DefaultProperty properties) {
// repository.save(properties);
// }
// }
// Path: src/main/java/com/github/vedenin/codingchallenge/restclient/FaultTolerantRestClient.java
import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import com.github.vedenin.codingchallenge.persistence.ErrorEntity;
import com.github.vedenin.codingchallenge.persistence.ErrorRepository;
import com.github.vedenin.codingchallenge.persistence.PropertyService;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit;
package com.github.vedenin.codingchallenge.restclient;
/**
* Rest client that used all services before one of services not returns
* correct result
* <p>
* Created by slava on 10.02.17.
*/
@Service("FaultTolerant")
public class FaultTolerantRestClient implements RestClient {
private static final long INIT_DURATION = 60L * 60L;
@Inject
private List<RestClient> list;
@Inject
private ErrorRepository errorRepository;
@Inject | private PropertyService propertyService; |
Vedenin/RestAndSpringMVC-CodingChallenge | src/main/java/com/github/vedenin/codingchallenge/restclient/FaultTolerantRestClient.java | // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/persistence/ErrorEntity.java
// @Entity
// public class ErrorEntity {
// @Id
// @GeneratedValue(strategy= GenerationType.AUTO)
// private Long id;
// private String errorMessage;
// private Exception exp;
//
// public ErrorEntity(String errorMessage, Exception exp) {
// this.errorMessage = errorMessage;
// this.exp = exp;
// }
//
// public ErrorEntity() {
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public Exception getExp() {
// return exp;
// }
//
// public void setExp(Exception exp) {
// this.exp = exp;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/persistence/ErrorRepository.java
// public interface ErrorRepository extends CrudRepository<ErrorEntity, Long> {
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/persistence/PropertyService.java
// @Service
// public class PropertyService {
// @Inject
// PropertyRepository repository;
//
// public DefaultProperty getDefaultProperties() {
// DefaultProperty properties = repository.findOne(1L);
// if(properties == null) {
// properties = new DefaultProperty();
// repository.save(properties);
// }
// return properties;
// }
//
// public void setDefaultProperties(DefaultProperty properties) {
// repository.save(properties);
// }
// }
| import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import com.github.vedenin.codingchallenge.persistence.ErrorEntity;
import com.github.vedenin.codingchallenge.persistence.ErrorRepository;
import com.github.vedenin.codingchallenge.persistence.PropertyService;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit; | package com.github.vedenin.codingchallenge.restclient;
/**
* Rest client that used all services before one of services not returns
* correct result
* <p>
* Created by slava on 10.02.17.
*/
@Service("FaultTolerant")
public class FaultTolerantRestClient implements RestClient {
private static final long INIT_DURATION = 60L * 60L;
@Inject
private List<RestClient> list;
@Inject
private ErrorRepository errorRepository;
@Inject
private PropertyService propertyService;
private Cache<CacheKey, BigDecimal> cache = CacheBuilder.newBuilder()
.expireAfterWrite(INIT_DURATION, TimeUnit.SECONDS).build();
private Long cacheDuration = INIT_DURATION;
| // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/persistence/ErrorEntity.java
// @Entity
// public class ErrorEntity {
// @Id
// @GeneratedValue(strategy= GenerationType.AUTO)
// private Long id;
// private String errorMessage;
// private Exception exp;
//
// public ErrorEntity(String errorMessage, Exception exp) {
// this.errorMessage = errorMessage;
// this.exp = exp;
// }
//
// public ErrorEntity() {
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public Exception getExp() {
// return exp;
// }
//
// public void setExp(Exception exp) {
// this.exp = exp;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/persistence/ErrorRepository.java
// public interface ErrorRepository extends CrudRepository<ErrorEntity, Long> {
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/persistence/PropertyService.java
// @Service
// public class PropertyService {
// @Inject
// PropertyRepository repository;
//
// public DefaultProperty getDefaultProperties() {
// DefaultProperty properties = repository.findOne(1L);
// if(properties == null) {
// properties = new DefaultProperty();
// repository.save(properties);
// }
// return properties;
// }
//
// public void setDefaultProperties(DefaultProperty properties) {
// repository.save(properties);
// }
// }
// Path: src/main/java/com/github/vedenin/codingchallenge/restclient/FaultTolerantRestClient.java
import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import com.github.vedenin.codingchallenge.persistence.ErrorEntity;
import com.github.vedenin.codingchallenge.persistence.ErrorRepository;
import com.github.vedenin.codingchallenge.persistence.PropertyService;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit;
package com.github.vedenin.codingchallenge.restclient;
/**
* Rest client that used all services before one of services not returns
* correct result
* <p>
* Created by slava on 10.02.17.
*/
@Service("FaultTolerant")
public class FaultTolerantRestClient implements RestClient {
private static final long INIT_DURATION = 60L * 60L;
@Inject
private List<RestClient> list;
@Inject
private ErrorRepository errorRepository;
@Inject
private PropertyService propertyService;
private Cache<CacheKey, BigDecimal> cache = CacheBuilder.newBuilder()
.expireAfterWrite(INIT_DURATION, TimeUnit.SECONDS).build();
private Long cacheDuration = INIT_DURATION;
| public BigDecimal getCurrentExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo) { |
Vedenin/RestAndSpringMVC-CodingChallenge | src/main/java/com/github/vedenin/codingchallenge/restclient/FaultTolerantRestClient.java | // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/persistence/ErrorEntity.java
// @Entity
// public class ErrorEntity {
// @Id
// @GeneratedValue(strategy= GenerationType.AUTO)
// private Long id;
// private String errorMessage;
// private Exception exp;
//
// public ErrorEntity(String errorMessage, Exception exp) {
// this.errorMessage = errorMessage;
// this.exp = exp;
// }
//
// public ErrorEntity() {
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public Exception getExp() {
// return exp;
// }
//
// public void setExp(Exception exp) {
// this.exp = exp;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/persistence/ErrorRepository.java
// public interface ErrorRepository extends CrudRepository<ErrorEntity, Long> {
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/persistence/PropertyService.java
// @Service
// public class PropertyService {
// @Inject
// PropertyRepository repository;
//
// public DefaultProperty getDefaultProperties() {
// DefaultProperty properties = repository.findOne(1L);
// if(properties == null) {
// properties = new DefaultProperty();
// repository.save(properties);
// }
// return properties;
// }
//
// public void setDefaultProperties(DefaultProperty properties) {
// repository.save(properties);
// }
// }
| import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import com.github.vedenin.codingchallenge.persistence.ErrorEntity;
import com.github.vedenin.codingchallenge.persistence.ErrorRepository;
import com.github.vedenin.codingchallenge.persistence.PropertyService;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit; | package com.github.vedenin.codingchallenge.restclient;
/**
* Rest client that used all services before one of services not returns
* correct result
* <p>
* Created by slava on 10.02.17.
*/
@Service("FaultTolerant")
public class FaultTolerantRestClient implements RestClient {
private static final long INIT_DURATION = 60L * 60L;
@Inject
private List<RestClient> list;
@Inject
private ErrorRepository errorRepository;
@Inject
private PropertyService propertyService;
private Cache<CacheKey, BigDecimal> cache = CacheBuilder.newBuilder()
.expireAfterWrite(INIT_DURATION, TimeUnit.SECONDS).build();
private Long cacheDuration = INIT_DURATION;
public BigDecimal getCurrentExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo) {
reInitCache();
CacheKey data = new CacheKey(currencyFrom, currencyTo, null);
BigDecimal result = cache.getIfPresent(data);
if(result != null) {
return result;
}
for(int i = 0; i < propertyService.getDefaultProperties().getReplyRestTimes(); i++) {
for (RestClient client : list) {
try {
result = client.getCurrentExchangeRates(currencyFrom, currencyTo);
if(result != null) {
cache.put(data, result);
return result;
}
} catch (Exception exp) { | // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/persistence/ErrorEntity.java
// @Entity
// public class ErrorEntity {
// @Id
// @GeneratedValue(strategy= GenerationType.AUTO)
// private Long id;
// private String errorMessage;
// private Exception exp;
//
// public ErrorEntity(String errorMessage, Exception exp) {
// this.errorMessage = errorMessage;
// this.exp = exp;
// }
//
// public ErrorEntity() {
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public Exception getExp() {
// return exp;
// }
//
// public void setExp(Exception exp) {
// this.exp = exp;
// }
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/persistence/ErrorRepository.java
// public interface ErrorRepository extends CrudRepository<ErrorEntity, Long> {
// }
//
// Path: src/main/java/com/github/vedenin/codingchallenge/persistence/PropertyService.java
// @Service
// public class PropertyService {
// @Inject
// PropertyRepository repository;
//
// public DefaultProperty getDefaultProperties() {
// DefaultProperty properties = repository.findOne(1L);
// if(properties == null) {
// properties = new DefaultProperty();
// repository.save(properties);
// }
// return properties;
// }
//
// public void setDefaultProperties(DefaultProperty properties) {
// repository.save(properties);
// }
// }
// Path: src/main/java/com/github/vedenin/codingchallenge/restclient/FaultTolerantRestClient.java
import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import com.github.vedenin.codingchallenge.persistence.ErrorEntity;
import com.github.vedenin.codingchallenge.persistence.ErrorRepository;
import com.github.vedenin.codingchallenge.persistence.PropertyService;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit;
package com.github.vedenin.codingchallenge.restclient;
/**
* Rest client that used all services before one of services not returns
* correct result
* <p>
* Created by slava on 10.02.17.
*/
@Service("FaultTolerant")
public class FaultTolerantRestClient implements RestClient {
private static final long INIT_DURATION = 60L * 60L;
@Inject
private List<RestClient> list;
@Inject
private ErrorRepository errorRepository;
@Inject
private PropertyService propertyService;
private Cache<CacheKey, BigDecimal> cache = CacheBuilder.newBuilder()
.expireAfterWrite(INIT_DURATION, TimeUnit.SECONDS).build();
private Long cacheDuration = INIT_DURATION;
public BigDecimal getCurrentExchangeRates(CurrencyEnum currencyFrom, CurrencyEnum currencyTo) {
reInitCache();
CacheKey data = new CacheKey(currencyFrom, currencyTo, null);
BigDecimal result = cache.getIfPresent(data);
if(result != null) {
return result;
}
for(int i = 0; i < propertyService.getDefaultProperties().getReplyRestTimes(); i++) {
for (RestClient client : list) {
try {
result = client.getCurrentExchangeRates(currencyFrom, currencyTo);
if(result != null) {
cache.put(data, result);
return result;
}
} catch (Exception exp) { | errorRepository.save(new ErrorEntity("Error when getCurrentExchangeRates, class: " + |
Vedenin/RestAndSpringMVC-CodingChallenge | src/main/java/com/github/vedenin/codingchallenge/mvc/model/ConverterFormModel.java | // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
| import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import javax.validation.constraints.AssertTrue;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.Date; | package com.github.vedenin.codingchallenge.mvc.model;
/**
* Model for converter page
*
* Created by vvedenin on 2/8/2017.
*/
public class ConverterFormModel {
@NotNull | // Path: src/main/java/com/github/vedenin/codingchallenge/common/CurrencyEnum.java
// public enum CurrencyEnum {
// EUR("EUR", "Euro (EUR)"),
// USD("USD", "US Dollar (USD)"),
// GBP("GBP", "British Pound (GBP)"),
// NZD("NZD", "New Zealand Dollar (NZD)"),
// AUD("AUD", "Australian Dollar (AUD)"),
// JPY("JPY", "Japanese Yen (JPY)"),
// HUF("HUF", "Hungarian Forint (HUF)"),
// RUB("RUB", "Russian Ruble (RUB)"),
// PLN("PLN", "Polish Zloty (PLN)");
// private final String code;
// private final String description;
//
// CurrencyEnum(String code, String description) {
// this.code = code;
// this.description = description;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getDescription() {
// return description;
// }
// }
// Path: src/main/java/com/github/vedenin/codingchallenge/mvc/model/ConverterFormModel.java
import com.github.vedenin.codingchallenge.common.CurrencyEnum;
import javax.validation.constraints.AssertTrue;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.Date;
package com.github.vedenin.codingchallenge.mvc.model;
/**
* Model for converter page
*
* Created by vvedenin on 2/8/2017.
*/
public class ConverterFormModel {
@NotNull | private String to = CurrencyEnum.USD.getCode(); |
bretthshelley/Maven-IIB9-Plug-In | src/test/java/ch/sbb/maven/plugins/iib/mojos/PrepareBarBuildWorkspaceMojoTest.java | // Path: src/main/java/ch/sbb/maven/plugins/iib/mojos/PrepareBarBuildWorkspaceMojo.java
// public static String verifyIibIncludeTypes(String includeTypes)
// {
// if (includeTypes == null || includeTypes.trim().isEmpty())
// {
// includeTypes = "zip";
// }
// // / let's split up the String by comma's, and rebuild the expression without the jar
//
// final String regex = "\\s*,[,\\s]*";
// String[] types = includeTypes.split(regex);
//
// String result = null;
// for (String type : types)
// {
// if (type.trim().equalsIgnoreCase("jar"))
// {
// continue;
// }
// if (result == null)
// {
// result = type.trim();
// }
// else
// {
// result += "," + type.trim();
// }
// }
// return result;
//
//
// }
| import static ch.sbb.maven.plugins.iib.mojos.PrepareBarBuildWorkspaceMojo.verifyIibIncludeTypes;
import junit.framework.Assert;
import org.junit.Test; | package ch.sbb.maven.plugins.iib.mojos;
public class PrepareBarBuildWorkspaceMojoTest {
@Test
public void verifyIncludeTypes()
{
String types = "zip,jar"; | // Path: src/main/java/ch/sbb/maven/plugins/iib/mojos/PrepareBarBuildWorkspaceMojo.java
// public static String verifyIibIncludeTypes(String includeTypes)
// {
// if (includeTypes == null || includeTypes.trim().isEmpty())
// {
// includeTypes = "zip";
// }
// // / let's split up the String by comma's, and rebuild the expression without the jar
//
// final String regex = "\\s*,[,\\s]*";
// String[] types = includeTypes.split(regex);
//
// String result = null;
// for (String type : types)
// {
// if (type.trim().equalsIgnoreCase("jar"))
// {
// continue;
// }
// if (result == null)
// {
// result = type.trim();
// }
// else
// {
// result += "," + type.trim();
// }
// }
// return result;
//
//
// }
// Path: src/test/java/ch/sbb/maven/plugins/iib/mojos/PrepareBarBuildWorkspaceMojoTest.java
import static ch.sbb.maven.plugins.iib.mojos.PrepareBarBuildWorkspaceMojo.verifyIibIncludeTypes;
import junit.framework.Assert;
import org.junit.Test;
package ch.sbb.maven.plugins.iib.mojos;
public class PrepareBarBuildWorkspaceMojoTest {
@Test
public void verifyIncludeTypes()
{
String types = "zip,jar"; | String actual = verifyIibIncludeTypes(types); |
bretthshelley/Maven-IIB9-Plug-In | src/main/java/ch/sbb/maven/plugins/iib/mojos/CleanBarBuildWorkspaceMojo.java | // Path: src/main/java/ch/sbb/maven/plugins/iib/utils/SkipUtil.java
// public class SkipUtil {
//
// @SuppressWarnings("rawtypes")
// static LinkedHashMap<Class, String> classGoalMap = new LinkedHashMap<Class, String>();
// List<String> skipGoals = new ArrayList<String>();
// String skipToGoal = null;
//
// static
// {
// classGoalMap.put(InitializeBarBuildWorkspaceMojo.class, "initialize");
// classGoalMap.put(PrepareBarBuildWorkspaceMojo.class, "generate-resources");
// classGoalMap.put(ValidateBarBuildWorkspaceMojo.class, "process-resources");
// classGoalMap.put(PackageBarMojo.class, "compile");
// classGoalMap.put(String.class, "test-compile");
// classGoalMap.put(ApplyBarOverridesMojo.class, "process-classes");
// classGoalMap.put(ValidateClassloaderApproachMojo.class, "process-classes");
// classGoalMap.put(MqsiDeployMojo.class, "pre-integration-test");
// classGoalMap.put(Integer.class, "integration-test");
// classGoalMap.put(Double.class, "verify");
// classGoalMap.put(DeployBarMojo.class, "deploy");
//
//
// }
//
// private static String getValidGoals()
// {
// boolean first = true;
// StringBuilder sb = new StringBuilder();
// for (String goal : classGoalMap.values())
// {
// if (!first)
// {
// sb.append(",");
// }
// sb.append(goal);
// first = false;
// }
// return sb.toString();
// }
//
//
// @SuppressWarnings("rawtypes")
// public boolean isSkip(Class clazz)
// {
// // / determine goals to skip from comma-separated list
// String skip = System.getProperty("skip");
// if (skip != null && !skip.trim().isEmpty())
// {
// String[] sa = skip.split(Pattern.quote(","));
// for (String goal : sa)
// {
// if (goal == null) {
// continue;
// }
// if (goal.trim().isEmpty()) {
// continue;
// }
// goal = goal.trim().toLowerCase();
// if (!classGoalMap.values().contains(goal)) {
// throw new RuntimeException("The '-Dskip=...' value(s) must be a comma-separated list of goal(s) from the group:" + getValidGoals());
//
// }
// skipGoals.add(goal);
// }
// }
//
// // / determine goals to skip from comma-separated list
// String skipTo = System.getProperty("skipTo");
// if (skipTo != null && !skipTo.trim().isEmpty())
// {
// skipTo = skipTo.toLowerCase().trim();
//
// if (!classGoalMap.values().contains(skipTo))
// {
// throw new RuntimeException("The '-DskipTo=...' value must be a single goal from the group:" + getValidGoals());
// }
// skipToGoal = skipTo;
//
// }
//
//
// if (skipGoals.isEmpty() && skipToGoal == null) {
// return false;
// }
//
// String currentGoal = classGoalMap.get(clazz);
// if (skipGoals.contains(currentGoal))
// {
// return true;
// }
//
// // / see if skipToGoal
// if (skipToGoal == null)
// {
// return false;
// }
//
//
// // / go through the list to determine if goal is before current
// if (skipToGoal.equals(currentGoal)) {
// return false;
// }
//
// List<String> goalsBefore = new ArrayList<String>();
// List<String> goalsAfter = new ArrayList<String>();
// boolean skipToGoalFound = false;
// for (String goal : classGoalMap.values())
// {
// if (goal.equals(skipToGoal))
// {
// skipToGoalFound = true;
// continue;
// }
// if (skipToGoalFound)
// {
// goalsAfter.add(goal);
// }
// else
// {
// goalsBefore.add(goal);
// }
// }
//
// if (goalsBefore.contains(currentGoal)) {
// return true;
// }
// if (goalsAfter.contains(currentGoal)) {
// return false;
// }
// return false;
//
//
// }
//
//
// }
| import java.io.File;
import java.io.IOException;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.codehaus.plexus.util.FileUtils;
import ch.sbb.maven.plugins.iib.utils.SkipUtil; | package ch.sbb.maven.plugins.iib.mojos;
/**
* Cleans up the ${iib.workspace} directory. Build errors will appear in the IIB Toolkit if .msgflow files are left under the ${iib.workspace} - the path determines the Namespace of the flow and that
* certainly won't match the original directory structure.
*/
@Mojo(name = "clean-bar-build-workspace", requiresProject = false)
public class CleanBarBuildWorkspaceMojo extends AbstractMojo {
/**
* The path of the workspace in which the projects were created.
*/
@Parameter(property = "workspace", defaultValue = "${project.build.directory}/iib/workspace", required = true)
protected File workspace;
/**
* set to true to disable the workspace cleaning
*/
@Parameter(property = "wipeoutWorkspace", defaultValue = "false")
protected boolean wipeoutWorkspace;
public void execute() throws MojoFailureException { | // Path: src/main/java/ch/sbb/maven/plugins/iib/utils/SkipUtil.java
// public class SkipUtil {
//
// @SuppressWarnings("rawtypes")
// static LinkedHashMap<Class, String> classGoalMap = new LinkedHashMap<Class, String>();
// List<String> skipGoals = new ArrayList<String>();
// String skipToGoal = null;
//
// static
// {
// classGoalMap.put(InitializeBarBuildWorkspaceMojo.class, "initialize");
// classGoalMap.put(PrepareBarBuildWorkspaceMojo.class, "generate-resources");
// classGoalMap.put(ValidateBarBuildWorkspaceMojo.class, "process-resources");
// classGoalMap.put(PackageBarMojo.class, "compile");
// classGoalMap.put(String.class, "test-compile");
// classGoalMap.put(ApplyBarOverridesMojo.class, "process-classes");
// classGoalMap.put(ValidateClassloaderApproachMojo.class, "process-classes");
// classGoalMap.put(MqsiDeployMojo.class, "pre-integration-test");
// classGoalMap.put(Integer.class, "integration-test");
// classGoalMap.put(Double.class, "verify");
// classGoalMap.put(DeployBarMojo.class, "deploy");
//
//
// }
//
// private static String getValidGoals()
// {
// boolean first = true;
// StringBuilder sb = new StringBuilder();
// for (String goal : classGoalMap.values())
// {
// if (!first)
// {
// sb.append(",");
// }
// sb.append(goal);
// first = false;
// }
// return sb.toString();
// }
//
//
// @SuppressWarnings("rawtypes")
// public boolean isSkip(Class clazz)
// {
// // / determine goals to skip from comma-separated list
// String skip = System.getProperty("skip");
// if (skip != null && !skip.trim().isEmpty())
// {
// String[] sa = skip.split(Pattern.quote(","));
// for (String goal : sa)
// {
// if (goal == null) {
// continue;
// }
// if (goal.trim().isEmpty()) {
// continue;
// }
// goal = goal.trim().toLowerCase();
// if (!classGoalMap.values().contains(goal)) {
// throw new RuntimeException("The '-Dskip=...' value(s) must be a comma-separated list of goal(s) from the group:" + getValidGoals());
//
// }
// skipGoals.add(goal);
// }
// }
//
// // / determine goals to skip from comma-separated list
// String skipTo = System.getProperty("skipTo");
// if (skipTo != null && !skipTo.trim().isEmpty())
// {
// skipTo = skipTo.toLowerCase().trim();
//
// if (!classGoalMap.values().contains(skipTo))
// {
// throw new RuntimeException("The '-DskipTo=...' value must be a single goal from the group:" + getValidGoals());
// }
// skipToGoal = skipTo;
//
// }
//
//
// if (skipGoals.isEmpty() && skipToGoal == null) {
// return false;
// }
//
// String currentGoal = classGoalMap.get(clazz);
// if (skipGoals.contains(currentGoal))
// {
// return true;
// }
//
// // / see if skipToGoal
// if (skipToGoal == null)
// {
// return false;
// }
//
//
// // / go through the list to determine if goal is before current
// if (skipToGoal.equals(currentGoal)) {
// return false;
// }
//
// List<String> goalsBefore = new ArrayList<String>();
// List<String> goalsAfter = new ArrayList<String>();
// boolean skipToGoalFound = false;
// for (String goal : classGoalMap.values())
// {
// if (goal.equals(skipToGoal))
// {
// skipToGoalFound = true;
// continue;
// }
// if (skipToGoalFound)
// {
// goalsAfter.add(goal);
// }
// else
// {
// goalsBefore.add(goal);
// }
// }
//
// if (goalsBefore.contains(currentGoal)) {
// return true;
// }
// if (goalsAfter.contains(currentGoal)) {
// return false;
// }
// return false;
//
//
// }
//
//
// }
// Path: src/main/java/ch/sbb/maven/plugins/iib/mojos/CleanBarBuildWorkspaceMojo.java
import java.io.File;
import java.io.IOException;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.codehaus.plexus.util.FileUtils;
import ch.sbb.maven.plugins.iib.utils.SkipUtil;
package ch.sbb.maven.plugins.iib.mojos;
/**
* Cleans up the ${iib.workspace} directory. Build errors will appear in the IIB Toolkit if .msgflow files are left under the ${iib.workspace} - the path determines the Namespace of the flow and that
* certainly won't match the original directory structure.
*/
@Mojo(name = "clean-bar-build-workspace", requiresProject = false)
public class CleanBarBuildWorkspaceMojo extends AbstractMojo {
/**
* The path of the workspace in which the projects were created.
*/
@Parameter(property = "workspace", defaultValue = "${project.build.directory}/iib/workspace", required = true)
protected File workspace;
/**
* set to true to disable the workspace cleaning
*/
@Parameter(property = "wipeoutWorkspace", defaultValue = "false")
protected boolean wipeoutWorkspace;
public void execute() throws MojoFailureException { | if (new SkipUtil().isSkip(this.getClass())) { |
bretthshelley/Maven-IIB9-Plug-In | src/main/java/ch/sbb/maven/plugins/iib/mojos/ValidateClassloaderApproachMojo.java | // Path: src/main/java/ch/sbb/maven/plugins/iib/utils/ConfigurationValidator.java
// public static void validateUseClassloaders(Boolean useClassloaders, Log log) throws MojoFailureException
// {
// if (useClassloaders == null)
// {
// logErrorStart(log);
// String[] messages = { getArgumentMissingString("useClassloaders") };
// logErrorBaseProblem(log, messages);
//
// String tagName = "useClassloaders";
// String exampleText = "false";
// String exampleTagString = getExampleTagString(tagName, exampleText);
// logErrorExample(log, new String[] { exampleTagString });
//
// String[] instructions = new String[] {
// "'useClassLoaders' indicates whether classloaders are in use with this bar;",
// "false adds dependent jars into workspace META-INF dir; true does not; ",
// "both true and false will unpack dependent jar resources.",
// "This also comes into play in the Bar Override process."
//
// };
//
// logErrorInstructions(log, instructions);
//
// logErrorFinish(log);
//
// throw new MojoFailureException(getArgumentMissingString("useClassloaders"));
// }
// }
//
// Path: src/main/java/ch/sbb/maven/plugins/iib/utils/ConfigurableProperties.java
// @SuppressWarnings("serial")
// public final class ConfigurableProperties extends TreeMap<String, String> {
//
// /**
// * returns a list of properties where the propName ends with .javaClassLoader
// *
// * @param configurableProperties
// * @return
// */
// public static List<String> getJavaClassLoaderProperties(List<String> configurableProperties) {
// List<String> clProps = new ArrayList<String>();
// for (String propEntry : configurableProperties) {
// if (getPropName(propEntry).endsWith(".javaClassLoader")) {
// clProps.add(propEntry);
// }
// }
//
// return clProps;
// }
//
// public static List<String> getPropNames(List<String> configurableProperties) {
// List<String> propNames = new ArrayList<String>();
// for (String confProp : configurableProperties) {
// // use the value up to an equals sign if present
// propNames.add(getPropName(confProp));
// }
// return propNames;
// }
//
// public static String getPropName(String configurablePropertyEntry) {
// // use the value up to an equals sign if present
// return (configurablePropertyEntry.split("=")[0]).trim();
// }
//
// public static String getPropValue(String configurablePropertyEntry) {
// // use the value up to an equals sign if present
// if (configurablePropertyEntry.split("=").length == 2) {
// return (configurablePropertyEntry.split("=")[1]).trim();
// }
// return "";
// }
//
//
// public void load(File file) throws IOException {
//
// // empty the existing data
// this.clear();
//
// // read the file line by line, adding it to the existing data
// LineIterator iterator = FileUtils.lineIterator(file, "UTF-8");
// try {
// while (iterator.hasNext()) {
// String line = iterator.nextLine();
//
// String key;
// String value;
//
// Integer equalsPos = line.indexOf("=");
//
// // if there is no "=", only the key is present
// if (equalsPos == -1) {
// key = line.trim();
// value = "";
// } else {
// // there is an "=" present, so split out the key & value
// key = line.substring(0, equalsPos).trim();
// value = line.substring(equalsPos + 1).trim();
// }
// this.put(key, value);
// }
// } finally {
// LineIterator.closeQuietly(iterator);
// }
// }
//
// public void save(File file) throws IOException {
//
// List<String> lines = new ArrayList<String>();
//
// for (Map.Entry<String, String> entry : this.entrySet()) {
// String line = entry.getKey();
// String value = entry.getValue();
// if (value != null && value.length() > 0) {
// line = line + " = " + value;
// }
// lines.add(line);
// }
//
// FileUtils.writeLines(file, lines);
// }
//
// }
| import static ch.sbb.maven.plugins.iib.utils.ConfigurationValidator.validateUseClassloaders;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import ch.sbb.maven.plugins.iib.utils.ConfigurableProperties; | package ch.sbb.maven.plugins.iib.mojos;
/**
* Goal which reads the default.properties file to figure out if the classloader approach for this bar project is consistent. Either all jar nodes in all flows must use a classloader or none of them
* should.
*/
@Mojo(name = "validate-classloader-approach")
public class ValidateClassloaderApproachMojo extends AbstractMojo {
/**
* The name of the default properties file to be generated from the bar file.
*/
@Parameter(property = "iib.defaultPropertiesFile", defaultValue = "${project.build.directory}/default.properties", required = true)
protected File defaultPropertiesFile;
/**
* Whether or not to fail the build if the classloader approach is invalid.
*/
@Parameter(property = "iib.failOnInvalidClassloader", defaultValue = "true", required = true)
protected Boolean failOnInvalidClassloader;
/**
* Whether classloaders are in use with this bar
*/
@Parameter(property = "iib.useClassloaders")
protected Boolean useClassloaders;
public void execute() throws MojoFailureException {
| // Path: src/main/java/ch/sbb/maven/plugins/iib/utils/ConfigurationValidator.java
// public static void validateUseClassloaders(Boolean useClassloaders, Log log) throws MojoFailureException
// {
// if (useClassloaders == null)
// {
// logErrorStart(log);
// String[] messages = { getArgumentMissingString("useClassloaders") };
// logErrorBaseProblem(log, messages);
//
// String tagName = "useClassloaders";
// String exampleText = "false";
// String exampleTagString = getExampleTagString(tagName, exampleText);
// logErrorExample(log, new String[] { exampleTagString });
//
// String[] instructions = new String[] {
// "'useClassLoaders' indicates whether classloaders are in use with this bar;",
// "false adds dependent jars into workspace META-INF dir; true does not; ",
// "both true and false will unpack dependent jar resources.",
// "This also comes into play in the Bar Override process."
//
// };
//
// logErrorInstructions(log, instructions);
//
// logErrorFinish(log);
//
// throw new MojoFailureException(getArgumentMissingString("useClassloaders"));
// }
// }
//
// Path: src/main/java/ch/sbb/maven/plugins/iib/utils/ConfigurableProperties.java
// @SuppressWarnings("serial")
// public final class ConfigurableProperties extends TreeMap<String, String> {
//
// /**
// * returns a list of properties where the propName ends with .javaClassLoader
// *
// * @param configurableProperties
// * @return
// */
// public static List<String> getJavaClassLoaderProperties(List<String> configurableProperties) {
// List<String> clProps = new ArrayList<String>();
// for (String propEntry : configurableProperties) {
// if (getPropName(propEntry).endsWith(".javaClassLoader")) {
// clProps.add(propEntry);
// }
// }
//
// return clProps;
// }
//
// public static List<String> getPropNames(List<String> configurableProperties) {
// List<String> propNames = new ArrayList<String>();
// for (String confProp : configurableProperties) {
// // use the value up to an equals sign if present
// propNames.add(getPropName(confProp));
// }
// return propNames;
// }
//
// public static String getPropName(String configurablePropertyEntry) {
// // use the value up to an equals sign if present
// return (configurablePropertyEntry.split("=")[0]).trim();
// }
//
// public static String getPropValue(String configurablePropertyEntry) {
// // use the value up to an equals sign if present
// if (configurablePropertyEntry.split("=").length == 2) {
// return (configurablePropertyEntry.split("=")[1]).trim();
// }
// return "";
// }
//
//
// public void load(File file) throws IOException {
//
// // empty the existing data
// this.clear();
//
// // read the file line by line, adding it to the existing data
// LineIterator iterator = FileUtils.lineIterator(file, "UTF-8");
// try {
// while (iterator.hasNext()) {
// String line = iterator.nextLine();
//
// String key;
// String value;
//
// Integer equalsPos = line.indexOf("=");
//
// // if there is no "=", only the key is present
// if (equalsPos == -1) {
// key = line.trim();
// value = "";
// } else {
// // there is an "=" present, so split out the key & value
// key = line.substring(0, equalsPos).trim();
// value = line.substring(equalsPos + 1).trim();
// }
// this.put(key, value);
// }
// } finally {
// LineIterator.closeQuietly(iterator);
// }
// }
//
// public void save(File file) throws IOException {
//
// List<String> lines = new ArrayList<String>();
//
// for (Map.Entry<String, String> entry : this.entrySet()) {
// String line = entry.getKey();
// String value = entry.getValue();
// if (value != null && value.length() > 0) {
// line = line + " = " + value;
// }
// lines.add(line);
// }
//
// FileUtils.writeLines(file, lines);
// }
//
// }
// Path: src/main/java/ch/sbb/maven/plugins/iib/mojos/ValidateClassloaderApproachMojo.java
import static ch.sbb.maven.plugins.iib.utils.ConfigurationValidator.validateUseClassloaders;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import ch.sbb.maven.plugins.iib.utils.ConfigurableProperties;
package ch.sbb.maven.plugins.iib.mojos;
/**
* Goal which reads the default.properties file to figure out if the classloader approach for this bar project is consistent. Either all jar nodes in all flows must use a classloader or none of them
* should.
*/
@Mojo(name = "validate-classloader-approach")
public class ValidateClassloaderApproachMojo extends AbstractMojo {
/**
* The name of the default properties file to be generated from the bar file.
*/
@Parameter(property = "iib.defaultPropertiesFile", defaultValue = "${project.build.directory}/default.properties", required = true)
protected File defaultPropertiesFile;
/**
* Whether or not to fail the build if the classloader approach is invalid.
*/
@Parameter(property = "iib.failOnInvalidClassloader", defaultValue = "true", required = true)
protected Boolean failOnInvalidClassloader;
/**
* Whether classloaders are in use with this bar
*/
@Parameter(property = "iib.useClassloaders")
protected Boolean useClassloaders;
public void execute() throws MojoFailureException {
| validateUseClassloaders(useClassloaders, getLog()); |
thheller/shadow-pgsql | src/java/shadow/pgsql/Database.java | // Path: src/java/shadow/pgsql/utils/RowProcessor.java
// public abstract class RowProcessor<ROW> implements ResultBuilder<Integer, Integer, ROW> {
//
// @Override
// public Integer init() {
// return 0;
// }
//
// public abstract void process(ROW row);
//
// @Override
// public Integer add(Integer state, ROW row) {
// process(row);
// return state + 1;
// }
//
// @Override
// public Integer complete(Integer state) {
// return state;
// }
// }
| import com.codahale.metrics.Counter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import shadow.pgsql.utils.RowProcessor;
import java.io.EOFException;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.List;
import java.util.Map; |
if (buf.get() != 'S') {
throw new IllegalStateException("ssl not accepted");
}
io = SSLSocketIO.start(channel, config.sslContext, config.host, config.port);
} else {
SocketChannel channel = SocketChannel.open(new InetSocketAddress(config.host, config.port));
channel.configureBlocking(true);
io = new SocketIO(channel);
//io = new StreamIO(new Socket(config.host, config.port));
}
pg = new Connection(this, io);
pg.startup(config.connectParams, config.authHandler);
timerContext.stop();
return pg;
}
void fetchSchemaInfo() throws IOException {
// fetch schema related things
try (Connection con = connect()) {
SQL pg_types = SQL.query("SELECT oid, typname FROM pg_type")
.withName("schema.types")
.buildRowsWith(Helpers.ROW_AS_LIST)
.buildResultsWith( | // Path: src/java/shadow/pgsql/utils/RowProcessor.java
// public abstract class RowProcessor<ROW> implements ResultBuilder<Integer, Integer, ROW> {
//
// @Override
// public Integer init() {
// return 0;
// }
//
// public abstract void process(ROW row);
//
// @Override
// public Integer add(Integer state, ROW row) {
// process(row);
// return state + 1;
// }
//
// @Override
// public Integer complete(Integer state) {
// return state;
// }
// }
// Path: src/java/shadow/pgsql/Database.java
import com.codahale.metrics.Counter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import shadow.pgsql.utils.RowProcessor;
import java.io.EOFException;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
if (buf.get() != 'S') {
throw new IllegalStateException("ssl not accepted");
}
io = SSLSocketIO.start(channel, config.sslContext, config.host, config.port);
} else {
SocketChannel channel = SocketChannel.open(new InetSocketAddress(config.host, config.port));
channel.configureBlocking(true);
io = new SocketIO(channel);
//io = new StreamIO(new Socket(config.host, config.port));
}
pg = new Connection(this, io);
pg.startup(config.connectParams, config.authHandler);
timerContext.stop();
return pg;
}
void fetchSchemaInfo() throws IOException {
// fetch schema related things
try (Connection con = connect()) {
SQL pg_types = SQL.query("SELECT oid, typname FROM pg_type")
.withName("schema.types")
.buildRowsWith(Helpers.ROW_AS_LIST)
.buildResultsWith( | new RowProcessor<List>() { |
thheller/shadow-pgsql | jmh/src/main/java/shadow/pgsql/benchmark/DatPojoBuilder.java | // Path: src/java/shadow/pgsql/ColumnInfo.java
// public class ColumnInfo {
// public final String name;
// public final int tableOid;
// public final int positionInTable;
// public final int typeOid;
// public final int typeSize;
// public final int typeMod;
//
// public ColumnInfo(String name, int tableOid, int positionInTable, int typeOid, int typeSize, int typeMod) {
// this.name = name;
// this.tableOid = tableOid;
// this.positionInTable = positionInTable;
// this.typeOid = typeOid;
// this.typeSize = typeSize;
// this.typeMod = typeMod;
// }
// }
//
// Path: src/java/shadow/pgsql/RowBuilder.java
// public interface RowBuilder<ACC, ROW> {
// ACC init();
//
// ACC add(ACC state, ColumnInfo columnInfo, int fieldIndex, Object value);
//
// ROW complete(ACC state);
//
// @FunctionalInterface
// interface Factory {
// RowBuilder create(ColumnInfo[] columns);
// }
// }
| import shadow.pgsql.ColumnInfo;
import shadow.pgsql.RowBuilder;
import java.math.BigDecimal; | package shadow.pgsql.benchmark;
/**
* Created by zilence on 20.09.15.
*/
class DatPojoBuilder implements RowBuilder<DatPojo, DatPojo> {
@Override
public DatPojo init() {
return new DatPojo();
}
@Override | // Path: src/java/shadow/pgsql/ColumnInfo.java
// public class ColumnInfo {
// public final String name;
// public final int tableOid;
// public final int positionInTable;
// public final int typeOid;
// public final int typeSize;
// public final int typeMod;
//
// public ColumnInfo(String name, int tableOid, int positionInTable, int typeOid, int typeSize, int typeMod) {
// this.name = name;
// this.tableOid = tableOid;
// this.positionInTable = positionInTable;
// this.typeOid = typeOid;
// this.typeSize = typeSize;
// this.typeMod = typeMod;
// }
// }
//
// Path: src/java/shadow/pgsql/RowBuilder.java
// public interface RowBuilder<ACC, ROW> {
// ACC init();
//
// ACC add(ACC state, ColumnInfo columnInfo, int fieldIndex, Object value);
//
// ROW complete(ACC state);
//
// @FunctionalInterface
// interface Factory {
// RowBuilder create(ColumnInfo[] columns);
// }
// }
// Path: jmh/src/main/java/shadow/pgsql/benchmark/DatPojoBuilder.java
import shadow.pgsql.ColumnInfo;
import shadow.pgsql.RowBuilder;
import java.math.BigDecimal;
package shadow.pgsql.benchmark;
/**
* Created by zilence on 20.09.15.
*/
class DatPojoBuilder implements RowBuilder<DatPojo, DatPojo> {
@Override
public DatPojo init() {
return new DatPojo();
}
@Override | public DatPojo add(DatPojo state, ColumnInfo columnInfo, int fieldIndex, Object value) { |
thheller/shadow-pgsql | src/java/shadow/pgsql/TypeRegistry.java | // Path: src/java/shadow/pgsql/types/Types.java
// public class Types {
// public static final int OID_NAME = 19;
// public static final int OID_INT8 = 20;
// public static final int OID_INT2 = 21;
// public static final int OID_INT4 = 23;
// public static final int OID_TEXT = 25;
// public static final int OID_OID = 26;
//
// public static final int OID_CHAR = 1042;
// public static final int OID_VARCHAR = 1043;
//
// public static final int OID_TIMESTAMP = 1114;
// public static final int OID_TIMESTAMPTZ = 1184;
//
// public static final int OID_NUMERIC = 1700;
//
// // how do you define variable length fields in text
// // "yyyy-MM-dd HH:mm:ss.SSS"
// public static final Timestamp TIMESTAMP = new Timestamp(OID_TIMESTAMP, "timestamp",
// new DateTimeFormatterBuilder()
// .appendValue(ChronoField.YEAR, 4)
// .appendLiteral("-")
// .appendValue(ChronoField.MONTH_OF_YEAR, 2)
// .appendLiteral("-")
// .appendValue(ChronoField.DAY_OF_MONTH, 2)
// .appendLiteral(" ")
// .appendValue(ChronoField.HOUR_OF_DAY, 2)
// .appendLiteral(":")
// .appendValue(ChronoField.MINUTE_OF_HOUR, 2)
// .appendLiteral(":")
// .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
// .appendFraction(ChronoField.MICRO_OF_SECOND, 0, 6, true)
// .toFormatter()
// ) {
// @Override
// protected Object convertParsed(Connection con, TemporalAccessor temporal) {
// // always return with timezone, just not worth it to use localdatetime
// return LocalDateTime.from(temporal).atZone(ZoneId.of(con.getParameterValue("TimeZone"))).toOffsetDateTime();
// }
// };
// public static final Timestamp TIMESTAMPTZ = new Timestamp(OID_TIMESTAMPTZ, "timestamptz",
// new DateTimeFormatterBuilder()
// .appendValue(ChronoField.YEAR, 4)
// .appendLiteral("-")
// .appendValue(ChronoField.MONTH_OF_YEAR, 2)
// .appendLiteral("-")
// .appendValue(ChronoField.DAY_OF_MONTH, 2)
// .appendLiteral(" ")
// .appendValue(ChronoField.HOUR_OF_DAY, 2)
// .appendLiteral(":")
// .appendValue(ChronoField.MINUTE_OF_HOUR, 2)
// .appendLiteral(":")
// .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
// .appendFraction(ChronoField.MICRO_OF_SECOND, 0, 6, true)
// .appendOffset("+HHmm", "+00")
// .toFormatter()
// ) {
// @Override
// protected Object convertParsed(Connection con, TemporalAccessor temporal) {
// return OffsetDateTime.from(temporal);
// }
// };
// public static final Date DATE = new Date();
//
// public static final Int2 INT2 = new Int2(OID_INT2, "int2");
// public static final TypedArray INT2_ARRAY = new TypedArray(INT2, TypedArray.makeReader(Short.TYPE), false);
//
// public static final Int4 OID = new Int4(OID_OID, "oid");
// public static final Int4 INT4 = new Int4(OID_INT4, "int4");
// public static final TypedArray INT4_ARRAY = new TypedArray(INT4, TypedArray.makeReader(Integer.TYPE), false);
//
// public static final Int8 INT8 = new Int8(OID_INT8, "int8");
// public static final TypedArray INT8_ARRAY = new TypedArray(INT8, TypedArray.makeReader(Long.TYPE), false);
//
// public static final Numeric NUMERIC = new Numeric();
// public static final TypedArray NUMERIC_ARRAY = new TypedArray(NUMERIC, TypedArray.makeReader(BigDecimal.class), false);
//
// public static final Text NAME = new Text(OID_NAME, "name");
// public static final Text TEXT = new Text(OID_TEXT, "text");
// public static final TypedArray TEXT_ARRAY = new TypedArray(TEXT, TypedArray.makeReader(String.class), true);
// public static final Text CHAR = new Text(OID_CHAR, "char");
// public static final Text VARCHAR = new Text(OID_VARCHAR, "varchar");
// public static final TypedArray VARCHAR_ARRAY = new TypedArray(VARCHAR, TypedArray.makeReader(String.class), true);
//
// public static final TypedArray TIMESTAMP_ARRAY = new TypedArray(TIMESTAMP, TypedArray.makeReader(OffsetDateTime.class), true);
// public static final TypedArray TIMESTAMPTZ_ARRAY = new TypedArray(TIMESTAMPTZ, TypedArray.makeReader(OffsetDateTime.class), true);
//
//
// public static final ByteA BYTEA = new ByteA();
//
// public static final Bool BOOL = new Bool();
// public static final Float4 FLOAT4 = new Float4();
// public static final Float8 FLOAT8 = new Float8();
//
// public static final HStore HSTORE = new HStore();
//
// public static final PgUUID UUID = new PgUUID();
// }
| import shadow.pgsql.types.Types;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map; | public Builder(Map<Integer, TypeHandler> typeHandlers, Map<String, TypeHandler> namedTypeHandlers, Map<ColumnByName, TypeHandler> customHandlers) {
this.typeHandlers = typeHandlers;
this.namedTypeHandlers = namedTypeHandlers;
this.customHandlers = customHandlers;
}
public Builder registerTypeHandler(TypeHandler handler) {
if (handler.getTypeOid() == -1) {
this.namedTypeHandlers.put(handler.getTypeName(), handler);
} else {
this.typeHandlers.put(handler.getTypeOid(), handler);
}
return this;
}
public Builder registerColumnHandler(String tableName, String columnName, TypeHandler handler) {
this.customHandlers.put(new ColumnByName(tableName, columnName), handler);
return this;
}
public TypeRegistry build() {
return new TypeRegistry(typeHandlers, namedTypeHandlers, customHandlers);
}
}
private static TypeRegistry createDefault() {
Builder b = new Builder();
TypeHandler[] defaults = new TypeHandler[]{ | // Path: src/java/shadow/pgsql/types/Types.java
// public class Types {
// public static final int OID_NAME = 19;
// public static final int OID_INT8 = 20;
// public static final int OID_INT2 = 21;
// public static final int OID_INT4 = 23;
// public static final int OID_TEXT = 25;
// public static final int OID_OID = 26;
//
// public static final int OID_CHAR = 1042;
// public static final int OID_VARCHAR = 1043;
//
// public static final int OID_TIMESTAMP = 1114;
// public static final int OID_TIMESTAMPTZ = 1184;
//
// public static final int OID_NUMERIC = 1700;
//
// // how do you define variable length fields in text
// // "yyyy-MM-dd HH:mm:ss.SSS"
// public static final Timestamp TIMESTAMP = new Timestamp(OID_TIMESTAMP, "timestamp",
// new DateTimeFormatterBuilder()
// .appendValue(ChronoField.YEAR, 4)
// .appendLiteral("-")
// .appendValue(ChronoField.MONTH_OF_YEAR, 2)
// .appendLiteral("-")
// .appendValue(ChronoField.DAY_OF_MONTH, 2)
// .appendLiteral(" ")
// .appendValue(ChronoField.HOUR_OF_DAY, 2)
// .appendLiteral(":")
// .appendValue(ChronoField.MINUTE_OF_HOUR, 2)
// .appendLiteral(":")
// .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
// .appendFraction(ChronoField.MICRO_OF_SECOND, 0, 6, true)
// .toFormatter()
// ) {
// @Override
// protected Object convertParsed(Connection con, TemporalAccessor temporal) {
// // always return with timezone, just not worth it to use localdatetime
// return LocalDateTime.from(temporal).atZone(ZoneId.of(con.getParameterValue("TimeZone"))).toOffsetDateTime();
// }
// };
// public static final Timestamp TIMESTAMPTZ = new Timestamp(OID_TIMESTAMPTZ, "timestamptz",
// new DateTimeFormatterBuilder()
// .appendValue(ChronoField.YEAR, 4)
// .appendLiteral("-")
// .appendValue(ChronoField.MONTH_OF_YEAR, 2)
// .appendLiteral("-")
// .appendValue(ChronoField.DAY_OF_MONTH, 2)
// .appendLiteral(" ")
// .appendValue(ChronoField.HOUR_OF_DAY, 2)
// .appendLiteral(":")
// .appendValue(ChronoField.MINUTE_OF_HOUR, 2)
// .appendLiteral(":")
// .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
// .appendFraction(ChronoField.MICRO_OF_SECOND, 0, 6, true)
// .appendOffset("+HHmm", "+00")
// .toFormatter()
// ) {
// @Override
// protected Object convertParsed(Connection con, TemporalAccessor temporal) {
// return OffsetDateTime.from(temporal);
// }
// };
// public static final Date DATE = new Date();
//
// public static final Int2 INT2 = new Int2(OID_INT2, "int2");
// public static final TypedArray INT2_ARRAY = new TypedArray(INT2, TypedArray.makeReader(Short.TYPE), false);
//
// public static final Int4 OID = new Int4(OID_OID, "oid");
// public static final Int4 INT4 = new Int4(OID_INT4, "int4");
// public static final TypedArray INT4_ARRAY = new TypedArray(INT4, TypedArray.makeReader(Integer.TYPE), false);
//
// public static final Int8 INT8 = new Int8(OID_INT8, "int8");
// public static final TypedArray INT8_ARRAY = new TypedArray(INT8, TypedArray.makeReader(Long.TYPE), false);
//
// public static final Numeric NUMERIC = new Numeric();
// public static final TypedArray NUMERIC_ARRAY = new TypedArray(NUMERIC, TypedArray.makeReader(BigDecimal.class), false);
//
// public static final Text NAME = new Text(OID_NAME, "name");
// public static final Text TEXT = new Text(OID_TEXT, "text");
// public static final TypedArray TEXT_ARRAY = new TypedArray(TEXT, TypedArray.makeReader(String.class), true);
// public static final Text CHAR = new Text(OID_CHAR, "char");
// public static final Text VARCHAR = new Text(OID_VARCHAR, "varchar");
// public static final TypedArray VARCHAR_ARRAY = new TypedArray(VARCHAR, TypedArray.makeReader(String.class), true);
//
// public static final TypedArray TIMESTAMP_ARRAY = new TypedArray(TIMESTAMP, TypedArray.makeReader(OffsetDateTime.class), true);
// public static final TypedArray TIMESTAMPTZ_ARRAY = new TypedArray(TIMESTAMPTZ, TypedArray.makeReader(OffsetDateTime.class), true);
//
//
// public static final ByteA BYTEA = new ByteA();
//
// public static final Bool BOOL = new Bool();
// public static final Float4 FLOAT4 = new Float4();
// public static final Float8 FLOAT8 = new Float8();
//
// public static final HStore HSTORE = new HStore();
//
// public static final PgUUID UUID = new PgUUID();
// }
// Path: src/java/shadow/pgsql/TypeRegistry.java
import shadow.pgsql.types.Types;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public Builder(Map<Integer, TypeHandler> typeHandlers, Map<String, TypeHandler> namedTypeHandlers, Map<ColumnByName, TypeHandler> customHandlers) {
this.typeHandlers = typeHandlers;
this.namedTypeHandlers = namedTypeHandlers;
this.customHandlers = customHandlers;
}
public Builder registerTypeHandler(TypeHandler handler) {
if (handler.getTypeOid() == -1) {
this.namedTypeHandlers.put(handler.getTypeName(), handler);
} else {
this.typeHandlers.put(handler.getTypeOid(), handler);
}
return this;
}
public Builder registerColumnHandler(String tableName, String columnName, TypeHandler handler) {
this.customHandlers.put(new ColumnByName(tableName, columnName), handler);
return this;
}
public TypeRegistry build() {
return new TypeRegistry(typeHandlers, namedTypeHandlers, customHandlers);
}
}
private static TypeRegistry createDefault() {
Builder b = new Builder();
TypeHandler[] defaults = new TypeHandler[]{ | Types.INT2, |
DmitryMalkovich/gito-github-client | app/src/main/java/com/dmitrymalkovich/android/githubanalytics/traffic/TrafficContract.java | // Path: app/src/main/java/com/dmitrymalkovich/android/githubanalytics/BasePresenter.java
// public interface BasePresenter {
//
// void start(Bundle savedInstanceState);
// }
//
// Path: app/src/main/java/com/dmitrymalkovich/android/githubanalytics/BaseView.java
// public interface BaseView<T> {
//
// void setPresenter(T presenter);
//
// }
| import android.database.Cursor;
import android.os.Bundle;
import com.dmitrymalkovich.android.githubanalytics.BasePresenter;
import com.dmitrymalkovich.android.githubanalytics.BaseView; | /*
* Copyright 2017. Dmitry Malkovich
*
* 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.dmitrymalkovich.android.githubanalytics.traffic;
class TrafficContract {
interface View extends BaseView<Presenter> {
void setLoadingIndicator(boolean active);
void showRepository(Cursor data);
void setEmptyState(boolean active);
void showReferrers(Cursor data);
void showClones(Cursor data);
void showViews(Cursor data);
void openUrl(String url);
}
| // Path: app/src/main/java/com/dmitrymalkovich/android/githubanalytics/BasePresenter.java
// public interface BasePresenter {
//
// void start(Bundle savedInstanceState);
// }
//
// Path: app/src/main/java/com/dmitrymalkovich/android/githubanalytics/BaseView.java
// public interface BaseView<T> {
//
// void setPresenter(T presenter);
//
// }
// Path: app/src/main/java/com/dmitrymalkovich/android/githubanalytics/traffic/TrafficContract.java
import android.database.Cursor;
import android.os.Bundle;
import com.dmitrymalkovich.android.githubanalytics.BasePresenter;
import com.dmitrymalkovich.android.githubanalytics.BaseView;
/*
* Copyright 2017. Dmitry Malkovich
*
* 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.dmitrymalkovich.android.githubanalytics.traffic;
class TrafficContract {
interface View extends BaseView<Presenter> {
void setLoadingIndicator(boolean active);
void showRepository(Cursor data);
void setEmptyState(boolean active);
void showReferrers(Cursor data);
void showClones(Cursor data);
void showViews(Cursor data);
void openUrl(String url);
}
| interface Presenter extends BasePresenter { |
DmitryMalkovich/gito-github-client | app/src/main/java/com/dmitrymalkovich/android/githubanalytics/data/source/local/contract/ClonesContract.java | // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/time/TimeConverter.java
// public class TimeConverter {
// private static final String LOG_TAG = TimeConverter.class.getSimpleName();
//
// public static long iso8601ToMilliseconds(String date) {
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
// long timeInMilliseconds = 0;
// try {
// Date parsedDate = df.parse(date);
// timeInMilliseconds = parsedDate.getTime();
// } catch (ParseException e) {
// Log.e(LOG_TAG, e.getMessage(), e);
// }
// return timeInMilliseconds;
// }
//
// public static TimeZone getGitHubDefaultTimeZone() {
// return TimeZone.getTimeZone("GMT");
// }
// }
//
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/Clones.java
// @SuppressWarnings("all")
// public class Clones {
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// @SerializedName("clones")
// private List<Clone> mClones;
//
// public List<Clone> asList() {
// return mClones;
// }
//
// public static class Clone {
// @SerializedName("timestamp")
// private String mTimestamp;
//
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// public String getTimestamp() {
// return mTimestamp;
// }
//
// public String getCount() {
// return mCount;
// }
//
// public String getUniques() {
// return mUniques;
// }
// }
// }
| import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.net.Uri;
import android.provider.BaseColumns;
import com.dmitrymalkovich.android.githubapi.core.time.TimeConverter;
import com.dmitrymalkovich.android.githubapi.core.data.Clones; | public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_CLONES).build();
public static final String CONTENT_TYPE =
ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_CLONES;
public static final String TABLE_NAME = "traffic_clones";
public static final String COLUMN_REPOSITORY_KEY = "repository_id";
public static final String COLUMN_CLONES_COUNT = "count";
public static final String COLUMN_CLONES_UNIQUES = "uniques";
public static final String COLUMN_CLONES_TIMESTAMP = "timestamp";
public static final String[] CLONES_COLUMNS = {
_ID,
COLUMN_REPOSITORY_KEY,
COLUMN_CLONES_COUNT,
COLUMN_CLONES_UNIQUES,
COLUMN_CLONES_TIMESTAMP
};
public static final int COL_ID = 0;
public static final int COL_REPOSITORY_KEY = 1;
public static final int COL_CLONES_COUNT = 2;
public static final int COL_CLONES_UNIQUES = 3;
public static final int COL_CLONES_TIMESTAMP = 4;
public static Uri buildUri(long id) {
return ContentUris.withAppendedId(CONTENT_URI, id);
}
| // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/time/TimeConverter.java
// public class TimeConverter {
// private static final String LOG_TAG = TimeConverter.class.getSimpleName();
//
// public static long iso8601ToMilliseconds(String date) {
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
// long timeInMilliseconds = 0;
// try {
// Date parsedDate = df.parse(date);
// timeInMilliseconds = parsedDate.getTime();
// } catch (ParseException e) {
// Log.e(LOG_TAG, e.getMessage(), e);
// }
// return timeInMilliseconds;
// }
//
// public static TimeZone getGitHubDefaultTimeZone() {
// return TimeZone.getTimeZone("GMT");
// }
// }
//
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/Clones.java
// @SuppressWarnings("all")
// public class Clones {
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// @SerializedName("clones")
// private List<Clone> mClones;
//
// public List<Clone> asList() {
// return mClones;
// }
//
// public static class Clone {
// @SerializedName("timestamp")
// private String mTimestamp;
//
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// public String getTimestamp() {
// return mTimestamp;
// }
//
// public String getCount() {
// return mCount;
// }
//
// public String getUniques() {
// return mUniques;
// }
// }
// }
// Path: app/src/main/java/com/dmitrymalkovich/android/githubanalytics/data/source/local/contract/ClonesContract.java
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.net.Uri;
import android.provider.BaseColumns;
import com.dmitrymalkovich.android.githubapi.core.time.TimeConverter;
import com.dmitrymalkovich.android.githubapi.core.data.Clones;
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_CLONES).build();
public static final String CONTENT_TYPE =
ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_CLONES;
public static final String TABLE_NAME = "traffic_clones";
public static final String COLUMN_REPOSITORY_KEY = "repository_id";
public static final String COLUMN_CLONES_COUNT = "count";
public static final String COLUMN_CLONES_UNIQUES = "uniques";
public static final String COLUMN_CLONES_TIMESTAMP = "timestamp";
public static final String[] CLONES_COLUMNS = {
_ID,
COLUMN_REPOSITORY_KEY,
COLUMN_CLONES_COUNT,
COLUMN_CLONES_UNIQUES,
COLUMN_CLONES_TIMESTAMP
};
public static final int COL_ID = 0;
public static final int COL_REPOSITORY_KEY = 1;
public static final int COL_CLONES_COUNT = 2;
public static final int COL_CLONES_UNIQUES = 3;
public static final int COL_CLONES_TIMESTAMP = 4;
public static Uri buildUri(long id) {
return ContentUris.withAppendedId(CONTENT_URI, id);
}
| public static ContentValues buildContentValues(long repositoryId, Clones.Clone clone) { |
DmitryMalkovich/gito-github-client | app/src/main/java/com/dmitrymalkovich/android/githubanalytics/data/source/local/contract/ClonesContract.java | // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/time/TimeConverter.java
// public class TimeConverter {
// private static final String LOG_TAG = TimeConverter.class.getSimpleName();
//
// public static long iso8601ToMilliseconds(String date) {
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
// long timeInMilliseconds = 0;
// try {
// Date parsedDate = df.parse(date);
// timeInMilliseconds = parsedDate.getTime();
// } catch (ParseException e) {
// Log.e(LOG_TAG, e.getMessage(), e);
// }
// return timeInMilliseconds;
// }
//
// public static TimeZone getGitHubDefaultTimeZone() {
// return TimeZone.getTimeZone("GMT");
// }
// }
//
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/Clones.java
// @SuppressWarnings("all")
// public class Clones {
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// @SerializedName("clones")
// private List<Clone> mClones;
//
// public List<Clone> asList() {
// return mClones;
// }
//
// public static class Clone {
// @SerializedName("timestamp")
// private String mTimestamp;
//
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// public String getTimestamp() {
// return mTimestamp;
// }
//
// public String getCount() {
// return mCount;
// }
//
// public String getUniques() {
// return mUniques;
// }
// }
// }
| import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.net.Uri;
import android.provider.BaseColumns;
import com.dmitrymalkovich.android.githubapi.core.time.TimeConverter;
import com.dmitrymalkovich.android.githubapi.core.data.Clones; |
public static final String CONTENT_TYPE =
ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_CLONES;
public static final String TABLE_NAME = "traffic_clones";
public static final String COLUMN_REPOSITORY_KEY = "repository_id";
public static final String COLUMN_CLONES_COUNT = "count";
public static final String COLUMN_CLONES_UNIQUES = "uniques";
public static final String COLUMN_CLONES_TIMESTAMP = "timestamp";
public static final String[] CLONES_COLUMNS = {
_ID,
COLUMN_REPOSITORY_KEY,
COLUMN_CLONES_COUNT,
COLUMN_CLONES_UNIQUES,
COLUMN_CLONES_TIMESTAMP
};
public static final int COL_ID = 0;
public static final int COL_REPOSITORY_KEY = 1;
public static final int COL_CLONES_COUNT = 2;
public static final int COL_CLONES_UNIQUES = 3;
public static final int COL_CLONES_TIMESTAMP = 4;
public static Uri buildUri(long id) {
return ContentUris.withAppendedId(CONTENT_URI, id);
}
public static ContentValues buildContentValues(long repositoryId, Clones.Clone clone) {
String timestamp = clone.getTimestamp(); | // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/time/TimeConverter.java
// public class TimeConverter {
// private static final String LOG_TAG = TimeConverter.class.getSimpleName();
//
// public static long iso8601ToMilliseconds(String date) {
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
// long timeInMilliseconds = 0;
// try {
// Date parsedDate = df.parse(date);
// timeInMilliseconds = parsedDate.getTime();
// } catch (ParseException e) {
// Log.e(LOG_TAG, e.getMessage(), e);
// }
// return timeInMilliseconds;
// }
//
// public static TimeZone getGitHubDefaultTimeZone() {
// return TimeZone.getTimeZone("GMT");
// }
// }
//
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/Clones.java
// @SuppressWarnings("all")
// public class Clones {
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// @SerializedName("clones")
// private List<Clone> mClones;
//
// public List<Clone> asList() {
// return mClones;
// }
//
// public static class Clone {
// @SerializedName("timestamp")
// private String mTimestamp;
//
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// public String getTimestamp() {
// return mTimestamp;
// }
//
// public String getCount() {
// return mCount;
// }
//
// public String getUniques() {
// return mUniques;
// }
// }
// }
// Path: app/src/main/java/com/dmitrymalkovich/android/githubanalytics/data/source/local/contract/ClonesContract.java
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.net.Uri;
import android.provider.BaseColumns;
import com.dmitrymalkovich.android.githubapi.core.time.TimeConverter;
import com.dmitrymalkovich.android.githubapi.core.data.Clones;
public static final String CONTENT_TYPE =
ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_CLONES;
public static final String TABLE_NAME = "traffic_clones";
public static final String COLUMN_REPOSITORY_KEY = "repository_id";
public static final String COLUMN_CLONES_COUNT = "count";
public static final String COLUMN_CLONES_UNIQUES = "uniques";
public static final String COLUMN_CLONES_TIMESTAMP = "timestamp";
public static final String[] CLONES_COLUMNS = {
_ID,
COLUMN_REPOSITORY_KEY,
COLUMN_CLONES_COUNT,
COLUMN_CLONES_UNIQUES,
COLUMN_CLONES_TIMESTAMP
};
public static final int COL_ID = 0;
public static final int COL_REPOSITORY_KEY = 1;
public static final int COL_CLONES_COUNT = 2;
public static final int COL_CLONES_UNIQUES = 3;
public static final int COL_CLONES_TIMESTAMP = 4;
public static Uri buildUri(long id) {
return ContentUris.withAppendedId(CONTENT_URI, id);
}
public static ContentValues buildContentValues(long repositoryId, Clones.Clone clone) {
String timestamp = clone.getTimestamp(); | long timeInMilliseconds = TimeConverter.iso8601ToMilliseconds(timestamp); |
DmitryMalkovich/gito-github-client | app/src/main/java/com/dmitrymalkovich/android/githubanalytics/repositories/PublicRepositoryContract.java | // Path: app/src/main/java/com/dmitrymalkovich/android/githubanalytics/BasePresenter.java
// public interface BasePresenter {
//
// void start(Bundle savedInstanceState);
// }
//
// Path: app/src/main/java/com/dmitrymalkovich/android/githubanalytics/BaseView.java
// public interface BaseView<T> {
//
// void setPresenter(T presenter);
//
// }
| import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import com.dmitrymalkovich.android.githubanalytics.BasePresenter;
import com.dmitrymalkovich.android.githubanalytics.BaseView; | /*
* Copyright 2017. Dmitry Malkovich
*
* 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.dmitrymalkovich.android.githubanalytics.repositories;
class PublicRepositoryContract {
interface View extends BaseView<Presenter> {
void setLoadingIndicator(boolean active);
void setRefreshIndicator(boolean active);
void showRepositories(Cursor data);
void openUrl(@NonNull String htmlUrl);
void setEmptyState(boolean active);
void setPinned(boolean active, long id);
}
| // Path: app/src/main/java/com/dmitrymalkovich/android/githubanalytics/BasePresenter.java
// public interface BasePresenter {
//
// void start(Bundle savedInstanceState);
// }
//
// Path: app/src/main/java/com/dmitrymalkovich/android/githubanalytics/BaseView.java
// public interface BaseView<T> {
//
// void setPresenter(T presenter);
//
// }
// Path: app/src/main/java/com/dmitrymalkovich/android/githubanalytics/repositories/PublicRepositoryContract.java
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import com.dmitrymalkovich.android.githubanalytics.BasePresenter;
import com.dmitrymalkovich.android.githubanalytics.BaseView;
/*
* Copyright 2017. Dmitry Malkovich
*
* 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.dmitrymalkovich.android.githubanalytics.repositories;
class PublicRepositoryContract {
interface View extends BaseView<Presenter> {
void setLoadingIndicator(boolean active);
void setRefreshIndicator(boolean active);
void showRepositories(Cursor data);
void openUrl(@NonNull String htmlUrl);
void setEmptyState(boolean active);
void setPinned(boolean active, long id);
}
| interface Presenter extends BasePresenter, SwipeRefreshLayout.OnRefreshListener { |
DmitryMalkovich/gito-github-client | github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/ExploreBuilder.java | // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/TrendingRepository.java
// @SuppressWarnings("all")
// public class TrendingRepository {
//
// @SerializedName("avatar")
// String mAvatar;
//
// @SerializedName("repo")
// String mRepo;
//
// @SerializedName("desc")
// String description;
//
// @SerializedName("owner")
// String mOwner;
//
// @SerializedName("stars")
// String mStars;
//
// @SerializedName("link")
// String mHtmlUrl;
//
// String mLanguage;
//
// String mPeriod;
//
// public String getName() {
// return mRepo;
// }
//
// public String getDescription() {
// return description;
// }
//
// public String getOwner() {
// return mOwner;
// }
//
// public String getWatchersCount() {
// return mStars;
// }
//
// public String getHtmlUrl() {
// return mHtmlUrl;
// }
//
// public String getAvatar() {
// return mAvatar;
// }
//
// public String getLanguage() {
// return mLanguage;
// }
//
// public void setLanguage(String language) {
// mLanguage = language;
// }
//
// public String getPeriod() {
// return mPeriod;
// }
//
// public void setPeriod(String period) {
// mPeriod = period;
// }
// }
| import android.support.annotation.WorkerThread;
import com.dmitrymalkovich.android.githubapi.core.data.TrendingRepository;
import java.io.IOException;
import java.util.List;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory; | /*
* Copyright 2017. Dmitry Malkovich
*
* 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.dmitrymalkovich.android.githubapi.core;
public class ExploreBuilder {
private static final String THIRD_PARTY_GITHUB_API_BASE_URL = "http://anly.leanapp.cn/";
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
private String mLanguage;
private String mPeriod;
public ExploreBuilder setLanguage(String language) {
mLanguage = language;
return this;
}
public ExploreBuilder setPeriod(String period) {
mPeriod = period;
return this;
}
@WorkerThread | // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/TrendingRepository.java
// @SuppressWarnings("all")
// public class TrendingRepository {
//
// @SerializedName("avatar")
// String mAvatar;
//
// @SerializedName("repo")
// String mRepo;
//
// @SerializedName("desc")
// String description;
//
// @SerializedName("owner")
// String mOwner;
//
// @SerializedName("stars")
// String mStars;
//
// @SerializedName("link")
// String mHtmlUrl;
//
// String mLanguage;
//
// String mPeriod;
//
// public String getName() {
// return mRepo;
// }
//
// public String getDescription() {
// return description;
// }
//
// public String getOwner() {
// return mOwner;
// }
//
// public String getWatchersCount() {
// return mStars;
// }
//
// public String getHtmlUrl() {
// return mHtmlUrl;
// }
//
// public String getAvatar() {
// return mAvatar;
// }
//
// public String getLanguage() {
// return mLanguage;
// }
//
// public void setLanguage(String language) {
// mLanguage = language;
// }
//
// public String getPeriod() {
// return mPeriod;
// }
//
// public void setPeriod(String period) {
// mPeriod = period;
// }
// }
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/ExploreBuilder.java
import android.support.annotation.WorkerThread;
import com.dmitrymalkovich.android.githubapi.core.data.TrendingRepository;
import java.io.IOException;
import java.util.List;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/*
* Copyright 2017. Dmitry Malkovich
*
* 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.dmitrymalkovich.android.githubapi.core;
public class ExploreBuilder {
private static final String THIRD_PARTY_GITHUB_API_BASE_URL = "http://anly.leanapp.cn/";
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
private String mLanguage;
private String mPeriod;
public ExploreBuilder setLanguage(String language) {
mLanguage = language;
return this;
}
public ExploreBuilder setPeriod(String period) {
mPeriod = period;
return this;
}
@WorkerThread | public List<TrendingRepository> getRepositories() throws IOException { |
DmitryMalkovich/gito-github-client | app/src/main/java/com/dmitrymalkovich/android/githubanalytics/data/source/local/contract/TrendingContract.java | // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/TrendingRepository.java
// @SuppressWarnings("all")
// public class TrendingRepository {
//
// @SerializedName("avatar")
// String mAvatar;
//
// @SerializedName("repo")
// String mRepo;
//
// @SerializedName("desc")
// String description;
//
// @SerializedName("owner")
// String mOwner;
//
// @SerializedName("stars")
// String mStars;
//
// @SerializedName("link")
// String mHtmlUrl;
//
// String mLanguage;
//
// String mPeriod;
//
// public String getName() {
// return mRepo;
// }
//
// public String getDescription() {
// return description;
// }
//
// public String getOwner() {
// return mOwner;
// }
//
// public String getWatchersCount() {
// return mStars;
// }
//
// public String getHtmlUrl() {
// return mHtmlUrl;
// }
//
// public String getAvatar() {
// return mAvatar;
// }
//
// public String getLanguage() {
// return mLanguage;
// }
//
// public void setLanguage(String language) {
// mLanguage = language;
// }
//
// public String getPeriod() {
// return mPeriod;
// }
//
// public void setPeriod(String period) {
// mPeriod = period;
// }
// }
| import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.net.Uri;
import android.provider.BaseColumns;
import com.dmitrymalkovich.android.githubapi.core.data.TrendingRepository; | public static final String COLUMN_LANGUAGE = "language";
public static final String COLUMN_DESCRIPTION = "description";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_AVATAR = "avatar";
public static final String COLUMN_PERIOD = "period";
public static final String[] TRENDING_COLUMNS = {
_ID,
COLUMN_HTML_URL,
COLUMN_WATCHER_COUNT,
COLUMN_LANGUAGE,
COLUMN_DESCRIPTION,
COLUMN_NAME,
COLUMN_AVATAR,
COLUMN_PERIOD
};
public static final int COL_ID = 0;
public static final int COL_HTML_URL = 1;
public static final int COL_WATCHER_COUNT = 2;
public static final int COL_LANGUAGE = 3;
public static final int COL_DESCRIPTION = 4;
public static final int COL_NAME = 5;
public static final int COL_AVATAR = 6;
public static final int COL_PERIOD = 7;
public static Uri buildUri(long id) {
return ContentUris.withAppendedId(CONTENT_URI, id);
}
| // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/TrendingRepository.java
// @SuppressWarnings("all")
// public class TrendingRepository {
//
// @SerializedName("avatar")
// String mAvatar;
//
// @SerializedName("repo")
// String mRepo;
//
// @SerializedName("desc")
// String description;
//
// @SerializedName("owner")
// String mOwner;
//
// @SerializedName("stars")
// String mStars;
//
// @SerializedName("link")
// String mHtmlUrl;
//
// String mLanguage;
//
// String mPeriod;
//
// public String getName() {
// return mRepo;
// }
//
// public String getDescription() {
// return description;
// }
//
// public String getOwner() {
// return mOwner;
// }
//
// public String getWatchersCount() {
// return mStars;
// }
//
// public String getHtmlUrl() {
// return mHtmlUrl;
// }
//
// public String getAvatar() {
// return mAvatar;
// }
//
// public String getLanguage() {
// return mLanguage;
// }
//
// public void setLanguage(String language) {
// mLanguage = language;
// }
//
// public String getPeriod() {
// return mPeriod;
// }
//
// public void setPeriod(String period) {
// mPeriod = period;
// }
// }
// Path: app/src/main/java/com/dmitrymalkovich/android/githubanalytics/data/source/local/contract/TrendingContract.java
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.net.Uri;
import android.provider.BaseColumns;
import com.dmitrymalkovich.android.githubapi.core.data.TrendingRepository;
public static final String COLUMN_LANGUAGE = "language";
public static final String COLUMN_DESCRIPTION = "description";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_AVATAR = "avatar";
public static final String COLUMN_PERIOD = "period";
public static final String[] TRENDING_COLUMNS = {
_ID,
COLUMN_HTML_URL,
COLUMN_WATCHER_COUNT,
COLUMN_LANGUAGE,
COLUMN_DESCRIPTION,
COLUMN_NAME,
COLUMN_AVATAR,
COLUMN_PERIOD
};
public static final int COL_ID = 0;
public static final int COL_HTML_URL = 1;
public static final int COL_WATCHER_COUNT = 2;
public static final int COL_LANGUAGE = 3;
public static final int COL_DESCRIPTION = 4;
public static final int COL_NAME = 5;
public static final int COL_AVATAR = 6;
public static final int COL_PERIOD = 7;
public static Uri buildUri(long id) {
return ContentUris.withAppendedId(CONTENT_URI, id);
}
| public static ContentValues buildContentValues(TrendingRepository trendingRepository, String period, |
DmitryMalkovich/gito-github-client | app/src/main/java/com/dmitrymalkovich/android/githubanalytics/data/source/local/contract/ReferrerContract.java | // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/ReferringSite.java
// @SuppressWarnings("all")
// public class ReferringSite {
//
// @SerializedName("referrer")
// private String mReferrer;
//
// @SerializedName("count")
// private int mCount;
//
// @SerializedName("uniques")
// private int mUniques;
//
// public String getReferrer() {
// return mReferrer;
// }
//
// public int getCount() {
// return mCount;
// }
//
// public int getUniques() {
// return mUniques;
// }
// }
| import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.net.Uri;
import android.provider.BaseColumns;
import com.dmitrymalkovich.android.githubapi.core.data.ReferringSite; | /*
* Copyright 2017. Dmitry Malkovich
*
* 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.dmitrymalkovich.android.githubanalytics.data.source.local.contract;
/**
* https://developer.github.com/v3/repos/traffic/
*/
public class ReferrerContract {
public static final String CONTENT_AUTHORITY = "com.dmitrymalkovich.android.githubanalytics.data";
public static final String PATH_REFERRERS = "traffic.paths";
private static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);
public static final class ReferrerEntry implements BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_REFERRERS).build();
public static final String CONTENT_TYPE =
ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_REFERRERS;
public static final String TABLE_NAME = "traffic_paths";
public static final String COLUMN_REPOSITORY_KEY = "repository_id";
public static final String COLUMN_REFERRER_REFERRER = "referrer";
public static final String COLUMN_REFERRER_COUNT = "count";
public static final String COLUMN_REFERRER_UNIQUES = "uniques";
public static final String[] REFERRER_COLUMNS = {
_ID,
COLUMN_REPOSITORY_KEY,
COLUMN_REFERRER_REFERRER,
COLUMN_REFERRER_COUNT,
COLUMN_REFERRER_UNIQUES
};
public static final int COL_ID = 0;
public static final int COL_REPOSITORY_KEY = 1;
public static final int COL_PATHS_REFERRER = 2;
public static final int COL_PATHS_COUNT = 3;
public static final int COL_PATHS_UNIQUES = 4;
public static Uri buildUri(long id) {
return ContentUris.withAppendedId(CONTENT_URI, id);
}
| // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/ReferringSite.java
// @SuppressWarnings("all")
// public class ReferringSite {
//
// @SerializedName("referrer")
// private String mReferrer;
//
// @SerializedName("count")
// private int mCount;
//
// @SerializedName("uniques")
// private int mUniques;
//
// public String getReferrer() {
// return mReferrer;
// }
//
// public int getCount() {
// return mCount;
// }
//
// public int getUniques() {
// return mUniques;
// }
// }
// Path: app/src/main/java/com/dmitrymalkovich/android/githubanalytics/data/source/local/contract/ReferrerContract.java
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.net.Uri;
import android.provider.BaseColumns;
import com.dmitrymalkovich.android.githubapi.core.data.ReferringSite;
/*
* Copyright 2017. Dmitry Malkovich
*
* 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.dmitrymalkovich.android.githubanalytics.data.source.local.contract;
/**
* https://developer.github.com/v3/repos/traffic/
*/
public class ReferrerContract {
public static final String CONTENT_AUTHORITY = "com.dmitrymalkovich.android.githubanalytics.data";
public static final String PATH_REFERRERS = "traffic.paths";
private static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);
public static final class ReferrerEntry implements BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_REFERRERS).build();
public static final String CONTENT_TYPE =
ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_REFERRERS;
public static final String TABLE_NAME = "traffic_paths";
public static final String COLUMN_REPOSITORY_KEY = "repository_id";
public static final String COLUMN_REFERRER_REFERRER = "referrer";
public static final String COLUMN_REFERRER_COUNT = "count";
public static final String COLUMN_REFERRER_UNIQUES = "uniques";
public static final String[] REFERRER_COLUMNS = {
_ID,
COLUMN_REPOSITORY_KEY,
COLUMN_REFERRER_REFERRER,
COLUMN_REFERRER_COUNT,
COLUMN_REFERRER_UNIQUES
};
public static final int COL_ID = 0;
public static final int COL_REPOSITORY_KEY = 1;
public static final int COL_PATHS_REFERRER = 2;
public static final int COL_PATHS_COUNT = 3;
public static final int COL_PATHS_UNIQUES = 4;
public static Uri buildUri(long id) {
return ContentUris.withAppendedId(CONTENT_URI, id);
}
| public static ContentValues createContentValues(long repositoryId, ReferringSite referrer) { |
DmitryMalkovich/gito-github-client | app/src/main/java/com/dmitrymalkovich/android/githubanalytics/trending/TrendingRepositoryContract.java | // Path: app/src/main/java/com/dmitrymalkovich/android/githubanalytics/BasePresenter.java
// public interface BasePresenter {
//
// void start(Bundle savedInstanceState);
// }
//
// Path: app/src/main/java/com/dmitrymalkovich/android/githubanalytics/BaseView.java
// public interface BaseView<T> {
//
// void setPresenter(T presenter);
//
// }
| import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import com.dmitrymalkovich.android.githubanalytics.BasePresenter;
import com.dmitrymalkovich.android.githubanalytics.BaseView; | /*
* Copyright 2017. Dmitry Malkovich
*
* 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.dmitrymalkovich.android.githubanalytics.trending;
class TrendingRepositoryContract {
interface View extends BaseView<Presenter> {
void setLoadingIndicator(boolean active);
void setRefreshIndicator(boolean active);
void showRepositories(Cursor data);
void openUrl(@NonNull String htmlUrl);
void selectTab(int position);
void setEmptyState(boolean active);
}
| // Path: app/src/main/java/com/dmitrymalkovich/android/githubanalytics/BasePresenter.java
// public interface BasePresenter {
//
// void start(Bundle savedInstanceState);
// }
//
// Path: app/src/main/java/com/dmitrymalkovich/android/githubanalytics/BaseView.java
// public interface BaseView<T> {
//
// void setPresenter(T presenter);
//
// }
// Path: app/src/main/java/com/dmitrymalkovich/android/githubanalytics/trending/TrendingRepositoryContract.java
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import com.dmitrymalkovich.android.githubanalytics.BasePresenter;
import com.dmitrymalkovich.android.githubanalytics.BaseView;
/*
* Copyright 2017. Dmitry Malkovich
*
* 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.dmitrymalkovich.android.githubanalytics.trending;
class TrendingRepositoryContract {
interface View extends BaseView<Presenter> {
void setLoadingIndicator(boolean active);
void setRefreshIndicator(boolean active);
void showRepositories(Cursor data);
void openUrl(@NonNull String htmlUrl);
void selectTab(int position);
void setEmptyState(boolean active);
}
| interface Presenter extends BasePresenter, SwipeRefreshLayout.OnRefreshListener { |
DmitryMalkovich/gito-github-client | github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/UserService.java | // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/User.java
// @SuppressWarnings("all")
// public class User {
//
// String mLogin;
// String mName;
// String mAvatarUrl;
// String mFollowers;
//
// public String getLogin() {
// return mLogin;
// }
//
// public void setLogin(String login) {
// mLogin = login;
// }
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// mName = name;
// }
//
// public String getAvatarUrl() {
// return mAvatarUrl;
// }
//
// public void setAvatarUrl(String avatarUrl) {
// mAvatarUrl = avatarUrl;
// }
//
// public String getFollowers() {
// return mFollowers;
// }
//
// public void setFollowers(String followers) {
// mFollowers = followers;
// }
// }
| import com.dmitrymalkovich.android.githubapi.core.data.User;
import java.io.IOException; | /*
* Copyright 2017. Dmitry Malkovich
*
* 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.dmitrymalkovich.android.githubapi.core;
public class UserService extends Service {
public UserService setToken(String token) {
return (UserService) super.setToken(token);
}
| // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/User.java
// @SuppressWarnings("all")
// public class User {
//
// String mLogin;
// String mName;
// String mAvatarUrl;
// String mFollowers;
//
// public String getLogin() {
// return mLogin;
// }
//
// public void setLogin(String login) {
// mLogin = login;
// }
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// mName = name;
// }
//
// public String getAvatarUrl() {
// return mAvatarUrl;
// }
//
// public void setAvatarUrl(String avatarUrl) {
// mAvatarUrl = avatarUrl;
// }
//
// public String getFollowers() {
// return mFollowers;
// }
//
// public void setFollowers(String followers) {
// mFollowers = followers;
// }
// }
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/UserService.java
import com.dmitrymalkovich.android.githubapi.core.data.User;
import java.io.IOException;
/*
* Copyright 2017. Dmitry Malkovich
*
* 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.dmitrymalkovich.android.githubapi.core;
public class UserService extends Service {
public UserService setToken(String token) {
return (UserService) super.setToken(token);
}
| public User getUser() throws IOException { |
DmitryMalkovich/gito-github-client | github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/Service.java | // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/AccessToken.java
// @SuppressWarnings("all")
// public class AccessToken {
//
// @SerializedName("access_token")
// private String mAccessToken;
// @SerializedName("token_type")
// private String mTokenType;
//
// public String getToken() {
// return mAccessToken;
// }
//
// public String getTokenType() {
// return mTokenType;
// }
//
// public void setTokenType(String tokenType) {
// this.mTokenType = tokenType;
// }
//
// public void setAccessToken(String accessToken) {
// this.mAccessToken = accessToken;
// }
// }
//
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/Star.java
// @SuppressWarnings("all")
// public class Star {
//
// @SerializedName("user")
// public User mUser;
// @SerializedName("starred_at")
// private String mStarredAt;
//
// public String getStarredAt() {
// return mStarredAt;
// }
//
// private class User {
// @SerializedName("id")
// private long mId;
//
// @SerializedName("login")
// private String mLogin;
//
// @SerializedName("url")
// private String mUrl;
//
// public long getId() {
// return mId;
// }
//
// public String getLogin() {
// return mLogin;
// }
//
// public String getUrl() {
// return mUrl;
// }
// }
// }
| import retrofit2.Converter;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import android.support.annotation.NonNull;
import com.dmitrymalkovich.android.githubapi.core.data.AccessToken;
import com.dmitrymalkovich.android.githubapi.core.data.Star;
import com.google.gson.annotations.SerializedName;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.List;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor; | /*
* Copyright 2017. Dmitry Malkovich
*
* 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.dmitrymalkovich.android.githubapi.core;
/**
* Credit to https://futurestud.io/tutorials/oauth-2-on-android-with-retrofit
* <p>
* OAuth GitHub API: https://developer.github.com/v3/oauth/
*/
public class Service {
public static final String API_URL_AUTH = "https://github.com/login/oauth/authorize/";
static final String API_HTTPS_BASE_URL = "https://api.github.com/";
private static final String API_BASE_URL = "https://github.com/";
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); | // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/AccessToken.java
// @SuppressWarnings("all")
// public class AccessToken {
//
// @SerializedName("access_token")
// private String mAccessToken;
// @SerializedName("token_type")
// private String mTokenType;
//
// public String getToken() {
// return mAccessToken;
// }
//
// public String getTokenType() {
// return mTokenType;
// }
//
// public void setTokenType(String tokenType) {
// this.mTokenType = tokenType;
// }
//
// public void setAccessToken(String accessToken) {
// this.mAccessToken = accessToken;
// }
// }
//
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/Star.java
// @SuppressWarnings("all")
// public class Star {
//
// @SerializedName("user")
// public User mUser;
// @SerializedName("starred_at")
// private String mStarredAt;
//
// public String getStarredAt() {
// return mStarredAt;
// }
//
// private class User {
// @SerializedName("id")
// private long mId;
//
// @SerializedName("login")
// private String mLogin;
//
// @SerializedName("url")
// private String mUrl;
//
// public long getId() {
// return mId;
// }
//
// public String getLogin() {
// return mLogin;
// }
//
// public String getUrl() {
// return mUrl;
// }
// }
// }
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/Service.java
import retrofit2.Converter;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import android.support.annotation.NonNull;
import com.dmitrymalkovich.android.githubapi.core.data.AccessToken;
import com.dmitrymalkovich.android.githubapi.core.data.Star;
import com.google.gson.annotations.SerializedName;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.List;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
/*
* Copyright 2017. Dmitry Malkovich
*
* 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.dmitrymalkovich.android.githubapi.core;
/**
* Credit to https://futurestud.io/tutorials/oauth-2-on-android-with-retrofit
* <p>
* OAuth GitHub API: https://developer.github.com/v3/oauth/
*/
public class Service {
public static final String API_URL_AUTH = "https://github.com/login/oauth/authorize/";
static final String API_HTTPS_BASE_URL = "https://api.github.com/";
private static final String API_BASE_URL = "https://github.com/";
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); | private AccessToken mAccessToken = new AccessToken(); |
DmitryMalkovich/gito-github-client | github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/Service.java | // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/AccessToken.java
// @SuppressWarnings("all")
// public class AccessToken {
//
// @SerializedName("access_token")
// private String mAccessToken;
// @SerializedName("token_type")
// private String mTokenType;
//
// public String getToken() {
// return mAccessToken;
// }
//
// public String getTokenType() {
// return mTokenType;
// }
//
// public void setTokenType(String tokenType) {
// this.mTokenType = tokenType;
// }
//
// public void setAccessToken(String accessToken) {
// this.mAccessToken = accessToken;
// }
// }
//
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/Star.java
// @SuppressWarnings("all")
// public class Star {
//
// @SerializedName("user")
// public User mUser;
// @SerializedName("starred_at")
// private String mStarredAt;
//
// public String getStarredAt() {
// return mStarredAt;
// }
//
// private class User {
// @SerializedName("id")
// private long mId;
//
// @SerializedName("login")
// private String mLogin;
//
// @SerializedName("url")
// private String mUrl;
//
// public long getId() {
// return mId;
// }
//
// public String getLogin() {
// return mLogin;
// }
//
// public String getUrl() {
// return mUrl;
// }
// }
// }
| import retrofit2.Converter;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import android.support.annotation.NonNull;
import com.dmitrymalkovich.android.githubapi.core.data.AccessToken;
import com.dmitrymalkovich.android.githubapi.core.data.Star;
import com.google.gson.annotations.SerializedName;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.List;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor; | Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_HTTPS_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(new OkHttpClient.Builder().build()).build();
Converter<ResponseBody, APIError> converter =
retrofit.responseBodyConverter(APIError.class, new Annotation[0]);
APIError error;
try {
error = converter.convert(response.errorBody());
} catch (IOException e) {
return new APIError();
}
return error;
}
public String getMessage() {
return mMessage;
}
}
public class Pagination {
public static final String LAST_PAGE = "last";
private static final String HEADER_LINK = "Link";
private int mLastPage;
| // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/AccessToken.java
// @SuppressWarnings("all")
// public class AccessToken {
//
// @SerializedName("access_token")
// private String mAccessToken;
// @SerializedName("token_type")
// private String mTokenType;
//
// public String getToken() {
// return mAccessToken;
// }
//
// public String getTokenType() {
// return mTokenType;
// }
//
// public void setTokenType(String tokenType) {
// this.mTokenType = tokenType;
// }
//
// public void setAccessToken(String accessToken) {
// this.mAccessToken = accessToken;
// }
// }
//
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/Star.java
// @SuppressWarnings("all")
// public class Star {
//
// @SerializedName("user")
// public User mUser;
// @SerializedName("starred_at")
// private String mStarredAt;
//
// public String getStarredAt() {
// return mStarredAt;
// }
//
// private class User {
// @SerializedName("id")
// private long mId;
//
// @SerializedName("login")
// private String mLogin;
//
// @SerializedName("url")
// private String mUrl;
//
// public long getId() {
// return mId;
// }
//
// public String getLogin() {
// return mLogin;
// }
//
// public String getUrl() {
// return mUrl;
// }
// }
// }
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/Service.java
import retrofit2.Converter;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import android.support.annotation.NonNull;
import com.dmitrymalkovich.android.githubapi.core.data.AccessToken;
import com.dmitrymalkovich.android.githubapi.core.data.Star;
import com.google.gson.annotations.SerializedName;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.List;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_HTTPS_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(new OkHttpClient.Builder().build()).build();
Converter<ResponseBody, APIError> converter =
retrofit.responseBodyConverter(APIError.class, new Annotation[0]);
APIError error;
try {
error = converter.convert(response.errorBody());
} catch (IOException e) {
return new APIError();
}
return error;
}
public String getMessage() {
return mMessage;
}
}
public class Pagination {
public static final String LAST_PAGE = "last";
private static final String HEADER_LINK = "Link";
private int mLastPage;
| public void parse(Response<List<Star>> response) { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.