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
rjohnsondev/java-libpst
src/main/java/com/pff/PSTTable7C.java
// Path: src/main/java/com/pff/PSTFile.java // public static final int PST_TYPE_ANSI = 14;
import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import static com.pff.PSTFile.PST_TYPE_ANSI;
this.columnDescriptors[col] = new ColumnDescriptor(tcHeaderNode, offset); // System.out.println("iBit: "+col+" " // +columnDescriptors[col].iBit); if (this.columnDescriptors[col].id == entityToExtract) { this.overrideCol = col; } offset += 8; } } // if we are asking for a specific column, only get that! if (this.overrideCol > -1) { this.cCols = this.overrideCol + 1; } // Read the key table /* System.out.printf("Key table:\n"); / **/ this.keyMap = new HashMap<>(); // byte[] keyTableInfo = getNodeInfo(hidRoot); final NodeInfo keyTableInfo = this.getNodeInfo(this.hidRoot); this.numberOfKeys = keyTableInfo.length() / (this.sizeOfItemKey + this.sizeOfItemValue); offset = 0; for (int x = 0; x < this.numberOfKeys; x++) { final int Context = (int) keyTableInfo.seekAndReadLong(offset, this.sizeOfItemKey); offset += this.sizeOfItemKey; final int RowIndex = (int) keyTableInfo.seekAndReadLong(offset, this.sizeOfItemValue); offset += this.sizeOfItemValue; this.keyMap.put(Context, RowIndex); }
// Path: src/main/java/com/pff/PSTFile.java // public static final int PST_TYPE_ANSI = 14; // Path: src/main/java/com/pff/PSTTable7C.java import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import static com.pff.PSTFile.PST_TYPE_ANSI; this.columnDescriptors[col] = new ColumnDescriptor(tcHeaderNode, offset); // System.out.println("iBit: "+col+" " // +columnDescriptors[col].iBit); if (this.columnDescriptors[col].id == entityToExtract) { this.overrideCol = col; } offset += 8; } } // if we are asking for a specific column, only get that! if (this.overrideCol > -1) { this.cCols = this.overrideCol + 1; } // Read the key table /* System.out.printf("Key table:\n"); / **/ this.keyMap = new HashMap<>(); // byte[] keyTableInfo = getNodeInfo(hidRoot); final NodeInfo keyTableInfo = this.getNodeInfo(this.hidRoot); this.numberOfKeys = keyTableInfo.length() / (this.sizeOfItemKey + this.sizeOfItemValue); offset = 0; for (int x = 0; x < this.numberOfKeys; x++) { final int Context = (int) keyTableInfo.seekAndReadLong(offset, this.sizeOfItemKey); offset += this.sizeOfItemKey; final int RowIndex = (int) keyTableInfo.seekAndReadLong(offset, this.sizeOfItemValue); offset += this.sizeOfItemValue; this.keyMap.put(Context, RowIndex); }
if (in.getPSTFile().getPSTFileType()==PST_TYPE_ANSI)
engagingspaces/vertx-graphql-service-discovery
graphql-service-publisher/src/test/java/io/engagingspaces/graphql/servicediscovery/publisher/SchemaRegistrarTest.java
// Path: graphql-testdata/src/main/java/org/example/graphql/testdata/droids/DroidsSchema.java // public static final GraphQLSchema droidsSchema = GraphQLSchema.newSchema() // .query(queryType) // .build(); // // Path: graphql-testdata/src/main/java/org/example/graphql/testdata/starwars/StarWarsSchema.java // public static final GraphQLSchema starWarsSchema = GraphQLSchema.newSchema() // .query(queryType) // .build();
import static org.junit.Assert.assertTrue; import io.vertx.core.Future; import io.vertx.core.Vertx; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import io.vertx.servicediscovery.ServiceDiscovery; import io.vertx.servicediscovery.ServiceDiscoveryOptions; import org.junit.*; import org.junit.runner.RunWith; import static org.example.graphql.testdata.droids.DroidsSchema.droidsSchema; import static org.example.graphql.testdata.starwars.StarWarsSchema.starWarsSchema; import static org.junit.Assert.assertEquals;
@Before public void setUp() { vertx = rule.vertx(); options = new ServiceDiscoveryOptions().setName("theDiscovery") .setAnnounceAddress("announceAddress").setUsageAddress("usageAddress"); schemaRegistrar = SchemaRegistrar.create(vertx); schemaPublisher = new TestClass(schemaRegistrar); } @After public void tearDown(TestContext context) { vertx.close(); schemaRegistrar.close(null, context.asyncAssertSuccess()); } @Test public void should_Manage_Schema_Registration_And_Close_Properly(TestContext context) { Async async = context.async(); context.assertNotNull(schemaRegistrar.getPublisherId()); schemaRegistrar = SchemaRegistrar.create(vertx, "thePublisherId"); context.assertEquals("thePublisherId", schemaRegistrar.getPublisherId()); ServiceDiscovery discovery = schemaRegistrar.getOrCreateDiscovery(options); context.assertNotNull(discovery); context.assertNotNull(schemaRegistrar.registrations()); context.assertEquals(0, schemaRegistrar.registrations().size()); // Fans of nested handlers, take note! ;) // Publish 1
// Path: graphql-testdata/src/main/java/org/example/graphql/testdata/droids/DroidsSchema.java // public static final GraphQLSchema droidsSchema = GraphQLSchema.newSchema() // .query(queryType) // .build(); // // Path: graphql-testdata/src/main/java/org/example/graphql/testdata/starwars/StarWarsSchema.java // public static final GraphQLSchema starWarsSchema = GraphQLSchema.newSchema() // .query(queryType) // .build(); // Path: graphql-service-publisher/src/test/java/io/engagingspaces/graphql/servicediscovery/publisher/SchemaRegistrarTest.java import static org.junit.Assert.assertTrue; import io.vertx.core.Future; import io.vertx.core.Vertx; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import io.vertx.servicediscovery.ServiceDiscovery; import io.vertx.servicediscovery.ServiceDiscoveryOptions; import org.junit.*; import org.junit.runner.RunWith; import static org.example.graphql.testdata.droids.DroidsSchema.droidsSchema; import static org.example.graphql.testdata.starwars.StarWarsSchema.starWarsSchema; import static org.junit.Assert.assertEquals; @Before public void setUp() { vertx = rule.vertx(); options = new ServiceDiscoveryOptions().setName("theDiscovery") .setAnnounceAddress("announceAddress").setUsageAddress("usageAddress"); schemaRegistrar = SchemaRegistrar.create(vertx); schemaPublisher = new TestClass(schemaRegistrar); } @After public void tearDown(TestContext context) { vertx.close(); schemaRegistrar.close(null, context.asyncAssertSuccess()); } @Test public void should_Manage_Schema_Registration_And_Close_Properly(TestContext context) { Async async = context.async(); context.assertNotNull(schemaRegistrar.getPublisherId()); schemaRegistrar = SchemaRegistrar.create(vertx, "thePublisherId"); context.assertEquals("thePublisherId", schemaRegistrar.getPublisherId()); ServiceDiscovery discovery = schemaRegistrar.getOrCreateDiscovery(options); context.assertNotNull(discovery); context.assertNotNull(schemaRegistrar.registrations()); context.assertEquals(0, schemaRegistrar.registrations().size()); // Fans of nested handlers, take note! ;) // Publish 1
schemaPublisher.publish(options, droidsSchema, rh -> {
engagingspaces/vertx-graphql-service-discovery
graphql-service-publisher/src/test/java/io/engagingspaces/graphql/servicediscovery/publisher/SchemaRegistrarTest.java
// Path: graphql-testdata/src/main/java/org/example/graphql/testdata/droids/DroidsSchema.java // public static final GraphQLSchema droidsSchema = GraphQLSchema.newSchema() // .query(queryType) // .build(); // // Path: graphql-testdata/src/main/java/org/example/graphql/testdata/starwars/StarWarsSchema.java // public static final GraphQLSchema starWarsSchema = GraphQLSchema.newSchema() // .query(queryType) // .build();
import static org.junit.Assert.assertTrue; import io.vertx.core.Future; import io.vertx.core.Vertx; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import io.vertx.servicediscovery.ServiceDiscovery; import io.vertx.servicediscovery.ServiceDiscoveryOptions; import org.junit.*; import org.junit.runner.RunWith; import static org.example.graphql.testdata.droids.DroidsSchema.droidsSchema; import static org.example.graphql.testdata.starwars.StarWarsSchema.starWarsSchema; import static org.junit.Assert.assertEquals;
.setAnnounceAddress("announceAddress").setUsageAddress("usageAddress"); schemaRegistrar = SchemaRegistrar.create(vertx); schemaPublisher = new TestClass(schemaRegistrar); } @After public void tearDown(TestContext context) { vertx.close(); schemaRegistrar.close(null, context.asyncAssertSuccess()); } @Test public void should_Manage_Schema_Registration_And_Close_Properly(TestContext context) { Async async = context.async(); context.assertNotNull(schemaRegistrar.getPublisherId()); schemaRegistrar = SchemaRegistrar.create(vertx, "thePublisherId"); context.assertEquals("thePublisherId", schemaRegistrar.getPublisherId()); ServiceDiscovery discovery = schemaRegistrar.getOrCreateDiscovery(options); context.assertNotNull(discovery); context.assertNotNull(schemaRegistrar.registrations()); context.assertEquals(0, schemaRegistrar.registrations().size()); // Fans of nested handlers, take note! ;) // Publish 1 schemaPublisher.publish(options, droidsSchema, rh -> { context.assertTrue(rh.succeeded()); context.assertEquals(1, schemaPublisher.registeredSchemas().size()); // Publish 2
// Path: graphql-testdata/src/main/java/org/example/graphql/testdata/droids/DroidsSchema.java // public static final GraphQLSchema droidsSchema = GraphQLSchema.newSchema() // .query(queryType) // .build(); // // Path: graphql-testdata/src/main/java/org/example/graphql/testdata/starwars/StarWarsSchema.java // public static final GraphQLSchema starWarsSchema = GraphQLSchema.newSchema() // .query(queryType) // .build(); // Path: graphql-service-publisher/src/test/java/io/engagingspaces/graphql/servicediscovery/publisher/SchemaRegistrarTest.java import static org.junit.Assert.assertTrue; import io.vertx.core.Future; import io.vertx.core.Vertx; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import io.vertx.servicediscovery.ServiceDiscovery; import io.vertx.servicediscovery.ServiceDiscoveryOptions; import org.junit.*; import org.junit.runner.RunWith; import static org.example.graphql.testdata.droids.DroidsSchema.droidsSchema; import static org.example.graphql.testdata.starwars.StarWarsSchema.starWarsSchema; import static org.junit.Assert.assertEquals; .setAnnounceAddress("announceAddress").setUsageAddress("usageAddress"); schemaRegistrar = SchemaRegistrar.create(vertx); schemaPublisher = new TestClass(schemaRegistrar); } @After public void tearDown(TestContext context) { vertx.close(); schemaRegistrar.close(null, context.asyncAssertSuccess()); } @Test public void should_Manage_Schema_Registration_And_Close_Properly(TestContext context) { Async async = context.async(); context.assertNotNull(schemaRegistrar.getPublisherId()); schemaRegistrar = SchemaRegistrar.create(vertx, "thePublisherId"); context.assertEquals("thePublisherId", schemaRegistrar.getPublisherId()); ServiceDiscovery discovery = schemaRegistrar.getOrCreateDiscovery(options); context.assertNotNull(discovery); context.assertNotNull(schemaRegistrar.registrations()); context.assertEquals(0, schemaRegistrar.registrations().size()); // Fans of nested handlers, take note! ;) // Publish 1 schemaPublisher.publish(options, droidsSchema, rh -> { context.assertTrue(rh.succeeded()); context.assertEquals(1, schemaPublisher.registeredSchemas().size()); // Publish 2
schemaPublisher.publish(options, starWarsSchema, rh2 -> {
engagingspaces/vertx-graphql-service-discovery
graphql-testdata/src/main/java/org/example/graphql/testdata/droids/DroidsData.java
// Path: graphql-testdata/src/main/java/org/example/graphql/testdata/utils/MapBuilder.java // public static <K, V> Map.Entry<K, V> entry(K key, V value) { // return new AbstractMap.SimpleEntry<>(key, value); // } // // Path: graphql-testdata/src/main/java/org/example/graphql/testdata/utils/MapBuilder.java // @SafeVarargs // public static <K, V> Map<K, V> immutableMapOf(Map.Entry<K, V> ...entries) { // return Collections.unmodifiableMap(mapOf(entries)); // }
import graphql.schema.DataFetcher; import graphql.schema.TypeResolver; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static org.example.graphql.testdata.utils.MapBuilder.entry; import static org.example.graphql.testdata.utils.MapBuilder.immutableMapOf;
/* * Copyright (c) 2016 The original author or authors * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package org.example.graphql.testdata.droids; /** * Test data converted from: * https://github.com/graphql-java/graphql-java/blob/master/src/test/groovy/graphql/StarWarsData.groovy * * @author <a href="https://github.com/aschrijver/">Arnold Schrijver</a> */ public interface DroidsData { Map<String, Object> threepio = immutableMapOf(
// Path: graphql-testdata/src/main/java/org/example/graphql/testdata/utils/MapBuilder.java // public static <K, V> Map.Entry<K, V> entry(K key, V value) { // return new AbstractMap.SimpleEntry<>(key, value); // } // // Path: graphql-testdata/src/main/java/org/example/graphql/testdata/utils/MapBuilder.java // @SafeVarargs // public static <K, V> Map<K, V> immutableMapOf(Map.Entry<K, V> ...entries) { // return Collections.unmodifiableMap(mapOf(entries)); // } // Path: graphql-testdata/src/main/java/org/example/graphql/testdata/droids/DroidsData.java import graphql.schema.DataFetcher; import graphql.schema.TypeResolver; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static org.example.graphql.testdata.utils.MapBuilder.entry; import static org.example.graphql.testdata.utils.MapBuilder.immutableMapOf; /* * Copyright (c) 2016 The original author or authors * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package org.example.graphql.testdata.droids; /** * Test data converted from: * https://github.com/graphql-java/graphql-java/blob/master/src/test/groovy/graphql/StarWarsData.groovy * * @author <a href="https://github.com/aschrijver/">Arnold Schrijver</a> */ public interface DroidsData { Map<String, Object> threepio = immutableMapOf(
entry("id", "2000"),
engagingspaces/vertx-graphql-service-discovery
graphql-service-consumer/src/test/java/io/engagingspaces/graphql/servicediscovery/consumer/DiscoveryRegistrationTest.java
// Path: graphql-core/src/main/java/io/engagingspaces/graphql/discovery/impl/AbstractRegistration.java // public class AbstractRegistration implements Registration { // // private final ServiceDiscovery discovery; // private final ServiceDiscoveryOptions options; // // protected AbstractRegistration(ServiceDiscovery discovery, ServiceDiscoveryOptions options) { // Objects.requireNonNull(discovery, "Service discovery cannot be null"); // this.discovery = discovery; // this.options = options; // } // // /** // * {@inheritDoc} // */ // @Override // public ServiceDiscovery getDiscovery() { // return discovery; // } // // /** // * {@inheritDoc} // */ // @Override // public ServiceDiscoveryOptions getDiscoveryOptions() { // return options == null ? null : new ServiceDiscoveryOptions(options); // } // // /** // * @param other the object to compare to this registration // * @return {@code true} when equal, {@code false} otherwise // */ // @Override // public boolean equals(Object other) { // if (other == this) { // return true; // } // if (!(other instanceof AbstractRegistration)) { // return false; // } // AbstractRegistration test = (AbstractRegistration) other; // return fieldEquals(discovery, test.discovery) && fieldEquals(options.getName(), test.options.getName()); // } // // private static boolean fieldEquals(Object value1, Object value2) { // return value1 == null ? value2 == null : value1.equals(value2); // } // // /** // * @return the hash code of the registration // */ // @Override // public int hashCode() { // int result = 17; // result = 31 * result + (discovery == null ? 0 : discovery.hashCode()); // result = 31 * result + (options.getName() == null ? 0 : options.getName().hashCode()); // return result; // } // }
import io.engagingspaces.graphql.discovery.impl.AbstractRegistration; import io.vertx.core.Vertx; import io.vertx.servicediscovery.ServiceDiscovery; import io.vertx.servicediscovery.ServiceDiscoveryOptions; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals;
private ServiceDiscoveryOptions options2; @Before public void setUp() { vertx = Vertx.vertx(); options = new ServiceDiscoveryOptions().setName("theDiscovery") .setAnnounceAddress("foo").setUsageAddress("bar"); options2 = new ServiceDiscoveryOptions().setName("theDiscovery2") .setAnnounceAddress("foo").setUsageAddress("bar"); discovery = ServiceDiscovery.create(vertx, options); discovery2 = ServiceDiscovery.create(vertx, options); } @Test public void should_Include_Record_Name_And_Type_In_Equality_Check() { DiscoveryRegistration result1 = DiscoveryRegistration.create(discovery, options); assertNotEquals(result1, new testRegistration(discovery, options)); assertEquals(result1, DiscoveryRegistration.create(discovery, options)); DiscoveryRegistration result2 = DiscoveryRegistration.create(discovery2, options); assertNotEquals(result1, result2); DiscoveryRegistration result3 = DiscoveryRegistration.create(discovery2, options2); assertNotEquals(result2, result3); // Ignore addresses DiscoveryRegistration result4 = DiscoveryRegistration.create(discovery2, options.setAnnounceAddress("baz").setUsageAddress("brr")); assertEquals(result2, result4); assertEquals(result2.hashCode(), result4.hashCode()); }
// Path: graphql-core/src/main/java/io/engagingspaces/graphql/discovery/impl/AbstractRegistration.java // public class AbstractRegistration implements Registration { // // private final ServiceDiscovery discovery; // private final ServiceDiscoveryOptions options; // // protected AbstractRegistration(ServiceDiscovery discovery, ServiceDiscoveryOptions options) { // Objects.requireNonNull(discovery, "Service discovery cannot be null"); // this.discovery = discovery; // this.options = options; // } // // /** // * {@inheritDoc} // */ // @Override // public ServiceDiscovery getDiscovery() { // return discovery; // } // // /** // * {@inheritDoc} // */ // @Override // public ServiceDiscoveryOptions getDiscoveryOptions() { // return options == null ? null : new ServiceDiscoveryOptions(options); // } // // /** // * @param other the object to compare to this registration // * @return {@code true} when equal, {@code false} otherwise // */ // @Override // public boolean equals(Object other) { // if (other == this) { // return true; // } // if (!(other instanceof AbstractRegistration)) { // return false; // } // AbstractRegistration test = (AbstractRegistration) other; // return fieldEquals(discovery, test.discovery) && fieldEquals(options.getName(), test.options.getName()); // } // // private static boolean fieldEquals(Object value1, Object value2) { // return value1 == null ? value2 == null : value1.equals(value2); // } // // /** // * @return the hash code of the registration // */ // @Override // public int hashCode() { // int result = 17; // result = 31 * result + (discovery == null ? 0 : discovery.hashCode()); // result = 31 * result + (options.getName() == null ? 0 : options.getName().hashCode()); // return result; // } // } // Path: graphql-service-consumer/src/test/java/io/engagingspaces/graphql/servicediscovery/consumer/DiscoveryRegistrationTest.java import io.engagingspaces.graphql.discovery.impl.AbstractRegistration; import io.vertx.core.Vertx; import io.vertx.servicediscovery.ServiceDiscovery; import io.vertx.servicediscovery.ServiceDiscoveryOptions; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; private ServiceDiscoveryOptions options2; @Before public void setUp() { vertx = Vertx.vertx(); options = new ServiceDiscoveryOptions().setName("theDiscovery") .setAnnounceAddress("foo").setUsageAddress("bar"); options2 = new ServiceDiscoveryOptions().setName("theDiscovery2") .setAnnounceAddress("foo").setUsageAddress("bar"); discovery = ServiceDiscovery.create(vertx, options); discovery2 = ServiceDiscovery.create(vertx, options); } @Test public void should_Include_Record_Name_And_Type_In_Equality_Check() { DiscoveryRegistration result1 = DiscoveryRegistration.create(discovery, options); assertNotEquals(result1, new testRegistration(discovery, options)); assertEquals(result1, DiscoveryRegistration.create(discovery, options)); DiscoveryRegistration result2 = DiscoveryRegistration.create(discovery2, options); assertNotEquals(result1, result2); DiscoveryRegistration result3 = DiscoveryRegistration.create(discovery2, options2); assertNotEquals(result2, result3); // Ignore addresses DiscoveryRegistration result4 = DiscoveryRegistration.create(discovery2, options.setAnnounceAddress("baz").setUsageAddress("brr")); assertEquals(result2, result4); assertEquals(result2.hashCode(), result4.hashCode()); }
private class testRegistration extends AbstractRegistration {
engagingspaces/vertx-graphql-service-discovery
graphql-testdata/src/main/java/org/example/graphql/testdata/starwars/HumanData.java
// Path: graphql-testdata/src/main/java/org/example/graphql/testdata/utils/MapBuilder.java // public static <K, V> Map.Entry<K, V> entry(K key, V value) { // return new AbstractMap.SimpleEntry<>(key, value); // } // // Path: graphql-testdata/src/main/java/org/example/graphql/testdata/utils/MapBuilder.java // @SafeVarargs // public static <K, V> Map<K, V> immutableMapOf(Map.Entry<K, V> ...entries) { // return Collections.unmodifiableMap(mapOf(entries)); // }
import graphql.schema.DataFetcher; import graphql.schema.TypeResolver; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static org.example.graphql.testdata.utils.MapBuilder.entry; import static org.example.graphql.testdata.utils.MapBuilder.immutableMapOf;
/* * Copyright (c) 2016 The original author or authors * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package org.example.graphql.testdata.starwars; /** * Test data converted from: * https://github.com/graphql-java/graphql-java/blob/master/src/test/groovy/graphql/StarWarsData.groovy * * @author <a href="https://github.com/aschrijver/">Arnold Schrijver</a> */ public interface HumanData { Map<String, Object> luke = immutableMapOf(
// Path: graphql-testdata/src/main/java/org/example/graphql/testdata/utils/MapBuilder.java // public static <K, V> Map.Entry<K, V> entry(K key, V value) { // return new AbstractMap.SimpleEntry<>(key, value); // } // // Path: graphql-testdata/src/main/java/org/example/graphql/testdata/utils/MapBuilder.java // @SafeVarargs // public static <K, V> Map<K, V> immutableMapOf(Map.Entry<K, V> ...entries) { // return Collections.unmodifiableMap(mapOf(entries)); // } // Path: graphql-testdata/src/main/java/org/example/graphql/testdata/starwars/HumanData.java import graphql.schema.DataFetcher; import graphql.schema.TypeResolver; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static org.example.graphql.testdata.utils.MapBuilder.entry; import static org.example.graphql.testdata.utils.MapBuilder.immutableMapOf; /* * Copyright (c) 2016 The original author or authors * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package org.example.graphql.testdata.starwars; /** * Test data converted from: * https://github.com/graphql-java/graphql-java/blob/master/src/test/groovy/graphql/StarWarsData.groovy * * @author <a href="https://github.com/aschrijver/">Arnold Schrijver</a> */ public interface HumanData { Map<String, Object> luke = immutableMapOf(
entry("id", "100"),
engagingspaces/vertx-graphql-service-discovery
graphql-core/src/test/java/io/engagingspaces/graphql/events/SchemaReferenceDataTest.java
// Path: graphql-core/src/main/java/io/engagingspaces/graphql/query/Queryable.java // @ProxyGen // public interface Queryable { // // /** // * Name of the discovery service type for GraphQL schema's. // */ // String SERVICE_TYPE = "graphql-service"; // // /** // * The prefix that is combined with the root query name of the associated GraphQL schema // * to form the {@link io.vertx.servicediscovery.Record#ENDPOINT} address used in service discovery. // */ // String ADDRESS_PREFIX = "service.graphql"; // // /** // * Creates a service proxy to the {@link Queryable} implementation // * at the specified address. // * <p> // * The {@link DeliveryOptions} to use on the returned message consumer must be passed as // * plain json, because it does not provide a toJson() method (see:vhttps://github.com/eclipse/vert.x/issues/1502). // * // * @param vertx the vert.x instance // * @param address the address of the service proxy // * @param deliveryOptions the delivery options to use on the message consumer // * @return the graphql service proxy // */ // static Queryable createProxy(Vertx vertx, String address, JsonObject deliveryOptions) { // return ProxyHelper.createProxy(Queryable.class, vertx, address, new DeliveryOptions(deliveryOptions)); // } // // /** // * Executes the GraphQL query on the GraphQL schema proxy. // * <p> // * On success a {@link QueryResult} is returned. While this indicates the query executor has finished processing, // * the query itself might still have failed, so be sure to check {@link QueryResult#isSucceeded()} and // * {@link QueryResult#getErrors()} properties on the query result afterwards. // * afterwards. // * // * @param graphqlQuery the graphql query // * @param resultHandler the result handler with the query result on success, or a failure // */ // void query(String graphqlQuery, Handler<AsyncResult<QueryResult>> resultHandler); // // /** // * Executes the GraphQL query on the GraphQL schema proxy using the provided variables. // * // * @param graphqlQuery the graphql query // * @param variables the query variables // * @param resultHandler the result handler with the graphql query result on success, or a failure // */ // void queryWithVariables(String graphqlQuery, JsonObject variables, // Handler<AsyncResult<QueryResult>> resultHandler); // // /** // * Invoked when the queryable service proxy closes. Does nothing by default, but can be overridden in sub-classes. // */ // @ProxyClose // default void close() { // // NO OP // } // }
import io.engagingspaces.graphql.query.Queryable; import io.vertx.core.json.JsonObject; import org.junit.Test; import static org.junit.Assert.*;
/* * Copyright (c) 2016 The original author or authors * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.engagingspaces.graphql.events; /** * Tests for the {@link SchemaReferenceData} data object. * * @author <a href="https://github.com/aschrijver/">Arnold Schrijver</a> */ public class SchemaReferenceDataTest { private static final JsonObject INPUT_DATA = new JsonObject( "{\n" + " \"id\": \"theDiscoveryName\"," + " \"record\": {\n" + " \"name\": \"theGraphQLServiceName\",\n" +
// Path: graphql-core/src/main/java/io/engagingspaces/graphql/query/Queryable.java // @ProxyGen // public interface Queryable { // // /** // * Name of the discovery service type for GraphQL schema's. // */ // String SERVICE_TYPE = "graphql-service"; // // /** // * The prefix that is combined with the root query name of the associated GraphQL schema // * to form the {@link io.vertx.servicediscovery.Record#ENDPOINT} address used in service discovery. // */ // String ADDRESS_PREFIX = "service.graphql"; // // /** // * Creates a service proxy to the {@link Queryable} implementation // * at the specified address. // * <p> // * The {@link DeliveryOptions} to use on the returned message consumer must be passed as // * plain json, because it does not provide a toJson() method (see:vhttps://github.com/eclipse/vert.x/issues/1502). // * // * @param vertx the vert.x instance // * @param address the address of the service proxy // * @param deliveryOptions the delivery options to use on the message consumer // * @return the graphql service proxy // */ // static Queryable createProxy(Vertx vertx, String address, JsonObject deliveryOptions) { // return ProxyHelper.createProxy(Queryable.class, vertx, address, new DeliveryOptions(deliveryOptions)); // } // // /** // * Executes the GraphQL query on the GraphQL schema proxy. // * <p> // * On success a {@link QueryResult} is returned. While this indicates the query executor has finished processing, // * the query itself might still have failed, so be sure to check {@link QueryResult#isSucceeded()} and // * {@link QueryResult#getErrors()} properties on the query result afterwards. // * afterwards. // * // * @param graphqlQuery the graphql query // * @param resultHandler the result handler with the query result on success, or a failure // */ // void query(String graphqlQuery, Handler<AsyncResult<QueryResult>> resultHandler); // // /** // * Executes the GraphQL query on the GraphQL schema proxy using the provided variables. // * // * @param graphqlQuery the graphql query // * @param variables the query variables // * @param resultHandler the result handler with the graphql query result on success, or a failure // */ // void queryWithVariables(String graphqlQuery, JsonObject variables, // Handler<AsyncResult<QueryResult>> resultHandler); // // /** // * Invoked when the queryable service proxy closes. Does nothing by default, but can be overridden in sub-classes. // */ // @ProxyClose // default void close() { // // NO OP // } // } // Path: graphql-core/src/test/java/io/engagingspaces/graphql/events/SchemaReferenceDataTest.java import io.engagingspaces.graphql.query.Queryable; import io.vertx.core.json.JsonObject; import org.junit.Test; import static org.junit.Assert.*; /* * Copyright (c) 2016 The original author or authors * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.engagingspaces.graphql.events; /** * Tests for the {@link SchemaReferenceData} data object. * * @author <a href="https://github.com/aschrijver/">Arnold Schrijver</a> */ public class SchemaReferenceDataTest { private static final JsonObject INPUT_DATA = new JsonObject( "{\n" + " \"id\": \"theDiscoveryName\"," + " \"record\": {\n" + " \"name\": \"theGraphQLServiceName\",\n" +
" \"type\": \"" + Queryable.SERVICE_TYPE + "\",\n" +
engagingspaces/vertx-graphql-service-discovery
graphql-service-publisher/src/test/java/io/engagingspaces/graphql/servicediscovery/service/impl/GraphQLServiceImplTest.java
// Path: graphql-core/src/main/java/io/engagingspaces/graphql/query/Queryable.java // @ProxyGen // public interface Queryable { // // /** // * Name of the discovery service type for GraphQL schema's. // */ // String SERVICE_TYPE = "graphql-service"; // // /** // * The prefix that is combined with the root query name of the associated GraphQL schema // * to form the {@link io.vertx.servicediscovery.Record#ENDPOINT} address used in service discovery. // */ // String ADDRESS_PREFIX = "service.graphql"; // // /** // * Creates a service proxy to the {@link Queryable} implementation // * at the specified address. // * <p> // * The {@link DeliveryOptions} to use on the returned message consumer must be passed as // * plain json, because it does not provide a toJson() method (see:vhttps://github.com/eclipse/vert.x/issues/1502). // * // * @param vertx the vert.x instance // * @param address the address of the service proxy // * @param deliveryOptions the delivery options to use on the message consumer // * @return the graphql service proxy // */ // static Queryable createProxy(Vertx vertx, String address, JsonObject deliveryOptions) { // return ProxyHelper.createProxy(Queryable.class, vertx, address, new DeliveryOptions(deliveryOptions)); // } // // /** // * Executes the GraphQL query on the GraphQL schema proxy. // * <p> // * On success a {@link QueryResult} is returned. While this indicates the query executor has finished processing, // * the query itself might still have failed, so be sure to check {@link QueryResult#isSucceeded()} and // * {@link QueryResult#getErrors()} properties on the query result afterwards. // * afterwards. // * // * @param graphqlQuery the graphql query // * @param resultHandler the result handler with the query result on success, or a failure // */ // void query(String graphqlQuery, Handler<AsyncResult<QueryResult>> resultHandler); // // /** // * Executes the GraphQL query on the GraphQL schema proxy using the provided variables. // * // * @param graphqlQuery the graphql query // * @param variables the query variables // * @param resultHandler the result handler with the graphql query result on success, or a failure // */ // void queryWithVariables(String graphqlQuery, JsonObject variables, // Handler<AsyncResult<QueryResult>> resultHandler); // // /** // * Invoked when the queryable service proxy closes. Does nothing by default, but can be overridden in sub-classes. // */ // @ProxyClose // default void close() { // // NO OP // } // }
import io.engagingspaces.graphql.query.Queryable; import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject; import io.vertx.ext.unit.junit.VertxUnitRunner; import io.vertx.servicediscovery.Record; import io.vertx.servicediscovery.ServiceDiscovery; import io.vertx.servicediscovery.ServiceDiscoveryOptions; import io.vertx.servicediscovery.ServiceReference; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull;
/* * Copyright (c) 2016 The original author or authors * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.engagingspaces.graphql.servicediscovery.service.impl; /** * Tests for graphql service type implementation class. * * @author <a href="https://github.com/aschrijver/">Arnold Schrijver</a> */ @RunWith(VertxUnitRunner.class) public class GraphQLServiceImplTest { private GraphQLServiceImpl graphQLService; private Vertx vertx; private ServiceDiscovery discovery; private Record record; private JsonObject config; @Before public void setUp() { vertx = Vertx.vertx(); discovery = ServiceDiscovery.create(vertx, new ServiceDiscoveryOptions().setName("test-discovery")); config = new JsonObject().put("deliveryOptions", new JsonObject().put("timeout", 1000).put("codecName", "theCodecName")); record = new Record().setLocation(new JsonObject().put(Record.ENDPOINT, "theEndpoint")); graphQLService = new io.engagingspaces.graphql.servicediscovery.service.impl.GraphQLServiceImpl(); } @Test public void should_Create_Service_Reference_With_Configuration() { ServiceReference reference = graphQLService.get(vertx, discovery, record, config); assertNotNull(reference); assertNull(reference.cached());
// Path: graphql-core/src/main/java/io/engagingspaces/graphql/query/Queryable.java // @ProxyGen // public interface Queryable { // // /** // * Name of the discovery service type for GraphQL schema's. // */ // String SERVICE_TYPE = "graphql-service"; // // /** // * The prefix that is combined with the root query name of the associated GraphQL schema // * to form the {@link io.vertx.servicediscovery.Record#ENDPOINT} address used in service discovery. // */ // String ADDRESS_PREFIX = "service.graphql"; // // /** // * Creates a service proxy to the {@link Queryable} implementation // * at the specified address. // * <p> // * The {@link DeliveryOptions} to use on the returned message consumer must be passed as // * plain json, because it does not provide a toJson() method (see:vhttps://github.com/eclipse/vert.x/issues/1502). // * // * @param vertx the vert.x instance // * @param address the address of the service proxy // * @param deliveryOptions the delivery options to use on the message consumer // * @return the graphql service proxy // */ // static Queryable createProxy(Vertx vertx, String address, JsonObject deliveryOptions) { // return ProxyHelper.createProxy(Queryable.class, vertx, address, new DeliveryOptions(deliveryOptions)); // } // // /** // * Executes the GraphQL query on the GraphQL schema proxy. // * <p> // * On success a {@link QueryResult} is returned. While this indicates the query executor has finished processing, // * the query itself might still have failed, so be sure to check {@link QueryResult#isSucceeded()} and // * {@link QueryResult#getErrors()} properties on the query result afterwards. // * afterwards. // * // * @param graphqlQuery the graphql query // * @param resultHandler the result handler with the query result on success, or a failure // */ // void query(String graphqlQuery, Handler<AsyncResult<QueryResult>> resultHandler); // // /** // * Executes the GraphQL query on the GraphQL schema proxy using the provided variables. // * // * @param graphqlQuery the graphql query // * @param variables the query variables // * @param resultHandler the result handler with the graphql query result on success, or a failure // */ // void queryWithVariables(String graphqlQuery, JsonObject variables, // Handler<AsyncResult<QueryResult>> resultHandler); // // /** // * Invoked when the queryable service proxy closes. Does nothing by default, but can be overridden in sub-classes. // */ // @ProxyClose // default void close() { // // NO OP // } // } // Path: graphql-service-publisher/src/test/java/io/engagingspaces/graphql/servicediscovery/service/impl/GraphQLServiceImplTest.java import io.engagingspaces.graphql.query.Queryable; import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject; import io.vertx.ext.unit.junit.VertxUnitRunner; import io.vertx.servicediscovery.Record; import io.vertx.servicediscovery.ServiceDiscovery; import io.vertx.servicediscovery.ServiceDiscoveryOptions; import io.vertx.servicediscovery.ServiceReference; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; /* * Copyright (c) 2016 The original author or authors * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.engagingspaces.graphql.servicediscovery.service.impl; /** * Tests for graphql service type implementation class. * * @author <a href="https://github.com/aschrijver/">Arnold Schrijver</a> */ @RunWith(VertxUnitRunner.class) public class GraphQLServiceImplTest { private GraphQLServiceImpl graphQLService; private Vertx vertx; private ServiceDiscovery discovery; private Record record; private JsonObject config; @Before public void setUp() { vertx = Vertx.vertx(); discovery = ServiceDiscovery.create(vertx, new ServiceDiscoveryOptions().setName("test-discovery")); config = new JsonObject().put("deliveryOptions", new JsonObject().put("timeout", 1000).put("codecName", "theCodecName")); record = new Record().setLocation(new JsonObject().put(Record.ENDPOINT, "theEndpoint")); graphQLService = new io.engagingspaces.graphql.servicediscovery.service.impl.GraphQLServiceImpl(); } @Test public void should_Create_Service_Reference_With_Configuration() { ServiceReference reference = graphQLService.get(vertx, discovery, record, config); assertNotNull(reference); assertNull(reference.cached());
Queryable serviceProxy = reference.get();
in-the-keyhole/khs-trouble-maker
src/main/java/khs/trouble/controller/ServicesHandler.java
// Path: src/main/java/khs/trouble/model/Service.java // public class Service { // // private String name; // private List<ServiceInstance> instances; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public List<ServiceInstance> getInstances() { // return instances; // } // // public void setInstances(List<ServiceInstance> instances) { // this.instances = instances; // } // } // // Path: src/main/java/khs/trouble/model/ServiceContainer.java // public class ServiceContainer { // // private List<Service> services; // // public List<Service> getServices() { // return services; // } // // public void setServices(List<Service> services) { // this.services = services; // } // }
import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import khs.trouble.model.Service; import khs.trouble.model.ServiceContainer;
package khs.trouble.controller; public class ServicesHandler extends TextWebSocketHandler { public List<WebSocketSession> sessions = new ArrayList<WebSocketSession>(); @Autowired private DiscoveryClient discoveryClient; @Autowired private ObjectMapper objectMapper;
// Path: src/main/java/khs/trouble/model/Service.java // public class Service { // // private String name; // private List<ServiceInstance> instances; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public List<ServiceInstance> getInstances() { // return instances; // } // // public void setInstances(List<ServiceInstance> instances) { // this.instances = instances; // } // } // // Path: src/main/java/khs/trouble/model/ServiceContainer.java // public class ServiceContainer { // // private List<Service> services; // // public List<Service> getServices() { // return services; // } // // public void setServices(List<Service> services) { // this.services = services; // } // } // Path: src/main/java/khs/trouble/controller/ServicesHandler.java import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import khs.trouble.model.Service; import khs.trouble.model.ServiceContainer; package khs.trouble.controller; public class ServicesHandler extends TextWebSocketHandler { public List<WebSocketSession> sessions = new ArrayList<WebSocketSession>(); @Autowired private DiscoveryClient discoveryClient; @Autowired private ObjectMapper objectMapper;
private ServiceContainer serviceContainer;
in-the-keyhole/khs-trouble-maker
src/main/java/khs/trouble/controller/ServicesHandler.java
// Path: src/main/java/khs/trouble/model/Service.java // public class Service { // // private String name; // private List<ServiceInstance> instances; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public List<ServiceInstance> getInstances() { // return instances; // } // // public void setInstances(List<ServiceInstance> instances) { // this.instances = instances; // } // } // // Path: src/main/java/khs/trouble/model/ServiceContainer.java // public class ServiceContainer { // // private List<Service> services; // // public List<Service> getServices() { // return services; // } // // public void setServices(List<Service> services) { // this.services = services; // } // }
import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import khs.trouble.model.Service; import khs.trouble.model.ServiceContainer;
package khs.trouble.controller; public class ServicesHandler extends TextWebSocketHandler { public List<WebSocketSession> sessions = new ArrayList<WebSocketSession>(); @Autowired private DiscoveryClient discoveryClient; @Autowired private ObjectMapper objectMapper; private ServiceContainer serviceContainer; public ServicesHandler() { super(); } @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { sessions.add(session); sendServices(session); } private void sendServices(WebSocketSession session) throws JsonProcessingException, IOException { session.sendMessage(new TextMessage(objectMapper.writeValueAsString(this.serviceContainer))); } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { sessions.remove(session); } @Scheduled(fixedDelayString = "${trouble.refreshInterval:30000}") private void fetchCurrentServices() throws JsonProcessingException, IOException { this.serviceContainer = new ServiceContainer();
// Path: src/main/java/khs/trouble/model/Service.java // public class Service { // // private String name; // private List<ServiceInstance> instances; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public List<ServiceInstance> getInstances() { // return instances; // } // // public void setInstances(List<ServiceInstance> instances) { // this.instances = instances; // } // } // // Path: src/main/java/khs/trouble/model/ServiceContainer.java // public class ServiceContainer { // // private List<Service> services; // // public List<Service> getServices() { // return services; // } // // public void setServices(List<Service> services) { // this.services = services; // } // } // Path: src/main/java/khs/trouble/controller/ServicesHandler.java import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import khs.trouble.model.Service; import khs.trouble.model.ServiceContainer; package khs.trouble.controller; public class ServicesHandler extends TextWebSocketHandler { public List<WebSocketSession> sessions = new ArrayList<WebSocketSession>(); @Autowired private DiscoveryClient discoveryClient; @Autowired private ObjectMapper objectMapper; private ServiceContainer serviceContainer; public ServicesHandler() { super(); } @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { sessions.add(session); sendServices(session); } private void sendServices(WebSocketSession session) throws JsonProcessingException, IOException { session.sendMessage(new TextMessage(objectMapper.writeValueAsString(this.serviceContainer))); } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { sessions.remove(session); } @Scheduled(fixedDelayString = "${trouble.refreshInterval:30000}") private void fetchCurrentServices() throws JsonProcessingException, IOException { this.serviceContainer = new ServiceContainer();
List<Service> services = new ArrayList<Service>();
in-the-keyhole/khs-trouble-maker
src/main/java/khs/trouble/service/impl/TroubleService.java
// Path: src/main/java/khs/trouble/util/FormatUrl.java // public class FormatUrl { // // public static String url(String route, boolean https ) { // return https ? "https" : "http" + "://"+ route; // } // // }
import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.Iterator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import org.springframework.cloud.netflix.eureka.EurekaDiscoveryClient; import khs.trouble.util.FormatUrl;
/* * Copyright 2015 Keyhole Software LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package khs.trouble.service.impl; @Service public class TroubleService { private Logger LOG = LoggerFactory.getLogger(TroubleService.class.getName()); @Autowired DiscoveryClient discoveryClient; @Autowired EventService eventService; @Value("${trouble.token}") String token; @Value("${trouble.timeout:300000}") Long timeout; @Value("${trouble.blocking-threads:200}") Integer threads; @Value("${trouble.ssl:false}") Boolean ssl; @Value("${eureka.client.registry-fetch-interval-seconds}") private Long monitorInterval; public String randomKill(String ltoken) { String serviceName = randomService(); eventService.randomKilled(serviceName); return kill(serviceName, "", ltoken); } public String kill(String serviceName, String instanceId, String ltoken) { if (token != ltoken) { throw new RuntimeException("Invalid Access Token"); }
// Path: src/main/java/khs/trouble/util/FormatUrl.java // public class FormatUrl { // // public static String url(String route, boolean https ) { // return https ? "https" : "http" + "://"+ route; // } // // } // Path: src/main/java/khs/trouble/service/impl/TroubleService.java import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.Iterator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import org.springframework.cloud.netflix.eureka.EurekaDiscoveryClient; import khs.trouble.util.FormatUrl; /* * Copyright 2015 Keyhole Software LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package khs.trouble.service.impl; @Service public class TroubleService { private Logger LOG = LoggerFactory.getLogger(TroubleService.class.getName()); @Autowired DiscoveryClient discoveryClient; @Autowired EventService eventService; @Value("${trouble.token}") String token; @Value("${trouble.timeout:300000}") Long timeout; @Value("${trouble.blocking-threads:200}") Integer threads; @Value("${trouble.ssl:false}") Boolean ssl; @Value("${eureka.client.registry-fetch-interval-seconds}") private Long monitorInterval; public String randomKill(String ltoken) { String serviceName = randomService(); eventService.randomKilled(serviceName); return kill(serviceName, "", ltoken); } public String kill(String serviceName, String instanceId, String ltoken) { if (token != ltoken) { throw new RuntimeException("Invalid Access Token"); }
String url = FormatUrl.url(serviceInstanceURL(serviceName, instanceId) + "trouble/kill", ssl);
in-the-keyhole/khs-trouble-maker
src/main/java/khs/trouble/service/impl/EventService.java
// Path: src/main/java/khs/trouble/model/Event.java // @Entity // @Table(name = "event") // public class Event { // // @Id // @GeneratedValue // @Column(name = "id") // private Long id; // // @Column(name = "created") // private Date created; // // @Column(name = "action") // private String action; // // @Column(name = "description", length = 500) // private String description; // // public String getAction() { // return action; // } // // public void setAction(String action) { // this.action = action; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Date getCreated() { // return created; // } // // public void setCreated(Date created) { // this.created = created; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: src/main/java/khs/trouble/repository/EventRepository.java // public interface EventRepository extends PagingAndSortingRepository<Event, Long> { // } // // Path: src/main/java/khs/trouble/controller/EventsHandler.java // @Component // public class EventsHandler extends TextWebSocketHandler { // // public List<WebSocketSession> sessions = new ArrayList<WebSocketSession>(); // // @Autowired // private EventService eventService; // // @Autowired // private ObjectMapper objectMapper; // // private EventContainer eventContainer; // // public EventsHandler() { // } // // @Override // public void afterConnectionEstablished(WebSocketSession session) throws Exception { // sessions.add(session); // sendEvents(session); // } // // private void sendEvents(WebSocketSession session) throws JsonProcessingException, IOException { // session.sendMessage(new TextMessage(objectMapper.writeValueAsString(this.eventContainer))); // } // // private void sendEvent(WebSocketSession session, Event event) throws JsonProcessingException, IOException { // session.sendMessage(new TextMessage(objectMapper.writeValueAsString(event))); // } // // public void sendSingleEvent(Event event) throws JsonProcessingException, IOException { // for (Iterator<WebSocketSession> iterator = sessions.iterator(); iterator.hasNext();) { // WebSocketSession session = iterator.next(); // sendEvent(session, event); // } // } // // @Override // public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { // sessions.remove(session); // } // // public void fetchCurrentEvents() throws JsonProcessingException, IOException { // this.eventContainer = new EventContainer(); // Iterable<Event> list = eventService.events(); // eventContainer.setEvents(list); // // for (Iterator<WebSocketSession> iterator = sessions.iterator(); iterator.hasNext();) { // WebSocketSession session = iterator.next(); // sendEvents(session); // } // } // }
import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.web.socket.WebSocketHandler; import khs.trouble.model.Event; import khs.trouble.repository.EventRepository; import khs.trouble.controller.EventsHandler;
/* * Copyright 2015 Keyhole Software LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package khs.trouble.service.impl; @Service public class EventService { @Autowired
// Path: src/main/java/khs/trouble/model/Event.java // @Entity // @Table(name = "event") // public class Event { // // @Id // @GeneratedValue // @Column(name = "id") // private Long id; // // @Column(name = "created") // private Date created; // // @Column(name = "action") // private String action; // // @Column(name = "description", length = 500) // private String description; // // public String getAction() { // return action; // } // // public void setAction(String action) { // this.action = action; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Date getCreated() { // return created; // } // // public void setCreated(Date created) { // this.created = created; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: src/main/java/khs/trouble/repository/EventRepository.java // public interface EventRepository extends PagingAndSortingRepository<Event, Long> { // } // // Path: src/main/java/khs/trouble/controller/EventsHandler.java // @Component // public class EventsHandler extends TextWebSocketHandler { // // public List<WebSocketSession> sessions = new ArrayList<WebSocketSession>(); // // @Autowired // private EventService eventService; // // @Autowired // private ObjectMapper objectMapper; // // private EventContainer eventContainer; // // public EventsHandler() { // } // // @Override // public void afterConnectionEstablished(WebSocketSession session) throws Exception { // sessions.add(session); // sendEvents(session); // } // // private void sendEvents(WebSocketSession session) throws JsonProcessingException, IOException { // session.sendMessage(new TextMessage(objectMapper.writeValueAsString(this.eventContainer))); // } // // private void sendEvent(WebSocketSession session, Event event) throws JsonProcessingException, IOException { // session.sendMessage(new TextMessage(objectMapper.writeValueAsString(event))); // } // // public void sendSingleEvent(Event event) throws JsonProcessingException, IOException { // for (Iterator<WebSocketSession> iterator = sessions.iterator(); iterator.hasNext();) { // WebSocketSession session = iterator.next(); // sendEvent(session, event); // } // } // // @Override // public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { // sessions.remove(session); // } // // public void fetchCurrentEvents() throws JsonProcessingException, IOException { // this.eventContainer = new EventContainer(); // Iterable<Event> list = eventService.events(); // eventContainer.setEvents(list); // // for (Iterator<WebSocketSession> iterator = sessions.iterator(); iterator.hasNext();) { // WebSocketSession session = iterator.next(); // sendEvents(session); // } // } // } // Path: src/main/java/khs/trouble/service/impl/EventService.java import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.web.socket.WebSocketHandler; import khs.trouble.model.Event; import khs.trouble.repository.EventRepository; import khs.trouble.controller.EventsHandler; /* * Copyright 2015 Keyhole Software LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package khs.trouble.service.impl; @Service public class EventService { @Autowired
private EventRepository repository;
in-the-keyhole/khs-trouble-maker
src/main/java/khs/trouble/service/impl/EventService.java
// Path: src/main/java/khs/trouble/model/Event.java // @Entity // @Table(name = "event") // public class Event { // // @Id // @GeneratedValue // @Column(name = "id") // private Long id; // // @Column(name = "created") // private Date created; // // @Column(name = "action") // private String action; // // @Column(name = "description", length = 500) // private String description; // // public String getAction() { // return action; // } // // public void setAction(String action) { // this.action = action; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Date getCreated() { // return created; // } // // public void setCreated(Date created) { // this.created = created; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: src/main/java/khs/trouble/repository/EventRepository.java // public interface EventRepository extends PagingAndSortingRepository<Event, Long> { // } // // Path: src/main/java/khs/trouble/controller/EventsHandler.java // @Component // public class EventsHandler extends TextWebSocketHandler { // // public List<WebSocketSession> sessions = new ArrayList<WebSocketSession>(); // // @Autowired // private EventService eventService; // // @Autowired // private ObjectMapper objectMapper; // // private EventContainer eventContainer; // // public EventsHandler() { // } // // @Override // public void afterConnectionEstablished(WebSocketSession session) throws Exception { // sessions.add(session); // sendEvents(session); // } // // private void sendEvents(WebSocketSession session) throws JsonProcessingException, IOException { // session.sendMessage(new TextMessage(objectMapper.writeValueAsString(this.eventContainer))); // } // // private void sendEvent(WebSocketSession session, Event event) throws JsonProcessingException, IOException { // session.sendMessage(new TextMessage(objectMapper.writeValueAsString(event))); // } // // public void sendSingleEvent(Event event) throws JsonProcessingException, IOException { // for (Iterator<WebSocketSession> iterator = sessions.iterator(); iterator.hasNext();) { // WebSocketSession session = iterator.next(); // sendEvent(session, event); // } // } // // @Override // public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { // sessions.remove(session); // } // // public void fetchCurrentEvents() throws JsonProcessingException, IOException { // this.eventContainer = new EventContainer(); // Iterable<Event> list = eventService.events(); // eventContainer.setEvents(list); // // for (Iterator<WebSocketSession> iterator = sessions.iterator(); iterator.hasNext();) { // WebSocketSession session = iterator.next(); // sendEvents(session); // } // } // }
import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.web.socket.WebSocketHandler; import khs.trouble.model.Event; import khs.trouble.repository.EventRepository; import khs.trouble.controller.EventsHandler;
/* * Copyright 2015 Keyhole Software LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package khs.trouble.service.impl; @Service public class EventService { @Autowired private EventRepository repository; @Autowired private WebSocketHandler eventsHandler; @Value("${trouble.timeout:300000}") private Long timeout;
// Path: src/main/java/khs/trouble/model/Event.java // @Entity // @Table(name = "event") // public class Event { // // @Id // @GeneratedValue // @Column(name = "id") // private Long id; // // @Column(name = "created") // private Date created; // // @Column(name = "action") // private String action; // // @Column(name = "description", length = 500) // private String description; // // public String getAction() { // return action; // } // // public void setAction(String action) { // this.action = action; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Date getCreated() { // return created; // } // // public void setCreated(Date created) { // this.created = created; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: src/main/java/khs/trouble/repository/EventRepository.java // public interface EventRepository extends PagingAndSortingRepository<Event, Long> { // } // // Path: src/main/java/khs/trouble/controller/EventsHandler.java // @Component // public class EventsHandler extends TextWebSocketHandler { // // public List<WebSocketSession> sessions = new ArrayList<WebSocketSession>(); // // @Autowired // private EventService eventService; // // @Autowired // private ObjectMapper objectMapper; // // private EventContainer eventContainer; // // public EventsHandler() { // } // // @Override // public void afterConnectionEstablished(WebSocketSession session) throws Exception { // sessions.add(session); // sendEvents(session); // } // // private void sendEvents(WebSocketSession session) throws JsonProcessingException, IOException { // session.sendMessage(new TextMessage(objectMapper.writeValueAsString(this.eventContainer))); // } // // private void sendEvent(WebSocketSession session, Event event) throws JsonProcessingException, IOException { // session.sendMessage(new TextMessage(objectMapper.writeValueAsString(event))); // } // // public void sendSingleEvent(Event event) throws JsonProcessingException, IOException { // for (Iterator<WebSocketSession> iterator = sessions.iterator(); iterator.hasNext();) { // WebSocketSession session = iterator.next(); // sendEvent(session, event); // } // } // // @Override // public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { // sessions.remove(session); // } // // public void fetchCurrentEvents() throws JsonProcessingException, IOException { // this.eventContainer = new EventContainer(); // Iterable<Event> list = eventService.events(); // eventContainer.setEvents(list); // // for (Iterator<WebSocketSession> iterator = sessions.iterator(); iterator.hasNext();) { // WebSocketSession session = iterator.next(); // sendEvents(session); // } // } // } // Path: src/main/java/khs/trouble/service/impl/EventService.java import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.web.socket.WebSocketHandler; import khs.trouble.model.Event; import khs.trouble.repository.EventRepository; import khs.trouble.controller.EventsHandler; /* * Copyright 2015 Keyhole Software LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package khs.trouble.service.impl; @Service public class EventService { @Autowired private EventRepository repository; @Autowired private WebSocketHandler eventsHandler; @Value("${trouble.timeout:300000}") private Long timeout;
private void sendEvent(Event event) {
in-the-keyhole/khs-trouble-maker
src/main/java/khs/trouble/service/impl/EventService.java
// Path: src/main/java/khs/trouble/model/Event.java // @Entity // @Table(name = "event") // public class Event { // // @Id // @GeneratedValue // @Column(name = "id") // private Long id; // // @Column(name = "created") // private Date created; // // @Column(name = "action") // private String action; // // @Column(name = "description", length = 500) // private String description; // // public String getAction() { // return action; // } // // public void setAction(String action) { // this.action = action; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Date getCreated() { // return created; // } // // public void setCreated(Date created) { // this.created = created; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: src/main/java/khs/trouble/repository/EventRepository.java // public interface EventRepository extends PagingAndSortingRepository<Event, Long> { // } // // Path: src/main/java/khs/trouble/controller/EventsHandler.java // @Component // public class EventsHandler extends TextWebSocketHandler { // // public List<WebSocketSession> sessions = new ArrayList<WebSocketSession>(); // // @Autowired // private EventService eventService; // // @Autowired // private ObjectMapper objectMapper; // // private EventContainer eventContainer; // // public EventsHandler() { // } // // @Override // public void afterConnectionEstablished(WebSocketSession session) throws Exception { // sessions.add(session); // sendEvents(session); // } // // private void sendEvents(WebSocketSession session) throws JsonProcessingException, IOException { // session.sendMessage(new TextMessage(objectMapper.writeValueAsString(this.eventContainer))); // } // // private void sendEvent(WebSocketSession session, Event event) throws JsonProcessingException, IOException { // session.sendMessage(new TextMessage(objectMapper.writeValueAsString(event))); // } // // public void sendSingleEvent(Event event) throws JsonProcessingException, IOException { // for (Iterator<WebSocketSession> iterator = sessions.iterator(); iterator.hasNext();) { // WebSocketSession session = iterator.next(); // sendEvent(session, event); // } // } // // @Override // public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { // sessions.remove(session); // } // // public void fetchCurrentEvents() throws JsonProcessingException, IOException { // this.eventContainer = new EventContainer(); // Iterable<Event> list = eventService.events(); // eventContainer.setEvents(list); // // for (Iterator<WebSocketSession> iterator = sessions.iterator(); iterator.hasNext();) { // WebSocketSession session = iterator.next(); // sendEvents(session); // } // } // }
import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.web.socket.WebSocketHandler; import khs.trouble.model.Event; import khs.trouble.repository.EventRepository; import khs.trouble.controller.EventsHandler;
/* * Copyright 2015 Keyhole Software LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package khs.trouble.service.impl; @Service public class EventService { @Autowired private EventRepository repository; @Autowired private WebSocketHandler eventsHandler; @Value("${trouble.timeout:300000}") private Long timeout; private void sendEvent(Event event) { try {
// Path: src/main/java/khs/trouble/model/Event.java // @Entity // @Table(name = "event") // public class Event { // // @Id // @GeneratedValue // @Column(name = "id") // private Long id; // // @Column(name = "created") // private Date created; // // @Column(name = "action") // private String action; // // @Column(name = "description", length = 500) // private String description; // // public String getAction() { // return action; // } // // public void setAction(String action) { // this.action = action; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Date getCreated() { // return created; // } // // public void setCreated(Date created) { // this.created = created; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: src/main/java/khs/trouble/repository/EventRepository.java // public interface EventRepository extends PagingAndSortingRepository<Event, Long> { // } // // Path: src/main/java/khs/trouble/controller/EventsHandler.java // @Component // public class EventsHandler extends TextWebSocketHandler { // // public List<WebSocketSession> sessions = new ArrayList<WebSocketSession>(); // // @Autowired // private EventService eventService; // // @Autowired // private ObjectMapper objectMapper; // // private EventContainer eventContainer; // // public EventsHandler() { // } // // @Override // public void afterConnectionEstablished(WebSocketSession session) throws Exception { // sessions.add(session); // sendEvents(session); // } // // private void sendEvents(WebSocketSession session) throws JsonProcessingException, IOException { // session.sendMessage(new TextMessage(objectMapper.writeValueAsString(this.eventContainer))); // } // // private void sendEvent(WebSocketSession session, Event event) throws JsonProcessingException, IOException { // session.sendMessage(new TextMessage(objectMapper.writeValueAsString(event))); // } // // public void sendSingleEvent(Event event) throws JsonProcessingException, IOException { // for (Iterator<WebSocketSession> iterator = sessions.iterator(); iterator.hasNext();) { // WebSocketSession session = iterator.next(); // sendEvent(session, event); // } // } // // @Override // public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { // sessions.remove(session); // } // // public void fetchCurrentEvents() throws JsonProcessingException, IOException { // this.eventContainer = new EventContainer(); // Iterable<Event> list = eventService.events(); // eventContainer.setEvents(list); // // for (Iterator<WebSocketSession> iterator = sessions.iterator(); iterator.hasNext();) { // WebSocketSession session = iterator.next(); // sendEvents(session); // } // } // } // Path: src/main/java/khs/trouble/service/impl/EventService.java import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.web.socket.WebSocketHandler; import khs.trouble.model.Event; import khs.trouble.repository.EventRepository; import khs.trouble.controller.EventsHandler; /* * Copyright 2015 Keyhole Software LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package khs.trouble.service.impl; @Service public class EventService { @Autowired private EventRepository repository; @Autowired private WebSocketHandler eventsHandler; @Value("${trouble.timeout:300000}") private Long timeout; private void sendEvent(Event event) { try {
((EventsHandler) eventsHandler).sendSingleEvent(event);
in-the-keyhole/khs-trouble-maker
src/main/java/khs/trouble/Application.java
// Path: src/main/java/khs/trouble/service/impl/EventService.java // @Service // public class EventService { // // @Autowired // private EventRepository repository; // // @Autowired // private WebSocketHandler eventsHandler; // // @Value("${trouble.timeout:300000}") // private Long timeout; // // // private void sendEvent(Event event) { // try { // ((EventsHandler) eventsHandler).sendSingleEvent(event); // } catch (Exception e) { // e.printStackTrace(); // } // } // // public void killed(String serviceName, String url) { // Event event = new Event(); // event.setCreated(new Date()); // event.setAction("KILLED"); // event.setDescription(serviceName.toUpperCase() + " killed at: " + url); // this.repository.save(event); // // sendEvent(event); // } // // public void randomKilled(String serviceName) { // Event event = new Event(); // event.setCreated(new Date()); // event.setAction("RANDOM"); // event.setDescription(serviceName.toUpperCase() + " selected to be killed"); // this.repository.save(event); // // sendEvent(event); // } // // public void load(String serviceName, String url, int threads) { // Event event = new Event(); // event.setCreated(new Date()); // event.setAction("LOAD"); // event.setDescription(serviceName.toUpperCase() + " Load of (" + threads + " threads) started at: " + url + " will timeout in " + timeout()); // this.repository.save(event); // // sendEvent(event); // } // // public void exception(String serviceName, String url) { // Event event = new Event(); // event.setCreated(new Date()); // event.setAction("EXCEPTION"); // event.setDescription(serviceName.toUpperCase() + " Exception thrown at: " + url); // this.repository.save(event); // // sendEvent(event); // } // // public void memory(String serviceName, String url) { // Event event = new Event(); // event.setCreated(new Date()); // event.setAction("MEMORY"); // event.setDescription(serviceName.toUpperCase() + " Memory Consumed at: " + url + " will timeout in " + timeout()); // this.repository.save(event); // // sendEvent(event); // } // // public void eventInfo(String msg) { // Event event = new Event(); // event.setCreated(new Date()); // event.setAction("INFO"); // event.setDescription(msg); // this.repository.save(event); // // sendEvent(event); // } // // public void attempted(String msg) { // Event event = new Event(); // event.setCreated(new Date()); // event.setAction("ATTEMPTED"); // event.setDescription(msg); // this.repository.save(event); // // sendEvent(event); // } // // public void started() { // Event event = new Event(); // event.setCreated(new Date()); // event.setAction("STARTED"); // event.setDescription("Trouble maker started"); // this.repository.save(event); // // sendEvent(event); // } // // public void notStarted() { // Event event = new Event(); // event.setCreated(new Date()); // event.setAction("NOT STARTED"); // event.setDescription("Service Registry Not Found, Make sure it has been started or is accessible"); // this.repository.save(event); // // sendEvent(event); // } // // public String timeout() { // String msg = timeout == 0 ? "NEVER" : "" + (timeout / 60000) + " minute(s)"; // return msg; // } // // public Iterable<Event> events() { // return this.repository.findAll(new Sort(Sort.Direction.ASC, "created")); // } // }
import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; import khs.trouble.service.impl.EventService;
/* * Copyright 2015 Keyhole Software LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package khs.trouble; @SpringBootApplication @EnableScheduling @EnableAsync @EnableDiscoveryClient public class Application { public static void main(final String[] args) { SpringApplication.run(Application.class, args); } @Autowired private DiscoveryClient discoveryClient; @Autowired
// Path: src/main/java/khs/trouble/service/impl/EventService.java // @Service // public class EventService { // // @Autowired // private EventRepository repository; // // @Autowired // private WebSocketHandler eventsHandler; // // @Value("${trouble.timeout:300000}") // private Long timeout; // // // private void sendEvent(Event event) { // try { // ((EventsHandler) eventsHandler).sendSingleEvent(event); // } catch (Exception e) { // e.printStackTrace(); // } // } // // public void killed(String serviceName, String url) { // Event event = new Event(); // event.setCreated(new Date()); // event.setAction("KILLED"); // event.setDescription(serviceName.toUpperCase() + " killed at: " + url); // this.repository.save(event); // // sendEvent(event); // } // // public void randomKilled(String serviceName) { // Event event = new Event(); // event.setCreated(new Date()); // event.setAction("RANDOM"); // event.setDescription(serviceName.toUpperCase() + " selected to be killed"); // this.repository.save(event); // // sendEvent(event); // } // // public void load(String serviceName, String url, int threads) { // Event event = new Event(); // event.setCreated(new Date()); // event.setAction("LOAD"); // event.setDescription(serviceName.toUpperCase() + " Load of (" + threads + " threads) started at: " + url + " will timeout in " + timeout()); // this.repository.save(event); // // sendEvent(event); // } // // public void exception(String serviceName, String url) { // Event event = new Event(); // event.setCreated(new Date()); // event.setAction("EXCEPTION"); // event.setDescription(serviceName.toUpperCase() + " Exception thrown at: " + url); // this.repository.save(event); // // sendEvent(event); // } // // public void memory(String serviceName, String url) { // Event event = new Event(); // event.setCreated(new Date()); // event.setAction("MEMORY"); // event.setDescription(serviceName.toUpperCase() + " Memory Consumed at: " + url + " will timeout in " + timeout()); // this.repository.save(event); // // sendEvent(event); // } // // public void eventInfo(String msg) { // Event event = new Event(); // event.setCreated(new Date()); // event.setAction("INFO"); // event.setDescription(msg); // this.repository.save(event); // // sendEvent(event); // } // // public void attempted(String msg) { // Event event = new Event(); // event.setCreated(new Date()); // event.setAction("ATTEMPTED"); // event.setDescription(msg); // this.repository.save(event); // // sendEvent(event); // } // // public void started() { // Event event = new Event(); // event.setCreated(new Date()); // event.setAction("STARTED"); // event.setDescription("Trouble maker started"); // this.repository.save(event); // // sendEvent(event); // } // // public void notStarted() { // Event event = new Event(); // event.setCreated(new Date()); // event.setAction("NOT STARTED"); // event.setDescription("Service Registry Not Found, Make sure it has been started or is accessible"); // this.repository.save(event); // // sendEvent(event); // } // // public String timeout() { // String msg = timeout == 0 ? "NEVER" : "" + (timeout / 60000) + " minute(s)"; // return msg; // } // // public Iterable<Event> events() { // return this.repository.findAll(new Sort(Sort.Direction.ASC, "created")); // } // } // Path: src/main/java/khs/trouble/Application.java import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; import khs.trouble.service.impl.EventService; /* * Copyright 2015 Keyhole Software LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package khs.trouble; @SpringBootApplication @EnableScheduling @EnableAsync @EnableDiscoveryClient public class Application { public static void main(final String[] args) { SpringApplication.run(Application.class, args); } @Autowired private DiscoveryClient discoveryClient; @Autowired
private EventService eventService;
in-the-keyhole/khs-trouble-maker
src/main/java/khs/trouble/WebSocketConfiguration.java
// Path: src/main/java/khs/trouble/controller/ServicesHandler.java // public class ServicesHandler extends TextWebSocketHandler { // // public List<WebSocketSession> sessions = new ArrayList<WebSocketSession>(); // // @Autowired // private DiscoveryClient discoveryClient; // // @Autowired // private ObjectMapper objectMapper; // // private ServiceContainer serviceContainer; // // public ServicesHandler() { // super(); // } // // @Override // public void afterConnectionEstablished(WebSocketSession session) throws Exception { // sessions.add(session); // sendServices(session); // } // // private void sendServices(WebSocketSession session) throws JsonProcessingException, IOException { // session.sendMessage(new TextMessage(objectMapper.writeValueAsString(this.serviceContainer))); // } // // @Override // public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { // sessions.remove(session); // } // // @Scheduled(fixedDelayString = "${trouble.refreshInterval:30000}") // private void fetchCurrentServices() throws JsonProcessingException, IOException { // this.serviceContainer = new ServiceContainer(); // List<Service> services = new ArrayList<Service>(); // serviceContainer.setServices(services); // // List<String> list = discoveryClient.getServices(); // for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) { // String serviceId = (String) iterator.next(); // Service application = new Service(); // application.setName(serviceId); // application.setInstances(discoveryClient.getInstances(serviceId)); // services.add(application); // } // for (Iterator<WebSocketSession> iterator = sessions.iterator(); iterator.hasNext();) { // WebSocketSession session = iterator.next(); // sendServices(session); // } // } // } // // Path: src/main/java/khs/trouble/controller/EventsHandler.java // @Component // public class EventsHandler extends TextWebSocketHandler { // // public List<WebSocketSession> sessions = new ArrayList<WebSocketSession>(); // // @Autowired // private EventService eventService; // // @Autowired // private ObjectMapper objectMapper; // // private EventContainer eventContainer; // // public EventsHandler() { // } // // @Override // public void afterConnectionEstablished(WebSocketSession session) throws Exception { // sessions.add(session); // sendEvents(session); // } // // private void sendEvents(WebSocketSession session) throws JsonProcessingException, IOException { // session.sendMessage(new TextMessage(objectMapper.writeValueAsString(this.eventContainer))); // } // // private void sendEvent(WebSocketSession session, Event event) throws JsonProcessingException, IOException { // session.sendMessage(new TextMessage(objectMapper.writeValueAsString(event))); // } // // public void sendSingleEvent(Event event) throws JsonProcessingException, IOException { // for (Iterator<WebSocketSession> iterator = sessions.iterator(); iterator.hasNext();) { // WebSocketSession session = iterator.next(); // sendEvent(session, event); // } // } // // @Override // public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { // sessions.remove(session); // } // // public void fetchCurrentEvents() throws JsonProcessingException, IOException { // this.eventContainer = new EventContainer(); // Iterable<Event> list = eventService.events(); // eventContainer.setEvents(list); // // for (Iterator<WebSocketSession> iterator = sessions.iterator(); iterator.hasNext();) { // WebSocketSession session = iterator.next(); // sendEvents(session); // } // } // }
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; import khs.trouble.controller.ServicesHandler; import khs.trouble.controller.EventsHandler;
package khs.trouble; //import org.springframework.beans.factory.annotation.Autowired; @EnableWebSocket @Configuration public class WebSocketConfiguration implements WebSocketConfigurer { // @Autowired // EventsHandler eventsHandler; @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(servicesHandler(), "/ws/services").setAllowedOrigins("*"); registry.addHandler(eventsHandler(), "/ws/events").setAllowedOrigins("*"); } @Bean public WebSocketHandler servicesHandler() {
// Path: src/main/java/khs/trouble/controller/ServicesHandler.java // public class ServicesHandler extends TextWebSocketHandler { // // public List<WebSocketSession> sessions = new ArrayList<WebSocketSession>(); // // @Autowired // private DiscoveryClient discoveryClient; // // @Autowired // private ObjectMapper objectMapper; // // private ServiceContainer serviceContainer; // // public ServicesHandler() { // super(); // } // // @Override // public void afterConnectionEstablished(WebSocketSession session) throws Exception { // sessions.add(session); // sendServices(session); // } // // private void sendServices(WebSocketSession session) throws JsonProcessingException, IOException { // session.sendMessage(new TextMessage(objectMapper.writeValueAsString(this.serviceContainer))); // } // // @Override // public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { // sessions.remove(session); // } // // @Scheduled(fixedDelayString = "${trouble.refreshInterval:30000}") // private void fetchCurrentServices() throws JsonProcessingException, IOException { // this.serviceContainer = new ServiceContainer(); // List<Service> services = new ArrayList<Service>(); // serviceContainer.setServices(services); // // List<String> list = discoveryClient.getServices(); // for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) { // String serviceId = (String) iterator.next(); // Service application = new Service(); // application.setName(serviceId); // application.setInstances(discoveryClient.getInstances(serviceId)); // services.add(application); // } // for (Iterator<WebSocketSession> iterator = sessions.iterator(); iterator.hasNext();) { // WebSocketSession session = iterator.next(); // sendServices(session); // } // } // } // // Path: src/main/java/khs/trouble/controller/EventsHandler.java // @Component // public class EventsHandler extends TextWebSocketHandler { // // public List<WebSocketSession> sessions = new ArrayList<WebSocketSession>(); // // @Autowired // private EventService eventService; // // @Autowired // private ObjectMapper objectMapper; // // private EventContainer eventContainer; // // public EventsHandler() { // } // // @Override // public void afterConnectionEstablished(WebSocketSession session) throws Exception { // sessions.add(session); // sendEvents(session); // } // // private void sendEvents(WebSocketSession session) throws JsonProcessingException, IOException { // session.sendMessage(new TextMessage(objectMapper.writeValueAsString(this.eventContainer))); // } // // private void sendEvent(WebSocketSession session, Event event) throws JsonProcessingException, IOException { // session.sendMessage(new TextMessage(objectMapper.writeValueAsString(event))); // } // // public void sendSingleEvent(Event event) throws JsonProcessingException, IOException { // for (Iterator<WebSocketSession> iterator = sessions.iterator(); iterator.hasNext();) { // WebSocketSession session = iterator.next(); // sendEvent(session, event); // } // } // // @Override // public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { // sessions.remove(session); // } // // public void fetchCurrentEvents() throws JsonProcessingException, IOException { // this.eventContainer = new EventContainer(); // Iterable<Event> list = eventService.events(); // eventContainer.setEvents(list); // // for (Iterator<WebSocketSession> iterator = sessions.iterator(); iterator.hasNext();) { // WebSocketSession session = iterator.next(); // sendEvents(session); // } // } // } // Path: src/main/java/khs/trouble/WebSocketConfiguration.java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; import khs.trouble.controller.ServicesHandler; import khs.trouble.controller.EventsHandler; package khs.trouble; //import org.springframework.beans.factory.annotation.Autowired; @EnableWebSocket @Configuration public class WebSocketConfiguration implements WebSocketConfigurer { // @Autowired // EventsHandler eventsHandler; @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(servicesHandler(), "/ws/services").setAllowedOrigins("*"); registry.addHandler(eventsHandler(), "/ws/events").setAllowedOrigins("*"); } @Bean public WebSocketHandler servicesHandler() {
return new ServicesHandler();
in-the-keyhole/khs-trouble-maker
src/main/java/khs/trouble/WebSocketConfiguration.java
// Path: src/main/java/khs/trouble/controller/ServicesHandler.java // public class ServicesHandler extends TextWebSocketHandler { // // public List<WebSocketSession> sessions = new ArrayList<WebSocketSession>(); // // @Autowired // private DiscoveryClient discoveryClient; // // @Autowired // private ObjectMapper objectMapper; // // private ServiceContainer serviceContainer; // // public ServicesHandler() { // super(); // } // // @Override // public void afterConnectionEstablished(WebSocketSession session) throws Exception { // sessions.add(session); // sendServices(session); // } // // private void sendServices(WebSocketSession session) throws JsonProcessingException, IOException { // session.sendMessage(new TextMessage(objectMapper.writeValueAsString(this.serviceContainer))); // } // // @Override // public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { // sessions.remove(session); // } // // @Scheduled(fixedDelayString = "${trouble.refreshInterval:30000}") // private void fetchCurrentServices() throws JsonProcessingException, IOException { // this.serviceContainer = new ServiceContainer(); // List<Service> services = new ArrayList<Service>(); // serviceContainer.setServices(services); // // List<String> list = discoveryClient.getServices(); // for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) { // String serviceId = (String) iterator.next(); // Service application = new Service(); // application.setName(serviceId); // application.setInstances(discoveryClient.getInstances(serviceId)); // services.add(application); // } // for (Iterator<WebSocketSession> iterator = sessions.iterator(); iterator.hasNext();) { // WebSocketSession session = iterator.next(); // sendServices(session); // } // } // } // // Path: src/main/java/khs/trouble/controller/EventsHandler.java // @Component // public class EventsHandler extends TextWebSocketHandler { // // public List<WebSocketSession> sessions = new ArrayList<WebSocketSession>(); // // @Autowired // private EventService eventService; // // @Autowired // private ObjectMapper objectMapper; // // private EventContainer eventContainer; // // public EventsHandler() { // } // // @Override // public void afterConnectionEstablished(WebSocketSession session) throws Exception { // sessions.add(session); // sendEvents(session); // } // // private void sendEvents(WebSocketSession session) throws JsonProcessingException, IOException { // session.sendMessage(new TextMessage(objectMapper.writeValueAsString(this.eventContainer))); // } // // private void sendEvent(WebSocketSession session, Event event) throws JsonProcessingException, IOException { // session.sendMessage(new TextMessage(objectMapper.writeValueAsString(event))); // } // // public void sendSingleEvent(Event event) throws JsonProcessingException, IOException { // for (Iterator<WebSocketSession> iterator = sessions.iterator(); iterator.hasNext();) { // WebSocketSession session = iterator.next(); // sendEvent(session, event); // } // } // // @Override // public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { // sessions.remove(session); // } // // public void fetchCurrentEvents() throws JsonProcessingException, IOException { // this.eventContainer = new EventContainer(); // Iterable<Event> list = eventService.events(); // eventContainer.setEvents(list); // // for (Iterator<WebSocketSession> iterator = sessions.iterator(); iterator.hasNext();) { // WebSocketSession session = iterator.next(); // sendEvents(session); // } // } // }
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; import khs.trouble.controller.ServicesHandler; import khs.trouble.controller.EventsHandler;
package khs.trouble; //import org.springframework.beans.factory.annotation.Autowired; @EnableWebSocket @Configuration public class WebSocketConfiguration implements WebSocketConfigurer { // @Autowired // EventsHandler eventsHandler; @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(servicesHandler(), "/ws/services").setAllowedOrigins("*"); registry.addHandler(eventsHandler(), "/ws/events").setAllowedOrigins("*"); } @Bean public WebSocketHandler servicesHandler() { return new ServicesHandler(); } @Bean public WebSocketHandler eventsHandler() {
// Path: src/main/java/khs/trouble/controller/ServicesHandler.java // public class ServicesHandler extends TextWebSocketHandler { // // public List<WebSocketSession> sessions = new ArrayList<WebSocketSession>(); // // @Autowired // private DiscoveryClient discoveryClient; // // @Autowired // private ObjectMapper objectMapper; // // private ServiceContainer serviceContainer; // // public ServicesHandler() { // super(); // } // // @Override // public void afterConnectionEstablished(WebSocketSession session) throws Exception { // sessions.add(session); // sendServices(session); // } // // private void sendServices(WebSocketSession session) throws JsonProcessingException, IOException { // session.sendMessage(new TextMessage(objectMapper.writeValueAsString(this.serviceContainer))); // } // // @Override // public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { // sessions.remove(session); // } // // @Scheduled(fixedDelayString = "${trouble.refreshInterval:30000}") // private void fetchCurrentServices() throws JsonProcessingException, IOException { // this.serviceContainer = new ServiceContainer(); // List<Service> services = new ArrayList<Service>(); // serviceContainer.setServices(services); // // List<String> list = discoveryClient.getServices(); // for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) { // String serviceId = (String) iterator.next(); // Service application = new Service(); // application.setName(serviceId); // application.setInstances(discoveryClient.getInstances(serviceId)); // services.add(application); // } // for (Iterator<WebSocketSession> iterator = sessions.iterator(); iterator.hasNext();) { // WebSocketSession session = iterator.next(); // sendServices(session); // } // } // } // // Path: src/main/java/khs/trouble/controller/EventsHandler.java // @Component // public class EventsHandler extends TextWebSocketHandler { // // public List<WebSocketSession> sessions = new ArrayList<WebSocketSession>(); // // @Autowired // private EventService eventService; // // @Autowired // private ObjectMapper objectMapper; // // private EventContainer eventContainer; // // public EventsHandler() { // } // // @Override // public void afterConnectionEstablished(WebSocketSession session) throws Exception { // sessions.add(session); // sendEvents(session); // } // // private void sendEvents(WebSocketSession session) throws JsonProcessingException, IOException { // session.sendMessage(new TextMessage(objectMapper.writeValueAsString(this.eventContainer))); // } // // private void sendEvent(WebSocketSession session, Event event) throws JsonProcessingException, IOException { // session.sendMessage(new TextMessage(objectMapper.writeValueAsString(event))); // } // // public void sendSingleEvent(Event event) throws JsonProcessingException, IOException { // for (Iterator<WebSocketSession> iterator = sessions.iterator(); iterator.hasNext();) { // WebSocketSession session = iterator.next(); // sendEvent(session, event); // } // } // // @Override // public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { // sessions.remove(session); // } // // public void fetchCurrentEvents() throws JsonProcessingException, IOException { // this.eventContainer = new EventContainer(); // Iterable<Event> list = eventService.events(); // eventContainer.setEvents(list); // // for (Iterator<WebSocketSession> iterator = sessions.iterator(); iterator.hasNext();) { // WebSocketSession session = iterator.next(); // sendEvents(session); // } // } // } // Path: src/main/java/khs/trouble/WebSocketConfiguration.java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; import khs.trouble.controller.ServicesHandler; import khs.trouble.controller.EventsHandler; package khs.trouble; //import org.springframework.beans.factory.annotation.Autowired; @EnableWebSocket @Configuration public class WebSocketConfiguration implements WebSocketConfigurer { // @Autowired // EventsHandler eventsHandler; @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(servicesHandler(), "/ws/services").setAllowedOrigins("*"); registry.addHandler(eventsHandler(), "/ws/events").setAllowedOrigins("*"); } @Bean public WebSocketHandler servicesHandler() { return new ServicesHandler(); } @Bean public WebSocketHandler eventsHandler() {
return new EventsHandler();
ustramooner/gwt-geom
src/gwt/awt/geom/Point2D.java
// Path: src/gwt/awt/utils/HashCode.java // public class HashCode { // int hashcode = 1837269811; // // @Override // public int hashCode() { // return hashcode; // } // public void append(Double value) { // hashcode += (value.hashCode() * 32); // } // public void append(Integer value) { // hashcode += (value.hashCode() * 32); // } // }
import gwt.awt.utils.HashCode; import java.io.Serializable;
* Returns the distance from this <code>Point2D</code> to a * specified <code>Point2D</code>. * * @param pt the specified point to be measured * against this <code>Point2D</code> * @return the distance between this <code>Point2D</code> and * the specified <code>Point2D</code>. * @since 1.2 */ public double distance(Point2D pt) { double px = pt.getX() - this.getX(); double py = pt.getY() - this.getY(); return Math.sqrt(px * px + py * py); } /** * Creates a new object of the same class and with the * same contents as this object. * @return a clone of this instance. * @exception OutOfMemoryError if there is not enough memory. * @see java.lang.Cloneable * @since 1.2 */ public abstract Object clone(); /** * Returns the hashcode for this <code>Point2D</code>. * @return a hash code for this <code>Point2D</code>. */ public int hashCode() {
// Path: src/gwt/awt/utils/HashCode.java // public class HashCode { // int hashcode = 1837269811; // // @Override // public int hashCode() { // return hashcode; // } // public void append(Double value) { // hashcode += (value.hashCode() * 32); // } // public void append(Integer value) { // hashcode += (value.hashCode() * 32); // } // } // Path: src/gwt/awt/geom/Point2D.java import gwt.awt.utils.HashCode; import java.io.Serializable; * Returns the distance from this <code>Point2D</code> to a * specified <code>Point2D</code>. * * @param pt the specified point to be measured * against this <code>Point2D</code> * @return the distance between this <code>Point2D</code> and * the specified <code>Point2D</code>. * @since 1.2 */ public double distance(Point2D pt) { double px = pt.getX() - this.getX(); double py = pt.getY() - this.getY(); return Math.sqrt(px * px + py * py); } /** * Creates a new object of the same class and with the * same contents as this object. * @return a clone of this instance. * @exception OutOfMemoryError if there is not enough memory. * @see java.lang.Cloneable * @since 1.2 */ public abstract Object clone(); /** * Returns the hashcode for this <code>Point2D</code>. * @return a hash code for this <code>Point2D</code>. */ public int hashCode() {
HashCode hashCode = new HashCode();
ustramooner/gwt-geom
src/gwt/awt/geom/Ellipse2D.java
// Path: src/gwt/awt/utils/HashCode.java // public class HashCode { // int hashcode = 1837269811; // // @Override // public int hashCode() { // return hashcode; // } // public void append(Double value) { // hashcode += (value.hashCode() * 32); // } // public void append(Integer value) { // hashcode += (value.hashCode() * 32); // } // }
import gwt.awt.utils.HashCode; import java.io.Serializable;
contains(x, y + h) && contains(x + w, y + h)); } /** * Returns an iteration object that defines the boundary of this * <code>Ellipse2D</code>. * The iterator for this class is multi-threaded safe, which means * that this <code>Ellipse2D</code> class guarantees that * modifications to the geometry of this <code>Ellipse2D</code> * object do not affect any iterations of that geometry that * are already in process. * @param at an optional <code>AffineTransform</code> to be applied to * the coordinates as they are returned in the iteration, or * <code>null</code> if untransformed coordinates are desired * @return the <code>PathIterator</code> object that returns the * geometry of the outline of this <code>Ellipse2D</code>, * one segment at a time. * @since 1.2 */ public PathIterator getPathIterator(AffineTransform at) { return new EllipseIterator(this, at); } /** * Returns the hashcode for this <code>Ellipse2D</code>. * @return the hashcode for this <code>Ellipse2D</code>. * @since 1.6 */ public int hashCode() {
// Path: src/gwt/awt/utils/HashCode.java // public class HashCode { // int hashcode = 1837269811; // // @Override // public int hashCode() { // return hashcode; // } // public void append(Double value) { // hashcode += (value.hashCode() * 32); // } // public void append(Integer value) { // hashcode += (value.hashCode() * 32); // } // } // Path: src/gwt/awt/geom/Ellipse2D.java import gwt.awt.utils.HashCode; import java.io.Serializable; contains(x, y + h) && contains(x + w, y + h)); } /** * Returns an iteration object that defines the boundary of this * <code>Ellipse2D</code>. * The iterator for this class is multi-threaded safe, which means * that this <code>Ellipse2D</code> class guarantees that * modifications to the geometry of this <code>Ellipse2D</code> * object do not affect any iterations of that geometry that * are already in process. * @param at an optional <code>AffineTransform</code> to be applied to * the coordinates as they are returned in the iteration, or * <code>null</code> if untransformed coordinates are desired * @return the <code>PathIterator</code> object that returns the * geometry of the outline of this <code>Ellipse2D</code>, * one segment at a time. * @since 1.2 */ public PathIterator getPathIterator(AffineTransform at) { return new EllipseIterator(this, at); } /** * Returns the hashcode for this <code>Ellipse2D</code>. * @return the hashcode for this <code>Ellipse2D</code>. * @since 1.6 */ public int hashCode() {
HashCode hashCode = new HashCode();
ustramooner/gwt-geom
src/gwt/awt/geom/Rectangle2D.java
// Path: src/gwt/awt/utils/HashCode.java // public class HashCode { // int hashcode = 1837269811; // // @Override // public int hashCode() { // return hashcode; // } // public void append(Double value) { // hashcode += (value.hashCode() * 32); // } // public void append(Integer value) { // hashcode += (value.hashCode() * 32); // } // }
import gwt.awt.utils.HashCode; import java.io.Serializable;
* Returns an iteration object that defines the boundary of the * flattened <code>Rectangle2D</code>. Since rectangles are already * flat, the <code>flatness</code> parameter is ignored. * The iterator for this class is multi-threaded safe, which means * that this <code>Rectangle2D</code> class guarantees that * modifications to the geometry of this <code>Rectangle2D</code> * object do not affect any iterations of that geometry that * are already in process. * @param at an optional <code>AffineTransform</code> to be applied to * the coordinates as they are returned in the iteration, or * <code>null</code> if untransformed coordinates are desired * @param flatness the maximum distance that the line segments used to * approximate the curved segments are allowed to deviate from any * point on the original curve. Since rectangles are already flat, * the <code>flatness</code> parameter is ignored. * @return the <code>PathIterator</code> object that returns the * geometry of the outline of this * <code>Rectangle2D</code>, one segment at a time. * @since 1.2 */ public PathIterator getPathIterator(AffineTransform at, double flatness) { return new RectIterator(this, at); } /** * Returns the hashcode for this <code>Rectangle2D</code>. * @return the hashcode for this <code>Rectangle2D</code>. * @since 1.2 */ public int hashCode() {
// Path: src/gwt/awt/utils/HashCode.java // public class HashCode { // int hashcode = 1837269811; // // @Override // public int hashCode() { // return hashcode; // } // public void append(Double value) { // hashcode += (value.hashCode() * 32); // } // public void append(Integer value) { // hashcode += (value.hashCode() * 32); // } // } // Path: src/gwt/awt/geom/Rectangle2D.java import gwt.awt.utils.HashCode; import java.io.Serializable; * Returns an iteration object that defines the boundary of the * flattened <code>Rectangle2D</code>. Since rectangles are already * flat, the <code>flatness</code> parameter is ignored. * The iterator for this class is multi-threaded safe, which means * that this <code>Rectangle2D</code> class guarantees that * modifications to the geometry of this <code>Rectangle2D</code> * object do not affect any iterations of that geometry that * are already in process. * @param at an optional <code>AffineTransform</code> to be applied to * the coordinates as they are returned in the iteration, or * <code>null</code> if untransformed coordinates are desired * @param flatness the maximum distance that the line segments used to * approximate the curved segments are allowed to deviate from any * point on the original curve. Since rectangles are already flat, * the <code>flatness</code> parameter is ignored. * @return the <code>PathIterator</code> object that returns the * geometry of the outline of this * <code>Rectangle2D</code>, one segment at a time. * @since 1.2 */ public PathIterator getPathIterator(AffineTransform at, double flatness) { return new RectIterator(this, at); } /** * Returns the hashcode for this <code>Rectangle2D</code>. * @return the hashcode for this <code>Rectangle2D</code>. * @since 1.2 */ public int hashCode() {
HashCode hashCode = new HashCode();
ustramooner/gwt-geom
src/gwt/awt/geom/RoundRectangle2D.java
// Path: src/gwt/awt/utils/HashCode.java // public class HashCode { // int hashcode = 1837269811; // // @Override // public int hashCode() { // return hashcode; // } // public void append(Double value) { // hashcode += (value.hashCode() * 32); // } // public void append(Integer value) { // hashcode += (value.hashCode() * 32); // } // }
import gwt.awt.utils.HashCode; import java.io.Serializable;
contains(x, y + h) && contains(x + w, y + h)); } /** * Returns an iteration object that defines the boundary of this * <code>RoundRectangle2D</code>. * The iterator for this class is multi-threaded safe, which means * that this <code>RoundRectangle2D</code> class guarantees that * modifications to the geometry of this <code>RoundRectangle2D</code> * object do not affect any iterations of that geometry that * are already in process. * @param at an optional <code>AffineTransform</code> to be applied to * the coordinates as they are returned in the iteration, or * <code>null</code> if untransformed coordinates are desired * @return the <code>PathIterator</code> object that returns the * geometry of the outline of this * <code>RoundRectangle2D</code>, one segment at a time. * @since 1.2 */ public PathIterator getPathIterator(AffineTransform at) { return new RoundRectIterator(this, at); } /** * Returns the hashcode for this <code>RoundRectangle2D</code>. * @return the hashcode for this <code>RoundRectangle2D</code>. * @since 1.6 */ public int hashCode() {
// Path: src/gwt/awt/utils/HashCode.java // public class HashCode { // int hashcode = 1837269811; // // @Override // public int hashCode() { // return hashcode; // } // public void append(Double value) { // hashcode += (value.hashCode() * 32); // } // public void append(Integer value) { // hashcode += (value.hashCode() * 32); // } // } // Path: src/gwt/awt/geom/RoundRectangle2D.java import gwt.awt.utils.HashCode; import java.io.Serializable; contains(x, y + h) && contains(x + w, y + h)); } /** * Returns an iteration object that defines the boundary of this * <code>RoundRectangle2D</code>. * The iterator for this class is multi-threaded safe, which means * that this <code>RoundRectangle2D</code> class guarantees that * modifications to the geometry of this <code>RoundRectangle2D</code> * object do not affect any iterations of that geometry that * are already in process. * @param at an optional <code>AffineTransform</code> to be applied to * the coordinates as they are returned in the iteration, or * <code>null</code> if untransformed coordinates are desired * @return the <code>PathIterator</code> object that returns the * geometry of the outline of this * <code>RoundRectangle2D</code>, one segment at a time. * @since 1.2 */ public PathIterator getPathIterator(AffineTransform at) { return new RoundRectIterator(this, at); } /** * Returns the hashcode for this <code>RoundRectangle2D</code>. * @return the hashcode for this <code>RoundRectangle2D</code>. * @since 1.6 */ public int hashCode() {
HashCode hashCode = new HashCode();
ustramooner/gwt-geom
src/gwt/awt/geom/Arc2D.java
// Path: src/gwt/awt/utils/HashCode.java // public class HashCode { // int hashcode = 1837269811; // // @Override // public int hashCode() { // return hashcode; // } // public void append(Double value) { // hashcode += (value.hashCode() * 32); // } // public void append(Integer value) { // hashcode += (value.hashCode() * 32); // } // }
import gwt.awt.utils.HashCode; import java.io.Serializable;
ye = yc + halfH * Math.sin(angle); return !origrect.intersectsLine(xc, yc, xe, ye); } /** * Returns an iteration object that defines the boundary of the * arc. * This iterator is multithread safe. * <code>Arc2D</code> guarantees that * modifications to the geometry of the arc * do not affect any iterations of that geometry that * are already in process. * * @param at an optional <CODE>AffineTransform</CODE> to be applied * to the coordinates as they are returned in the iteration, or null * if the untransformed coordinates are desired. * * @return A <CODE>PathIterator</CODE> that defines the arc's boundary. * @since 1.2 */ public PathIterator getPathIterator(AffineTransform at) { return new ArcIterator(this, at); } /** * Returns the hashcode for this <code>Arc2D</code>. * @return the hashcode for this <code>Arc2D</code>. * @since 1.6 */ public int hashCode() {
// Path: src/gwt/awt/utils/HashCode.java // public class HashCode { // int hashcode = 1837269811; // // @Override // public int hashCode() { // return hashcode; // } // public void append(Double value) { // hashcode += (value.hashCode() * 32); // } // public void append(Integer value) { // hashcode += (value.hashCode() * 32); // } // } // Path: src/gwt/awt/geom/Arc2D.java import gwt.awt.utils.HashCode; import java.io.Serializable; ye = yc + halfH * Math.sin(angle); return !origrect.intersectsLine(xc, yc, xe, ye); } /** * Returns an iteration object that defines the boundary of the * arc. * This iterator is multithread safe. * <code>Arc2D</code> guarantees that * modifications to the geometry of the arc * do not affect any iterations of that geometry that * are already in process. * * @param at an optional <CODE>AffineTransform</CODE> to be applied * to the coordinates as they are returned in the iteration, or null * if the untransformed coordinates are desired. * * @return A <CODE>PathIterator</CODE> that defines the arc's boundary. * @since 1.2 */ public PathIterator getPathIterator(AffineTransform at) { return new ArcIterator(this, at); } /** * Returns the hashcode for this <code>Arc2D</code>. * @return the hashcode for this <code>Arc2D</code>. * @since 1.6 */ public int hashCode() {
HashCode hashCode = new HashCode();
SunnyBat/PAXChecker
src/main/java/com/github/sunnybat/paxchecker/browser/PaxsiteReader.java
// Path: src/main/java/com/github/sunnybat/paxchecker/DataTracker.java // public class DataTracker { // // private static long dataUsed; // // /** // * Adds an amount of data (in bytes) used by the program. This should be called whenever a network // * connection is made. // * // * @param data The amount of data (in bytes) to add to the total data used // */ // public static synchronized void addDataUsed(long data) { // dataUsed += data; // } // // /** // * Gets the amount of data (in bytes) used by the program. // * // * @return The amount of data (in bytes) used by the program // */ // public static synchronized long getDataUsed() { // return dataUsed; // } // // /** // * Gets the amount of data in megabytes used by the program. Note that the double only extends out // * two decimal places. // * // * @return The amount of data in megabytes used by the program // */ // public static synchronized double getDataUsedMB() { // return (double) ((int) ((double) getDataUsed() / 1024 / 1024 * 100)) / 100; // *100 to make the double have two extra numbers, round with typecasting to integer, then divide that by 100 and typecast to double to get a double with two decimal places // } // } // // Path: src/main/java/com/github/sunnybat/paxchecker/Expo.java // public enum Expo { // // WEST, EAST, SOUTH, AUS; // // @Override // public String toString() { // String name = super.toString(); // return "PAX " + name.charAt(0) + name.toLowerCase().substring(1); // } // // public static Expo parseExpo(String expo) { // expo = expo.toLowerCase(); // if (expo.contains("prime") || expo.contains("west")) { // return WEST; // } else if (expo.contains("east")) { // return EAST; // } else if (expo.contains("south")) { // return SOUTH; // } else if (expo.contains("aus")) { // return AUS; // } else { // throw new IllegalArgumentException("No expo found"); // } // } // }
import com.github.sunnybat.commoncode.error.ErrorBuilder; import com.github.sunnybat.paxchecker.DataTracker; import com.github.sunnybat.paxchecker.Expo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.SocketTimeoutException; import java.net.URL; import java.net.UnknownHostException;
package com.github.sunnybat.paxchecker.browser; /** * * @author Sunny */ public class PaxsiteReader { private Expo expoToCheck; /** * Creates a new PaxsiteReader for the given Expo. If toCheck is null, this defaults to Expo.WEST. * * @param toCheck The Expo to check */ public PaxsiteReader(Expo toCheck) { if (toCheck == null) { toCheck = Expo.WEST; } expoToCheck = toCheck; } /** * Gets the current Showclix link on the registration page. * * @return The first Showclix link found, or "[STATUS]" if an exception occurs */ public String getCurrentShowclixLink() { try { URL urlToConnectTo = new URL(getWebsiteLink(expoToCheck) + "/registration"); String link = findShowclixLink(urlToConnectTo); return link; } catch (MalformedURLException mue) { } return "[NoConnection]"; } /** * Finds the first Showclix link on the given page. * * @param urlToConnectTo The URL to connect to * @return The first Showclix link found, or "[STATUS]" if an exception occurs. */ private String findShowclixLink(URL urlToConnectTo) { BufferedReader lineReader = null; try { String line; lineReader = setUpConnection(urlToConnectTo); while ((line = lineReader.readLine()) != null) {
// Path: src/main/java/com/github/sunnybat/paxchecker/DataTracker.java // public class DataTracker { // // private static long dataUsed; // // /** // * Adds an amount of data (in bytes) used by the program. This should be called whenever a network // * connection is made. // * // * @param data The amount of data (in bytes) to add to the total data used // */ // public static synchronized void addDataUsed(long data) { // dataUsed += data; // } // // /** // * Gets the amount of data (in bytes) used by the program. // * // * @return The amount of data (in bytes) used by the program // */ // public static synchronized long getDataUsed() { // return dataUsed; // } // // /** // * Gets the amount of data in megabytes used by the program. Note that the double only extends out // * two decimal places. // * // * @return The amount of data in megabytes used by the program // */ // public static synchronized double getDataUsedMB() { // return (double) ((int) ((double) getDataUsed() / 1024 / 1024 * 100)) / 100; // *100 to make the double have two extra numbers, round with typecasting to integer, then divide that by 100 and typecast to double to get a double with two decimal places // } // } // // Path: src/main/java/com/github/sunnybat/paxchecker/Expo.java // public enum Expo { // // WEST, EAST, SOUTH, AUS; // // @Override // public String toString() { // String name = super.toString(); // return "PAX " + name.charAt(0) + name.toLowerCase().substring(1); // } // // public static Expo parseExpo(String expo) { // expo = expo.toLowerCase(); // if (expo.contains("prime") || expo.contains("west")) { // return WEST; // } else if (expo.contains("east")) { // return EAST; // } else if (expo.contains("south")) { // return SOUTH; // } else if (expo.contains("aus")) { // return AUS; // } else { // throw new IllegalArgumentException("No expo found"); // } // } // } // Path: src/main/java/com/github/sunnybat/paxchecker/browser/PaxsiteReader.java import com.github.sunnybat.commoncode.error.ErrorBuilder; import com.github.sunnybat.paxchecker.DataTracker; import com.github.sunnybat.paxchecker.Expo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.SocketTimeoutException; import java.net.URL; import java.net.UnknownHostException; package com.github.sunnybat.paxchecker.browser; /** * * @author Sunny */ public class PaxsiteReader { private Expo expoToCheck; /** * Creates a new PaxsiteReader for the given Expo. If toCheck is null, this defaults to Expo.WEST. * * @param toCheck The Expo to check */ public PaxsiteReader(Expo toCheck) { if (toCheck == null) { toCheck = Expo.WEST; } expoToCheck = toCheck; } /** * Gets the current Showclix link on the registration page. * * @return The first Showclix link found, or "[STATUS]" if an exception occurs */ public String getCurrentShowclixLink() { try { URL urlToConnectTo = new URL(getWebsiteLink(expoToCheck) + "/registration"); String link = findShowclixLink(urlToConnectTo); return link; } catch (MalformedURLException mue) { } return "[NoConnection]"; } /** * Finds the first Showclix link on the given page. * * @param urlToConnectTo The URL to connect to * @return The first Showclix link found, or "[STATUS]" if an exception occurs. */ private String findShowclixLink(URL urlToConnectTo) { BufferedReader lineReader = null; try { String line; lineReader = setUpConnection(urlToConnectTo); while ((line = lineReader.readLine()) != null) {
DataTracker.addDataUsed(line.length());
SunnyBat/PAXChecker
src/main/java/com/github/sunnybat/paxchecker/notification/NotificationHandler.java
// Path: src/main/java/com/github/sunnybat/paxchecker/DataTracker.java // public class DataTracker { // // private static long dataUsed; // // /** // * Adds an amount of data (in bytes) used by the program. This should be called whenever a network // * connection is made. // * // * @param data The amount of data (in bytes) to add to the total data used // */ // public static synchronized void addDataUsed(long data) { // dataUsed += data; // } // // /** // * Gets the amount of data (in bytes) used by the program. // * // * @return The amount of data (in bytes) used by the program // */ // public static synchronized long getDataUsed() { // return dataUsed; // } // // /** // * Gets the amount of data in megabytes used by the program. Note that the double only extends out // * two decimal places. // * // * @return The amount of data in megabytes used by the program // */ // public static synchronized double getDataUsedMB() { // return (double) ((int) ((double) getDataUsed() / 1024 / 1024 * 100)) / 100; // *100 to make the double have two extra numbers, round with typecasting to integer, then divide that by 100 and typecast to double to get a double with two decimal places // } // }
import com.github.sunnybat.commoncode.error.ErrorBuilder; import com.github.sunnybat.paxchecker.DataTracker; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.concurrent.CountDownLatch;
anonymousStatistics = true; } public void setHeadless() { isHeadless = true; } /** * This loads all new notifications. This method will block until complete. */ public void loadNotifications() { if (lastNotificationID.equals("DISABLE")) { return; } URLConnection inputConnection; InputStream textInputStream; BufferedReader myReader = null; try { URL notificationURL; if (anonymousStatistics) { notificationURL = new URL(NOTIFICATIONS_LINK_ANONYMOUS); } else { notificationURL = new URL(NOTIFICATIONS_LINK); } inputConnection = notificationURL.openConnection(); textInputStream = inputConnection.getInputStream(); myReader = new BufferedReader(new InputStreamReader(textInputStream)); String line; Notification currNotification = null; while ((line = myReader.readLine()) != null) {
// Path: src/main/java/com/github/sunnybat/paxchecker/DataTracker.java // public class DataTracker { // // private static long dataUsed; // // /** // * Adds an amount of data (in bytes) used by the program. This should be called whenever a network // * connection is made. // * // * @param data The amount of data (in bytes) to add to the total data used // */ // public static synchronized void addDataUsed(long data) { // dataUsed += data; // } // // /** // * Gets the amount of data (in bytes) used by the program. // * // * @return The amount of data (in bytes) used by the program // */ // public static synchronized long getDataUsed() { // return dataUsed; // } // // /** // * Gets the amount of data in megabytes used by the program. Note that the double only extends out // * two decimal places. // * // * @return The amount of data in megabytes used by the program // */ // public static synchronized double getDataUsedMB() { // return (double) ((int) ((double) getDataUsed() / 1024 / 1024 * 100)) / 100; // *100 to make the double have two extra numbers, round with typecasting to integer, then divide that by 100 and typecast to double to get a double with two decimal places // } // } // Path: src/main/java/com/github/sunnybat/paxchecker/notification/NotificationHandler.java import com.github.sunnybat.commoncode.error.ErrorBuilder; import com.github.sunnybat.paxchecker.DataTracker; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.concurrent.CountDownLatch; anonymousStatistics = true; } public void setHeadless() { isHeadless = true; } /** * This loads all new notifications. This method will block until complete. */ public void loadNotifications() { if (lastNotificationID.equals("DISABLE")) { return; } URLConnection inputConnection; InputStream textInputStream; BufferedReader myReader = null; try { URL notificationURL; if (anonymousStatistics) { notificationURL = new URL(NOTIFICATIONS_LINK_ANONYMOUS); } else { notificationURL = new URL(NOTIFICATIONS_LINK); } inputConnection = notificationURL.openConnection(); textInputStream = inputConnection.getInputStream(); myReader = new BufferedReader(new InputStreamReader(textInputStream)); String line; Notification currNotification = null; while ((line = myReader.readLine()) != null) {
DataTracker.addDataUsed(line.length());
SunnyBat/PAXChecker
src/main/java/com/github/sunnybat/paxchecker/Audio.java
// Path: src/main/java/com/github/sunnybat/paxchecker/resources/ResourceLoader.java // public class ResourceLoader { // // /** // * Attempts to load the given file from the PAXChecker resources. // * // * @param fileName The name of the file to load // * @return The InputStream containing the File // * @throws FileNotFoundException If the file does not exist // */ // public static InputStream loadResource(String fileName) throws FileNotFoundException { // File inputFile = new File(ResourceConstants.RESOURCE_LOCATION + fileName); // InputStream in = new java.io.FileInputStream(inputFile); // return in; // } // // }
import com.github.sunnybat.commoncode.error.ErrorBuilder; import com.github.sunnybat.paxchecker.resources.ResourceLoader; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.DataLine; import javax.sound.sampled.LineEvent; import javax.sound.sampled.LineListener; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException;
new ErrorBuilder() .setErrorTitle("Cannot use audio file") .setErrorMessage("Currently, the only supported alarm audio format is .WAV files. If you would like" + " to see support for other audio formats, let me know!") .buildWindow(); } else { Audio.alarmFile = alarmFile; System.out.println("Set alarm file to " + alarmFile.getName()); } } /** * Plays the alarm. Note that this checks {@link #soundEnabled()} to make sure it's supposed to * play. This method only allows one sound to play at a time, and resets the sound currently * playing to the beginning. * * @return True if the alarm was successfully started, false if not */ public static boolean playAlarm() { if (!playSound) { return false; } try { if (clip != null) { clip.stop(); } InputStream audioSrc; if (alarmFile != null) { audioSrc = new FileInputStream(alarmFile); } else {
// Path: src/main/java/com/github/sunnybat/paxchecker/resources/ResourceLoader.java // public class ResourceLoader { // // /** // * Attempts to load the given file from the PAXChecker resources. // * // * @param fileName The name of the file to load // * @return The InputStream containing the File // * @throws FileNotFoundException If the file does not exist // */ // public static InputStream loadResource(String fileName) throws FileNotFoundException { // File inputFile = new File(ResourceConstants.RESOURCE_LOCATION + fileName); // InputStream in = new java.io.FileInputStream(inputFile); // return in; // } // // } // Path: src/main/java/com/github/sunnybat/paxchecker/Audio.java import com.github.sunnybat.commoncode.error.ErrorBuilder; import com.github.sunnybat.paxchecker.resources.ResourceLoader; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.DataLine; import javax.sound.sampled.LineEvent; import javax.sound.sampled.LineListener; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; new ErrorBuilder() .setErrorTitle("Cannot use audio file") .setErrorMessage("Currently, the only supported alarm audio format is .WAV files. If you would like" + " to see support for other audio formats, let me know!") .buildWindow(); } else { Audio.alarmFile = alarmFile; System.out.println("Set alarm file to " + alarmFile.getName()); } } /** * Plays the alarm. Note that this checks {@link #soundEnabled()} to make sure it's supposed to * play. This method only allows one sound to play at a time, and resets the sound currently * playing to the beginning. * * @return True if the alarm was successfully started, false if not */ public static boolean playAlarm() { if (!playSound) { return false; } try { if (clip != null) { clip.stop(); } InputStream audioSrc; if (alarmFile != null) { audioSrc = new FileInputStream(alarmFile); } else {
audioSrc = ResourceLoader.loadResource("Alarm.wav");
SunnyBat/PAXChecker
src/main/java/com/github/sunnybat/paxchecker/browser/ShowclixReader.java
// Path: src/main/java/com/github/sunnybat/paxchecker/DataTracker.java // public class DataTracker { // // private static long dataUsed; // // /** // * Adds an amount of data (in bytes) used by the program. This should be called whenever a network // * connection is made. // * // * @param data The amount of data (in bytes) to add to the total data used // */ // public static synchronized void addDataUsed(long data) { // dataUsed += data; // } // // /** // * Gets the amount of data (in bytes) used by the program. // * // * @return The amount of data (in bytes) used by the program // */ // public static synchronized long getDataUsed() { // return dataUsed; // } // // /** // * Gets the amount of data in megabytes used by the program. Note that the double only extends out // * two decimal places. // * // * @return The amount of data in megabytes used by the program // */ // public static synchronized double getDataUsedMB() { // return (double) ((int) ((double) getDataUsed() / 1024 / 1024 * 100)) / 100; // *100 to make the double have two extra numbers, round with typecasting to integer, then divide that by 100 and typecast to double to get a double with two decimal places // } // } // // Path: src/main/java/com/github/sunnybat/paxchecker/Expo.java // public enum Expo { // // WEST, EAST, SOUTH, AUS; // // @Override // public String toString() { // String name = super.toString(); // return "PAX " + name.charAt(0) + name.toLowerCase().substring(1); // } // // public static Expo parseExpo(String expo) { // expo = expo.toLowerCase(); // if (expo.contains("prime") || expo.contains("west")) { // return WEST; // } else if (expo.contains("east")) { // return EAST; // } else if (expo.contains("south")) { // return SOUTH; // } else if (expo.contains("aus")) { // return AUS; // } else { // throw new IllegalArgumentException("No expo found"); // } // } // }
import com.github.sunnybat.paxchecker.DataTracker; import com.github.sunnybat.paxchecker.Expo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.Set; import java.util.TreeSet; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException;
package com.github.sunnybat.paxchecker.browser; /** * * @author Sunny */ public class ShowclixReader { private static final String API_LINK_BASE = "https://api.showclix.com/"; private static final String API_EXTENSION_SELLER = "Seller/"; private static final String API_EXTENSION_PARTNER = "Partner/"; private static final String API_EXTENSION_VENUE = "Venue/"; private static final String API_EXTENSION_EVENT = "Event/"; private static final String EVENT_LINK_BASE = "https://www.showclix.com/event/"; private static final String EVENTS_ATTRIBUTE_LINK = "?follow[]=events"; private boolean strictFiltering;
// Path: src/main/java/com/github/sunnybat/paxchecker/DataTracker.java // public class DataTracker { // // private static long dataUsed; // // /** // * Adds an amount of data (in bytes) used by the program. This should be called whenever a network // * connection is made. // * // * @param data The amount of data (in bytes) to add to the total data used // */ // public static synchronized void addDataUsed(long data) { // dataUsed += data; // } // // /** // * Gets the amount of data (in bytes) used by the program. // * // * @return The amount of data (in bytes) used by the program // */ // public static synchronized long getDataUsed() { // return dataUsed; // } // // /** // * Gets the amount of data in megabytes used by the program. Note that the double only extends out // * two decimal places. // * // * @return The amount of data in megabytes used by the program // */ // public static synchronized double getDataUsedMB() { // return (double) ((int) ((double) getDataUsed() / 1024 / 1024 * 100)) / 100; // *100 to make the double have two extra numbers, round with typecasting to integer, then divide that by 100 and typecast to double to get a double with two decimal places // } // } // // Path: src/main/java/com/github/sunnybat/paxchecker/Expo.java // public enum Expo { // // WEST, EAST, SOUTH, AUS; // // @Override // public String toString() { // String name = super.toString(); // return "PAX " + name.charAt(0) + name.toLowerCase().substring(1); // } // // public static Expo parseExpo(String expo) { // expo = expo.toLowerCase(); // if (expo.contains("prime") || expo.contains("west")) { // return WEST; // } else if (expo.contains("east")) { // return EAST; // } else if (expo.contains("south")) { // return SOUTH; // } else if (expo.contains("aus")) { // return AUS; // } else { // throw new IllegalArgumentException("No expo found"); // } // } // } // Path: src/main/java/com/github/sunnybat/paxchecker/browser/ShowclixReader.java import com.github.sunnybat.paxchecker.DataTracker; import com.github.sunnybat.paxchecker.Expo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.Set; import java.util.TreeSet; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; package com.github.sunnybat.paxchecker.browser; /** * * @author Sunny */ public class ShowclixReader { private static final String API_LINK_BASE = "https://api.showclix.com/"; private static final String API_EXTENSION_SELLER = "Seller/"; private static final String API_EXTENSION_PARTNER = "Partner/"; private static final String API_EXTENSION_VENUE = "Venue/"; private static final String API_EXTENSION_EVENT = "Event/"; private static final String EVENT_LINK_BASE = "https://www.showclix.com/event/"; private static final String EVENTS_ATTRIBUTE_LINK = "?follow[]=events"; private boolean strictFiltering;
private Expo expoToCheck;
SunnyBat/PAXChecker
src/main/java/com/github/sunnybat/paxchecker/browser/ShowclixReader.java
// Path: src/main/java/com/github/sunnybat/paxchecker/DataTracker.java // public class DataTracker { // // private static long dataUsed; // // /** // * Adds an amount of data (in bytes) used by the program. This should be called whenever a network // * connection is made. // * // * @param data The amount of data (in bytes) to add to the total data used // */ // public static synchronized void addDataUsed(long data) { // dataUsed += data; // } // // /** // * Gets the amount of data (in bytes) used by the program. // * // * @return The amount of data (in bytes) used by the program // */ // public static synchronized long getDataUsed() { // return dataUsed; // } // // /** // * Gets the amount of data in megabytes used by the program. Note that the double only extends out // * two decimal places. // * // * @return The amount of data in megabytes used by the program // */ // public static synchronized double getDataUsedMB() { // return (double) ((int) ((double) getDataUsed() / 1024 / 1024 * 100)) / 100; // *100 to make the double have two extra numbers, round with typecasting to integer, then divide that by 100 and typecast to double to get a double with two decimal places // } // } // // Path: src/main/java/com/github/sunnybat/paxchecker/Expo.java // public enum Expo { // // WEST, EAST, SOUTH, AUS; // // @Override // public String toString() { // String name = super.toString(); // return "PAX " + name.charAt(0) + name.toLowerCase().substring(1); // } // // public static Expo parseExpo(String expo) { // expo = expo.toLowerCase(); // if (expo.contains("prime") || expo.contains("west")) { // return WEST; // } else if (expo.contains("east")) { // return EAST; // } else if (expo.contains("south")) { // return SOUTH; // } else if (expo.contains("aus")) { // return AUS; // } else { // throw new IllegalArgumentException("No expo found"); // } // } // }
import com.github.sunnybat.paxchecker.DataTracker; import com.github.sunnybat.paxchecker.Expo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.Set; import java.util.TreeSet; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException;
case WEST: return 13961; case EAST: return 16418; case SOUTH: return 20012; case AUS: return 15820; default: System.out.println("SR: Unknown expo: " + expo); return 13961; } } /** * Reads the JSON from the given URL. Note that this does NOT check whether or not this page * contains valid JSON text. This method will also attempt to fix any invalid JSON found. This * only fixes known JSON parsing errors. * * @param url The URL to parse from * @return The (fixed) text from the page */ private static String readJSONFromURL(URL url) { try { HttpURLConnection httpCon = Browser.setUpConnection(url); httpCon.setConnectTimeout(500); BufferedReader reader = new BufferedReader(new InputStreamReader(httpCon.getInputStream())); StringBuilder build = new StringBuilder(); String line; while ((line = reader.readLine()) != null) {
// Path: src/main/java/com/github/sunnybat/paxchecker/DataTracker.java // public class DataTracker { // // private static long dataUsed; // // /** // * Adds an amount of data (in bytes) used by the program. This should be called whenever a network // * connection is made. // * // * @param data The amount of data (in bytes) to add to the total data used // */ // public static synchronized void addDataUsed(long data) { // dataUsed += data; // } // // /** // * Gets the amount of data (in bytes) used by the program. // * // * @return The amount of data (in bytes) used by the program // */ // public static synchronized long getDataUsed() { // return dataUsed; // } // // /** // * Gets the amount of data in megabytes used by the program. Note that the double only extends out // * two decimal places. // * // * @return The amount of data in megabytes used by the program // */ // public static synchronized double getDataUsedMB() { // return (double) ((int) ((double) getDataUsed() / 1024 / 1024 * 100)) / 100; // *100 to make the double have two extra numbers, round with typecasting to integer, then divide that by 100 and typecast to double to get a double with two decimal places // } // } // // Path: src/main/java/com/github/sunnybat/paxchecker/Expo.java // public enum Expo { // // WEST, EAST, SOUTH, AUS; // // @Override // public String toString() { // String name = super.toString(); // return "PAX " + name.charAt(0) + name.toLowerCase().substring(1); // } // // public static Expo parseExpo(String expo) { // expo = expo.toLowerCase(); // if (expo.contains("prime") || expo.contains("west")) { // return WEST; // } else if (expo.contains("east")) { // return EAST; // } else if (expo.contains("south")) { // return SOUTH; // } else if (expo.contains("aus")) { // return AUS; // } else { // throw new IllegalArgumentException("No expo found"); // } // } // } // Path: src/main/java/com/github/sunnybat/paxchecker/browser/ShowclixReader.java import com.github.sunnybat.paxchecker.DataTracker; import com.github.sunnybat.paxchecker.Expo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.Set; import java.util.TreeSet; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; case WEST: return 13961; case EAST: return 16418; case SOUTH: return 20012; case AUS: return 15820; default: System.out.println("SR: Unknown expo: " + expo); return 13961; } } /** * Reads the JSON from the given URL. Note that this does NOT check whether or not this page * contains valid JSON text. This method will also attempt to fix any invalid JSON found. This * only fixes known JSON parsing errors. * * @param url The URL to parse from * @return The (fixed) text from the page */ private static String readJSONFromURL(URL url) { try { HttpURLConnection httpCon = Browser.setUpConnection(url); httpCon.setConnectTimeout(500); BufferedReader reader = new BufferedReader(new InputStreamReader(httpCon.getInputStream())); StringBuilder build = new StringBuilder(); String line; while ((line = reader.readLine()) != null) {
DataTracker.addDataUsed(line.length());
SunnyBat/PAXChecker
src/main/java/com/github/sunnybat/paxchecker/setup/email/AuthGmail.java
// Path: src/main/java/com/github/sunnybat/paxchecker/resources/ResourceConstants.java // public class ResourceConstants { // // /** // * The path to the folder that resources are stored in. Contains a trailing Line.Separator. // */ // public static final String RESOURCE_LOCATION = getResourceLocation(); // public static final String CLIENT_SECRET_JSON_PATH = "com/github/sunnybat/paxchecker/resources/keys/client_secret.json"; // public static final String TWITTER_KEYS_PATH = "com/github/sunnybat/paxchecker/resources/keys/twitter_secret.ini"; // public static final Map<String, String> DEFAULT_FILE_INFO = getDefaultFileInfo(); // // private static Map<String, String> getDefaultFileInfo() { // TODO: Better method than this... Probably file with constants // Map<String, String> ret = new TreeMap<>(); // ret.put("Alarm.wav", "https://www.dropbox.com/s/9s1frqkgduv226s/Alarm.wav?dl=1"); // ret.put("Alert.png", "https://www.dropbox.com/s/xv1g1f2bzttv3kv/alert.png?dl=1"); // ret.put("PAXWest.png", "https://www.dropbox.com/s/nu6iavrdggv64df/PAXWest.png?dl=1"); // ret.put("PAXEast.png", "https://www.dropbox.com/s/fv3rawxyyc0ihbl/PAXEast.png?dl=1"); // ret.put("PAXSouth.png", "https://www.dropbox.com/s/gku3zea8529b3co/PAXSouth.png?dl=1"); // ret.put("PAXAus.png", "https://www.dropbox.com/s/gku3zea8529b3co/PAXSouth.png?dl=1"); // return ret; // } // // private static String getResourceLocation() { // String os = System.getProperty("os.name").toLowerCase(); // if (os.contains("windows")) { // return System.getenv("APPDATA") + "/PAXChecker/"; // Has / and \ in path, but Java apparently doesn't care // } else if (os.contains("mac")) { // System.out.println("RD PATH: " + System.getProperty("user.home") + "/Library/Application Support/PAXChecker/"); // return System.getProperty("user.home") + "/Library/Application Support/PAXChecker/"; // } else if (os.contains("linux") || os.contains("ubuntu")) { // return System.getProperty("user.home") + "/.PAXChecker/"; // } else { // Store in current folder, we have no clue what OS this is // return "PAXChecker/"; // } // } // // }
import com.github.sunnybat.commoncode.email.account.GmailAccount; import com.github.sunnybat.commoncode.error.ErrorBuilder; import com.github.sunnybat.commoncode.oauth.OauthStatusUpdater; import com.github.sunnybat.paxchecker.resources.ResourceConstants; import java.awt.Color; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.datatransfer.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.io.IOException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import javax.swing.GroupLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; import javax.swing.LayoutStyle; import javax.swing.SwingUtilities; import javax.swing.SwingWorker;
@Override public void recordCurrentFields() { savedGmailAccount = currentGmailAccount; } @Override public void resetChanges() { currentGmailAccount = savedGmailAccount; updatePanel(isAuthenticated()); } @Override public boolean isAuthenticated() { return currentGmailAccount != null; } @Override public GmailAccount getEmailAccount() { return currentGmailAccount; } public void authenticate() { try { authWithoutWait(true).get(); } catch (InterruptedException | ExecutionException e) { } } private AuthenticationWorker authWithoutWait(boolean failIfNoAutoAuth) { authCallback.run();
// Path: src/main/java/com/github/sunnybat/paxchecker/resources/ResourceConstants.java // public class ResourceConstants { // // /** // * The path to the folder that resources are stored in. Contains a trailing Line.Separator. // */ // public static final String RESOURCE_LOCATION = getResourceLocation(); // public static final String CLIENT_SECRET_JSON_PATH = "com/github/sunnybat/paxchecker/resources/keys/client_secret.json"; // public static final String TWITTER_KEYS_PATH = "com/github/sunnybat/paxchecker/resources/keys/twitter_secret.ini"; // public static final Map<String, String> DEFAULT_FILE_INFO = getDefaultFileInfo(); // // private static Map<String, String> getDefaultFileInfo() { // TODO: Better method than this... Probably file with constants // Map<String, String> ret = new TreeMap<>(); // ret.put("Alarm.wav", "https://www.dropbox.com/s/9s1frqkgduv226s/Alarm.wav?dl=1"); // ret.put("Alert.png", "https://www.dropbox.com/s/xv1g1f2bzttv3kv/alert.png?dl=1"); // ret.put("PAXWest.png", "https://www.dropbox.com/s/nu6iavrdggv64df/PAXWest.png?dl=1"); // ret.put("PAXEast.png", "https://www.dropbox.com/s/fv3rawxyyc0ihbl/PAXEast.png?dl=1"); // ret.put("PAXSouth.png", "https://www.dropbox.com/s/gku3zea8529b3co/PAXSouth.png?dl=1"); // ret.put("PAXAus.png", "https://www.dropbox.com/s/gku3zea8529b3co/PAXSouth.png?dl=1"); // return ret; // } // // private static String getResourceLocation() { // String os = System.getProperty("os.name").toLowerCase(); // if (os.contains("windows")) { // return System.getenv("APPDATA") + "/PAXChecker/"; // Has / and \ in path, but Java apparently doesn't care // } else if (os.contains("mac")) { // System.out.println("RD PATH: " + System.getProperty("user.home") + "/Library/Application Support/PAXChecker/"); // return System.getProperty("user.home") + "/Library/Application Support/PAXChecker/"; // } else if (os.contains("linux") || os.contains("ubuntu")) { // return System.getProperty("user.home") + "/.PAXChecker/"; // } else { // Store in current folder, we have no clue what OS this is // return "PAXChecker/"; // } // } // // } // Path: src/main/java/com/github/sunnybat/paxchecker/setup/email/AuthGmail.java import com.github.sunnybat.commoncode.email.account.GmailAccount; import com.github.sunnybat.commoncode.error.ErrorBuilder; import com.github.sunnybat.commoncode.oauth.OauthStatusUpdater; import com.github.sunnybat.paxchecker.resources.ResourceConstants; import java.awt.Color; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.datatransfer.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.io.IOException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import javax.swing.GroupLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; import javax.swing.LayoutStyle; import javax.swing.SwingUtilities; import javax.swing.SwingWorker; @Override public void recordCurrentFields() { savedGmailAccount = currentGmailAccount; } @Override public void resetChanges() { currentGmailAccount = savedGmailAccount; updatePanel(isAuthenticated()); } @Override public boolean isAuthenticated() { return currentGmailAccount != null; } @Override public GmailAccount getEmailAccount() { return currentGmailAccount; } public void authenticate() { try { authWithoutWait(true).get(); } catch (InterruptedException | ExecutionException e) { } } private AuthenticationWorker authWithoutWait(boolean failIfNoAutoAuth) { authCallback.run();
currentGmailAccount = new GmailAccount("PAXChecker", ResourceConstants.RESOURCE_LOCATION, ResourceConstants.CLIENT_SECRET_JSON_PATH);
onesocialweb/osw-openfire-plugin
src/java/org/onesocialweb/openfire/model/vcard4/PersistentTelField.java
// Path: src/java/org/onesocialweb/openfire/model/acl/PersistentAclRule.java // @Entity(name="AclRule") // public class PersistentAclRule implements AclRule { // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclSubject.class, fetch=FetchType.EAGER) // private List<AclSubject> subjects = new ArrayList<AclSubject>(); // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclAction.class, fetch=FetchType.EAGER) // private List<AclAction> actions = new ArrayList<AclAction>(); // // @Override // public List<AclAction> getActions() { // return actions; // } // // @Override // public void setActions(List<AclAction> actions) { // this.actions = actions; // } // // @Override // public List<AclSubject> getSubjects() { // return subjects; // } // // @Override // public void setSubjects(List<AclSubject> subjects) { // this.subjects = subjects; // } // // @Override // public void addAction(AclAction action) { // this.actions.add(action); // } // // @Override // public void addSubject(AclSubject subject) { // this.subjects.add(subject); // } // // @Override // public void removeAction(AclAction action) { // this.actions.remove(action); // } // // @Override // public void removeSubject(AclSubject subject) { // this.subjects.remove(subject); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof AclRule) { // AclRule rule = (AclRule) obj; // return actions.equals(rule.getActions()) // && subjects.equals(rule.getSubjects()); // } else { // return false; // } // } // // @Override // public String toString() { // StringBuffer buffer = new StringBuffer(); // buffer.append("[AclRule "); // for (AclAction action : actions) { // buffer.append(action); // } // for (AclSubject subject : subjects) { // buffer.append(subject); // } // buffer.append("]"); // return buffer.toString(); // } // // @Override // public boolean hasAction(AclAction action) { // if (actions == null || action == null) return false; // // for (AclAction target : actions) { // if (target.equals(action)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasSubject(AclSubject subject) { // if (subjects == null || subject == null) return false; // // for (AclSubject target : subjects) { // if (target.equals(subject)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasActions() { // return (actions != null && !actions.isEmpty()); // } // // @Override // public boolean hasSubjects() { // return (subjects != null && !subjects.isEmpty()); // } // // @Override // public List<AclAction> getActions(String name, String permission) { // List<AclAction> result = new ArrayList<AclAction>(); // // if (actions == null) return result; // // for (AclAction target : actions) { // if (target.getName().equals(name) && target.getPermission().equals(permission)) { // result.add(target); // } // } // // return result; // } // // @Override // public List<AclSubject> getSubjects(String type) { // List<AclSubject> result = new ArrayList<AclSubject>(); // // if (subjects == null || type == null) return result; // // for (AclSubject aclSubject : result) { // if (aclSubject.getType().equals(type)) { // result.add(aclSubject); // } // } // // return result; // } // // }
import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.OneToMany; import org.onesocialweb.model.acl.AclRule; import org.onesocialweb.model.vcard4.TelField; import org.onesocialweb.openfire.model.acl.PersistentAclRule;
package org.onesocialweb.openfire.model.vcard4; @Entity(name="TelField") public class PersistentTelField extends TelField{
// Path: src/java/org/onesocialweb/openfire/model/acl/PersistentAclRule.java // @Entity(name="AclRule") // public class PersistentAclRule implements AclRule { // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclSubject.class, fetch=FetchType.EAGER) // private List<AclSubject> subjects = new ArrayList<AclSubject>(); // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclAction.class, fetch=FetchType.EAGER) // private List<AclAction> actions = new ArrayList<AclAction>(); // // @Override // public List<AclAction> getActions() { // return actions; // } // // @Override // public void setActions(List<AclAction> actions) { // this.actions = actions; // } // // @Override // public List<AclSubject> getSubjects() { // return subjects; // } // // @Override // public void setSubjects(List<AclSubject> subjects) { // this.subjects = subjects; // } // // @Override // public void addAction(AclAction action) { // this.actions.add(action); // } // // @Override // public void addSubject(AclSubject subject) { // this.subjects.add(subject); // } // // @Override // public void removeAction(AclAction action) { // this.actions.remove(action); // } // // @Override // public void removeSubject(AclSubject subject) { // this.subjects.remove(subject); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof AclRule) { // AclRule rule = (AclRule) obj; // return actions.equals(rule.getActions()) // && subjects.equals(rule.getSubjects()); // } else { // return false; // } // } // // @Override // public String toString() { // StringBuffer buffer = new StringBuffer(); // buffer.append("[AclRule "); // for (AclAction action : actions) { // buffer.append(action); // } // for (AclSubject subject : subjects) { // buffer.append(subject); // } // buffer.append("]"); // return buffer.toString(); // } // // @Override // public boolean hasAction(AclAction action) { // if (actions == null || action == null) return false; // // for (AclAction target : actions) { // if (target.equals(action)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasSubject(AclSubject subject) { // if (subjects == null || subject == null) return false; // // for (AclSubject target : subjects) { // if (target.equals(subject)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasActions() { // return (actions != null && !actions.isEmpty()); // } // // @Override // public boolean hasSubjects() { // return (subjects != null && !subjects.isEmpty()); // } // // @Override // public List<AclAction> getActions(String name, String permission) { // List<AclAction> result = new ArrayList<AclAction>(); // // if (actions == null) return result; // // for (AclAction target : actions) { // if (target.getName().equals(name) && target.getPermission().equals(permission)) { // result.add(target); // } // } // // return result; // } // // @Override // public List<AclSubject> getSubjects(String type) { // List<AclSubject> result = new ArrayList<AclSubject>(); // // if (subjects == null || type == null) return result; // // for (AclSubject aclSubject : result) { // if (aclSubject.getType().equals(type)) { // result.add(aclSubject); // } // } // // return result; // } // // } // Path: src/java/org/onesocialweb/openfire/model/vcard4/PersistentTelField.java import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.OneToMany; import org.onesocialweb.model.acl.AclRule; import org.onesocialweb.model.vcard4.TelField; import org.onesocialweb.openfire.model.acl.PersistentAclRule; package org.onesocialweb.openfire.model.vcard4; @Entity(name="TelField") public class PersistentTelField extends TelField{
@OneToMany(cascade=CascadeType.ALL, targetEntity=PersistentAclRule.class, fetch=FetchType.EAGER)
onesocialweb/osw-openfire-plugin
src/java/org/onesocialweb/openfire/handler/activity/PEPActivityHandler.java
// Path: src/java/org/onesocialweb/openfire/handler/pep/PEPCommandHandler.java // public abstract class PEPCommandHandler extends BasicModule { // // /** // * Create a basic module with the given name. // * // * @param moduleName The name for the module or null to use the default // */ // public PEPCommandHandler(String moduleName) { // super(moduleName); // } // // public abstract IQ handleIQ(IQ packet) throws UnauthorizedException; // // public abstract String getCommand(); // // } // // Path: src/java/org/onesocialweb/openfire/handler/pep/PEPNodeHandler.java // public abstract class PEPNodeHandler extends BasicModule { // // /** // * Create a basic module with the given name. // * // * @param moduleName The name for the module or null to use the default // */ // public PEPNodeHandler(String moduleName) { // super(moduleName); // } // // public abstract IQ handleIQ(IQ packet) throws UnauthorizedException; // // public abstract String getNode(); // // }
import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.dom4j.Element; import org.jivesoftware.openfire.XMPPServer; import org.jivesoftware.openfire.auth.UnauthorizedException; import org.onesocialweb.openfire.handler.pep.PEPCommandHandler; import org.onesocialweb.openfire.handler.pep.PEPNodeHandler; import org.xmpp.packet.IQ; import org.xmpp.packet.PacketError;
/* * Copyright 2010 Vodafone Group Services Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.onesocialweb.openfire.handler.activity; public class PEPActivityHandler extends PEPNodeHandler { public static String NODE = "urn:xmpp:microblog:0"; private XMPPServer server;
// Path: src/java/org/onesocialweb/openfire/handler/pep/PEPCommandHandler.java // public abstract class PEPCommandHandler extends BasicModule { // // /** // * Create a basic module with the given name. // * // * @param moduleName The name for the module or null to use the default // */ // public PEPCommandHandler(String moduleName) { // super(moduleName); // } // // public abstract IQ handleIQ(IQ packet) throws UnauthorizedException; // // public abstract String getCommand(); // // } // // Path: src/java/org/onesocialweb/openfire/handler/pep/PEPNodeHandler.java // public abstract class PEPNodeHandler extends BasicModule { // // /** // * Create a basic module with the given name. // * // * @param moduleName The name for the module or null to use the default // */ // public PEPNodeHandler(String moduleName) { // super(moduleName); // } // // public abstract IQ handleIQ(IQ packet) throws UnauthorizedException; // // public abstract String getNode(); // // } // Path: src/java/org/onesocialweb/openfire/handler/activity/PEPActivityHandler.java import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.dom4j.Element; import org.jivesoftware.openfire.XMPPServer; import org.jivesoftware.openfire.auth.UnauthorizedException; import org.onesocialweb.openfire.handler.pep.PEPCommandHandler; import org.onesocialweb.openfire.handler.pep.PEPNodeHandler; import org.xmpp.packet.IQ; import org.xmpp.packet.PacketError; /* * Copyright 2010 Vodafone Group Services Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.onesocialweb.openfire.handler.activity; public class PEPActivityHandler extends PEPNodeHandler { public static String NODE = "urn:xmpp:microblog:0"; private XMPPServer server;
private Map<String, PEPCommandHandler> handlers = new ConcurrentHashMap<String, PEPCommandHandler>();
onesocialweb/osw-openfire-plugin
src/java/org/onesocialweb/openfire/model/vcard4/PersistentVCard4DomReader.java
// Path: src/java/org/onesocialweb/openfire/model/acl/PersistentAclDomReader.java // public class PersistentAclDomReader extends AclDomReader { // // @Override // protected AclFactory getAclFactory() { // return new PersistentAclFactory(); // } // // }
import org.onesocialweb.model.vcard4.VCard4Factory; import org.onesocialweb.openfire.model.acl.PersistentAclDomReader; import org.onesocialweb.xml.dom.AclDomReader; import org.onesocialweb.xml.dom.VCard4DomReader;
/* * Copyright 2010 Vodafone Group Services Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.onesocialweb.openfire.model.vcard4; public class PersistentVCard4DomReader extends VCard4DomReader { @Override protected AclDomReader getAclDomReader() {
// Path: src/java/org/onesocialweb/openfire/model/acl/PersistentAclDomReader.java // public class PersistentAclDomReader extends AclDomReader { // // @Override // protected AclFactory getAclFactory() { // return new PersistentAclFactory(); // } // // } // Path: src/java/org/onesocialweb/openfire/model/vcard4/PersistentVCard4DomReader.java import org.onesocialweb.model.vcard4.VCard4Factory; import org.onesocialweb.openfire.model.acl.PersistentAclDomReader; import org.onesocialweb.xml.dom.AclDomReader; import org.onesocialweb.xml.dom.VCard4DomReader; /* * Copyright 2010 Vodafone Group Services Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.onesocialweb.openfire.model.vcard4; public class PersistentVCard4DomReader extends VCard4DomReader { @Override protected AclDomReader getAclDomReader() {
return new PersistentAclDomReader();
onesocialweb/osw-openfire-plugin
src/java/org/onesocialweb/openfire/model/vcard4/PersistentBirthdayField.java
// Path: src/java/org/onesocialweb/openfire/model/acl/PersistentAclRule.java // @Entity(name="AclRule") // public class PersistentAclRule implements AclRule { // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclSubject.class, fetch=FetchType.EAGER) // private List<AclSubject> subjects = new ArrayList<AclSubject>(); // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclAction.class, fetch=FetchType.EAGER) // private List<AclAction> actions = new ArrayList<AclAction>(); // // @Override // public List<AclAction> getActions() { // return actions; // } // // @Override // public void setActions(List<AclAction> actions) { // this.actions = actions; // } // // @Override // public List<AclSubject> getSubjects() { // return subjects; // } // // @Override // public void setSubjects(List<AclSubject> subjects) { // this.subjects = subjects; // } // // @Override // public void addAction(AclAction action) { // this.actions.add(action); // } // // @Override // public void addSubject(AclSubject subject) { // this.subjects.add(subject); // } // // @Override // public void removeAction(AclAction action) { // this.actions.remove(action); // } // // @Override // public void removeSubject(AclSubject subject) { // this.subjects.remove(subject); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof AclRule) { // AclRule rule = (AclRule) obj; // return actions.equals(rule.getActions()) // && subjects.equals(rule.getSubjects()); // } else { // return false; // } // } // // @Override // public String toString() { // StringBuffer buffer = new StringBuffer(); // buffer.append("[AclRule "); // for (AclAction action : actions) { // buffer.append(action); // } // for (AclSubject subject : subjects) { // buffer.append(subject); // } // buffer.append("]"); // return buffer.toString(); // } // // @Override // public boolean hasAction(AclAction action) { // if (actions == null || action == null) return false; // // for (AclAction target : actions) { // if (target.equals(action)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasSubject(AclSubject subject) { // if (subjects == null || subject == null) return false; // // for (AclSubject target : subjects) { // if (target.equals(subject)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasActions() { // return (actions != null && !actions.isEmpty()); // } // // @Override // public boolean hasSubjects() { // return (subjects != null && !subjects.isEmpty()); // } // // @Override // public List<AclAction> getActions(String name, String permission) { // List<AclAction> result = new ArrayList<AclAction>(); // // if (actions == null) return result; // // for (AclAction target : actions) { // if (target.getName().equals(name) && target.getPermission().equals(permission)) { // result.add(target); // } // } // // return result; // } // // @Override // public List<AclSubject> getSubjects(String type) { // List<AclSubject> result = new ArrayList<AclSubject>(); // // if (subjects == null || type == null) return result; // // for (AclSubject aclSubject : result) { // if (aclSubject.getType().equals(type)) { // result.add(aclSubject); // } // } // // return result; // } // // }
import javax.persistence.TemporalType; import org.onesocialweb.model.acl.AclRule; import org.onesocialweb.model.atom.DefaultAtomHelper; import org.onesocialweb.model.vcard4.BirthdayField; import org.onesocialweb.openfire.model.acl.PersistentAclRule; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.OneToMany; import javax.persistence.Temporal;
/* * Copyright 2010 Vodafone Group Services Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.onesocialweb.openfire.model.vcard4; @Entity(name="BirthdayField") public class PersistentBirthdayField extends BirthdayField {
// Path: src/java/org/onesocialweb/openfire/model/acl/PersistentAclRule.java // @Entity(name="AclRule") // public class PersistentAclRule implements AclRule { // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclSubject.class, fetch=FetchType.EAGER) // private List<AclSubject> subjects = new ArrayList<AclSubject>(); // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclAction.class, fetch=FetchType.EAGER) // private List<AclAction> actions = new ArrayList<AclAction>(); // // @Override // public List<AclAction> getActions() { // return actions; // } // // @Override // public void setActions(List<AclAction> actions) { // this.actions = actions; // } // // @Override // public List<AclSubject> getSubjects() { // return subjects; // } // // @Override // public void setSubjects(List<AclSubject> subjects) { // this.subjects = subjects; // } // // @Override // public void addAction(AclAction action) { // this.actions.add(action); // } // // @Override // public void addSubject(AclSubject subject) { // this.subjects.add(subject); // } // // @Override // public void removeAction(AclAction action) { // this.actions.remove(action); // } // // @Override // public void removeSubject(AclSubject subject) { // this.subjects.remove(subject); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof AclRule) { // AclRule rule = (AclRule) obj; // return actions.equals(rule.getActions()) // && subjects.equals(rule.getSubjects()); // } else { // return false; // } // } // // @Override // public String toString() { // StringBuffer buffer = new StringBuffer(); // buffer.append("[AclRule "); // for (AclAction action : actions) { // buffer.append(action); // } // for (AclSubject subject : subjects) { // buffer.append(subject); // } // buffer.append("]"); // return buffer.toString(); // } // // @Override // public boolean hasAction(AclAction action) { // if (actions == null || action == null) return false; // // for (AclAction target : actions) { // if (target.equals(action)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasSubject(AclSubject subject) { // if (subjects == null || subject == null) return false; // // for (AclSubject target : subjects) { // if (target.equals(subject)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasActions() { // return (actions != null && !actions.isEmpty()); // } // // @Override // public boolean hasSubjects() { // return (subjects != null && !subjects.isEmpty()); // } // // @Override // public List<AclAction> getActions(String name, String permission) { // List<AclAction> result = new ArrayList<AclAction>(); // // if (actions == null) return result; // // for (AclAction target : actions) { // if (target.getName().equals(name) && target.getPermission().equals(permission)) { // result.add(target); // } // } // // return result; // } // // @Override // public List<AclSubject> getSubjects(String type) { // List<AclSubject> result = new ArrayList<AclSubject>(); // // if (subjects == null || type == null) return result; // // for (AclSubject aclSubject : result) { // if (aclSubject.getType().equals(type)) { // result.add(aclSubject); // } // } // // return result; // } // // } // Path: src/java/org/onesocialweb/openfire/model/vcard4/PersistentBirthdayField.java import javax.persistence.TemporalType; import org.onesocialweb.model.acl.AclRule; import org.onesocialweb.model.atom.DefaultAtomHelper; import org.onesocialweb.model.vcard4.BirthdayField; import org.onesocialweb.openfire.model.acl.PersistentAclRule; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.OneToMany; import javax.persistence.Temporal; /* * Copyright 2010 Vodafone Group Services Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.onesocialweb.openfire.model.vcard4; @Entity(name="BirthdayField") public class PersistentBirthdayField extends BirthdayField {
@OneToMany(cascade=CascadeType.ALL, targetEntity=PersistentAclRule.class, fetch=FetchType.EAGER)
onesocialweb/osw-openfire-plugin
src/java/org/onesocialweb/openfire/model/relation/PersistentRelationDomReader.java
// Path: src/java/org/onesocialweb/openfire/model/acl/PersistentAclDomReader.java // public class PersistentAclDomReader extends AclDomReader { // // @Override // protected AclFactory getAclFactory() { // return new PersistentAclFactory(); // } // // }
import org.onesocialweb.model.relation.RelationFactory; import org.onesocialweb.openfire.model.acl.PersistentAclDomReader; import org.onesocialweb.xml.dom.AclDomReader; import org.onesocialweb.xml.dom.RelationDomReader;
/* * Copyright 2010 Vodafone Group Services Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.onesocialweb.openfire.model.relation; public class PersistentRelationDomReader extends RelationDomReader { @Override protected AclDomReader getAclDomReader() {
// Path: src/java/org/onesocialweb/openfire/model/acl/PersistentAclDomReader.java // public class PersistentAclDomReader extends AclDomReader { // // @Override // protected AclFactory getAclFactory() { // return new PersistentAclFactory(); // } // // } // Path: src/java/org/onesocialweb/openfire/model/relation/PersistentRelationDomReader.java import org.onesocialweb.model.relation.RelationFactory; import org.onesocialweb.openfire.model.acl.PersistentAclDomReader; import org.onesocialweb.xml.dom.AclDomReader; import org.onesocialweb.xml.dom.RelationDomReader; /* * Copyright 2010 Vodafone Group Services Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.onesocialweb.openfire.model.relation; public class PersistentRelationDomReader extends RelationDomReader { @Override protected AclDomReader getAclDomReader() {
return new PersistentAclDomReader();
onesocialweb/osw-openfire-plugin
src/java/org/onesocialweb/openfire/model/vcard4/PersistentNameField.java
// Path: src/java/org/onesocialweb/openfire/model/acl/PersistentAclRule.java // @Entity(name="AclRule") // public class PersistentAclRule implements AclRule { // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclSubject.class, fetch=FetchType.EAGER) // private List<AclSubject> subjects = new ArrayList<AclSubject>(); // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclAction.class, fetch=FetchType.EAGER) // private List<AclAction> actions = new ArrayList<AclAction>(); // // @Override // public List<AclAction> getActions() { // return actions; // } // // @Override // public void setActions(List<AclAction> actions) { // this.actions = actions; // } // // @Override // public List<AclSubject> getSubjects() { // return subjects; // } // // @Override // public void setSubjects(List<AclSubject> subjects) { // this.subjects = subjects; // } // // @Override // public void addAction(AclAction action) { // this.actions.add(action); // } // // @Override // public void addSubject(AclSubject subject) { // this.subjects.add(subject); // } // // @Override // public void removeAction(AclAction action) { // this.actions.remove(action); // } // // @Override // public void removeSubject(AclSubject subject) { // this.subjects.remove(subject); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof AclRule) { // AclRule rule = (AclRule) obj; // return actions.equals(rule.getActions()) // && subjects.equals(rule.getSubjects()); // } else { // return false; // } // } // // @Override // public String toString() { // StringBuffer buffer = new StringBuffer(); // buffer.append("[AclRule "); // for (AclAction action : actions) { // buffer.append(action); // } // for (AclSubject subject : subjects) { // buffer.append(subject); // } // buffer.append("]"); // return buffer.toString(); // } // // @Override // public boolean hasAction(AclAction action) { // if (actions == null || action == null) return false; // // for (AclAction target : actions) { // if (target.equals(action)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasSubject(AclSubject subject) { // if (subjects == null || subject == null) return false; // // for (AclSubject target : subjects) { // if (target.equals(subject)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasActions() { // return (actions != null && !actions.isEmpty()); // } // // @Override // public boolean hasSubjects() { // return (subjects != null && !subjects.isEmpty()); // } // // @Override // public List<AclAction> getActions(String name, String permission) { // List<AclAction> result = new ArrayList<AclAction>(); // // if (actions == null) return result; // // for (AclAction target : actions) { // if (target.getName().equals(name) && target.getPermission().equals(permission)) { // result.add(target); // } // } // // return result; // } // // @Override // public List<AclSubject> getSubjects(String type) { // List<AclSubject> result = new ArrayList<AclSubject>(); // // if (subjects == null || type == null) return result; // // for (AclSubject aclSubject : result) { // if (aclSubject.getType().equals(type)) { // result.add(aclSubject); // } // } // // return result; // } // // }
import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.OneToMany; import org.onesocialweb.model.acl.AclRule; import org.onesocialweb.model.vcard4.NameField; import org.onesocialweb.openfire.model.acl.PersistentAclRule;
package org.onesocialweb.openfire.model.vcard4; @Entity(name="NameField") public class PersistentNameField extends NameField {
// Path: src/java/org/onesocialweb/openfire/model/acl/PersistentAclRule.java // @Entity(name="AclRule") // public class PersistentAclRule implements AclRule { // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclSubject.class, fetch=FetchType.EAGER) // private List<AclSubject> subjects = new ArrayList<AclSubject>(); // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclAction.class, fetch=FetchType.EAGER) // private List<AclAction> actions = new ArrayList<AclAction>(); // // @Override // public List<AclAction> getActions() { // return actions; // } // // @Override // public void setActions(List<AclAction> actions) { // this.actions = actions; // } // // @Override // public List<AclSubject> getSubjects() { // return subjects; // } // // @Override // public void setSubjects(List<AclSubject> subjects) { // this.subjects = subjects; // } // // @Override // public void addAction(AclAction action) { // this.actions.add(action); // } // // @Override // public void addSubject(AclSubject subject) { // this.subjects.add(subject); // } // // @Override // public void removeAction(AclAction action) { // this.actions.remove(action); // } // // @Override // public void removeSubject(AclSubject subject) { // this.subjects.remove(subject); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof AclRule) { // AclRule rule = (AclRule) obj; // return actions.equals(rule.getActions()) // && subjects.equals(rule.getSubjects()); // } else { // return false; // } // } // // @Override // public String toString() { // StringBuffer buffer = new StringBuffer(); // buffer.append("[AclRule "); // for (AclAction action : actions) { // buffer.append(action); // } // for (AclSubject subject : subjects) { // buffer.append(subject); // } // buffer.append("]"); // return buffer.toString(); // } // // @Override // public boolean hasAction(AclAction action) { // if (actions == null || action == null) return false; // // for (AclAction target : actions) { // if (target.equals(action)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasSubject(AclSubject subject) { // if (subjects == null || subject == null) return false; // // for (AclSubject target : subjects) { // if (target.equals(subject)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasActions() { // return (actions != null && !actions.isEmpty()); // } // // @Override // public boolean hasSubjects() { // return (subjects != null && !subjects.isEmpty()); // } // // @Override // public List<AclAction> getActions(String name, String permission) { // List<AclAction> result = new ArrayList<AclAction>(); // // if (actions == null) return result; // // for (AclAction target : actions) { // if (target.getName().equals(name) && target.getPermission().equals(permission)) { // result.add(target); // } // } // // return result; // } // // @Override // public List<AclSubject> getSubjects(String type) { // List<AclSubject> result = new ArrayList<AclSubject>(); // // if (subjects == null || type == null) return result; // // for (AclSubject aclSubject : result) { // if (aclSubject.getType().equals(type)) { // result.add(aclSubject); // } // } // // return result; // } // // } // Path: src/java/org/onesocialweb/openfire/model/vcard4/PersistentNameField.java import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.OneToMany; import org.onesocialweb.model.acl.AclRule; import org.onesocialweb.model.vcard4.NameField; import org.onesocialweb.openfire.model.acl.PersistentAclRule; package org.onesocialweb.openfire.model.vcard4; @Entity(name="NameField") public class PersistentNameField extends NameField {
@OneToMany(cascade=CascadeType.ALL, targetEntity=PersistentAclRule.class, fetch=FetchType.EAGER)
onesocialweb/osw-openfire-plugin
src/java/org/onesocialweb/openfire/handler/inbox/PEPInboxHandler.java
// Path: src/java/org/onesocialweb/openfire/handler/pep/PEPCommandHandler.java // public abstract class PEPCommandHandler extends BasicModule { // // /** // * Create a basic module with the given name. // * // * @param moduleName The name for the module or null to use the default // */ // public PEPCommandHandler(String moduleName) { // super(moduleName); // } // // public abstract IQ handleIQ(IQ packet) throws UnauthorizedException; // // public abstract String getCommand(); // // } // // Path: src/java/org/onesocialweb/openfire/handler/pep/PEPNodeHandler.java // public abstract class PEPNodeHandler extends BasicModule { // // /** // * Create a basic module with the given name. // * // * @param moduleName The name for the module or null to use the default // */ // public PEPNodeHandler(String moduleName) { // super(moduleName); // } // // public abstract IQ handleIQ(IQ packet) throws UnauthorizedException; // // public abstract String getNode(); // // }
import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.dom4j.Element; import org.jivesoftware.openfire.XMPPServer; import org.jivesoftware.openfire.auth.UnauthorizedException; import org.onesocialweb.openfire.handler.pep.PEPCommandHandler; import org.onesocialweb.openfire.handler.pep.PEPNodeHandler; import org.xmpp.packet.IQ; import org.xmpp.packet.PacketError;
/* * Copyright 2010 Vodafone Group Services Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.onesocialweb.openfire.handler.inbox; public class PEPInboxHandler extends PEPNodeHandler { public static String NODE = "http://onesocialweb.org/spec/1.0/inbox"; private XMPPServer server;
// Path: src/java/org/onesocialweb/openfire/handler/pep/PEPCommandHandler.java // public abstract class PEPCommandHandler extends BasicModule { // // /** // * Create a basic module with the given name. // * // * @param moduleName The name for the module or null to use the default // */ // public PEPCommandHandler(String moduleName) { // super(moduleName); // } // // public abstract IQ handleIQ(IQ packet) throws UnauthorizedException; // // public abstract String getCommand(); // // } // // Path: src/java/org/onesocialweb/openfire/handler/pep/PEPNodeHandler.java // public abstract class PEPNodeHandler extends BasicModule { // // /** // * Create a basic module with the given name. // * // * @param moduleName The name for the module or null to use the default // */ // public PEPNodeHandler(String moduleName) { // super(moduleName); // } // // public abstract IQ handleIQ(IQ packet) throws UnauthorizedException; // // public abstract String getNode(); // // } // Path: src/java/org/onesocialweb/openfire/handler/inbox/PEPInboxHandler.java import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.dom4j.Element; import org.jivesoftware.openfire.XMPPServer; import org.jivesoftware.openfire.auth.UnauthorizedException; import org.onesocialweb.openfire.handler.pep.PEPCommandHandler; import org.onesocialweb.openfire.handler.pep.PEPNodeHandler; import org.xmpp.packet.IQ; import org.xmpp.packet.PacketError; /* * Copyright 2010 Vodafone Group Services Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.onesocialweb.openfire.handler.inbox; public class PEPInboxHandler extends PEPNodeHandler { public static String NODE = "http://onesocialweb.org/spec/1.0/inbox"; private XMPPServer server;
private Map<String, PEPCommandHandler> handlers = new ConcurrentHashMap<String, PEPCommandHandler>();
onesocialweb/osw-openfire-plugin
src/java/org/onesocialweb/openfire/model/relation/PersistentRelation.java
// Path: src/java/org/onesocialweb/openfire/model/acl/PersistentAclRule.java // @Entity(name="AclRule") // public class PersistentAclRule implements AclRule { // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclSubject.class, fetch=FetchType.EAGER) // private List<AclSubject> subjects = new ArrayList<AclSubject>(); // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclAction.class, fetch=FetchType.EAGER) // private List<AclAction> actions = new ArrayList<AclAction>(); // // @Override // public List<AclAction> getActions() { // return actions; // } // // @Override // public void setActions(List<AclAction> actions) { // this.actions = actions; // } // // @Override // public List<AclSubject> getSubjects() { // return subjects; // } // // @Override // public void setSubjects(List<AclSubject> subjects) { // this.subjects = subjects; // } // // @Override // public void addAction(AclAction action) { // this.actions.add(action); // } // // @Override // public void addSubject(AclSubject subject) { // this.subjects.add(subject); // } // // @Override // public void removeAction(AclAction action) { // this.actions.remove(action); // } // // @Override // public void removeSubject(AclSubject subject) { // this.subjects.remove(subject); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof AclRule) { // AclRule rule = (AclRule) obj; // return actions.equals(rule.getActions()) // && subjects.equals(rule.getSubjects()); // } else { // return false; // } // } // // @Override // public String toString() { // StringBuffer buffer = new StringBuffer(); // buffer.append("[AclRule "); // for (AclAction action : actions) { // buffer.append(action); // } // for (AclSubject subject : subjects) { // buffer.append(subject); // } // buffer.append("]"); // return buffer.toString(); // } // // @Override // public boolean hasAction(AclAction action) { // if (actions == null || action == null) return false; // // for (AclAction target : actions) { // if (target.equals(action)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasSubject(AclSubject subject) { // if (subjects == null || subject == null) return false; // // for (AclSubject target : subjects) { // if (target.equals(subject)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasActions() { // return (actions != null && !actions.isEmpty()); // } // // @Override // public boolean hasSubjects() { // return (subjects != null && !subjects.isEmpty()); // } // // @Override // public List<AclAction> getActions(String name, String permission) { // List<AclAction> result = new ArrayList<AclAction>(); // // if (actions == null) return result; // // for (AclAction target : actions) { // if (target.getName().equals(name) && target.getPermission().equals(permission)) { // result.add(target); // } // } // // return result; // } // // @Override // public List<AclSubject> getSubjects(String type) { // List<AclSubject> result = new ArrayList<AclSubject>(); // // if (subjects == null || type == null) return result; // // for (AclSubject aclSubject : result) { // if (aclSubject.getType().equals(type)) { // result.add(aclSubject); // } // } // // return result; // } // // }
import org.onesocialweb.openfire.model.acl.PersistentAclRule; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Embeddable; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.OneToMany; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.onesocialweb.model.acl.AclRule; import org.onesocialweb.model.relation.Relation;
/* * Copyright 2010 Vodafone Group Services Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.onesocialweb.openfire.model.relation; @Embeddable @Entity(name="Relation") public class PersistentRelation implements Relation { @Basic private String guid; @Basic private String comment; @Basic private String origin; @Basic private String message; @Basic private String nature; @Basic private String owner; @Basic @Temporal(TemporalType.TIMESTAMP) private Date published; @Basic private String status; @Basic private String target;
// Path: src/java/org/onesocialweb/openfire/model/acl/PersistentAclRule.java // @Entity(name="AclRule") // public class PersistentAclRule implements AclRule { // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclSubject.class, fetch=FetchType.EAGER) // private List<AclSubject> subjects = new ArrayList<AclSubject>(); // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclAction.class, fetch=FetchType.EAGER) // private List<AclAction> actions = new ArrayList<AclAction>(); // // @Override // public List<AclAction> getActions() { // return actions; // } // // @Override // public void setActions(List<AclAction> actions) { // this.actions = actions; // } // // @Override // public List<AclSubject> getSubjects() { // return subjects; // } // // @Override // public void setSubjects(List<AclSubject> subjects) { // this.subjects = subjects; // } // // @Override // public void addAction(AclAction action) { // this.actions.add(action); // } // // @Override // public void addSubject(AclSubject subject) { // this.subjects.add(subject); // } // // @Override // public void removeAction(AclAction action) { // this.actions.remove(action); // } // // @Override // public void removeSubject(AclSubject subject) { // this.subjects.remove(subject); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof AclRule) { // AclRule rule = (AclRule) obj; // return actions.equals(rule.getActions()) // && subjects.equals(rule.getSubjects()); // } else { // return false; // } // } // // @Override // public String toString() { // StringBuffer buffer = new StringBuffer(); // buffer.append("[AclRule "); // for (AclAction action : actions) { // buffer.append(action); // } // for (AclSubject subject : subjects) { // buffer.append(subject); // } // buffer.append("]"); // return buffer.toString(); // } // // @Override // public boolean hasAction(AclAction action) { // if (actions == null || action == null) return false; // // for (AclAction target : actions) { // if (target.equals(action)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasSubject(AclSubject subject) { // if (subjects == null || subject == null) return false; // // for (AclSubject target : subjects) { // if (target.equals(subject)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasActions() { // return (actions != null && !actions.isEmpty()); // } // // @Override // public boolean hasSubjects() { // return (subjects != null && !subjects.isEmpty()); // } // // @Override // public List<AclAction> getActions(String name, String permission) { // List<AclAction> result = new ArrayList<AclAction>(); // // if (actions == null) return result; // // for (AclAction target : actions) { // if (target.getName().equals(name) && target.getPermission().equals(permission)) { // result.add(target); // } // } // // return result; // } // // @Override // public List<AclSubject> getSubjects(String type) { // List<AclSubject> result = new ArrayList<AclSubject>(); // // if (subjects == null || type == null) return result; // // for (AclSubject aclSubject : result) { // if (aclSubject.getType().equals(type)) { // result.add(aclSubject); // } // } // // return result; // } // // } // Path: src/java/org/onesocialweb/openfire/model/relation/PersistentRelation.java import org.onesocialweb.openfire.model.acl.PersistentAclRule; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Embeddable; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.OneToMany; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.onesocialweb.model.acl.AclRule; import org.onesocialweb.model.relation.Relation; /* * Copyright 2010 Vodafone Group Services Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.onesocialweb.openfire.model.relation; @Embeddable @Entity(name="Relation") public class PersistentRelation implements Relation { @Basic private String guid; @Basic private String comment; @Basic private String origin; @Basic private String message; @Basic private String nature; @Basic private String owner; @Basic @Temporal(TemporalType.TIMESTAMP) private Date published; @Basic private String status; @Basic private String target;
@OneToMany(cascade=CascadeType.ALL, targetEntity=PersistentAclRule.class, fetch=FetchType.EAGER)
onesocialweb/osw-openfire-plugin
src/java/org/onesocialweb/openfire/model/vcard4/PersistentUrlField.java
// Path: src/java/org/onesocialweb/openfire/model/acl/PersistentAclRule.java // @Entity(name="AclRule") // public class PersistentAclRule implements AclRule { // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclSubject.class, fetch=FetchType.EAGER) // private List<AclSubject> subjects = new ArrayList<AclSubject>(); // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclAction.class, fetch=FetchType.EAGER) // private List<AclAction> actions = new ArrayList<AclAction>(); // // @Override // public List<AclAction> getActions() { // return actions; // } // // @Override // public void setActions(List<AclAction> actions) { // this.actions = actions; // } // // @Override // public List<AclSubject> getSubjects() { // return subjects; // } // // @Override // public void setSubjects(List<AclSubject> subjects) { // this.subjects = subjects; // } // // @Override // public void addAction(AclAction action) { // this.actions.add(action); // } // // @Override // public void addSubject(AclSubject subject) { // this.subjects.add(subject); // } // // @Override // public void removeAction(AclAction action) { // this.actions.remove(action); // } // // @Override // public void removeSubject(AclSubject subject) { // this.subjects.remove(subject); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof AclRule) { // AclRule rule = (AclRule) obj; // return actions.equals(rule.getActions()) // && subjects.equals(rule.getSubjects()); // } else { // return false; // } // } // // @Override // public String toString() { // StringBuffer buffer = new StringBuffer(); // buffer.append("[AclRule "); // for (AclAction action : actions) { // buffer.append(action); // } // for (AclSubject subject : subjects) { // buffer.append(subject); // } // buffer.append("]"); // return buffer.toString(); // } // // @Override // public boolean hasAction(AclAction action) { // if (actions == null || action == null) return false; // // for (AclAction target : actions) { // if (target.equals(action)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasSubject(AclSubject subject) { // if (subjects == null || subject == null) return false; // // for (AclSubject target : subjects) { // if (target.equals(subject)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasActions() { // return (actions != null && !actions.isEmpty()); // } // // @Override // public boolean hasSubjects() { // return (subjects != null && !subjects.isEmpty()); // } // // @Override // public List<AclAction> getActions(String name, String permission) { // List<AclAction> result = new ArrayList<AclAction>(); // // if (actions == null) return result; // // for (AclAction target : actions) { // if (target.getName().equals(name) && target.getPermission().equals(permission)) { // result.add(target); // } // } // // return result; // } // // @Override // public List<AclSubject> getSubjects(String type) { // List<AclSubject> result = new ArrayList<AclSubject>(); // // if (subjects == null || type == null) return result; // // for (AclSubject aclSubject : result) { // if (aclSubject.getType().equals(type)) { // result.add(aclSubject); // } // } // // return result; // } // // }
import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.OneToMany; import org.onesocialweb.model.acl.AclRule; import org.onesocialweb.model.vcard4.URLField; import org.onesocialweb.openfire.model.acl.PersistentAclRule;
package org.onesocialweb.openfire.model.vcard4; @Entity(name="URLField") public class PersistentUrlField extends URLField {
// Path: src/java/org/onesocialweb/openfire/model/acl/PersistentAclRule.java // @Entity(name="AclRule") // public class PersistentAclRule implements AclRule { // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclSubject.class, fetch=FetchType.EAGER) // private List<AclSubject> subjects = new ArrayList<AclSubject>(); // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclAction.class, fetch=FetchType.EAGER) // private List<AclAction> actions = new ArrayList<AclAction>(); // // @Override // public List<AclAction> getActions() { // return actions; // } // // @Override // public void setActions(List<AclAction> actions) { // this.actions = actions; // } // // @Override // public List<AclSubject> getSubjects() { // return subjects; // } // // @Override // public void setSubjects(List<AclSubject> subjects) { // this.subjects = subjects; // } // // @Override // public void addAction(AclAction action) { // this.actions.add(action); // } // // @Override // public void addSubject(AclSubject subject) { // this.subjects.add(subject); // } // // @Override // public void removeAction(AclAction action) { // this.actions.remove(action); // } // // @Override // public void removeSubject(AclSubject subject) { // this.subjects.remove(subject); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof AclRule) { // AclRule rule = (AclRule) obj; // return actions.equals(rule.getActions()) // && subjects.equals(rule.getSubjects()); // } else { // return false; // } // } // // @Override // public String toString() { // StringBuffer buffer = new StringBuffer(); // buffer.append("[AclRule "); // for (AclAction action : actions) { // buffer.append(action); // } // for (AclSubject subject : subjects) { // buffer.append(subject); // } // buffer.append("]"); // return buffer.toString(); // } // // @Override // public boolean hasAction(AclAction action) { // if (actions == null || action == null) return false; // // for (AclAction target : actions) { // if (target.equals(action)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasSubject(AclSubject subject) { // if (subjects == null || subject == null) return false; // // for (AclSubject target : subjects) { // if (target.equals(subject)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasActions() { // return (actions != null && !actions.isEmpty()); // } // // @Override // public boolean hasSubjects() { // return (subjects != null && !subjects.isEmpty()); // } // // @Override // public List<AclAction> getActions(String name, String permission) { // List<AclAction> result = new ArrayList<AclAction>(); // // if (actions == null) return result; // // for (AclAction target : actions) { // if (target.getName().equals(name) && target.getPermission().equals(permission)) { // result.add(target); // } // } // // return result; // } // // @Override // public List<AclSubject> getSubjects(String type) { // List<AclSubject> result = new ArrayList<AclSubject>(); // // if (subjects == null || type == null) return result; // // for (AclSubject aclSubject : result) { // if (aclSubject.getType().equals(type)) { // result.add(aclSubject); // } // } // // return result; // } // // } // Path: src/java/org/onesocialweb/openfire/model/vcard4/PersistentUrlField.java import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.OneToMany; import org.onesocialweb.model.acl.AclRule; import org.onesocialweb.model.vcard4.URLField; import org.onesocialweb.openfire.model.acl.PersistentAclRule; package org.onesocialweb.openfire.model.vcard4; @Entity(name="URLField") public class PersistentUrlField extends URLField {
@OneToMany(cascade=CascadeType.ALL, targetEntity=PersistentAclRule.class, fetch=FetchType.EAGER)
onesocialweb/osw-openfire-plugin
src/java/org/onesocialweb/openfire/model/PersistentActivityMessage.java
// Path: src/java/org/onesocialweb/openfire/model/activity/PersistentActivityEntry.java // @Entity(name="ActivityEntry") // @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) // @Table(name="Activities") // public class PersistentActivityEntry extends PersistentAtomEntry implements ActivityEntry { // // @OneToOne(cascade=CascadeType.ALL, targetEntity=PersistentActivityActor.class, fetch=FetchType.EAGER) // private ActivityActor actor; // // @OneToMany(cascade=CascadeType.ALL, targetEntity=PersistentAclRule.class, fetch=FetchType.EAGER) // private List<AclRule> rules = new ArrayList<AclRule>(); // // @OneToMany(cascade=CascadeType.ALL, targetEntity=PersistentActivityObject.class, fetch=FetchType.EAGER) // private List<ActivityObject> objects = new ArrayList<ActivityObject>(); // // @OneToMany(cascade=CascadeType.ALL, targetEntity=PersistentActivityVerb.class, fetch=FetchType.EAGER) // private List<ActivityVerb> verbs = new ArrayList<ActivityVerb>(); // // @Override // public void addObject(ActivityObject object) { // this.objects.add(object); // } // // @Override // public void addVerb(ActivityVerb verb) { // this.verbs.add(verb); // } // // @Override // public void addAclRule(AclRule rule) { // this.rules.add(rule); // } // // @Override // public List<AclRule> getAclRules() { // return rules; // } // // @Override // public ActivityActor getActor() { // return actor; // } // // @Override // public List<ActivityObject> getObjects() { // return objects; // } // // @Override // public List<ActivityVerb> getVerbs() { // return verbs; // } // // @Override // public void removeObject(ActivityObject object) { // this.objects.remove(object); // } // // @Override // public void removeVerb(ActivityVerb verb) { // this.verbs.remove(verb); // } // // @Override // public void removeAclRule(AclRule rule) { // this.rules.remove(rule); // } // // @Override // public void setAclRules(List<AclRule> rules) { // this.rules = rules; // } // // @Override // public void setActor(final ActivityActor actor) { // this.actor = actor; // } // // @Override // public void setObjects(List<ActivityObject> objects) { // this.objects = objects; // } // // @Override // public void setVerbs(final List<ActivityVerb> verbs) { // this.verbs = verbs; // } // // @Override // public String toString() { // StringBuffer buffer = new StringBuffer(); // buffer.append("[ActivityEntry "); // buffer.append(super.toString()); // if (actor != null) { // buffer.append("actor:" + actor + " "); // } // for (ActivityVerb verb : verbs) { // buffer.append(verb.toString()); // } // for (ActivityObject object : objects) { // buffer.append(object.toString()); // } // for (AclRule rule : rules) { // buffer.append(rule.toString()); // } // buffer.append("]"); // return buffer.toString(); // } // // @Override // public boolean hasAclRules() { // return (rules != null && rules.size() > 0); // } // // @Override // public boolean hasActor() { // return (actor != null); // } // // @Override // public boolean hasObjects() { // return (objects != null && objects.size() > 0); // } // // @Override // public boolean hasVerbs() { // return (verbs != null && verbs.size() > 0); // } // // }
import java.util.Date; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.OneToOne; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.onesocialweb.model.activity.ActivityEntry; import org.onesocialweb.openfire.model.activity.PersistentActivityEntry;
/* * Copyright 2010 Vodafone Group Services Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.onesocialweb.openfire.model; @Entity(name = "Messages") public class PersistentActivityMessage implements ActivityMessage { @Basic private String sender; @Basic private String recipient; @Temporal(TemporalType.TIMESTAMP) private Date received;
// Path: src/java/org/onesocialweb/openfire/model/activity/PersistentActivityEntry.java // @Entity(name="ActivityEntry") // @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) // @Table(name="Activities") // public class PersistentActivityEntry extends PersistentAtomEntry implements ActivityEntry { // // @OneToOne(cascade=CascadeType.ALL, targetEntity=PersistentActivityActor.class, fetch=FetchType.EAGER) // private ActivityActor actor; // // @OneToMany(cascade=CascadeType.ALL, targetEntity=PersistentAclRule.class, fetch=FetchType.EAGER) // private List<AclRule> rules = new ArrayList<AclRule>(); // // @OneToMany(cascade=CascadeType.ALL, targetEntity=PersistentActivityObject.class, fetch=FetchType.EAGER) // private List<ActivityObject> objects = new ArrayList<ActivityObject>(); // // @OneToMany(cascade=CascadeType.ALL, targetEntity=PersistentActivityVerb.class, fetch=FetchType.EAGER) // private List<ActivityVerb> verbs = new ArrayList<ActivityVerb>(); // // @Override // public void addObject(ActivityObject object) { // this.objects.add(object); // } // // @Override // public void addVerb(ActivityVerb verb) { // this.verbs.add(verb); // } // // @Override // public void addAclRule(AclRule rule) { // this.rules.add(rule); // } // // @Override // public List<AclRule> getAclRules() { // return rules; // } // // @Override // public ActivityActor getActor() { // return actor; // } // // @Override // public List<ActivityObject> getObjects() { // return objects; // } // // @Override // public List<ActivityVerb> getVerbs() { // return verbs; // } // // @Override // public void removeObject(ActivityObject object) { // this.objects.remove(object); // } // // @Override // public void removeVerb(ActivityVerb verb) { // this.verbs.remove(verb); // } // // @Override // public void removeAclRule(AclRule rule) { // this.rules.remove(rule); // } // // @Override // public void setAclRules(List<AclRule> rules) { // this.rules = rules; // } // // @Override // public void setActor(final ActivityActor actor) { // this.actor = actor; // } // // @Override // public void setObjects(List<ActivityObject> objects) { // this.objects = objects; // } // // @Override // public void setVerbs(final List<ActivityVerb> verbs) { // this.verbs = verbs; // } // // @Override // public String toString() { // StringBuffer buffer = new StringBuffer(); // buffer.append("[ActivityEntry "); // buffer.append(super.toString()); // if (actor != null) { // buffer.append("actor:" + actor + " "); // } // for (ActivityVerb verb : verbs) { // buffer.append(verb.toString()); // } // for (ActivityObject object : objects) { // buffer.append(object.toString()); // } // for (AclRule rule : rules) { // buffer.append(rule.toString()); // } // buffer.append("]"); // return buffer.toString(); // } // // @Override // public boolean hasAclRules() { // return (rules != null && rules.size() > 0); // } // // @Override // public boolean hasActor() { // return (actor != null); // } // // @Override // public boolean hasObjects() { // return (objects != null && objects.size() > 0); // } // // @Override // public boolean hasVerbs() { // return (verbs != null && verbs.size() > 0); // } // // } // Path: src/java/org/onesocialweb/openfire/model/PersistentActivityMessage.java import java.util.Date; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.OneToOne; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.onesocialweb.model.activity.ActivityEntry; import org.onesocialweb.openfire.model.activity.PersistentActivityEntry; /* * Copyright 2010 Vodafone Group Services Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.onesocialweb.openfire.model; @Entity(name = "Messages") public class PersistentActivityMessage implements ActivityMessage { @Basic private String sender; @Basic private String recipient; @Temporal(TemporalType.TIMESTAMP) private Date received;
@OneToOne(cascade = CascadeType.ALL, targetEntity = PersistentActivityEntry.class, fetch = FetchType.EAGER)
onesocialweb/osw-openfire-plugin
src/java/org/onesocialweb/openfire/web/FileServlet.java
// Path: src/java/org/onesocialweb/openfire/exception/AuthenticationException.java // @SuppressWarnings("serial") // public class AuthenticationException extends Exception { // // } // // Path: src/java/org/onesocialweb/openfire/exception/InvalidParameterValueException.java // @SuppressWarnings("serial") // public class InvalidParameterValueException extends Exception { // // private final String parameter; // // private final String value; // // public InvalidParameterValueException(String parameter, String value) { // this.parameter = parameter; // this.value = value; // } // // public String getParameter() { // return parameter; // } // // public String getValue() { // return value; // } // // } // // Path: src/java/org/onesocialweb/openfire/exception/MissingParameterException.java // @SuppressWarnings("serial") // public class MissingParameterException extends Exception { // // private final String parameter; // // public MissingParameterException(String parameter) { // this.parameter = parameter; // } // // public String getParameter() { // return parameter; // } // // } // // Path: src/java/org/onesocialweb/openfire/model/FileEntry.java // public interface FileEntry { // // public String getId(); // // public void setId(String id); // // public String getName(); // // public void setName(String name); // // public String getType(); // // public void setType(String type); // // public String getOwner(); // // public void setOwner(String owner); // // public long getSize(); // // public void setSize(long size); // // }
import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.List; import java.util.UUID; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.ProgressListener; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.jivesoftware.admin.AuthCheckFilter; import org.jivesoftware.util.JiveGlobals; import org.onesocialweb.openfire.exception.AuthenticationException; import org.onesocialweb.openfire.exception.InvalidParameterValueException; import org.onesocialweb.openfire.exception.MissingParameterException; import org.onesocialweb.openfire.model.FileEntry; import org.xmpp.packet.JID;
/* * Copyright 2010 Vodafone Group Services Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.onesocialweb.openfire.web; @SuppressWarnings("serial") public class FileServlet extends HttpServlet { private static final long NOTIFICATION_THRESHOLD = 256000; private static int BUFFSIZE = 64000; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final PrintWriter out = response.getWriter(); try { processGet(request, response);
// Path: src/java/org/onesocialweb/openfire/exception/AuthenticationException.java // @SuppressWarnings("serial") // public class AuthenticationException extends Exception { // // } // // Path: src/java/org/onesocialweb/openfire/exception/InvalidParameterValueException.java // @SuppressWarnings("serial") // public class InvalidParameterValueException extends Exception { // // private final String parameter; // // private final String value; // // public InvalidParameterValueException(String parameter, String value) { // this.parameter = parameter; // this.value = value; // } // // public String getParameter() { // return parameter; // } // // public String getValue() { // return value; // } // // } // // Path: src/java/org/onesocialweb/openfire/exception/MissingParameterException.java // @SuppressWarnings("serial") // public class MissingParameterException extends Exception { // // private final String parameter; // // public MissingParameterException(String parameter) { // this.parameter = parameter; // } // // public String getParameter() { // return parameter; // } // // } // // Path: src/java/org/onesocialweb/openfire/model/FileEntry.java // public interface FileEntry { // // public String getId(); // // public void setId(String id); // // public String getName(); // // public void setName(String name); // // public String getType(); // // public void setType(String type); // // public String getOwner(); // // public void setOwner(String owner); // // public long getSize(); // // public void setSize(long size); // // } // Path: src/java/org/onesocialweb/openfire/web/FileServlet.java import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.List; import java.util.UUID; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.ProgressListener; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.jivesoftware.admin.AuthCheckFilter; import org.jivesoftware.util.JiveGlobals; import org.onesocialweb.openfire.exception.AuthenticationException; import org.onesocialweb.openfire.exception.InvalidParameterValueException; import org.onesocialweb.openfire.exception.MissingParameterException; import org.onesocialweb.openfire.model.FileEntry; import org.xmpp.packet.JID; /* * Copyright 2010 Vodafone Group Services Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.onesocialweb.openfire.web; @SuppressWarnings("serial") public class FileServlet extends HttpServlet { private static final long NOTIFICATION_THRESHOLD = 256000; private static int BUFFSIZE = 64000; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final PrintWriter out = response.getWriter(); try { processGet(request, response);
} catch (MissingParameterException e) {
onesocialweb/osw-openfire-plugin
src/java/org/onesocialweb/openfire/web/FileServlet.java
// Path: src/java/org/onesocialweb/openfire/exception/AuthenticationException.java // @SuppressWarnings("serial") // public class AuthenticationException extends Exception { // // } // // Path: src/java/org/onesocialweb/openfire/exception/InvalidParameterValueException.java // @SuppressWarnings("serial") // public class InvalidParameterValueException extends Exception { // // private final String parameter; // // private final String value; // // public InvalidParameterValueException(String parameter, String value) { // this.parameter = parameter; // this.value = value; // } // // public String getParameter() { // return parameter; // } // // public String getValue() { // return value; // } // // } // // Path: src/java/org/onesocialweb/openfire/exception/MissingParameterException.java // @SuppressWarnings("serial") // public class MissingParameterException extends Exception { // // private final String parameter; // // public MissingParameterException(String parameter) { // this.parameter = parameter; // } // // public String getParameter() { // return parameter; // } // // } // // Path: src/java/org/onesocialweb/openfire/model/FileEntry.java // public interface FileEntry { // // public String getId(); // // public void setId(String id); // // public String getName(); // // public void setName(String name); // // public String getType(); // // public void setType(String type); // // public String getOwner(); // // public void setOwner(String owner); // // public long getSize(); // // public void setSize(long size); // // }
import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.List; import java.util.UUID; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.ProgressListener; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.jivesoftware.admin.AuthCheckFilter; import org.jivesoftware.util.JiveGlobals; import org.onesocialweb.openfire.exception.AuthenticationException; import org.onesocialweb.openfire.exception.InvalidParameterValueException; import org.onesocialweb.openfire.exception.MissingParameterException; import org.onesocialweb.openfire.model.FileEntry; import org.xmpp.packet.JID;
catch (Exception e) { out.println("Exception occured: " + e.getMessage()); e.printStackTrace(out); } out.flush(); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final PrintWriter out = response.getWriter(); try { processPost(request, response); } catch (Exception e) { out.println("Exception occured: " + e.getMessage()); e.printStackTrace(out); } out.flush(); } private void processPost(HttpServletRequest request, HttpServletResponse response) throws Exception { final PrintWriter out = response.getWriter(); // 1- Bind this request to a XMPP JID final JID user = getAuthenticatedUser(request); if (user == null) {
// Path: src/java/org/onesocialweb/openfire/exception/AuthenticationException.java // @SuppressWarnings("serial") // public class AuthenticationException extends Exception { // // } // // Path: src/java/org/onesocialweb/openfire/exception/InvalidParameterValueException.java // @SuppressWarnings("serial") // public class InvalidParameterValueException extends Exception { // // private final String parameter; // // private final String value; // // public InvalidParameterValueException(String parameter, String value) { // this.parameter = parameter; // this.value = value; // } // // public String getParameter() { // return parameter; // } // // public String getValue() { // return value; // } // // } // // Path: src/java/org/onesocialweb/openfire/exception/MissingParameterException.java // @SuppressWarnings("serial") // public class MissingParameterException extends Exception { // // private final String parameter; // // public MissingParameterException(String parameter) { // this.parameter = parameter; // } // // public String getParameter() { // return parameter; // } // // } // // Path: src/java/org/onesocialweb/openfire/model/FileEntry.java // public interface FileEntry { // // public String getId(); // // public void setId(String id); // // public String getName(); // // public void setName(String name); // // public String getType(); // // public void setType(String type); // // public String getOwner(); // // public void setOwner(String owner); // // public long getSize(); // // public void setSize(long size); // // } // Path: src/java/org/onesocialweb/openfire/web/FileServlet.java import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.List; import java.util.UUID; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.ProgressListener; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.jivesoftware.admin.AuthCheckFilter; import org.jivesoftware.util.JiveGlobals; import org.onesocialweb.openfire.exception.AuthenticationException; import org.onesocialweb.openfire.exception.InvalidParameterValueException; import org.onesocialweb.openfire.exception.MissingParameterException; import org.onesocialweb.openfire.model.FileEntry; import org.xmpp.packet.JID; catch (Exception e) { out.println("Exception occured: " + e.getMessage()); e.printStackTrace(out); } out.flush(); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final PrintWriter out = response.getWriter(); try { processPost(request, response); } catch (Exception e) { out.println("Exception occured: " + e.getMessage()); e.printStackTrace(out); } out.flush(); } private void processPost(HttpServletRequest request, HttpServletResponse response) throws Exception { final PrintWriter out = response.getWriter(); // 1- Bind this request to a XMPP JID final JID user = getAuthenticatedUser(request); if (user == null) {
throw new AuthenticationException();
onesocialweb/osw-openfire-plugin
src/java/org/onesocialweb/openfire/web/FileServlet.java
// Path: src/java/org/onesocialweb/openfire/exception/AuthenticationException.java // @SuppressWarnings("serial") // public class AuthenticationException extends Exception { // // } // // Path: src/java/org/onesocialweb/openfire/exception/InvalidParameterValueException.java // @SuppressWarnings("serial") // public class InvalidParameterValueException extends Exception { // // private final String parameter; // // private final String value; // // public InvalidParameterValueException(String parameter, String value) { // this.parameter = parameter; // this.value = value; // } // // public String getParameter() { // return parameter; // } // // public String getValue() { // return value; // } // // } // // Path: src/java/org/onesocialweb/openfire/exception/MissingParameterException.java // @SuppressWarnings("serial") // public class MissingParameterException extends Exception { // // private final String parameter; // // public MissingParameterException(String parameter) { // this.parameter = parameter; // } // // public String getParameter() { // return parameter; // } // // } // // Path: src/java/org/onesocialweb/openfire/model/FileEntry.java // public interface FileEntry { // // public String getId(); // // public void setId(String id); // // public String getName(); // // public void setName(String name); // // public String getType(); // // public void setType(String type); // // public String getOwner(); // // public void setOwner(String owner); // // public long getSize(); // // public void setSize(long size); // // }
import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.List; import java.util.UUID; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.ProgressListener; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.jivesoftware.admin.AuthCheckFilter; import org.jivesoftware.util.JiveGlobals; import org.onesocialweb.openfire.exception.AuthenticationException; import org.onesocialweb.openfire.exception.InvalidParameterValueException; import org.onesocialweb.openfire.exception.MissingParameterException; import org.onesocialweb.openfire.model.FileEntry; import org.xmpp.packet.JID;
// Get the request ID final String requestId = request.getParameter("requestId"); // Create a progress listener ProgressListener progressListener = new ProgressListener() { private long lastNotification = 0; public void update(long pBytesRead, long pContentLength, int pItems) { if (lastNotification == 0 || (pBytesRead - lastNotification) > NOTIFICATION_THRESHOLD) { lastNotification = pBytesRead; UploadManager.getInstance().updateProgress(user, pBytesRead, pContentLength, requestId); } } }; upload.setProgressListener(progressListener); // Process the upload List items = upload.parseRequest(request); for (Object objItem : items) { FileItem item = (FileItem) objItem; if (!item.isFormField()) { String fileID = UUID.randomUUID().toString(); File target = new File(getUploadFolder(), fileID); item.write(target); UploadManager.getInstance().commitFile(user, target, item.getName(), requestId); break; // Store only one file } } }
// Path: src/java/org/onesocialweb/openfire/exception/AuthenticationException.java // @SuppressWarnings("serial") // public class AuthenticationException extends Exception { // // } // // Path: src/java/org/onesocialweb/openfire/exception/InvalidParameterValueException.java // @SuppressWarnings("serial") // public class InvalidParameterValueException extends Exception { // // private final String parameter; // // private final String value; // // public InvalidParameterValueException(String parameter, String value) { // this.parameter = parameter; // this.value = value; // } // // public String getParameter() { // return parameter; // } // // public String getValue() { // return value; // } // // } // // Path: src/java/org/onesocialweb/openfire/exception/MissingParameterException.java // @SuppressWarnings("serial") // public class MissingParameterException extends Exception { // // private final String parameter; // // public MissingParameterException(String parameter) { // this.parameter = parameter; // } // // public String getParameter() { // return parameter; // } // // } // // Path: src/java/org/onesocialweb/openfire/model/FileEntry.java // public interface FileEntry { // // public String getId(); // // public void setId(String id); // // public String getName(); // // public void setName(String name); // // public String getType(); // // public void setType(String type); // // public String getOwner(); // // public void setOwner(String owner); // // public long getSize(); // // public void setSize(long size); // // } // Path: src/java/org/onesocialweb/openfire/web/FileServlet.java import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.List; import java.util.UUID; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.ProgressListener; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.jivesoftware.admin.AuthCheckFilter; import org.jivesoftware.util.JiveGlobals; import org.onesocialweb.openfire.exception.AuthenticationException; import org.onesocialweb.openfire.exception.InvalidParameterValueException; import org.onesocialweb.openfire.exception.MissingParameterException; import org.onesocialweb.openfire.model.FileEntry; import org.xmpp.packet.JID; // Get the request ID final String requestId = request.getParameter("requestId"); // Create a progress listener ProgressListener progressListener = new ProgressListener() { private long lastNotification = 0; public void update(long pBytesRead, long pContentLength, int pItems) { if (lastNotification == 0 || (pBytesRead - lastNotification) > NOTIFICATION_THRESHOLD) { lastNotification = pBytesRead; UploadManager.getInstance().updateProgress(user, pBytesRead, pContentLength, requestId); } } }; upload.setProgressListener(progressListener); // Process the upload List items = upload.parseRequest(request); for (Object objItem : items) { FileItem item = (FileItem) objItem; if (!item.isFormField()) { String fileID = UUID.randomUUID().toString(); File target = new File(getUploadFolder(), fileID); item.write(target); UploadManager.getInstance().commitFile(user, target, item.getName(), requestId); break; // Store only one file } } }
private void processGet(HttpServletRequest request, HttpServletResponse response) throws MissingParameterException, IOException, InvalidParameterValueException {
onesocialweb/osw-openfire-plugin
src/java/org/onesocialweb/openfire/web/FileServlet.java
// Path: src/java/org/onesocialweb/openfire/exception/AuthenticationException.java // @SuppressWarnings("serial") // public class AuthenticationException extends Exception { // // } // // Path: src/java/org/onesocialweb/openfire/exception/InvalidParameterValueException.java // @SuppressWarnings("serial") // public class InvalidParameterValueException extends Exception { // // private final String parameter; // // private final String value; // // public InvalidParameterValueException(String parameter, String value) { // this.parameter = parameter; // this.value = value; // } // // public String getParameter() { // return parameter; // } // // public String getValue() { // return value; // } // // } // // Path: src/java/org/onesocialweb/openfire/exception/MissingParameterException.java // @SuppressWarnings("serial") // public class MissingParameterException extends Exception { // // private final String parameter; // // public MissingParameterException(String parameter) { // this.parameter = parameter; // } // // public String getParameter() { // return parameter; // } // // } // // Path: src/java/org/onesocialweb/openfire/model/FileEntry.java // public interface FileEntry { // // public String getId(); // // public void setId(String id); // // public String getName(); // // public void setName(String name); // // public String getType(); // // public void setType(String type); // // public String getOwner(); // // public void setOwner(String owner); // // public long getSize(); // // public void setSize(long size); // // }
import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.List; import java.util.UUID; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.ProgressListener; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.jivesoftware.admin.AuthCheckFilter; import org.jivesoftware.util.JiveGlobals; import org.onesocialweb.openfire.exception.AuthenticationException; import org.onesocialweb.openfire.exception.InvalidParameterValueException; import org.onesocialweb.openfire.exception.MissingParameterException; import org.onesocialweb.openfire.model.FileEntry; import org.xmpp.packet.JID;
} }; upload.setProgressListener(progressListener); // Process the upload List items = upload.parseRequest(request); for (Object objItem : items) { FileItem item = (FileItem) objItem; if (!item.isFormField()) { String fileID = UUID.randomUUID().toString(); File target = new File(getUploadFolder(), fileID); item.write(target); UploadManager.getInstance().commitFile(user, target, item.getName(), requestId); break; // Store only one file } } } private void processGet(HttpServletRequest request, HttpServletResponse response) throws MissingParameterException, IOException, InvalidParameterValueException { // Validate the request token // TODO // Process the parameters String fileId = request.getParameter("fileId"); if (fileId == null || fileId.isEmpty()) { throw new MissingParameterException("fileId"); } // Get the file entry
// Path: src/java/org/onesocialweb/openfire/exception/AuthenticationException.java // @SuppressWarnings("serial") // public class AuthenticationException extends Exception { // // } // // Path: src/java/org/onesocialweb/openfire/exception/InvalidParameterValueException.java // @SuppressWarnings("serial") // public class InvalidParameterValueException extends Exception { // // private final String parameter; // // private final String value; // // public InvalidParameterValueException(String parameter, String value) { // this.parameter = parameter; // this.value = value; // } // // public String getParameter() { // return parameter; // } // // public String getValue() { // return value; // } // // } // // Path: src/java/org/onesocialweb/openfire/exception/MissingParameterException.java // @SuppressWarnings("serial") // public class MissingParameterException extends Exception { // // private final String parameter; // // public MissingParameterException(String parameter) { // this.parameter = parameter; // } // // public String getParameter() { // return parameter; // } // // } // // Path: src/java/org/onesocialweb/openfire/model/FileEntry.java // public interface FileEntry { // // public String getId(); // // public void setId(String id); // // public String getName(); // // public void setName(String name); // // public String getType(); // // public void setType(String type); // // public String getOwner(); // // public void setOwner(String owner); // // public long getSize(); // // public void setSize(long size); // // } // Path: src/java/org/onesocialweb/openfire/web/FileServlet.java import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.List; import java.util.UUID; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.ProgressListener; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.jivesoftware.admin.AuthCheckFilter; import org.jivesoftware.util.JiveGlobals; import org.onesocialweb.openfire.exception.AuthenticationException; import org.onesocialweb.openfire.exception.InvalidParameterValueException; import org.onesocialweb.openfire.exception.MissingParameterException; import org.onesocialweb.openfire.model.FileEntry; import org.xmpp.packet.JID; } }; upload.setProgressListener(progressListener); // Process the upload List items = upload.parseRequest(request); for (Object objItem : items) { FileItem item = (FileItem) objItem; if (!item.isFormField()) { String fileID = UUID.randomUUID().toString(); File target = new File(getUploadFolder(), fileID); item.write(target); UploadManager.getInstance().commitFile(user, target, item.getName(), requestId); break; // Store only one file } } } private void processGet(HttpServletRequest request, HttpServletResponse response) throws MissingParameterException, IOException, InvalidParameterValueException { // Validate the request token // TODO // Process the parameters String fileId = request.getParameter("fileId"); if (fileId == null || fileId.isEmpty()) { throw new MissingParameterException("fileId"); } // Get the file entry
FileEntry fileEntry = UploadManager.getInstance().getFile(fileId);
onesocialweb/osw-openfire-plugin
src/java/org/onesocialweb/openfire/model/activity/PersistentActivityDomReader.java
// Path: src/java/org/onesocialweb/openfire/model/acl/PersistentAclDomReader.java // public class PersistentAclDomReader extends AclDomReader { // // @Override // protected AclFactory getAclFactory() { // return new PersistentAclFactory(); // } // // } // // Path: src/java/org/onesocialweb/openfire/model/atom/PersistentAtomDomReader.java // public class PersistentAtomDomReader extends AtomDomReader { // // @Override // protected AtomFactory getAtomFactory() { // return new PersistentAtomFactory(); // } // // @Override // protected Date parseDate(String atomDate) { // return DefaultAtomHelper.parseDate(atomDate); // } // // }
import java.util.Date; import org.onesocialweb.model.activity.ActivityFactory; import org.onesocialweb.model.atom.DefaultAtomHelper; import org.onesocialweb.openfire.model.acl.PersistentAclDomReader; import org.onesocialweb.openfire.model.atom.PersistentAtomDomReader; import org.onesocialweb.xml.dom.AclDomReader; import org.onesocialweb.xml.dom.ActivityDomReader; import org.onesocialweb.xml.dom.AtomDomReader;
/* * Copyright 2010 Vodafone Group Services Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.onesocialweb.openfire.model.activity; public class PersistentActivityDomReader extends ActivityDomReader { @Override protected AclDomReader getAclDomReader() {
// Path: src/java/org/onesocialweb/openfire/model/acl/PersistentAclDomReader.java // public class PersistentAclDomReader extends AclDomReader { // // @Override // protected AclFactory getAclFactory() { // return new PersistentAclFactory(); // } // // } // // Path: src/java/org/onesocialweb/openfire/model/atom/PersistentAtomDomReader.java // public class PersistentAtomDomReader extends AtomDomReader { // // @Override // protected AtomFactory getAtomFactory() { // return new PersistentAtomFactory(); // } // // @Override // protected Date parseDate(String atomDate) { // return DefaultAtomHelper.parseDate(atomDate); // } // // } // Path: src/java/org/onesocialweb/openfire/model/activity/PersistentActivityDomReader.java import java.util.Date; import org.onesocialweb.model.activity.ActivityFactory; import org.onesocialweb.model.atom.DefaultAtomHelper; import org.onesocialweb.openfire.model.acl.PersistentAclDomReader; import org.onesocialweb.openfire.model.atom.PersistentAtomDomReader; import org.onesocialweb.xml.dom.AclDomReader; import org.onesocialweb.xml.dom.ActivityDomReader; import org.onesocialweb.xml.dom.AtomDomReader; /* * Copyright 2010 Vodafone Group Services Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.onesocialweb.openfire.model.activity; public class PersistentActivityDomReader extends ActivityDomReader { @Override protected AclDomReader getAclDomReader() {
return new PersistentAclDomReader();
onesocialweb/osw-openfire-plugin
src/java/org/onesocialweb/openfire/model/activity/PersistentActivityDomReader.java
// Path: src/java/org/onesocialweb/openfire/model/acl/PersistentAclDomReader.java // public class PersistentAclDomReader extends AclDomReader { // // @Override // protected AclFactory getAclFactory() { // return new PersistentAclFactory(); // } // // } // // Path: src/java/org/onesocialweb/openfire/model/atom/PersistentAtomDomReader.java // public class PersistentAtomDomReader extends AtomDomReader { // // @Override // protected AtomFactory getAtomFactory() { // return new PersistentAtomFactory(); // } // // @Override // protected Date parseDate(String atomDate) { // return DefaultAtomHelper.parseDate(atomDate); // } // // }
import java.util.Date; import org.onesocialweb.model.activity.ActivityFactory; import org.onesocialweb.model.atom.DefaultAtomHelper; import org.onesocialweb.openfire.model.acl.PersistentAclDomReader; import org.onesocialweb.openfire.model.atom.PersistentAtomDomReader; import org.onesocialweb.xml.dom.AclDomReader; import org.onesocialweb.xml.dom.ActivityDomReader; import org.onesocialweb.xml.dom.AtomDomReader;
/* * Copyright 2010 Vodafone Group Services Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.onesocialweb.openfire.model.activity; public class PersistentActivityDomReader extends ActivityDomReader { @Override protected AclDomReader getAclDomReader() { return new PersistentAclDomReader(); } @Override protected ActivityFactory getActivityFactory() { return new PersistentActivityFactory(); } @Override protected AtomDomReader getAtomDomReader() {
// Path: src/java/org/onesocialweb/openfire/model/acl/PersistentAclDomReader.java // public class PersistentAclDomReader extends AclDomReader { // // @Override // protected AclFactory getAclFactory() { // return new PersistentAclFactory(); // } // // } // // Path: src/java/org/onesocialweb/openfire/model/atom/PersistentAtomDomReader.java // public class PersistentAtomDomReader extends AtomDomReader { // // @Override // protected AtomFactory getAtomFactory() { // return new PersistentAtomFactory(); // } // // @Override // protected Date parseDate(String atomDate) { // return DefaultAtomHelper.parseDate(atomDate); // } // // } // Path: src/java/org/onesocialweb/openfire/model/activity/PersistentActivityDomReader.java import java.util.Date; import org.onesocialweb.model.activity.ActivityFactory; import org.onesocialweb.model.atom.DefaultAtomHelper; import org.onesocialweb.openfire.model.acl.PersistentAclDomReader; import org.onesocialweb.openfire.model.atom.PersistentAtomDomReader; import org.onesocialweb.xml.dom.AclDomReader; import org.onesocialweb.xml.dom.ActivityDomReader; import org.onesocialweb.xml.dom.AtomDomReader; /* * Copyright 2010 Vodafone Group Services Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.onesocialweb.openfire.model.activity; public class PersistentActivityDomReader extends ActivityDomReader { @Override protected AclDomReader getAclDomReader() { return new PersistentAclDomReader(); } @Override protected ActivityFactory getActivityFactory() { return new PersistentActivityFactory(); } @Override protected AtomDomReader getAtomDomReader() {
return new PersistentAtomDomReader();
onesocialweb/osw-openfire-plugin
src/java/org/onesocialweb/openfire/model/vcard4/PersistentTimeZoneField.java
// Path: src/java/org/onesocialweb/openfire/model/acl/PersistentAclRule.java // @Entity(name="AclRule") // public class PersistentAclRule implements AclRule { // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclSubject.class, fetch=FetchType.EAGER) // private List<AclSubject> subjects = new ArrayList<AclSubject>(); // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclAction.class, fetch=FetchType.EAGER) // private List<AclAction> actions = new ArrayList<AclAction>(); // // @Override // public List<AclAction> getActions() { // return actions; // } // // @Override // public void setActions(List<AclAction> actions) { // this.actions = actions; // } // // @Override // public List<AclSubject> getSubjects() { // return subjects; // } // // @Override // public void setSubjects(List<AclSubject> subjects) { // this.subjects = subjects; // } // // @Override // public void addAction(AclAction action) { // this.actions.add(action); // } // // @Override // public void addSubject(AclSubject subject) { // this.subjects.add(subject); // } // // @Override // public void removeAction(AclAction action) { // this.actions.remove(action); // } // // @Override // public void removeSubject(AclSubject subject) { // this.subjects.remove(subject); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof AclRule) { // AclRule rule = (AclRule) obj; // return actions.equals(rule.getActions()) // && subjects.equals(rule.getSubjects()); // } else { // return false; // } // } // // @Override // public String toString() { // StringBuffer buffer = new StringBuffer(); // buffer.append("[AclRule "); // for (AclAction action : actions) { // buffer.append(action); // } // for (AclSubject subject : subjects) { // buffer.append(subject); // } // buffer.append("]"); // return buffer.toString(); // } // // @Override // public boolean hasAction(AclAction action) { // if (actions == null || action == null) return false; // // for (AclAction target : actions) { // if (target.equals(action)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasSubject(AclSubject subject) { // if (subjects == null || subject == null) return false; // // for (AclSubject target : subjects) { // if (target.equals(subject)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasActions() { // return (actions != null && !actions.isEmpty()); // } // // @Override // public boolean hasSubjects() { // return (subjects != null && !subjects.isEmpty()); // } // // @Override // public List<AclAction> getActions(String name, String permission) { // List<AclAction> result = new ArrayList<AclAction>(); // // if (actions == null) return result; // // for (AclAction target : actions) { // if (target.getName().equals(name) && target.getPermission().equals(permission)) { // result.add(target); // } // } // // return result; // } // // @Override // public List<AclSubject> getSubjects(String type) { // List<AclSubject> result = new ArrayList<AclSubject>(); // // if (subjects == null || type == null) return result; // // for (AclSubject aclSubject : result) { // if (aclSubject.getType().equals(type)) { // result.add(aclSubject); // } // } // // return result; // } // // }
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.TimeZone; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.OneToMany; import org.onesocialweb.model.acl.AclRule; import org.onesocialweb.model.vcard4.TimeZoneField; import org.onesocialweb.openfire.model.acl.PersistentAclRule;
package org.onesocialweb.openfire.model.vcard4; @Entity(name="TimeZoneField") public class PersistentTimeZoneField extends TimeZoneField {
// Path: src/java/org/onesocialweb/openfire/model/acl/PersistentAclRule.java // @Entity(name="AclRule") // public class PersistentAclRule implements AclRule { // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclSubject.class, fetch=FetchType.EAGER) // private List<AclSubject> subjects = new ArrayList<AclSubject>(); // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclAction.class, fetch=FetchType.EAGER) // private List<AclAction> actions = new ArrayList<AclAction>(); // // @Override // public List<AclAction> getActions() { // return actions; // } // // @Override // public void setActions(List<AclAction> actions) { // this.actions = actions; // } // // @Override // public List<AclSubject> getSubjects() { // return subjects; // } // // @Override // public void setSubjects(List<AclSubject> subjects) { // this.subjects = subjects; // } // // @Override // public void addAction(AclAction action) { // this.actions.add(action); // } // // @Override // public void addSubject(AclSubject subject) { // this.subjects.add(subject); // } // // @Override // public void removeAction(AclAction action) { // this.actions.remove(action); // } // // @Override // public void removeSubject(AclSubject subject) { // this.subjects.remove(subject); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof AclRule) { // AclRule rule = (AclRule) obj; // return actions.equals(rule.getActions()) // && subjects.equals(rule.getSubjects()); // } else { // return false; // } // } // // @Override // public String toString() { // StringBuffer buffer = new StringBuffer(); // buffer.append("[AclRule "); // for (AclAction action : actions) { // buffer.append(action); // } // for (AclSubject subject : subjects) { // buffer.append(subject); // } // buffer.append("]"); // return buffer.toString(); // } // // @Override // public boolean hasAction(AclAction action) { // if (actions == null || action == null) return false; // // for (AclAction target : actions) { // if (target.equals(action)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasSubject(AclSubject subject) { // if (subjects == null || subject == null) return false; // // for (AclSubject target : subjects) { // if (target.equals(subject)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasActions() { // return (actions != null && !actions.isEmpty()); // } // // @Override // public boolean hasSubjects() { // return (subjects != null && !subjects.isEmpty()); // } // // @Override // public List<AclAction> getActions(String name, String permission) { // List<AclAction> result = new ArrayList<AclAction>(); // // if (actions == null) return result; // // for (AclAction target : actions) { // if (target.getName().equals(name) && target.getPermission().equals(permission)) { // result.add(target); // } // } // // return result; // } // // @Override // public List<AclSubject> getSubjects(String type) { // List<AclSubject> result = new ArrayList<AclSubject>(); // // if (subjects == null || type == null) return result; // // for (AclSubject aclSubject : result) { // if (aclSubject.getType().equals(type)) { // result.add(aclSubject); // } // } // // return result; // } // // } // Path: src/java/org/onesocialweb/openfire/model/vcard4/PersistentTimeZoneField.java import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.TimeZone; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.OneToMany; import org.onesocialweb.model.acl.AclRule; import org.onesocialweb.model.vcard4.TimeZoneField; import org.onesocialweb.openfire.model.acl.PersistentAclRule; package org.onesocialweb.openfire.model.vcard4; @Entity(name="TimeZoneField") public class PersistentTimeZoneField extends TimeZoneField {
@OneToMany(cascade=CascadeType.ALL, targetEntity=PersistentAclRule.class, fetch=FetchType.EAGER)
onesocialweb/osw-openfire-plugin
src/java/org/onesocialweb/openfire/model/vcard4/PersistentNoteField.java
// Path: src/java/org/onesocialweb/openfire/model/acl/PersistentAclRule.java // @Entity(name="AclRule") // public class PersistentAclRule implements AclRule { // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclSubject.class, fetch=FetchType.EAGER) // private List<AclSubject> subjects = new ArrayList<AclSubject>(); // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclAction.class, fetch=FetchType.EAGER) // private List<AclAction> actions = new ArrayList<AclAction>(); // // @Override // public List<AclAction> getActions() { // return actions; // } // // @Override // public void setActions(List<AclAction> actions) { // this.actions = actions; // } // // @Override // public List<AclSubject> getSubjects() { // return subjects; // } // // @Override // public void setSubjects(List<AclSubject> subjects) { // this.subjects = subjects; // } // // @Override // public void addAction(AclAction action) { // this.actions.add(action); // } // // @Override // public void addSubject(AclSubject subject) { // this.subjects.add(subject); // } // // @Override // public void removeAction(AclAction action) { // this.actions.remove(action); // } // // @Override // public void removeSubject(AclSubject subject) { // this.subjects.remove(subject); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof AclRule) { // AclRule rule = (AclRule) obj; // return actions.equals(rule.getActions()) // && subjects.equals(rule.getSubjects()); // } else { // return false; // } // } // // @Override // public String toString() { // StringBuffer buffer = new StringBuffer(); // buffer.append("[AclRule "); // for (AclAction action : actions) { // buffer.append(action); // } // for (AclSubject subject : subjects) { // buffer.append(subject); // } // buffer.append("]"); // return buffer.toString(); // } // // @Override // public boolean hasAction(AclAction action) { // if (actions == null || action == null) return false; // // for (AclAction target : actions) { // if (target.equals(action)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasSubject(AclSubject subject) { // if (subjects == null || subject == null) return false; // // for (AclSubject target : subjects) { // if (target.equals(subject)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasActions() { // return (actions != null && !actions.isEmpty()); // } // // @Override // public boolean hasSubjects() { // return (subjects != null && !subjects.isEmpty()); // } // // @Override // public List<AclAction> getActions(String name, String permission) { // List<AclAction> result = new ArrayList<AclAction>(); // // if (actions == null) return result; // // for (AclAction target : actions) { // if (target.getName().equals(name) && target.getPermission().equals(permission)) { // result.add(target); // } // } // // return result; // } // // @Override // public List<AclSubject> getSubjects(String type) { // List<AclSubject> result = new ArrayList<AclSubject>(); // // if (subjects == null || type == null) return result; // // for (AclSubject aclSubject : result) { // if (aclSubject.getType().equals(type)) { // result.add(aclSubject); // } // } // // return result; // } // // }
import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.OneToMany; import org.onesocialweb.model.acl.AclRule; import org.onesocialweb.model.vcard4.NoteField; import org.onesocialweb.openfire.model.acl.PersistentAclRule;
/* * Copyright 2010 Vodafone Group Services Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.onesocialweb.openfire.model.vcard4; @Entity(name="NoteField") public class PersistentNoteField extends NoteField {
// Path: src/java/org/onesocialweb/openfire/model/acl/PersistentAclRule.java // @Entity(name="AclRule") // public class PersistentAclRule implements AclRule { // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclSubject.class, fetch=FetchType.EAGER) // private List<AclSubject> subjects = new ArrayList<AclSubject>(); // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclAction.class, fetch=FetchType.EAGER) // private List<AclAction> actions = new ArrayList<AclAction>(); // // @Override // public List<AclAction> getActions() { // return actions; // } // // @Override // public void setActions(List<AclAction> actions) { // this.actions = actions; // } // // @Override // public List<AclSubject> getSubjects() { // return subjects; // } // // @Override // public void setSubjects(List<AclSubject> subjects) { // this.subjects = subjects; // } // // @Override // public void addAction(AclAction action) { // this.actions.add(action); // } // // @Override // public void addSubject(AclSubject subject) { // this.subjects.add(subject); // } // // @Override // public void removeAction(AclAction action) { // this.actions.remove(action); // } // // @Override // public void removeSubject(AclSubject subject) { // this.subjects.remove(subject); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof AclRule) { // AclRule rule = (AclRule) obj; // return actions.equals(rule.getActions()) // && subjects.equals(rule.getSubjects()); // } else { // return false; // } // } // // @Override // public String toString() { // StringBuffer buffer = new StringBuffer(); // buffer.append("[AclRule "); // for (AclAction action : actions) { // buffer.append(action); // } // for (AclSubject subject : subjects) { // buffer.append(subject); // } // buffer.append("]"); // return buffer.toString(); // } // // @Override // public boolean hasAction(AclAction action) { // if (actions == null || action == null) return false; // // for (AclAction target : actions) { // if (target.equals(action)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasSubject(AclSubject subject) { // if (subjects == null || subject == null) return false; // // for (AclSubject target : subjects) { // if (target.equals(subject)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasActions() { // return (actions != null && !actions.isEmpty()); // } // // @Override // public boolean hasSubjects() { // return (subjects != null && !subjects.isEmpty()); // } // // @Override // public List<AclAction> getActions(String name, String permission) { // List<AclAction> result = new ArrayList<AclAction>(); // // if (actions == null) return result; // // for (AclAction target : actions) { // if (target.getName().equals(name) && target.getPermission().equals(permission)) { // result.add(target); // } // } // // return result; // } // // @Override // public List<AclSubject> getSubjects(String type) { // List<AclSubject> result = new ArrayList<AclSubject>(); // // if (subjects == null || type == null) return result; // // for (AclSubject aclSubject : result) { // if (aclSubject.getType().equals(type)) { // result.add(aclSubject); // } // } // // return result; // } // // } // Path: src/java/org/onesocialweb/openfire/model/vcard4/PersistentNoteField.java import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.OneToMany; import org.onesocialweb.model.acl.AclRule; import org.onesocialweb.model.vcard4.NoteField; import org.onesocialweb.openfire.model.acl.PersistentAclRule; /* * Copyright 2010 Vodafone Group Services Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.onesocialweb.openfire.model.vcard4; @Entity(name="NoteField") public class PersistentNoteField extends NoteField {
@OneToMany(cascade=CascadeType.ALL, targetEntity=PersistentAclRule.class, fetch=FetchType.EAGER)
onesocialweb/osw-openfire-plugin
src/java/org/onesocialweb/openfire/model/vcard4/PersistentEmailField.java
// Path: src/java/org/onesocialweb/openfire/model/acl/PersistentAclRule.java // @Entity(name="AclRule") // public class PersistentAclRule implements AclRule { // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclSubject.class, fetch=FetchType.EAGER) // private List<AclSubject> subjects = new ArrayList<AclSubject>(); // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclAction.class, fetch=FetchType.EAGER) // private List<AclAction> actions = new ArrayList<AclAction>(); // // @Override // public List<AclAction> getActions() { // return actions; // } // // @Override // public void setActions(List<AclAction> actions) { // this.actions = actions; // } // // @Override // public List<AclSubject> getSubjects() { // return subjects; // } // // @Override // public void setSubjects(List<AclSubject> subjects) { // this.subjects = subjects; // } // // @Override // public void addAction(AclAction action) { // this.actions.add(action); // } // // @Override // public void addSubject(AclSubject subject) { // this.subjects.add(subject); // } // // @Override // public void removeAction(AclAction action) { // this.actions.remove(action); // } // // @Override // public void removeSubject(AclSubject subject) { // this.subjects.remove(subject); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof AclRule) { // AclRule rule = (AclRule) obj; // return actions.equals(rule.getActions()) // && subjects.equals(rule.getSubjects()); // } else { // return false; // } // } // // @Override // public String toString() { // StringBuffer buffer = new StringBuffer(); // buffer.append("[AclRule "); // for (AclAction action : actions) { // buffer.append(action); // } // for (AclSubject subject : subjects) { // buffer.append(subject); // } // buffer.append("]"); // return buffer.toString(); // } // // @Override // public boolean hasAction(AclAction action) { // if (actions == null || action == null) return false; // // for (AclAction target : actions) { // if (target.equals(action)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasSubject(AclSubject subject) { // if (subjects == null || subject == null) return false; // // for (AclSubject target : subjects) { // if (target.equals(subject)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasActions() { // return (actions != null && !actions.isEmpty()); // } // // @Override // public boolean hasSubjects() { // return (subjects != null && !subjects.isEmpty()); // } // // @Override // public List<AclAction> getActions(String name, String permission) { // List<AclAction> result = new ArrayList<AclAction>(); // // if (actions == null) return result; // // for (AclAction target : actions) { // if (target.getName().equals(name) && target.getPermission().equals(permission)) { // result.add(target); // } // } // // return result; // } // // @Override // public List<AclSubject> getSubjects(String type) { // List<AclSubject> result = new ArrayList<AclSubject>(); // // if (subjects == null || type == null) return result; // // for (AclSubject aclSubject : result) { // if (aclSubject.getType().equals(type)) { // result.add(aclSubject); // } // } // // return result; // } // // }
import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.OneToMany; import org.onesocialweb.model.acl.AclRule; import org.onesocialweb.model.vcard4.EmailField; import org.onesocialweb.openfire.model.acl.PersistentAclRule;
package org.onesocialweb.openfire.model.vcard4; @Entity(name="EmailField") public class PersistentEmailField extends EmailField {
// Path: src/java/org/onesocialweb/openfire/model/acl/PersistentAclRule.java // @Entity(name="AclRule") // public class PersistentAclRule implements AclRule { // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclSubject.class, fetch=FetchType.EAGER) // private List<AclSubject> subjects = new ArrayList<AclSubject>(); // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclAction.class, fetch=FetchType.EAGER) // private List<AclAction> actions = new ArrayList<AclAction>(); // // @Override // public List<AclAction> getActions() { // return actions; // } // // @Override // public void setActions(List<AclAction> actions) { // this.actions = actions; // } // // @Override // public List<AclSubject> getSubjects() { // return subjects; // } // // @Override // public void setSubjects(List<AclSubject> subjects) { // this.subjects = subjects; // } // // @Override // public void addAction(AclAction action) { // this.actions.add(action); // } // // @Override // public void addSubject(AclSubject subject) { // this.subjects.add(subject); // } // // @Override // public void removeAction(AclAction action) { // this.actions.remove(action); // } // // @Override // public void removeSubject(AclSubject subject) { // this.subjects.remove(subject); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof AclRule) { // AclRule rule = (AclRule) obj; // return actions.equals(rule.getActions()) // && subjects.equals(rule.getSubjects()); // } else { // return false; // } // } // // @Override // public String toString() { // StringBuffer buffer = new StringBuffer(); // buffer.append("[AclRule "); // for (AclAction action : actions) { // buffer.append(action); // } // for (AclSubject subject : subjects) { // buffer.append(subject); // } // buffer.append("]"); // return buffer.toString(); // } // // @Override // public boolean hasAction(AclAction action) { // if (actions == null || action == null) return false; // // for (AclAction target : actions) { // if (target.equals(action)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasSubject(AclSubject subject) { // if (subjects == null || subject == null) return false; // // for (AclSubject target : subjects) { // if (target.equals(subject)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasActions() { // return (actions != null && !actions.isEmpty()); // } // // @Override // public boolean hasSubjects() { // return (subjects != null && !subjects.isEmpty()); // } // // @Override // public List<AclAction> getActions(String name, String permission) { // List<AclAction> result = new ArrayList<AclAction>(); // // if (actions == null) return result; // // for (AclAction target : actions) { // if (target.getName().equals(name) && target.getPermission().equals(permission)) { // result.add(target); // } // } // // return result; // } // // @Override // public List<AclSubject> getSubjects(String type) { // List<AclSubject> result = new ArrayList<AclSubject>(); // // if (subjects == null || type == null) return result; // // for (AclSubject aclSubject : result) { // if (aclSubject.getType().equals(type)) { // result.add(aclSubject); // } // } // // return result; // } // // } // Path: src/java/org/onesocialweb/openfire/model/vcard4/PersistentEmailField.java import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.OneToMany; import org.onesocialweb.model.acl.AclRule; import org.onesocialweb.model.vcard4.EmailField; import org.onesocialweb.openfire.model.acl.PersistentAclRule; package org.onesocialweb.openfire.model.vcard4; @Entity(name="EmailField") public class PersistentEmailField extends EmailField {
@OneToMany(cascade=CascadeType.ALL, targetEntity=PersistentAclRule.class, fetch=FetchType.EAGER)
onesocialweb/osw-openfire-plugin
src/java/org/onesocialweb/openfire/model/vcard4/PersistentFullNameField.java
// Path: src/java/org/onesocialweb/openfire/model/acl/PersistentAclRule.java // @Entity(name="AclRule") // public class PersistentAclRule implements AclRule { // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclSubject.class, fetch=FetchType.EAGER) // private List<AclSubject> subjects = new ArrayList<AclSubject>(); // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclAction.class, fetch=FetchType.EAGER) // private List<AclAction> actions = new ArrayList<AclAction>(); // // @Override // public List<AclAction> getActions() { // return actions; // } // // @Override // public void setActions(List<AclAction> actions) { // this.actions = actions; // } // // @Override // public List<AclSubject> getSubjects() { // return subjects; // } // // @Override // public void setSubjects(List<AclSubject> subjects) { // this.subjects = subjects; // } // // @Override // public void addAction(AclAction action) { // this.actions.add(action); // } // // @Override // public void addSubject(AclSubject subject) { // this.subjects.add(subject); // } // // @Override // public void removeAction(AclAction action) { // this.actions.remove(action); // } // // @Override // public void removeSubject(AclSubject subject) { // this.subjects.remove(subject); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof AclRule) { // AclRule rule = (AclRule) obj; // return actions.equals(rule.getActions()) // && subjects.equals(rule.getSubjects()); // } else { // return false; // } // } // // @Override // public String toString() { // StringBuffer buffer = new StringBuffer(); // buffer.append("[AclRule "); // for (AclAction action : actions) { // buffer.append(action); // } // for (AclSubject subject : subjects) { // buffer.append(subject); // } // buffer.append("]"); // return buffer.toString(); // } // // @Override // public boolean hasAction(AclAction action) { // if (actions == null || action == null) return false; // // for (AclAction target : actions) { // if (target.equals(action)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasSubject(AclSubject subject) { // if (subjects == null || subject == null) return false; // // for (AclSubject target : subjects) { // if (target.equals(subject)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasActions() { // return (actions != null && !actions.isEmpty()); // } // // @Override // public boolean hasSubjects() { // return (subjects != null && !subjects.isEmpty()); // } // // @Override // public List<AclAction> getActions(String name, String permission) { // List<AclAction> result = new ArrayList<AclAction>(); // // if (actions == null) return result; // // for (AclAction target : actions) { // if (target.getName().equals(name) && target.getPermission().equals(permission)) { // result.add(target); // } // } // // return result; // } // // @Override // public List<AclSubject> getSubjects(String type) { // List<AclSubject> result = new ArrayList<AclSubject>(); // // if (subjects == null || type == null) return result; // // for (AclSubject aclSubject : result) { // if (aclSubject.getType().equals(type)) { // result.add(aclSubject); // } // } // // return result; // } // // }
import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.OneToMany; import org.onesocialweb.model.acl.AclRule; import org.onesocialweb.model.vcard4.FullNameField; import org.onesocialweb.openfire.model.acl.PersistentAclRule;
/* * Copyright 2010 Vodafone Group Services Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.onesocialweb.openfire.model.vcard4; @Entity(name="FullNameField") public class PersistentFullNameField extends FullNameField {
// Path: src/java/org/onesocialweb/openfire/model/acl/PersistentAclRule.java // @Entity(name="AclRule") // public class PersistentAclRule implements AclRule { // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclSubject.class, fetch=FetchType.EAGER) // private List<AclSubject> subjects = new ArrayList<AclSubject>(); // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclAction.class, fetch=FetchType.EAGER) // private List<AclAction> actions = new ArrayList<AclAction>(); // // @Override // public List<AclAction> getActions() { // return actions; // } // // @Override // public void setActions(List<AclAction> actions) { // this.actions = actions; // } // // @Override // public List<AclSubject> getSubjects() { // return subjects; // } // // @Override // public void setSubjects(List<AclSubject> subjects) { // this.subjects = subjects; // } // // @Override // public void addAction(AclAction action) { // this.actions.add(action); // } // // @Override // public void addSubject(AclSubject subject) { // this.subjects.add(subject); // } // // @Override // public void removeAction(AclAction action) { // this.actions.remove(action); // } // // @Override // public void removeSubject(AclSubject subject) { // this.subjects.remove(subject); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof AclRule) { // AclRule rule = (AclRule) obj; // return actions.equals(rule.getActions()) // && subjects.equals(rule.getSubjects()); // } else { // return false; // } // } // // @Override // public String toString() { // StringBuffer buffer = new StringBuffer(); // buffer.append("[AclRule "); // for (AclAction action : actions) { // buffer.append(action); // } // for (AclSubject subject : subjects) { // buffer.append(subject); // } // buffer.append("]"); // return buffer.toString(); // } // // @Override // public boolean hasAction(AclAction action) { // if (actions == null || action == null) return false; // // for (AclAction target : actions) { // if (target.equals(action)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasSubject(AclSubject subject) { // if (subjects == null || subject == null) return false; // // for (AclSubject target : subjects) { // if (target.equals(subject)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasActions() { // return (actions != null && !actions.isEmpty()); // } // // @Override // public boolean hasSubjects() { // return (subjects != null && !subjects.isEmpty()); // } // // @Override // public List<AclAction> getActions(String name, String permission) { // List<AclAction> result = new ArrayList<AclAction>(); // // if (actions == null) return result; // // for (AclAction target : actions) { // if (target.getName().equals(name) && target.getPermission().equals(permission)) { // result.add(target); // } // } // // return result; // } // // @Override // public List<AclSubject> getSubjects(String type) { // List<AclSubject> result = new ArrayList<AclSubject>(); // // if (subjects == null || type == null) return result; // // for (AclSubject aclSubject : result) { // if (aclSubject.getType().equals(type)) { // result.add(aclSubject); // } // } // // return result; // } // // } // Path: src/java/org/onesocialweb/openfire/model/vcard4/PersistentFullNameField.java import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.OneToMany; import org.onesocialweb.model.acl.AclRule; import org.onesocialweb.model.vcard4.FullNameField; import org.onesocialweb.openfire.model.acl.PersistentAclRule; /* * Copyright 2010 Vodafone Group Services Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.onesocialweb.openfire.model.vcard4; @Entity(name="FullNameField") public class PersistentFullNameField extends FullNameField {
@OneToMany(cascade=CascadeType.ALL, targetEntity=PersistentAclRule.class, fetch=FetchType.EAGER)
onesocialweb/osw-openfire-plugin
src/java/org/onesocialweb/openfire/model/vcard4/PersistentGenderField.java
// Path: src/java/org/onesocialweb/openfire/model/acl/PersistentAclRule.java // @Entity(name="AclRule") // public class PersistentAclRule implements AclRule { // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclSubject.class, fetch=FetchType.EAGER) // private List<AclSubject> subjects = new ArrayList<AclSubject>(); // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclAction.class, fetch=FetchType.EAGER) // private List<AclAction> actions = new ArrayList<AclAction>(); // // @Override // public List<AclAction> getActions() { // return actions; // } // // @Override // public void setActions(List<AclAction> actions) { // this.actions = actions; // } // // @Override // public List<AclSubject> getSubjects() { // return subjects; // } // // @Override // public void setSubjects(List<AclSubject> subjects) { // this.subjects = subjects; // } // // @Override // public void addAction(AclAction action) { // this.actions.add(action); // } // // @Override // public void addSubject(AclSubject subject) { // this.subjects.add(subject); // } // // @Override // public void removeAction(AclAction action) { // this.actions.remove(action); // } // // @Override // public void removeSubject(AclSubject subject) { // this.subjects.remove(subject); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof AclRule) { // AclRule rule = (AclRule) obj; // return actions.equals(rule.getActions()) // && subjects.equals(rule.getSubjects()); // } else { // return false; // } // } // // @Override // public String toString() { // StringBuffer buffer = new StringBuffer(); // buffer.append("[AclRule "); // for (AclAction action : actions) { // buffer.append(action); // } // for (AclSubject subject : subjects) { // buffer.append(subject); // } // buffer.append("]"); // return buffer.toString(); // } // // @Override // public boolean hasAction(AclAction action) { // if (actions == null || action == null) return false; // // for (AclAction target : actions) { // if (target.equals(action)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasSubject(AclSubject subject) { // if (subjects == null || subject == null) return false; // // for (AclSubject target : subjects) { // if (target.equals(subject)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasActions() { // return (actions != null && !actions.isEmpty()); // } // // @Override // public boolean hasSubjects() { // return (subjects != null && !subjects.isEmpty()); // } // // @Override // public List<AclAction> getActions(String name, String permission) { // List<AclAction> result = new ArrayList<AclAction>(); // // if (actions == null) return result; // // for (AclAction target : actions) { // if (target.getName().equals(name) && target.getPermission().equals(permission)) { // result.add(target); // } // } // // return result; // } // // @Override // public List<AclSubject> getSubjects(String type) { // List<AclSubject> result = new ArrayList<AclSubject>(); // // if (subjects == null || type == null) return result; // // for (AclSubject aclSubject : result) { // if (aclSubject.getType().equals(type)) { // result.add(aclSubject); // } // } // // return result; // } // // }
import org.onesocialweb.openfire.model.acl.PersistentAclRule; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.OneToMany; import org.onesocialweb.model.acl.AclRule; import org.onesocialweb.model.vcard4.GenderField;
/* * Copyright 2010 Vodafone Group Services Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.onesocialweb.openfire.model.vcard4; @Entity(name="GenderField") public class PersistentGenderField extends GenderField {
// Path: src/java/org/onesocialweb/openfire/model/acl/PersistentAclRule.java // @Entity(name="AclRule") // public class PersistentAclRule implements AclRule { // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclSubject.class, fetch=FetchType.EAGER) // private List<AclSubject> subjects = new ArrayList<AclSubject>(); // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclAction.class, fetch=FetchType.EAGER) // private List<AclAction> actions = new ArrayList<AclAction>(); // // @Override // public List<AclAction> getActions() { // return actions; // } // // @Override // public void setActions(List<AclAction> actions) { // this.actions = actions; // } // // @Override // public List<AclSubject> getSubjects() { // return subjects; // } // // @Override // public void setSubjects(List<AclSubject> subjects) { // this.subjects = subjects; // } // // @Override // public void addAction(AclAction action) { // this.actions.add(action); // } // // @Override // public void addSubject(AclSubject subject) { // this.subjects.add(subject); // } // // @Override // public void removeAction(AclAction action) { // this.actions.remove(action); // } // // @Override // public void removeSubject(AclSubject subject) { // this.subjects.remove(subject); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof AclRule) { // AclRule rule = (AclRule) obj; // return actions.equals(rule.getActions()) // && subjects.equals(rule.getSubjects()); // } else { // return false; // } // } // // @Override // public String toString() { // StringBuffer buffer = new StringBuffer(); // buffer.append("[AclRule "); // for (AclAction action : actions) { // buffer.append(action); // } // for (AclSubject subject : subjects) { // buffer.append(subject); // } // buffer.append("]"); // return buffer.toString(); // } // // @Override // public boolean hasAction(AclAction action) { // if (actions == null || action == null) return false; // // for (AclAction target : actions) { // if (target.equals(action)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasSubject(AclSubject subject) { // if (subjects == null || subject == null) return false; // // for (AclSubject target : subjects) { // if (target.equals(subject)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasActions() { // return (actions != null && !actions.isEmpty()); // } // // @Override // public boolean hasSubjects() { // return (subjects != null && !subjects.isEmpty()); // } // // @Override // public List<AclAction> getActions(String name, String permission) { // List<AclAction> result = new ArrayList<AclAction>(); // // if (actions == null) return result; // // for (AclAction target : actions) { // if (target.getName().equals(name) && target.getPermission().equals(permission)) { // result.add(target); // } // } // // return result; // } // // @Override // public List<AclSubject> getSubjects(String type) { // List<AclSubject> result = new ArrayList<AclSubject>(); // // if (subjects == null || type == null) return result; // // for (AclSubject aclSubject : result) { // if (aclSubject.getType().equals(type)) { // result.add(aclSubject); // } // } // // return result; // } // // } // Path: src/java/org/onesocialweb/openfire/model/vcard4/PersistentGenderField.java import org.onesocialweb.openfire.model.acl.PersistentAclRule; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.OneToMany; import org.onesocialweb.model.acl.AclRule; import org.onesocialweb.model.vcard4.GenderField; /* * Copyright 2010 Vodafone Group Services Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.onesocialweb.openfire.model.vcard4; @Entity(name="GenderField") public class PersistentGenderField extends GenderField {
@OneToMany(cascade=CascadeType.ALL, targetEntity=PersistentAclRule.class, fetch=FetchType.EAGER)
onesocialweb/osw-openfire-plugin
src/java/org/onesocialweb/openfire/model/vcard4/PersistentPhotoField.java
// Path: src/java/org/onesocialweb/openfire/model/acl/PersistentAclRule.java // @Entity(name="AclRule") // public class PersistentAclRule implements AclRule { // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclSubject.class, fetch=FetchType.EAGER) // private List<AclSubject> subjects = new ArrayList<AclSubject>(); // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclAction.class, fetch=FetchType.EAGER) // private List<AclAction> actions = new ArrayList<AclAction>(); // // @Override // public List<AclAction> getActions() { // return actions; // } // // @Override // public void setActions(List<AclAction> actions) { // this.actions = actions; // } // // @Override // public List<AclSubject> getSubjects() { // return subjects; // } // // @Override // public void setSubjects(List<AclSubject> subjects) { // this.subjects = subjects; // } // // @Override // public void addAction(AclAction action) { // this.actions.add(action); // } // // @Override // public void addSubject(AclSubject subject) { // this.subjects.add(subject); // } // // @Override // public void removeAction(AclAction action) { // this.actions.remove(action); // } // // @Override // public void removeSubject(AclSubject subject) { // this.subjects.remove(subject); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof AclRule) { // AclRule rule = (AclRule) obj; // return actions.equals(rule.getActions()) // && subjects.equals(rule.getSubjects()); // } else { // return false; // } // } // // @Override // public String toString() { // StringBuffer buffer = new StringBuffer(); // buffer.append("[AclRule "); // for (AclAction action : actions) { // buffer.append(action); // } // for (AclSubject subject : subjects) { // buffer.append(subject); // } // buffer.append("]"); // return buffer.toString(); // } // // @Override // public boolean hasAction(AclAction action) { // if (actions == null || action == null) return false; // // for (AclAction target : actions) { // if (target.equals(action)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasSubject(AclSubject subject) { // if (subjects == null || subject == null) return false; // // for (AclSubject target : subjects) { // if (target.equals(subject)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasActions() { // return (actions != null && !actions.isEmpty()); // } // // @Override // public boolean hasSubjects() { // return (subjects != null && !subjects.isEmpty()); // } // // @Override // public List<AclAction> getActions(String name, String permission) { // List<AclAction> result = new ArrayList<AclAction>(); // // if (actions == null) return result; // // for (AclAction target : actions) { // if (target.getName().equals(name) && target.getPermission().equals(permission)) { // result.add(target); // } // } // // return result; // } // // @Override // public List<AclSubject> getSubjects(String type) { // List<AclSubject> result = new ArrayList<AclSubject>(); // // if (subjects == null || type == null) return result; // // for (AclSubject aclSubject : result) { // if (aclSubject.getType().equals(type)) { // result.add(aclSubject); // } // } // // return result; // } // // }
import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.OneToMany; import org.onesocialweb.model.acl.AclRule; import org.onesocialweb.model.vcard4.PhotoField; import org.onesocialweb.openfire.model.acl.PersistentAclRule;
/* * Copyright 2010 Vodafone Group Services Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.onesocialweb.openfire.model.vcard4; @Entity(name="PhotoField") public class PersistentPhotoField extends PhotoField {
// Path: src/java/org/onesocialweb/openfire/model/acl/PersistentAclRule.java // @Entity(name="AclRule") // public class PersistentAclRule implements AclRule { // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclSubject.class, fetch=FetchType.EAGER) // private List<AclSubject> subjects = new ArrayList<AclSubject>(); // // @OneToMany(cascade=CascadeType.ALL, targetEntity=org.onesocialweb.openfire.model.acl.PersistentAclAction.class, fetch=FetchType.EAGER) // private List<AclAction> actions = new ArrayList<AclAction>(); // // @Override // public List<AclAction> getActions() { // return actions; // } // // @Override // public void setActions(List<AclAction> actions) { // this.actions = actions; // } // // @Override // public List<AclSubject> getSubjects() { // return subjects; // } // // @Override // public void setSubjects(List<AclSubject> subjects) { // this.subjects = subjects; // } // // @Override // public void addAction(AclAction action) { // this.actions.add(action); // } // // @Override // public void addSubject(AclSubject subject) { // this.subjects.add(subject); // } // // @Override // public void removeAction(AclAction action) { // this.actions.remove(action); // } // // @Override // public void removeSubject(AclSubject subject) { // this.subjects.remove(subject); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof AclRule) { // AclRule rule = (AclRule) obj; // return actions.equals(rule.getActions()) // && subjects.equals(rule.getSubjects()); // } else { // return false; // } // } // // @Override // public String toString() { // StringBuffer buffer = new StringBuffer(); // buffer.append("[AclRule "); // for (AclAction action : actions) { // buffer.append(action); // } // for (AclSubject subject : subjects) { // buffer.append(subject); // } // buffer.append("]"); // return buffer.toString(); // } // // @Override // public boolean hasAction(AclAction action) { // if (actions == null || action == null) return false; // // for (AclAction target : actions) { // if (target.equals(action)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasSubject(AclSubject subject) { // if (subjects == null || subject == null) return false; // // for (AclSubject target : subjects) { // if (target.equals(subject)) { // return true; // } // } // // return false; // } // // @Override // public boolean hasActions() { // return (actions != null && !actions.isEmpty()); // } // // @Override // public boolean hasSubjects() { // return (subjects != null && !subjects.isEmpty()); // } // // @Override // public List<AclAction> getActions(String name, String permission) { // List<AclAction> result = new ArrayList<AclAction>(); // // if (actions == null) return result; // // for (AclAction target : actions) { // if (target.getName().equals(name) && target.getPermission().equals(permission)) { // result.add(target); // } // } // // return result; // } // // @Override // public List<AclSubject> getSubjects(String type) { // List<AclSubject> result = new ArrayList<AclSubject>(); // // if (subjects == null || type == null) return result; // // for (AclSubject aclSubject : result) { // if (aclSubject.getType().equals(type)) { // result.add(aclSubject); // } // } // // return result; // } // // } // Path: src/java/org/onesocialweb/openfire/model/vcard4/PersistentPhotoField.java import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.OneToMany; import org.onesocialweb.model.acl.AclRule; import org.onesocialweb.model.vcard4.PhotoField; import org.onesocialweb.openfire.model.acl.PersistentAclRule; /* * Copyright 2010 Vodafone Group Services Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.onesocialweb.openfire.model.vcard4; @Entity(name="PhotoField") public class PersistentPhotoField extends PhotoField {
@OneToMany(cascade=CascadeType.ALL, targetEntity=PersistentAclRule.class, fetch=FetchType.EAGER)
takyonxxx/Flight-Computer-Android-Flightradar24
src/com/nutiteq/utils/MbTilesDatabaseHelper.java
// Path: src/com/nutiteq/utils/UtfGridHelper.java // public static class MBTileUTFGrid { // public String[] grid = null; // public String[] keys = null; // public JSONObject data = null; // // }
import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import com.nutiteq.components.MapTile; import com.nutiteq.components.MutableMapPos; import com.nutiteq.utils.UtfGridHelper.MBTileUTFGrid; import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Template;
.rawQuery("SELECT name,value FROM metadata",null); while(c.moveToNext()){ metadata.put(c.getString(0), c.getString(1)); } while (c.moveToNext()); c.close(); return metadata; } /** * Query UTFGrid tooltip values from database for given hover/clicked location * * @param p position on map, in EPSG3857 * @param zoom current map zoom * @return KV map with data from JSON. If template is given then templated_teaser and templated_full values are added with HTML */ public Map<String, String> getUtfGridTooltips(MapTile clickedTile, MutableMapPos tilePos) { Map<String, String> data = new HashMap<String, String>(); // what is current tile in clicked location, and specific pixel of this int tileSize = 256; int zoom = clickedTile.zoom; int clickedX = (int) (tilePos.x * 256); int clickedY = 256 - (int) (tilePos.y * 256); //Log.debug("clicked on tile "+zoom+"/"+clickedTile.x+"/"+clickedTile.y+" point:"+clickedX+":"+clickedY); // get UTFGrid data for the tile
// Path: src/com/nutiteq/utils/UtfGridHelper.java // public static class MBTileUTFGrid { // public String[] grid = null; // public String[] keys = null; // public JSONObject data = null; // // } // Path: src/com/nutiteq/utils/MbTilesDatabaseHelper.java import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import com.nutiteq.components.MapTile; import com.nutiteq.components.MutableMapPos; import com.nutiteq.utils.UtfGridHelper.MBTileUTFGrid; import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Template; .rawQuery("SELECT name,value FROM metadata",null); while(c.moveToNext()){ metadata.put(c.getString(0), c.getString(1)); } while (c.moveToNext()); c.close(); return metadata; } /** * Query UTFGrid tooltip values from database for given hover/clicked location * * @param p position on map, in EPSG3857 * @param zoom current map zoom * @return KV map with data from JSON. If template is given then templated_teaser and templated_full values are added with HTML */ public Map<String, String> getUtfGridTooltips(MapTile clickedTile, MutableMapPos tilePos) { Map<String, String> data = new HashMap<String, String>(); // what is current tile in clicked location, and specific pixel of this int tileSize = 256; int zoom = clickedTile.zoom; int clickedX = (int) (tilePos.x * 256); int clickedY = 256 - (int) (tilePos.y * 256); //Log.debug("clicked on tile "+zoom+"/"+clickedTile.x+"/"+clickedTile.y+" point:"+clickedX+":"+clickedY); // get UTFGrid data for the tile
MBTileUTFGrid grid = getUTFGrid((int)zoom, clickedTile.x, (1 << (zoom)) - 1 - clickedTile.y);
takyonxxx/Flight-Computer-Android-Flightradar24
src/com/flightcomputer/PressureAltimeterActivity.java
// Path: src/com/flightcomputer/utilities/KalmanFilter.java // public class KalmanFilter { // // The state we are tracking, namely: // private double x_abs_; // The absolute value of x. // private double x_vel_; // The rate of change of x. // // // Covariance matrix for the state. // private double p_abs_abs_; // private double p_abs_vel_; // private double p_vel_vel_; // // // The variance of the acceleration noise input in the system model. // private double var_accel_; // // // Constructor. Assumes a variance of 1.0 for the system model's // // acceleration noise input, in units per second squared. // public KalmanFilter() { // setAccelerationVariance(1.); // reset(); // } // // // Constructor. Caller supplies the variance for the system model's // // acceleration noise input, in units per second squared. // public KalmanFilter(double var_accel) { // setAccelerationVariance(var_accel); // reset(); // } // // // The following three methods reset the filter. All of them assign a huge // // variance to the tracked absolute quantity and a var_accel_ variance to // // its derivative, so the very next measurement will essentially be // // copied directly into the filter. Still, we provide methods that allow // // you to specify initial settings for the filter's tracked state. // // public void reset() { // reset(0., 0.); // } // // public void reset(double abs_value) { // reset(abs_value, 0.); // } // // public void reset(double abs_value, double vel_value) { // x_abs_ = abs_value; // x_vel_ = vel_value; // p_abs_abs_ = 1.e10; // p_abs_vel_ = 0.; // p_vel_vel_ = var_accel_; // } // // // Sets the variance for the acceleration noise input in the system model, // // in units per second squared. // public void setAccelerationVariance(double var_accel) { // var_accel_ = var_accel; // } // // // Updates state given a sensor measurement of the absolute value of x, // // the variance of that measurement, and the interval since the last // // measurement in seconds. This interval must be greater than 0; for the // // first measurement after a reset(), it's safe to use 1.0. // public void update(double z_abs, double var_z_abs, double dt) { // // Note: math is not optimized by hand. Let the compiler sort it out. // // Predict step. // // Update state estimate. // x_abs_ += x_vel_ * dt; // // Update state covariance. The last term mixes in acceleration noise. // p_abs_abs_ += 2.*dt*p_abs_vel_ + dt*dt*p_vel_vel_ + var_accel_*dt*dt*dt*dt/4.; // p_abs_vel_ += dt*p_vel_vel_ + var_accel_*dt*dt*dt/2.; // p_vel_vel_ += + var_accel_*dt*dt; // // // Update step. // double y = z_abs - x_abs_; // Innovation. // double s_inv = 1. / (p_abs_abs_ + var_z_abs); // Innovation precision. // double k_abs = p_abs_abs_*s_inv; // Kalman gain // double k_vel = p_abs_vel_*s_inv; // // Update state estimate. // x_abs_ += k_abs * y; // x_vel_ += k_vel * y; // // Update state covariance. // p_vel_vel_ -= p_abs_vel_*k_vel; // p_abs_vel_ -= p_abs_vel_*k_abs; // p_abs_abs_ -= p_abs_abs_*k_abs; // } // // // Getters for the state and its covariance. // public double getXAbs() { return x_abs_; } // public double getXVel() { return x_vel_; } // public double getCovAbsAbs() { return p_abs_abs_; } // public double getCovAbsVel() { return p_abs_vel_; } // public double getCovVelVel() { return p_vel_vel_; } // }
import com.flightcomputer.utilities.KalmanFilter; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.os.SystemClock; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView;
package com.flightcomputer; public class PressureAltimeterActivity extends Activity implements SensorEventListener { // A reference to this activity, for use in anonymous classes. private PressureAltimeterActivity this_activity_; // Handles for all of the moving parts of the altimeter. private ImageView altimeter_needle_100_; private ImageView altimeter_needle_1000_; private ImageView altimeter_needle_10000_; private ImageView altimeter_pressure_dial_; private Button Altdec,Altinc,Exit; // Handle for the debug text view. private TextView debugTextView_; // Pressure sensor and sensor manager. private Sensor sensor_pressure_; private SensorManager sensor_manager_; // Sea level pressure in inches of mercury. private double slp_inHg_; // Current measured pressure in millibars. It's aviation; you just have to // get used to ugly unit combos like this. private double pressure_hPa_; // Kalman filter for smoothing the measured pressure.
// Path: src/com/flightcomputer/utilities/KalmanFilter.java // public class KalmanFilter { // // The state we are tracking, namely: // private double x_abs_; // The absolute value of x. // private double x_vel_; // The rate of change of x. // // // Covariance matrix for the state. // private double p_abs_abs_; // private double p_abs_vel_; // private double p_vel_vel_; // // // The variance of the acceleration noise input in the system model. // private double var_accel_; // // // Constructor. Assumes a variance of 1.0 for the system model's // // acceleration noise input, in units per second squared. // public KalmanFilter() { // setAccelerationVariance(1.); // reset(); // } // // // Constructor. Caller supplies the variance for the system model's // // acceleration noise input, in units per second squared. // public KalmanFilter(double var_accel) { // setAccelerationVariance(var_accel); // reset(); // } // // // The following three methods reset the filter. All of them assign a huge // // variance to the tracked absolute quantity and a var_accel_ variance to // // its derivative, so the very next measurement will essentially be // // copied directly into the filter. Still, we provide methods that allow // // you to specify initial settings for the filter's tracked state. // // public void reset() { // reset(0., 0.); // } // // public void reset(double abs_value) { // reset(abs_value, 0.); // } // // public void reset(double abs_value, double vel_value) { // x_abs_ = abs_value; // x_vel_ = vel_value; // p_abs_abs_ = 1.e10; // p_abs_vel_ = 0.; // p_vel_vel_ = var_accel_; // } // // // Sets the variance for the acceleration noise input in the system model, // // in units per second squared. // public void setAccelerationVariance(double var_accel) { // var_accel_ = var_accel; // } // // // Updates state given a sensor measurement of the absolute value of x, // // the variance of that measurement, and the interval since the last // // measurement in seconds. This interval must be greater than 0; for the // // first measurement after a reset(), it's safe to use 1.0. // public void update(double z_abs, double var_z_abs, double dt) { // // Note: math is not optimized by hand. Let the compiler sort it out. // // Predict step. // // Update state estimate. // x_abs_ += x_vel_ * dt; // // Update state covariance. The last term mixes in acceleration noise. // p_abs_abs_ += 2.*dt*p_abs_vel_ + dt*dt*p_vel_vel_ + var_accel_*dt*dt*dt*dt/4.; // p_abs_vel_ += dt*p_vel_vel_ + var_accel_*dt*dt*dt/2.; // p_vel_vel_ += + var_accel_*dt*dt; // // // Update step. // double y = z_abs - x_abs_; // Innovation. // double s_inv = 1. / (p_abs_abs_ + var_z_abs); // Innovation precision. // double k_abs = p_abs_abs_*s_inv; // Kalman gain // double k_vel = p_abs_vel_*s_inv; // // Update state estimate. // x_abs_ += k_abs * y; // x_vel_ += k_vel * y; // // Update state covariance. // p_vel_vel_ -= p_abs_vel_*k_vel; // p_abs_vel_ -= p_abs_vel_*k_abs; // p_abs_abs_ -= p_abs_abs_*k_abs; // } // // // Getters for the state and its covariance. // public double getXAbs() { return x_abs_; } // public double getXVel() { return x_vel_; } // public double getCovAbsAbs() { return p_abs_abs_; } // public double getCovAbsVel() { return p_abs_vel_; } // public double getCovVelVel() { return p_vel_vel_; } // } // Path: src/com/flightcomputer/PressureAltimeterActivity.java import com.flightcomputer.utilities.KalmanFilter; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.os.SystemClock; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; package com.flightcomputer; public class PressureAltimeterActivity extends Activity implements SensorEventListener { // A reference to this activity, for use in anonymous classes. private PressureAltimeterActivity this_activity_; // Handles for all of the moving parts of the altimeter. private ImageView altimeter_needle_100_; private ImageView altimeter_needle_1000_; private ImageView altimeter_needle_10000_; private ImageView altimeter_pressure_dial_; private Button Altdec,Altinc,Exit; // Handle for the debug text view. private TextView debugTextView_; // Pressure sensor and sensor manager. private Sensor sensor_pressure_; private SensorManager sensor_manager_; // Sea level pressure in inches of mercury. private double slp_inHg_; // Current measured pressure in millibars. It's aviation; you just have to // get used to ugly unit combos like this. private double pressure_hPa_; // Kalman filter for smoothing the measured pressure.
private KalmanFilter pressure_hPa_filter_;
StevenRudenko/BleSensorTag
app/src/main/java/sample/ble/sensortag/fusion/engine/SensorFusionEngine.java
// Path: app/src/main/java/sample/ble/sensortag/config/AppConfig.java // public class AppConfig { // /** Debug flag to enable local sensors fustion. */ // public static final boolean LOCAL_SENSOR_FUSION = false; // /** Indicates whether {@link sample.ble.sensortag.BleSensorsRecordService} would be enabled. */ // public static final boolean ENABLE_RECORD_SERVICE = false; // /** Enables magnet sensor to be used while sensor fusion calculation. */ // public static final boolean SENSOR_FUSION_USE_MAGNET_SENSOR = false; // // /** Sensor Tag Device name. */ // public static final String SENSOR_TAG_DEVICE_NAME = "SensorTag"; // /** Sensor Tag Device name. */ // public static final String SENSOR_TAG_V2_DEVICE_NAME = "CC2650 SensorTag"; // /** Metawear Device name. */ // public static final String METAWEAR_DEVICE_NAME = "MetaWear"; // // /** Supported devices. */ // public static final Set<String> SUPPORTED_DEVICES = new HashSet<>(); // public static final Set<String> SENSOR_FUSION_DEVICES = new HashSet<>(); // { // // supported devices // SUPPORTED_DEVICES.add(SENSOR_TAG_DEVICE_NAME); // SUPPORTED_DEVICES.add(SENSOR_TAG_V2_DEVICE_NAME); // SUPPORTED_DEVICES.add(METAWEAR_DEVICE_NAME); // // sensor fusion devices // SENSOR_FUSION_DEVICES.add(SENSOR_TAG_DEVICE_NAME); // } // }
import android.hardware.SensorManager; import java.util.TimerTask; import sample.ble.sensortag.config.AppConfig;
private final float[] accMagOrientation = new float[3]; // final orientation angles from sensor fusion private final float[] fusedOrientation = new float[3]; // accelerometer and magnetometer based rotation matrix private final float[] rotationMatrix = new float[9]; private float timestamp; public SensorFusionEngine() { gyroOrientation[0] = 0.0f; gyroOrientation[1] = 0.0f; gyroOrientation[2] = 0.0f; // initialise gyroMatrix with identity matrix gyroMatrix[0] = 1.0f; gyroMatrix[1] = 0.0f; gyroMatrix[2] = 0.0f; gyroMatrix[3] = 0.0f; gyroMatrix[4] = 1.0f; gyroMatrix[5] = 0.0f; gyroMatrix[6] = 0.0f; gyroMatrix[7] = 0.0f; gyroMatrix[8] = 1.0f; } public float[] getFusedOrientation() { return fusedOrientation; } public void onAccDataUpdate(float[] accel) { System.arraycopy(accel, 0, this.accel, 0, 3); calculateAccMagOrientation(); } public void onMagDataUpdate(float[] magnet) {
// Path: app/src/main/java/sample/ble/sensortag/config/AppConfig.java // public class AppConfig { // /** Debug flag to enable local sensors fustion. */ // public static final boolean LOCAL_SENSOR_FUSION = false; // /** Indicates whether {@link sample.ble.sensortag.BleSensorsRecordService} would be enabled. */ // public static final boolean ENABLE_RECORD_SERVICE = false; // /** Enables magnet sensor to be used while sensor fusion calculation. */ // public static final boolean SENSOR_FUSION_USE_MAGNET_SENSOR = false; // // /** Sensor Tag Device name. */ // public static final String SENSOR_TAG_DEVICE_NAME = "SensorTag"; // /** Sensor Tag Device name. */ // public static final String SENSOR_TAG_V2_DEVICE_NAME = "CC2650 SensorTag"; // /** Metawear Device name. */ // public static final String METAWEAR_DEVICE_NAME = "MetaWear"; // // /** Supported devices. */ // public static final Set<String> SUPPORTED_DEVICES = new HashSet<>(); // public static final Set<String> SENSOR_FUSION_DEVICES = new HashSet<>(); // { // // supported devices // SUPPORTED_DEVICES.add(SENSOR_TAG_DEVICE_NAME); // SUPPORTED_DEVICES.add(SENSOR_TAG_V2_DEVICE_NAME); // SUPPORTED_DEVICES.add(METAWEAR_DEVICE_NAME); // // sensor fusion devices // SENSOR_FUSION_DEVICES.add(SENSOR_TAG_DEVICE_NAME); // } // } // Path: app/src/main/java/sample/ble/sensortag/fusion/engine/SensorFusionEngine.java import android.hardware.SensorManager; import java.util.TimerTask; import sample.ble.sensortag.config.AppConfig; private final float[] accMagOrientation = new float[3]; // final orientation angles from sensor fusion private final float[] fusedOrientation = new float[3]; // accelerometer and magnetometer based rotation matrix private final float[] rotationMatrix = new float[9]; private float timestamp; public SensorFusionEngine() { gyroOrientation[0] = 0.0f; gyroOrientation[1] = 0.0f; gyroOrientation[2] = 0.0f; // initialise gyroMatrix with identity matrix gyroMatrix[0] = 1.0f; gyroMatrix[1] = 0.0f; gyroMatrix[2] = 0.0f; gyroMatrix[3] = 0.0f; gyroMatrix[4] = 1.0f; gyroMatrix[5] = 0.0f; gyroMatrix[6] = 0.0f; gyroMatrix[7] = 0.0f; gyroMatrix[8] = 1.0f; } public float[] getFusedOrientation() { return fusedOrientation; } public void onAccDataUpdate(float[] accel) { System.arraycopy(accel, 0, this.accel, 0, 3); calculateAccMagOrientation(); } public void onMagDataUpdate(float[] magnet) {
if (AppConfig.SENSOR_FUSION_USE_MAGNET_SENSOR)
wuman/AndroidImageLoader
library/src/main/java/com/wuman/androidimageloader/AbstractViewBinder.java
// Path: library/src/main/java/com/wuman/androidimageloader/ImageLoader.java // public static enum LoadSource { // /** // * Returned when an image was loaded from memory cache. // */ // CACHE_MEMORY, // /** // * Returned when an image was loaded from disk cache. // */ // CACHE_DISK, // /** // * Returned when an image was loaded from an external source. The // * default is via HttpUrlConnection. // */ // EXTERNAL // }
import java.lang.ref.WeakReference; import java.util.Map; import java.util.WeakHashMap; import android.graphics.Bitmap; import android.text.TextUtils; import com.wuman.androidimageloader.ImageLoader.LoadSource;
public final void setLoadingResource(int loading) { mLoadingResource = loading; } public final void setErrorResource(int error) { mErrorResource = error; } public void unbind(T view) { mViewBindings.remove(view); } public void bind(T view, String url) { if (view == null) { throw new NullPointerException("view is null"); } if (url == null) { throw new NullPointerException("URL is null"); } // reset if wrong URL if (!TextUtils.equals(url, mViewBindings.get(view))) { unbind(view); } mViewBindings.put(view, url); } protected abstract void onImageLoaded(T view, Bitmap bitmap, String url,
// Path: library/src/main/java/com/wuman/androidimageloader/ImageLoader.java // public static enum LoadSource { // /** // * Returned when an image was loaded from memory cache. // */ // CACHE_MEMORY, // /** // * Returned when an image was loaded from disk cache. // */ // CACHE_DISK, // /** // * Returned when an image was loaded from an external source. The // * default is via HttpUrlConnection. // */ // EXTERNAL // } // Path: library/src/main/java/com/wuman/androidimageloader/AbstractViewBinder.java import java.lang.ref.WeakReference; import java.util.Map; import java.util.WeakHashMap; import android.graphics.Bitmap; import android.text.TextUtils; import com.wuman.androidimageloader.ImageLoader.LoadSource; public final void setLoadingResource(int loading) { mLoadingResource = loading; } public final void setErrorResource(int error) { mErrorResource = error; } public void unbind(T view) { mViewBindings.remove(view); } public void bind(T view, String url) { if (view == null) { throw new NullPointerException("view is null"); } if (url == null) { throw new NullPointerException("URL is null"); } // reset if wrong URL if (!TextUtils.equals(url, mViewBindings.get(view))) { unbind(view); } mViewBindings.put(view, url); } protected abstract void onImageLoaded(T view, Bitmap bitmap, String url,
LoadSource loadSource);
wuman/AndroidImageLoader
library/src/main/java/com/wuman/androidimageloader/ImageViewBinder.java
// Path: library/src/main/java/com/wuman/androidimageloader/ImageLoader.java // public static enum LoadResult { // /** // * Returned when an image was already loaded from memory cache. // */ // OK, // /** // * Returned when an image needs to be loaded asynchronously, either from // * disk cache or from network. // * <p> // * Callers may wish to assign a placeholder or show a progress spinner // * while the image is being loaded whenever this value is returned. // */ // LOADING, // /** // * Returned when an attempt to load the image has already been made and // * it failed. // * <p> // * Callers may wish to show an error indicator when this value is // * returned. // * // * @see ImageLoader.Callback // */ // ERROR // } // // Path: library/src/main/java/com/wuman/androidimageloader/ImageLoader.java // public static enum LoadSource { // /** // * Returned when an image was loaded from memory cache. // */ // CACHE_MEMORY, // /** // * Returned when an image was loaded from disk cache. // */ // CACHE_DISK, // /** // * Returned when an image was loaded from an external source. The // * default is via HttpUrlConnection. // */ // EXTERNAL // }
import android.graphics.Bitmap; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListAdapter; import com.nineoldandroids.animation.ObjectAnimator; import com.nineoldandroids.view.ViewPropertyAnimator; import com.wuman.androidimageloader.ImageLoader.LoadResult; import com.wuman.androidimageloader.ImageLoader.LoadSource;
} public ImageViewBinder setFadeIn(boolean fadeIn) { mFadeIn = fadeIn; return this; } @Override public void unbind(ImageView view) { super.unbind(view); ViewPropertyAnimator.animate(view).cancel(); view.setImageDrawable(null); } @Override public void bind(ImageView view, String url) { super.bind(view, url); // @formatter:off if (LOAD_ON_FLING && mScrollState == OnScrollListener.SCROLL_STATE_FLING) { Bitmap bitmap = mImageLoader.loadOnlyFromMemCache(url); if (bitmap != null) { view.setImageBitmap(bitmap); } else { view.setImageResource(mLoadingResource); } } else // @formatter:on {
// Path: library/src/main/java/com/wuman/androidimageloader/ImageLoader.java // public static enum LoadResult { // /** // * Returned when an image was already loaded from memory cache. // */ // OK, // /** // * Returned when an image needs to be loaded asynchronously, either from // * disk cache or from network. // * <p> // * Callers may wish to assign a placeholder or show a progress spinner // * while the image is being loaded whenever this value is returned. // */ // LOADING, // /** // * Returned when an attempt to load the image has already been made and // * it failed. // * <p> // * Callers may wish to show an error indicator when this value is // * returned. // * // * @see ImageLoader.Callback // */ // ERROR // } // // Path: library/src/main/java/com/wuman/androidimageloader/ImageLoader.java // public static enum LoadSource { // /** // * Returned when an image was loaded from memory cache. // */ // CACHE_MEMORY, // /** // * Returned when an image was loaded from disk cache. // */ // CACHE_DISK, // /** // * Returned when an image was loaded from an external source. The // * default is via HttpUrlConnection. // */ // EXTERNAL // } // Path: library/src/main/java/com/wuman/androidimageloader/ImageViewBinder.java import android.graphics.Bitmap; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListAdapter; import com.nineoldandroids.animation.ObjectAnimator; import com.nineoldandroids.view.ViewPropertyAnimator; import com.wuman.androidimageloader.ImageLoader.LoadResult; import com.wuman.androidimageloader.ImageLoader.LoadSource; } public ImageViewBinder setFadeIn(boolean fadeIn) { mFadeIn = fadeIn; return this; } @Override public void unbind(ImageView view) { super.unbind(view); ViewPropertyAnimator.animate(view).cancel(); view.setImageDrawable(null); } @Override public void bind(ImageView view, String url) { super.bind(view, url); // @formatter:off if (LOAD_ON_FLING && mScrollState == OnScrollListener.SCROLL_STATE_FLING) { Bitmap bitmap = mImageLoader.loadOnlyFromMemCache(url); if (bitmap != null) { view.setImageBitmap(bitmap); } else { view.setImageResource(mLoadingResource); } } else // @formatter:on {
LoadResult bindResult = mImageLoader.load(url, new ViewCallback(
wuman/AndroidImageLoader
library/src/main/java/com/wuman/androidimageloader/ImageViewBinder.java
// Path: library/src/main/java/com/wuman/androidimageloader/ImageLoader.java // public static enum LoadResult { // /** // * Returned when an image was already loaded from memory cache. // */ // OK, // /** // * Returned when an image needs to be loaded asynchronously, either from // * disk cache or from network. // * <p> // * Callers may wish to assign a placeholder or show a progress spinner // * while the image is being loaded whenever this value is returned. // */ // LOADING, // /** // * Returned when an attempt to load the image has already been made and // * it failed. // * <p> // * Callers may wish to show an error indicator when this value is // * returned. // * // * @see ImageLoader.Callback // */ // ERROR // } // // Path: library/src/main/java/com/wuman/androidimageloader/ImageLoader.java // public static enum LoadSource { // /** // * Returned when an image was loaded from memory cache. // */ // CACHE_MEMORY, // /** // * Returned when an image was loaded from disk cache. // */ // CACHE_DISK, // /** // * Returned when an image was loaded from an external source. The // * default is via HttpUrlConnection. // */ // EXTERNAL // }
import android.graphics.Bitmap; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListAdapter; import com.nineoldandroids.animation.ObjectAnimator; import com.nineoldandroids.view.ViewPropertyAnimator; import com.wuman.androidimageloader.ImageLoader.LoadResult; import com.wuman.androidimageloader.ImageLoader.LoadSource;
ViewPropertyAnimator.animate(view).cancel(); view.setImageDrawable(null); } @Override public void bind(ImageView view, String url) { super.bind(view, url); // @formatter:off if (LOAD_ON_FLING && mScrollState == OnScrollListener.SCROLL_STATE_FLING) { Bitmap bitmap = mImageLoader.loadOnlyFromMemCache(url); if (bitmap != null) { view.setImageBitmap(bitmap); } else { view.setImageResource(mLoadingResource); } } else // @formatter:on { LoadResult bindResult = mImageLoader.load(url, new ViewCallback( view)); if (bindResult == LoadResult.LOADING) { view.setImageResource(mLoadingResource); } } } @Override protected void onImageLoaded(ImageView view, Bitmap bitmap, String url,
// Path: library/src/main/java/com/wuman/androidimageloader/ImageLoader.java // public static enum LoadResult { // /** // * Returned when an image was already loaded from memory cache. // */ // OK, // /** // * Returned when an image needs to be loaded asynchronously, either from // * disk cache or from network. // * <p> // * Callers may wish to assign a placeholder or show a progress spinner // * while the image is being loaded whenever this value is returned. // */ // LOADING, // /** // * Returned when an attempt to load the image has already been made and // * it failed. // * <p> // * Callers may wish to show an error indicator when this value is // * returned. // * // * @see ImageLoader.Callback // */ // ERROR // } // // Path: library/src/main/java/com/wuman/androidimageloader/ImageLoader.java // public static enum LoadSource { // /** // * Returned when an image was loaded from memory cache. // */ // CACHE_MEMORY, // /** // * Returned when an image was loaded from disk cache. // */ // CACHE_DISK, // /** // * Returned when an image was loaded from an external source. The // * default is via HttpUrlConnection. // */ // EXTERNAL // } // Path: library/src/main/java/com/wuman/androidimageloader/ImageViewBinder.java import android.graphics.Bitmap; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListAdapter; import com.nineoldandroids.animation.ObjectAnimator; import com.nineoldandroids.view.ViewPropertyAnimator; import com.wuman.androidimageloader.ImageLoader.LoadResult; import com.wuman.androidimageloader.ImageLoader.LoadSource; ViewPropertyAnimator.animate(view).cancel(); view.setImageDrawable(null); } @Override public void bind(ImageView view, String url) { super.bind(view, url); // @formatter:off if (LOAD_ON_FLING && mScrollState == OnScrollListener.SCROLL_STATE_FLING) { Bitmap bitmap = mImageLoader.loadOnlyFromMemCache(url); if (bitmap != null) { view.setImageBitmap(bitmap); } else { view.setImageResource(mLoadingResource); } } else // @formatter:on { LoadResult bindResult = mImageLoader.load(url, new ViewCallback( view)); if (bindResult == LoadResult.LOADING) { view.setImageResource(mLoadingResource); } } } @Override protected void onImageLoaded(ImageView view, Bitmap bitmap, String url,
LoadSource loadSource) {
wuman/AndroidImageLoader
samples/src/main/java/com/wuman/androidimageloader/samples/ui/Loadable.java
// Path: samples/src/main/java/com/wuman/androidimageloader/samples/provider/SamplesContract.java // public class SamplesContract { // // public static final Uri AUTHORITY_URI = Uri // .parse(ContentResolver.SCHEME_CONTENT + "://" // + SamplesContract.class.getPackage().getName()); // public static final String AUTHORITY = AUTHORITY_URI.getAuthority(); // // public static interface PhotoColumns extends BaseColumns { // String SECRET = "photo_secret"; // String SERVER = "photo_server"; // String FARM = "photo_farm"; // String TITLE = "photo_title"; // } // // public static interface InterestingPhotos extends PhotoColumns { // Uri CONTENT_URI = Uri.withAppendedPath(AUTHORITY_URI, // "flickr_interestingness"); // String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/" // + SamplesContract.class.getPackage().getName() // + ".interestingness"; // String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/" // + SamplesContract.class.getPackage().getName() // + ".interestingness"; // } // // /** // * Specifies the maximum age of cached content. // */ // public static final String PARAM_MAX_AGE = "max-age"; // // /** // * Specifies the number of items to retrieve. // */ // public static final String PARAM_NUMBER = "n"; // // private static long getLongQueryParameter(Uri uri, String key, // long defaultValue) { // String value = uri.getQueryParameter(key); // return value != null ? Long.parseLong(value) : defaultValue; // } // // private static int getIntQueryParameter(Uri uri, String key, // int defaultValue) { // String value = uri.getQueryParameter(key); // return value != null ? Integer.parseInt(value) : defaultValue; // } // // private static Uri setLongQueryParameter(Uri uri, String key, long value) { // if (0 != uri.getQueryParameters(key).size()) { // throw new IllegalArgumentException(key + " is already specified."); // } // return uri.buildUpon().appendQueryParameter(key, Long.toString(value)) // .build(); // } // // private static Uri setIntQueryParameter(Uri uri, String key, int value) { // if (0 != uri.getQueryParameters(key).size()) { // throw new IllegalArgumentException(key + " is already specified."); // } // return uri.buildUpon() // .appendQueryParameter(key, Integer.toString(value)).build(); // } // // public static int getNumber(Uri uri, int defaultValue) { // return getIntQueryParameter(uri, PARAM_NUMBER, defaultValue); // } // // public static Uri setNumber(Uri uri, int value) { // return setIntQueryParameter(uri, PARAM_NUMBER, value); // } // // public static long getMaxAge(Uri uri, long defaultValue) { // return getLongQueryParameter(uri, PARAM_MAX_AGE, defaultValue); // } // // public static Uri setMaxAge(Uri uri, long value) { // return setLongQueryParameter(uri, PARAM_MAX_AGE, value); // } // // public static Uri refresh(Uri uri) { // return setMaxAge(uri, 0); // } // // private SamplesContract() { // } // }
import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.LoaderManager; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import com.wuman.androidfeedloader.FeedExtras; import com.wuman.androidimageloader.samples.provider.SamplesContract;
mLoaderManager.destroyLoader(mLoaderId); } public void retry() { Bundle args = new Bundle(); args.putInt(ARG_NUMBER, mTargetCount); args.putLong(ARG_MAX_AGE, 0L); mLoaderManager.restartLoader(mLoaderId, args, this); } public void refresh() { Bundle args = new Bundle(); args.putInt(ARG_NUMBER, mCount); args.putLong(ARG_MAX_AGE, 0L); mLoaderManager.restartLoader(mLoaderId, args, this); } /** * Appends query parameters to a {@link CursorLoader} {@link Uri}. * * @param loader * the {@link CursorLoader} to modify. * @param args * the arguments. * @return the modified {@link CursorLoader}. */ private CursorLoader appendQueryParameters(CursorLoader loader, Bundle args) { Uri.Builder builder = loader.getUri().buildUpon(); if (args.containsKey(ARG_NUMBER)) { int n = args.getInt(ARG_NUMBER);
// Path: samples/src/main/java/com/wuman/androidimageloader/samples/provider/SamplesContract.java // public class SamplesContract { // // public static final Uri AUTHORITY_URI = Uri // .parse(ContentResolver.SCHEME_CONTENT + "://" // + SamplesContract.class.getPackage().getName()); // public static final String AUTHORITY = AUTHORITY_URI.getAuthority(); // // public static interface PhotoColumns extends BaseColumns { // String SECRET = "photo_secret"; // String SERVER = "photo_server"; // String FARM = "photo_farm"; // String TITLE = "photo_title"; // } // // public static interface InterestingPhotos extends PhotoColumns { // Uri CONTENT_URI = Uri.withAppendedPath(AUTHORITY_URI, // "flickr_interestingness"); // String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/" // + SamplesContract.class.getPackage().getName() // + ".interestingness"; // String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/" // + SamplesContract.class.getPackage().getName() // + ".interestingness"; // } // // /** // * Specifies the maximum age of cached content. // */ // public static final String PARAM_MAX_AGE = "max-age"; // // /** // * Specifies the number of items to retrieve. // */ // public static final String PARAM_NUMBER = "n"; // // private static long getLongQueryParameter(Uri uri, String key, // long defaultValue) { // String value = uri.getQueryParameter(key); // return value != null ? Long.parseLong(value) : defaultValue; // } // // private static int getIntQueryParameter(Uri uri, String key, // int defaultValue) { // String value = uri.getQueryParameter(key); // return value != null ? Integer.parseInt(value) : defaultValue; // } // // private static Uri setLongQueryParameter(Uri uri, String key, long value) { // if (0 != uri.getQueryParameters(key).size()) { // throw new IllegalArgumentException(key + " is already specified."); // } // return uri.buildUpon().appendQueryParameter(key, Long.toString(value)) // .build(); // } // // private static Uri setIntQueryParameter(Uri uri, String key, int value) { // if (0 != uri.getQueryParameters(key).size()) { // throw new IllegalArgumentException(key + " is already specified."); // } // return uri.buildUpon() // .appendQueryParameter(key, Integer.toString(value)).build(); // } // // public static int getNumber(Uri uri, int defaultValue) { // return getIntQueryParameter(uri, PARAM_NUMBER, defaultValue); // } // // public static Uri setNumber(Uri uri, int value) { // return setIntQueryParameter(uri, PARAM_NUMBER, value); // } // // public static long getMaxAge(Uri uri, long defaultValue) { // return getLongQueryParameter(uri, PARAM_MAX_AGE, defaultValue); // } // // public static Uri setMaxAge(Uri uri, long value) { // return setLongQueryParameter(uri, PARAM_MAX_AGE, value); // } // // public static Uri refresh(Uri uri) { // return setMaxAge(uri, 0); // } // // private SamplesContract() { // } // } // Path: samples/src/main/java/com/wuman/androidimageloader/samples/ui/Loadable.java import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.LoaderManager; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import com.wuman.androidfeedloader.FeedExtras; import com.wuman.androidimageloader.samples.provider.SamplesContract; mLoaderManager.destroyLoader(mLoaderId); } public void retry() { Bundle args = new Bundle(); args.putInt(ARG_NUMBER, mTargetCount); args.putLong(ARG_MAX_AGE, 0L); mLoaderManager.restartLoader(mLoaderId, args, this); } public void refresh() { Bundle args = new Bundle(); args.putInt(ARG_NUMBER, mCount); args.putLong(ARG_MAX_AGE, 0L); mLoaderManager.restartLoader(mLoaderId, args, this); } /** * Appends query parameters to a {@link CursorLoader} {@link Uri}. * * @param loader * the {@link CursorLoader} to modify. * @param args * the arguments. * @return the modified {@link CursorLoader}. */ private CursorLoader appendQueryParameters(CursorLoader loader, Bundle args) { Uri.Builder builder = loader.getUri().buildUpon(); if (args.containsKey(ARG_NUMBER)) { int n = args.getInt(ARG_NUMBER);
builder.appendQueryParameter(SamplesContract.PARAM_NUMBER,
SpudCompat/SpudCompat
src/main/java/net/techcable/spudcompat/metadata/DefaultingMetadataTransformer.java
// Path: src/main/java/net/techcable/spudcompat/ProtocolVersion.java // @RequiredArgsConstructor // public enum ProtocolVersion { // v1_7_10(5), // v1_8(47); // // public boolean isBefore(ProtocolVersion other) { // return this.getId() < other.getId(); // } // // private final int versionNumber; // // public int getId() { // return versionNumber; // } // // public static final int MAX_ID; // private static final ProtocolVersion[] BY_ID; // // static { // int maxId = 0; // for (ProtocolVersion version : values()) { // if (version.getId() > maxId) { // maxId = version.getId(); // } // } // MAX_ID = maxId; // BY_ID = new ProtocolVersion[MAX_ID + 1]; // for (ProtocolVersion version : values()) { // int id = version.getId(); // if (BY_ID[id] != null) throw new AssertionError("Already a version with id: " + id); // BY_ID[id] = version; // } // } // // public static ProtocolVersion getById(int id) { // if (id < 0) { // throw new IllegalArgumentException("Negative id: " + id); // } else if (id < BY_ID.length) { // return BY_ID[id]; // } else { // return null; // } // } // }
import java.util.Arrays; import java.util.Optional; import java.util.OptionalInt; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import net.techcable.spudcompat.ProtocolVersion;
package net.techcable.spudcompat.metadata; public class DefaultingMetadataTransformer implements MetadataTransformer { private final int[] indexes; private final MetadataDataValue[] defaults; private DefaultingMetadataTransformer(int[] indexes, MetadataDataValue[] defaults) { this.indexes = indexes; this.defaults = defaults;
// Path: src/main/java/net/techcable/spudcompat/ProtocolVersion.java // @RequiredArgsConstructor // public enum ProtocolVersion { // v1_7_10(5), // v1_8(47); // // public boolean isBefore(ProtocolVersion other) { // return this.getId() < other.getId(); // } // // private final int versionNumber; // // public int getId() { // return versionNumber; // } // // public static final int MAX_ID; // private static final ProtocolVersion[] BY_ID; // // static { // int maxId = 0; // for (ProtocolVersion version : values()) { // if (version.getId() > maxId) { // maxId = version.getId(); // } // } // MAX_ID = maxId; // BY_ID = new ProtocolVersion[MAX_ID + 1]; // for (ProtocolVersion version : values()) { // int id = version.getId(); // if (BY_ID[id] != null) throw new AssertionError("Already a version with id: " + id); // BY_ID[id] = version; // } // } // // public static ProtocolVersion getById(int id) { // if (id < 0) { // throw new IllegalArgumentException("Negative id: " + id); // } else if (id < BY_ID.length) { // return BY_ID[id]; // } else { // return null; // } // } // } // Path: src/main/java/net/techcable/spudcompat/metadata/DefaultingMetadataTransformer.java import java.util.Arrays; import java.util.Optional; import java.util.OptionalInt; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import net.techcable.spudcompat.ProtocolVersion; package net.techcable.spudcompat.metadata; public class DefaultingMetadataTransformer implements MetadataTransformer { private final int[] indexes; private final MetadataDataValue[] defaults; private DefaultingMetadataTransformer(int[] indexes, MetadataDataValue[] defaults) { this.indexes = indexes; this.defaults = defaults;
for (ProtocolVersion version : ProtocolVersion.values()) {
SpudCompat/SpudCompat
src/main/java/net/techcable/spudcompat/ItemStack.java
// Path: src/main/java/net/techcable/spudcompat/nbt/NBT.java // public interface NBT { // public Tag getValue(); // public void write(ByteBuf buf); // // // /** // * Calculate the length of the NBT, then return a lazy reading nbt-object. // * <p>This allows you to defer reading the nbt until later, often saving space and time.</p> // * <p>Caution: Some errors may not be found until later.</p> // * // * @param buf the buf to read from // * @return a lazy-reading NBT object // */ // public static NBT lazyRead(ByteBuf buf) { // return lazyRead(buf, NBTUtils.calculateNBTLength(buf)); // } // // /** // * Return a NBT object that will read the given number of bytes from the buffer, and turn it into NBT only if/when needed. // * <p>This allows you to defer reading the nbt until later, saving space and time.</p> // * <p>Warning: Errors in the NBT will not be found until later.</p> // * // * @param buf the buf to read from // * @param length the amount to read // * @return a lazy-reading NBT object // */ // public static NBT lazyRead(ByteBuf buf, int length) { // return new LazyReadingNBT(buf.readBytes(length)); // } // // /** // * Read the nbt from the given byte buf // * // * @param buf the buf to read the nbt from // * @return the nbt // */ // @SneakyThrows(IOException.class) // ByteBufs don't throw IOExceptions // public static NBT read(ByteBuf buf) { // return read(new ByteBufInputStream(buf)); // } // // /** // * Read the nbt from the given input stream // * // * @param in the stream to read the nbt from // * @return the nbt // */ // public static NBT read(InputStream in) throws IOException { // return new SimpleNBT(NBTIO.readTag(new DataInputStream(in))); // } // // public static NBT create(Tag tag) { // return new SimpleNBT(tag); // } // }
import lombok.*; import lombok.experimental.*; import java.util.Optional; import com.google.common.base.Preconditions; import io.netty.buffer.ByteBuf; import net.techcable.spudcompat.nbt.NBT;
package net.techcable.spudcompat; /** * An immutable item stack, with mutable nbt */ @Getter @Wither public class ItemStack { private final Material type; private final int amount; @Getter(AccessLevel.NONE) // we call this 'getRawData' in case we ever provide an abstraction private final short data;
// Path: src/main/java/net/techcable/spudcompat/nbt/NBT.java // public interface NBT { // public Tag getValue(); // public void write(ByteBuf buf); // // // /** // * Calculate the length of the NBT, then return a lazy reading nbt-object. // * <p>This allows you to defer reading the nbt until later, often saving space and time.</p> // * <p>Caution: Some errors may not be found until later.</p> // * // * @param buf the buf to read from // * @return a lazy-reading NBT object // */ // public static NBT lazyRead(ByteBuf buf) { // return lazyRead(buf, NBTUtils.calculateNBTLength(buf)); // } // // /** // * Return a NBT object that will read the given number of bytes from the buffer, and turn it into NBT only if/when needed. // * <p>This allows you to defer reading the nbt until later, saving space and time.</p> // * <p>Warning: Errors in the NBT will not be found until later.</p> // * // * @param buf the buf to read from // * @param length the amount to read // * @return a lazy-reading NBT object // */ // public static NBT lazyRead(ByteBuf buf, int length) { // return new LazyReadingNBT(buf.readBytes(length)); // } // // /** // * Read the nbt from the given byte buf // * // * @param buf the buf to read the nbt from // * @return the nbt // */ // @SneakyThrows(IOException.class) // ByteBufs don't throw IOExceptions // public static NBT read(ByteBuf buf) { // return read(new ByteBufInputStream(buf)); // } // // /** // * Read the nbt from the given input stream // * // * @param in the stream to read the nbt from // * @return the nbt // */ // public static NBT read(InputStream in) throws IOException { // return new SimpleNBT(NBTIO.readTag(new DataInputStream(in))); // } // // public static NBT create(Tag tag) { // return new SimpleNBT(tag); // } // } // Path: src/main/java/net/techcable/spudcompat/ItemStack.java import lombok.*; import lombok.experimental.*; import java.util.Optional; import com.google.common.base.Preconditions; import io.netty.buffer.ByteBuf; import net.techcable.spudcompat.nbt.NBT; package net.techcable.spudcompat; /** * An immutable item stack, with mutable nbt */ @Getter @Wither public class ItemStack { private final Material type; private final int amount; @Getter(AccessLevel.NONE) // we call this 'getRawData' in case we ever provide an abstraction private final short data;
private final Optional<NBT> nbt;
SpudCompat/SpudCompat
src/main/java/net/techcable/spudcompat/protocol/PlayerConnection.java
// Path: src/main/java/net/techcable/spudcompat/ProtocolVersion.java // @RequiredArgsConstructor // public enum ProtocolVersion { // v1_7_10(5), // v1_8(47); // // public boolean isBefore(ProtocolVersion other) { // return this.getId() < other.getId(); // } // // private final int versionNumber; // // public int getId() { // return versionNumber; // } // // public static final int MAX_ID; // private static final ProtocolVersion[] BY_ID; // // static { // int maxId = 0; // for (ProtocolVersion version : values()) { // if (version.getId() > maxId) { // maxId = version.getId(); // } // } // MAX_ID = maxId; // BY_ID = new ProtocolVersion[MAX_ID + 1]; // for (ProtocolVersion version : values()) { // int id = version.getId(); // if (BY_ID[id] != null) throw new AssertionError("Already a version with id: " + id); // BY_ID[id] = version; // } // } // // public static ProtocolVersion getById(int id) { // if (id < 0) { // throw new IllegalArgumentException("Negative id: " + id); // } else if (id < BY_ID.length) { // return BY_ID[id]; // } else { // return null; // } // } // } // // Path: src/main/java/net/techcable/spudcompat/protocol/injector/RawPacket.java // @Getter // public class RawPacket extends AbstractReferenceCounted { // private final ByteBuf allData; // private final ByteBuf packetData; // private final int id; // private final ProtocolState protocolState; // private final ProtocolDirection direction; // private final PacketType type; // // private RawPacket(ByteBuf allData, ByteBuf packetData, int id, ProtocolState protocolState, ProtocolDirection direction) { // this.allData = allData.retain(); // this.packetData = packetData.retain(); // this.id = id; // this.protocolState = checkNotNull(protocolState, "Null state"); // this.direction = checkNotNull(direction, "Null direction"); // this.type = PacketType.getById(id, protocolState, direction); // } // // public ByteBuf getAllData() { // assertValid(); // return allData; // } // // public ByteBuf getPacketData() { // assertValid(); // return packetData; // } // // // public boolean isKnownType() { // return getType() != null; // } // // public static RawPacket fromWrapper(PacketWrapper wrapper, ProtocolState protocolState, ProtocolDirection direction) { // return fromBuffer(checkNotNull(wrapper, "Null wrapper").buf, protocolState, direction); // } // // public static RawPacket fromBuffer(ByteBuf buf, ProtocolState protocolState, ProtocolDirection direction) { // checkNotNull(buf, "Null buffer"); // checkNotNull(protocolState, "Null state"); // checkNotNull(direction, "Null direction"); // buf = Unpooled.unmodifiableBuffer(buf.duplicate()); // Read-only // ByteBuf allData = buf.duplicate(); // int id = DefinedPacket.readVarInt(buf); // return new RawPacket(allData, buf.slice(), id, protocolState, direction); // } // // @Override // protected void deallocate() { // allData.release(); // packetData.release(); // } // // private void assertValid() { // if (refCnt() <= 0) throw new IllegalReferenceCountException("Packet deallocated"); // } // }
import io.netty.channel.Channel; import net.md_5.bungee.api.connection.Server; import net.techcable.spudcompat.ProtocolVersion; import net.techcable.spudcompat.protocol.injector.RawPacket;
package net.techcable.spudcompat.protocol; public interface PlayerConnection { public default boolean isSupportedVersion() {
// Path: src/main/java/net/techcable/spudcompat/ProtocolVersion.java // @RequiredArgsConstructor // public enum ProtocolVersion { // v1_7_10(5), // v1_8(47); // // public boolean isBefore(ProtocolVersion other) { // return this.getId() < other.getId(); // } // // private final int versionNumber; // // public int getId() { // return versionNumber; // } // // public static final int MAX_ID; // private static final ProtocolVersion[] BY_ID; // // static { // int maxId = 0; // for (ProtocolVersion version : values()) { // if (version.getId() > maxId) { // maxId = version.getId(); // } // } // MAX_ID = maxId; // BY_ID = new ProtocolVersion[MAX_ID + 1]; // for (ProtocolVersion version : values()) { // int id = version.getId(); // if (BY_ID[id] != null) throw new AssertionError("Already a version with id: " + id); // BY_ID[id] = version; // } // } // // public static ProtocolVersion getById(int id) { // if (id < 0) { // throw new IllegalArgumentException("Negative id: " + id); // } else if (id < BY_ID.length) { // return BY_ID[id]; // } else { // return null; // } // } // } // // Path: src/main/java/net/techcable/spudcompat/protocol/injector/RawPacket.java // @Getter // public class RawPacket extends AbstractReferenceCounted { // private final ByteBuf allData; // private final ByteBuf packetData; // private final int id; // private final ProtocolState protocolState; // private final ProtocolDirection direction; // private final PacketType type; // // private RawPacket(ByteBuf allData, ByteBuf packetData, int id, ProtocolState protocolState, ProtocolDirection direction) { // this.allData = allData.retain(); // this.packetData = packetData.retain(); // this.id = id; // this.protocolState = checkNotNull(protocolState, "Null state"); // this.direction = checkNotNull(direction, "Null direction"); // this.type = PacketType.getById(id, protocolState, direction); // } // // public ByteBuf getAllData() { // assertValid(); // return allData; // } // // public ByteBuf getPacketData() { // assertValid(); // return packetData; // } // // // public boolean isKnownType() { // return getType() != null; // } // // public static RawPacket fromWrapper(PacketWrapper wrapper, ProtocolState protocolState, ProtocolDirection direction) { // return fromBuffer(checkNotNull(wrapper, "Null wrapper").buf, protocolState, direction); // } // // public static RawPacket fromBuffer(ByteBuf buf, ProtocolState protocolState, ProtocolDirection direction) { // checkNotNull(buf, "Null buffer"); // checkNotNull(protocolState, "Null state"); // checkNotNull(direction, "Null direction"); // buf = Unpooled.unmodifiableBuffer(buf.duplicate()); // Read-only // ByteBuf allData = buf.duplicate(); // int id = DefinedPacket.readVarInt(buf); // return new RawPacket(allData, buf.slice(), id, protocolState, direction); // } // // @Override // protected void deallocate() { // allData.release(); // packetData.release(); // } // // private void assertValid() { // if (refCnt() <= 0) throw new IllegalReferenceCountException("Packet deallocated"); // } // } // Path: src/main/java/net/techcable/spudcompat/protocol/PlayerConnection.java import io.netty.channel.Channel; import net.md_5.bungee.api.connection.Server; import net.techcable.spudcompat.ProtocolVersion; import net.techcable.spudcompat.protocol.injector.RawPacket; package net.techcable.spudcompat.protocol; public interface PlayerConnection { public default boolean isSupportedVersion() {
return ProtocolVersion.getById(getVersionId()) != null;
SpudCompat/SpudCompat
src/main/java/net/techcable/spudcompat/protocol/PlayerConnection.java
// Path: src/main/java/net/techcable/spudcompat/ProtocolVersion.java // @RequiredArgsConstructor // public enum ProtocolVersion { // v1_7_10(5), // v1_8(47); // // public boolean isBefore(ProtocolVersion other) { // return this.getId() < other.getId(); // } // // private final int versionNumber; // // public int getId() { // return versionNumber; // } // // public static final int MAX_ID; // private static final ProtocolVersion[] BY_ID; // // static { // int maxId = 0; // for (ProtocolVersion version : values()) { // if (version.getId() > maxId) { // maxId = version.getId(); // } // } // MAX_ID = maxId; // BY_ID = new ProtocolVersion[MAX_ID + 1]; // for (ProtocolVersion version : values()) { // int id = version.getId(); // if (BY_ID[id] != null) throw new AssertionError("Already a version with id: " + id); // BY_ID[id] = version; // } // } // // public static ProtocolVersion getById(int id) { // if (id < 0) { // throw new IllegalArgumentException("Negative id: " + id); // } else if (id < BY_ID.length) { // return BY_ID[id]; // } else { // return null; // } // } // } // // Path: src/main/java/net/techcable/spudcompat/protocol/injector/RawPacket.java // @Getter // public class RawPacket extends AbstractReferenceCounted { // private final ByteBuf allData; // private final ByteBuf packetData; // private final int id; // private final ProtocolState protocolState; // private final ProtocolDirection direction; // private final PacketType type; // // private RawPacket(ByteBuf allData, ByteBuf packetData, int id, ProtocolState protocolState, ProtocolDirection direction) { // this.allData = allData.retain(); // this.packetData = packetData.retain(); // this.id = id; // this.protocolState = checkNotNull(protocolState, "Null state"); // this.direction = checkNotNull(direction, "Null direction"); // this.type = PacketType.getById(id, protocolState, direction); // } // // public ByteBuf getAllData() { // assertValid(); // return allData; // } // // public ByteBuf getPacketData() { // assertValid(); // return packetData; // } // // // public boolean isKnownType() { // return getType() != null; // } // // public static RawPacket fromWrapper(PacketWrapper wrapper, ProtocolState protocolState, ProtocolDirection direction) { // return fromBuffer(checkNotNull(wrapper, "Null wrapper").buf, protocolState, direction); // } // // public static RawPacket fromBuffer(ByteBuf buf, ProtocolState protocolState, ProtocolDirection direction) { // checkNotNull(buf, "Null buffer"); // checkNotNull(protocolState, "Null state"); // checkNotNull(direction, "Null direction"); // buf = Unpooled.unmodifiableBuffer(buf.duplicate()); // Read-only // ByteBuf allData = buf.duplicate(); // int id = DefinedPacket.readVarInt(buf); // return new RawPacket(allData, buf.slice(), id, protocolState, direction); // } // // @Override // protected void deallocate() { // allData.release(); // packetData.release(); // } // // private void assertValid() { // if (refCnt() <= 0) throw new IllegalReferenceCountException("Packet deallocated"); // } // }
import io.netty.channel.Channel; import net.md_5.bungee.api.connection.Server; import net.techcable.spudcompat.ProtocolVersion; import net.techcable.spudcompat.protocol.injector.RawPacket;
package net.techcable.spudcompat.protocol; public interface PlayerConnection { public default boolean isSupportedVersion() { return ProtocolVersion.getById(getVersionId()) != null; } public default ProtocolVersion getVersion() { int id = getVersionId(); ProtocolVersion version = ProtocolVersion.getById(id); if (version != null) { return version; } else { throw new IllegalStateException("Unsupported version: " + id); } } public ProtocolState getState(); public int getVersionId();
// Path: src/main/java/net/techcable/spudcompat/ProtocolVersion.java // @RequiredArgsConstructor // public enum ProtocolVersion { // v1_7_10(5), // v1_8(47); // // public boolean isBefore(ProtocolVersion other) { // return this.getId() < other.getId(); // } // // private final int versionNumber; // // public int getId() { // return versionNumber; // } // // public static final int MAX_ID; // private static final ProtocolVersion[] BY_ID; // // static { // int maxId = 0; // for (ProtocolVersion version : values()) { // if (version.getId() > maxId) { // maxId = version.getId(); // } // } // MAX_ID = maxId; // BY_ID = new ProtocolVersion[MAX_ID + 1]; // for (ProtocolVersion version : values()) { // int id = version.getId(); // if (BY_ID[id] != null) throw new AssertionError("Already a version with id: " + id); // BY_ID[id] = version; // } // } // // public static ProtocolVersion getById(int id) { // if (id < 0) { // throw new IllegalArgumentException("Negative id: " + id); // } else if (id < BY_ID.length) { // return BY_ID[id]; // } else { // return null; // } // } // } // // Path: src/main/java/net/techcable/spudcompat/protocol/injector/RawPacket.java // @Getter // public class RawPacket extends AbstractReferenceCounted { // private final ByteBuf allData; // private final ByteBuf packetData; // private final int id; // private final ProtocolState protocolState; // private final ProtocolDirection direction; // private final PacketType type; // // private RawPacket(ByteBuf allData, ByteBuf packetData, int id, ProtocolState protocolState, ProtocolDirection direction) { // this.allData = allData.retain(); // this.packetData = packetData.retain(); // this.id = id; // this.protocolState = checkNotNull(protocolState, "Null state"); // this.direction = checkNotNull(direction, "Null direction"); // this.type = PacketType.getById(id, protocolState, direction); // } // // public ByteBuf getAllData() { // assertValid(); // return allData; // } // // public ByteBuf getPacketData() { // assertValid(); // return packetData; // } // // // public boolean isKnownType() { // return getType() != null; // } // // public static RawPacket fromWrapper(PacketWrapper wrapper, ProtocolState protocolState, ProtocolDirection direction) { // return fromBuffer(checkNotNull(wrapper, "Null wrapper").buf, protocolState, direction); // } // // public static RawPacket fromBuffer(ByteBuf buf, ProtocolState protocolState, ProtocolDirection direction) { // checkNotNull(buf, "Null buffer"); // checkNotNull(protocolState, "Null state"); // checkNotNull(direction, "Null direction"); // buf = Unpooled.unmodifiableBuffer(buf.duplicate()); // Read-only // ByteBuf allData = buf.duplicate(); // int id = DefinedPacket.readVarInt(buf); // return new RawPacket(allData, buf.slice(), id, protocolState, direction); // } // // @Override // protected void deallocate() { // allData.release(); // packetData.release(); // } // // private void assertValid() { // if (refCnt() <= 0) throw new IllegalReferenceCountException("Packet deallocated"); // } // } // Path: src/main/java/net/techcable/spudcompat/protocol/PlayerConnection.java import io.netty.channel.Channel; import net.md_5.bungee.api.connection.Server; import net.techcable.spudcompat.ProtocolVersion; import net.techcable.spudcompat.protocol.injector.RawPacket; package net.techcable.spudcompat.protocol; public interface PlayerConnection { public default boolean isSupportedVersion() { return ProtocolVersion.getById(getVersionId()) != null; } public default ProtocolVersion getVersion() { int id = getVersionId(); ProtocolVersion version = ProtocolVersion.getById(id); if (version != null) { return version; } else { throw new IllegalStateException("Unsupported version: " + id); } } public ProtocolState getState(); public int getVersionId();
public void sendPacket(RawPacket rawPacket);
SpudCompat/SpudCompat
src/main/java/net/techcable/spudcompat/protocol/injector/PacketListener.java
// Path: src/main/java/net/techcable/spudcompat/ProtocolVersion.java // @RequiredArgsConstructor // public enum ProtocolVersion { // v1_7_10(5), // v1_8(47); // // public boolean isBefore(ProtocolVersion other) { // return this.getId() < other.getId(); // } // // private final int versionNumber; // // public int getId() { // return versionNumber; // } // // public static final int MAX_ID; // private static final ProtocolVersion[] BY_ID; // // static { // int maxId = 0; // for (ProtocolVersion version : values()) { // if (version.getId() > maxId) { // maxId = version.getId(); // } // } // MAX_ID = maxId; // BY_ID = new ProtocolVersion[MAX_ID + 1]; // for (ProtocolVersion version : values()) { // int id = version.getId(); // if (BY_ID[id] != null) throw new AssertionError("Already a version with id: " + id); // BY_ID[id] = version; // } // } // // public static ProtocolVersion getById(int id) { // if (id < 0) { // throw new IllegalArgumentException("Negative id: " + id); // } else if (id < BY_ID.length) { // return BY_ID[id]; // } else { // return null; // } // } // } // // Path: src/main/java/net/techcable/spudcompat/protocol/Packet.java // public interface Packet { // public PacketType getType(); // // public void write(ByteBuf buf, ProtocolVersion version, ProtocolState state, ProtocolDirection direction); // // public default RawPacket toRaw(ByteBufAllocator allocator, ProtocolVersion version, ProtocolState state, ProtocolDirection direction) { // ByteBuf buf = allocator.buffer(); // write(buf, version, state, direction); // RawPacket raw = RawPacket.fromBuffer(buf, state, direction); // buf.release(); // assert buf.refCnt() != 0; // assert raw.getType() == this.getType(); // return raw; // } // } // // Path: src/main/java/net/techcable/spudcompat/protocol/PlayerConnection.java // public interface PlayerConnection { // // public default boolean isSupportedVersion() { // return ProtocolVersion.getById(getVersionId()) != null; // } // // public default ProtocolVersion getVersion() { // int id = getVersionId(); // ProtocolVersion version = ProtocolVersion.getById(id); // if (version != null) { // return version; // } else { // throw new IllegalStateException("Unsupported version: " + id); // } // } // // public ProtocolState getState(); // // public int getVersionId(); // // public void sendPacket(RawPacket rawPacket); // // public Channel getChannel(); // // public Server getServer(); // } // // Path: src/main/java/net/techcable/spudcompat/protocol/ProtocolDirection.java // public enum ProtocolDirection { // CLIENTBOUND(ProtocolConstants.Direction.TO_CLIENT), // SERVERBOUND(ProtocolConstants.Direction.TO_SERVER); // // private ProtocolDirection(ProtocolConstants.Direction bungee) { // this.bungee = checkNotNull(bungee, "Null bungee direction"); // } // // private final ProtocolConstants.Direction bungee; // // public ProtocolConstants.Direction asBungee() { // return bungee; // } // } // // Path: src/main/java/net/techcable/spudcompat/protocol/ProtocolState.java // @RequiredArgsConstructor // public enum ProtocolState { // HANDSHAKE(Protocol.HANDSHAKE), // LOGIN(Protocol.LOGIN), // PLAY(Protocol.GAME), // STATUS(Protocol.STATUS); // // private final Protocol bungee; // // public Protocol toBungee() { // return bungee; // } // }
import lombok.*; import net.techcable.spudcompat.ProtocolVersion; import net.techcable.spudcompat.protocol.Packet; import net.techcable.spudcompat.protocol.PlayerConnection; import net.techcable.spudcompat.protocol.ProtocolDirection; import net.techcable.spudcompat.protocol.ProtocolState; import static com.google.common.base.Preconditions.checkNotNull;
package net.techcable.spudcompat.protocol.injector; public interface PacketListener { public default Result onRawSend(PlayerConnection connection, RawPacket packet) { return Result.IGNORED; } public default Result onRawReceive(PlayerConnection connection, RawPacket packet) { return Result.IGNORED; }
// Path: src/main/java/net/techcable/spudcompat/ProtocolVersion.java // @RequiredArgsConstructor // public enum ProtocolVersion { // v1_7_10(5), // v1_8(47); // // public boolean isBefore(ProtocolVersion other) { // return this.getId() < other.getId(); // } // // private final int versionNumber; // // public int getId() { // return versionNumber; // } // // public static final int MAX_ID; // private static final ProtocolVersion[] BY_ID; // // static { // int maxId = 0; // for (ProtocolVersion version : values()) { // if (version.getId() > maxId) { // maxId = version.getId(); // } // } // MAX_ID = maxId; // BY_ID = new ProtocolVersion[MAX_ID + 1]; // for (ProtocolVersion version : values()) { // int id = version.getId(); // if (BY_ID[id] != null) throw new AssertionError("Already a version with id: " + id); // BY_ID[id] = version; // } // } // // public static ProtocolVersion getById(int id) { // if (id < 0) { // throw new IllegalArgumentException("Negative id: " + id); // } else if (id < BY_ID.length) { // return BY_ID[id]; // } else { // return null; // } // } // } // // Path: src/main/java/net/techcable/spudcompat/protocol/Packet.java // public interface Packet { // public PacketType getType(); // // public void write(ByteBuf buf, ProtocolVersion version, ProtocolState state, ProtocolDirection direction); // // public default RawPacket toRaw(ByteBufAllocator allocator, ProtocolVersion version, ProtocolState state, ProtocolDirection direction) { // ByteBuf buf = allocator.buffer(); // write(buf, version, state, direction); // RawPacket raw = RawPacket.fromBuffer(buf, state, direction); // buf.release(); // assert buf.refCnt() != 0; // assert raw.getType() == this.getType(); // return raw; // } // } // // Path: src/main/java/net/techcable/spudcompat/protocol/PlayerConnection.java // public interface PlayerConnection { // // public default boolean isSupportedVersion() { // return ProtocolVersion.getById(getVersionId()) != null; // } // // public default ProtocolVersion getVersion() { // int id = getVersionId(); // ProtocolVersion version = ProtocolVersion.getById(id); // if (version != null) { // return version; // } else { // throw new IllegalStateException("Unsupported version: " + id); // } // } // // public ProtocolState getState(); // // public int getVersionId(); // // public void sendPacket(RawPacket rawPacket); // // public Channel getChannel(); // // public Server getServer(); // } // // Path: src/main/java/net/techcable/spudcompat/protocol/ProtocolDirection.java // public enum ProtocolDirection { // CLIENTBOUND(ProtocolConstants.Direction.TO_CLIENT), // SERVERBOUND(ProtocolConstants.Direction.TO_SERVER); // // private ProtocolDirection(ProtocolConstants.Direction bungee) { // this.bungee = checkNotNull(bungee, "Null bungee direction"); // } // // private final ProtocolConstants.Direction bungee; // // public ProtocolConstants.Direction asBungee() { // return bungee; // } // } // // Path: src/main/java/net/techcable/spudcompat/protocol/ProtocolState.java // @RequiredArgsConstructor // public enum ProtocolState { // HANDSHAKE(Protocol.HANDSHAKE), // LOGIN(Protocol.LOGIN), // PLAY(Protocol.GAME), // STATUS(Protocol.STATUS); // // private final Protocol bungee; // // public Protocol toBungee() { // return bungee; // } // } // Path: src/main/java/net/techcable/spudcompat/protocol/injector/PacketListener.java import lombok.*; import net.techcable.spudcompat.ProtocolVersion; import net.techcable.spudcompat.protocol.Packet; import net.techcable.spudcompat.protocol.PlayerConnection; import net.techcable.spudcompat.protocol.ProtocolDirection; import net.techcable.spudcompat.protocol.ProtocolState; import static com.google.common.base.Preconditions.checkNotNull; package net.techcable.spudcompat.protocol.injector; public interface PacketListener { public default Result onRawSend(PlayerConnection connection, RawPacket packet) { return Result.IGNORED; } public default Result onRawReceive(PlayerConnection connection, RawPacket packet) { return Result.IGNORED; }
public Result onSend(PlayerConnection connection, Packet definedPacket);
SpudCompat/SpudCompat
src/main/java/net/techcable/spudcompat/protocol/injector/PacketListener.java
// Path: src/main/java/net/techcable/spudcompat/ProtocolVersion.java // @RequiredArgsConstructor // public enum ProtocolVersion { // v1_7_10(5), // v1_8(47); // // public boolean isBefore(ProtocolVersion other) { // return this.getId() < other.getId(); // } // // private final int versionNumber; // // public int getId() { // return versionNumber; // } // // public static final int MAX_ID; // private static final ProtocolVersion[] BY_ID; // // static { // int maxId = 0; // for (ProtocolVersion version : values()) { // if (version.getId() > maxId) { // maxId = version.getId(); // } // } // MAX_ID = maxId; // BY_ID = new ProtocolVersion[MAX_ID + 1]; // for (ProtocolVersion version : values()) { // int id = version.getId(); // if (BY_ID[id] != null) throw new AssertionError("Already a version with id: " + id); // BY_ID[id] = version; // } // } // // public static ProtocolVersion getById(int id) { // if (id < 0) { // throw new IllegalArgumentException("Negative id: " + id); // } else if (id < BY_ID.length) { // return BY_ID[id]; // } else { // return null; // } // } // } // // Path: src/main/java/net/techcable/spudcompat/protocol/Packet.java // public interface Packet { // public PacketType getType(); // // public void write(ByteBuf buf, ProtocolVersion version, ProtocolState state, ProtocolDirection direction); // // public default RawPacket toRaw(ByteBufAllocator allocator, ProtocolVersion version, ProtocolState state, ProtocolDirection direction) { // ByteBuf buf = allocator.buffer(); // write(buf, version, state, direction); // RawPacket raw = RawPacket.fromBuffer(buf, state, direction); // buf.release(); // assert buf.refCnt() != 0; // assert raw.getType() == this.getType(); // return raw; // } // } // // Path: src/main/java/net/techcable/spudcompat/protocol/PlayerConnection.java // public interface PlayerConnection { // // public default boolean isSupportedVersion() { // return ProtocolVersion.getById(getVersionId()) != null; // } // // public default ProtocolVersion getVersion() { // int id = getVersionId(); // ProtocolVersion version = ProtocolVersion.getById(id); // if (version != null) { // return version; // } else { // throw new IllegalStateException("Unsupported version: " + id); // } // } // // public ProtocolState getState(); // // public int getVersionId(); // // public void sendPacket(RawPacket rawPacket); // // public Channel getChannel(); // // public Server getServer(); // } // // Path: src/main/java/net/techcable/spudcompat/protocol/ProtocolDirection.java // public enum ProtocolDirection { // CLIENTBOUND(ProtocolConstants.Direction.TO_CLIENT), // SERVERBOUND(ProtocolConstants.Direction.TO_SERVER); // // private ProtocolDirection(ProtocolConstants.Direction bungee) { // this.bungee = checkNotNull(bungee, "Null bungee direction"); // } // // private final ProtocolConstants.Direction bungee; // // public ProtocolConstants.Direction asBungee() { // return bungee; // } // } // // Path: src/main/java/net/techcable/spudcompat/protocol/ProtocolState.java // @RequiredArgsConstructor // public enum ProtocolState { // HANDSHAKE(Protocol.HANDSHAKE), // LOGIN(Protocol.LOGIN), // PLAY(Protocol.GAME), // STATUS(Protocol.STATUS); // // private final Protocol bungee; // // public Protocol toBungee() { // return bungee; // } // }
import lombok.*; import net.techcable.spudcompat.ProtocolVersion; import net.techcable.spudcompat.protocol.Packet; import net.techcable.spudcompat.protocol.PlayerConnection; import net.techcable.spudcompat.protocol.ProtocolDirection; import net.techcable.spudcompat.protocol.ProtocolState; import static com.google.common.base.Preconditions.checkNotNull;
package net.techcable.spudcompat.protocol.injector; public interface PacketListener { public default Result onRawSend(PlayerConnection connection, RawPacket packet) { return Result.IGNORED; } public default Result onRawReceive(PlayerConnection connection, RawPacket packet) { return Result.IGNORED; } public Result onSend(PlayerConnection connection, Packet definedPacket); public Result onReceive(PlayerConnection connection, Packet definedPacket); @Getter @RequiredArgsConstructor(access = AccessLevel.PRIVATE) public static class Result { private final boolean canceled; private final RawPacket result;
// Path: src/main/java/net/techcable/spudcompat/ProtocolVersion.java // @RequiredArgsConstructor // public enum ProtocolVersion { // v1_7_10(5), // v1_8(47); // // public boolean isBefore(ProtocolVersion other) { // return this.getId() < other.getId(); // } // // private final int versionNumber; // // public int getId() { // return versionNumber; // } // // public static final int MAX_ID; // private static final ProtocolVersion[] BY_ID; // // static { // int maxId = 0; // for (ProtocolVersion version : values()) { // if (version.getId() > maxId) { // maxId = version.getId(); // } // } // MAX_ID = maxId; // BY_ID = new ProtocolVersion[MAX_ID + 1]; // for (ProtocolVersion version : values()) { // int id = version.getId(); // if (BY_ID[id] != null) throw new AssertionError("Already a version with id: " + id); // BY_ID[id] = version; // } // } // // public static ProtocolVersion getById(int id) { // if (id < 0) { // throw new IllegalArgumentException("Negative id: " + id); // } else if (id < BY_ID.length) { // return BY_ID[id]; // } else { // return null; // } // } // } // // Path: src/main/java/net/techcable/spudcompat/protocol/Packet.java // public interface Packet { // public PacketType getType(); // // public void write(ByteBuf buf, ProtocolVersion version, ProtocolState state, ProtocolDirection direction); // // public default RawPacket toRaw(ByteBufAllocator allocator, ProtocolVersion version, ProtocolState state, ProtocolDirection direction) { // ByteBuf buf = allocator.buffer(); // write(buf, version, state, direction); // RawPacket raw = RawPacket.fromBuffer(buf, state, direction); // buf.release(); // assert buf.refCnt() != 0; // assert raw.getType() == this.getType(); // return raw; // } // } // // Path: src/main/java/net/techcable/spudcompat/protocol/PlayerConnection.java // public interface PlayerConnection { // // public default boolean isSupportedVersion() { // return ProtocolVersion.getById(getVersionId()) != null; // } // // public default ProtocolVersion getVersion() { // int id = getVersionId(); // ProtocolVersion version = ProtocolVersion.getById(id); // if (version != null) { // return version; // } else { // throw new IllegalStateException("Unsupported version: " + id); // } // } // // public ProtocolState getState(); // // public int getVersionId(); // // public void sendPacket(RawPacket rawPacket); // // public Channel getChannel(); // // public Server getServer(); // } // // Path: src/main/java/net/techcable/spudcompat/protocol/ProtocolDirection.java // public enum ProtocolDirection { // CLIENTBOUND(ProtocolConstants.Direction.TO_CLIENT), // SERVERBOUND(ProtocolConstants.Direction.TO_SERVER); // // private ProtocolDirection(ProtocolConstants.Direction bungee) { // this.bungee = checkNotNull(bungee, "Null bungee direction"); // } // // private final ProtocolConstants.Direction bungee; // // public ProtocolConstants.Direction asBungee() { // return bungee; // } // } // // Path: src/main/java/net/techcable/spudcompat/protocol/ProtocolState.java // @RequiredArgsConstructor // public enum ProtocolState { // HANDSHAKE(Protocol.HANDSHAKE), // LOGIN(Protocol.LOGIN), // PLAY(Protocol.GAME), // STATUS(Protocol.STATUS); // // private final Protocol bungee; // // public Protocol toBungee() { // return bungee; // } // } // Path: src/main/java/net/techcable/spudcompat/protocol/injector/PacketListener.java import lombok.*; import net.techcable.spudcompat.ProtocolVersion; import net.techcable.spudcompat.protocol.Packet; import net.techcable.spudcompat.protocol.PlayerConnection; import net.techcable.spudcompat.protocol.ProtocolDirection; import net.techcable.spudcompat.protocol.ProtocolState; import static com.google.common.base.Preconditions.checkNotNull; package net.techcable.spudcompat.protocol.injector; public interface PacketListener { public default Result onRawSend(PlayerConnection connection, RawPacket packet) { return Result.IGNORED; } public default Result onRawReceive(PlayerConnection connection, RawPacket packet) { return Result.IGNORED; } public Result onSend(PlayerConnection connection, Packet definedPacket); public Result onReceive(PlayerConnection connection, Packet definedPacket); @Getter @RequiredArgsConstructor(access = AccessLevel.PRIVATE) public static class Result { private final boolean canceled; private final RawPacket result;
private final ProtocolVersion version;
SpudCompat/SpudCompat
src/main/java/net/techcable/spudcompat/protocol/injector/PacketListener.java
// Path: src/main/java/net/techcable/spudcompat/ProtocolVersion.java // @RequiredArgsConstructor // public enum ProtocolVersion { // v1_7_10(5), // v1_8(47); // // public boolean isBefore(ProtocolVersion other) { // return this.getId() < other.getId(); // } // // private final int versionNumber; // // public int getId() { // return versionNumber; // } // // public static final int MAX_ID; // private static final ProtocolVersion[] BY_ID; // // static { // int maxId = 0; // for (ProtocolVersion version : values()) { // if (version.getId() > maxId) { // maxId = version.getId(); // } // } // MAX_ID = maxId; // BY_ID = new ProtocolVersion[MAX_ID + 1]; // for (ProtocolVersion version : values()) { // int id = version.getId(); // if (BY_ID[id] != null) throw new AssertionError("Already a version with id: " + id); // BY_ID[id] = version; // } // } // // public static ProtocolVersion getById(int id) { // if (id < 0) { // throw new IllegalArgumentException("Negative id: " + id); // } else if (id < BY_ID.length) { // return BY_ID[id]; // } else { // return null; // } // } // } // // Path: src/main/java/net/techcable/spudcompat/protocol/Packet.java // public interface Packet { // public PacketType getType(); // // public void write(ByteBuf buf, ProtocolVersion version, ProtocolState state, ProtocolDirection direction); // // public default RawPacket toRaw(ByteBufAllocator allocator, ProtocolVersion version, ProtocolState state, ProtocolDirection direction) { // ByteBuf buf = allocator.buffer(); // write(buf, version, state, direction); // RawPacket raw = RawPacket.fromBuffer(buf, state, direction); // buf.release(); // assert buf.refCnt() != 0; // assert raw.getType() == this.getType(); // return raw; // } // } // // Path: src/main/java/net/techcable/spudcompat/protocol/PlayerConnection.java // public interface PlayerConnection { // // public default boolean isSupportedVersion() { // return ProtocolVersion.getById(getVersionId()) != null; // } // // public default ProtocolVersion getVersion() { // int id = getVersionId(); // ProtocolVersion version = ProtocolVersion.getById(id); // if (version != null) { // return version; // } else { // throw new IllegalStateException("Unsupported version: " + id); // } // } // // public ProtocolState getState(); // // public int getVersionId(); // // public void sendPacket(RawPacket rawPacket); // // public Channel getChannel(); // // public Server getServer(); // } // // Path: src/main/java/net/techcable/spudcompat/protocol/ProtocolDirection.java // public enum ProtocolDirection { // CLIENTBOUND(ProtocolConstants.Direction.TO_CLIENT), // SERVERBOUND(ProtocolConstants.Direction.TO_SERVER); // // private ProtocolDirection(ProtocolConstants.Direction bungee) { // this.bungee = checkNotNull(bungee, "Null bungee direction"); // } // // private final ProtocolConstants.Direction bungee; // // public ProtocolConstants.Direction asBungee() { // return bungee; // } // } // // Path: src/main/java/net/techcable/spudcompat/protocol/ProtocolState.java // @RequiredArgsConstructor // public enum ProtocolState { // HANDSHAKE(Protocol.HANDSHAKE), // LOGIN(Protocol.LOGIN), // PLAY(Protocol.GAME), // STATUS(Protocol.STATUS); // // private final Protocol bungee; // // public Protocol toBungee() { // return bungee; // } // }
import lombok.*; import net.techcable.spudcompat.ProtocolVersion; import net.techcable.spudcompat.protocol.Packet; import net.techcable.spudcompat.protocol.PlayerConnection; import net.techcable.spudcompat.protocol.ProtocolDirection; import net.techcable.spudcompat.protocol.ProtocolState; import static com.google.common.base.Preconditions.checkNotNull;
package net.techcable.spudcompat.protocol.injector; public interface PacketListener { public default Result onRawSend(PlayerConnection connection, RawPacket packet) { return Result.IGNORED; } public default Result onRawReceive(PlayerConnection connection, RawPacket packet) { return Result.IGNORED; } public Result onSend(PlayerConnection connection, Packet definedPacket); public Result onReceive(PlayerConnection connection, Packet definedPacket); @Getter @RequiredArgsConstructor(access = AccessLevel.PRIVATE) public static class Result { private final boolean canceled; private final RawPacket result; private final ProtocolVersion version; public Result(RawPacket result, ProtocolVersion version) { this(false, checkNotNull(result, "Null result"), checkNotNull(version, "Null version")); }
// Path: src/main/java/net/techcable/spudcompat/ProtocolVersion.java // @RequiredArgsConstructor // public enum ProtocolVersion { // v1_7_10(5), // v1_8(47); // // public boolean isBefore(ProtocolVersion other) { // return this.getId() < other.getId(); // } // // private final int versionNumber; // // public int getId() { // return versionNumber; // } // // public static final int MAX_ID; // private static final ProtocolVersion[] BY_ID; // // static { // int maxId = 0; // for (ProtocolVersion version : values()) { // if (version.getId() > maxId) { // maxId = version.getId(); // } // } // MAX_ID = maxId; // BY_ID = new ProtocolVersion[MAX_ID + 1]; // for (ProtocolVersion version : values()) { // int id = version.getId(); // if (BY_ID[id] != null) throw new AssertionError("Already a version with id: " + id); // BY_ID[id] = version; // } // } // // public static ProtocolVersion getById(int id) { // if (id < 0) { // throw new IllegalArgumentException("Negative id: " + id); // } else if (id < BY_ID.length) { // return BY_ID[id]; // } else { // return null; // } // } // } // // Path: src/main/java/net/techcable/spudcompat/protocol/Packet.java // public interface Packet { // public PacketType getType(); // // public void write(ByteBuf buf, ProtocolVersion version, ProtocolState state, ProtocolDirection direction); // // public default RawPacket toRaw(ByteBufAllocator allocator, ProtocolVersion version, ProtocolState state, ProtocolDirection direction) { // ByteBuf buf = allocator.buffer(); // write(buf, version, state, direction); // RawPacket raw = RawPacket.fromBuffer(buf, state, direction); // buf.release(); // assert buf.refCnt() != 0; // assert raw.getType() == this.getType(); // return raw; // } // } // // Path: src/main/java/net/techcable/spudcompat/protocol/PlayerConnection.java // public interface PlayerConnection { // // public default boolean isSupportedVersion() { // return ProtocolVersion.getById(getVersionId()) != null; // } // // public default ProtocolVersion getVersion() { // int id = getVersionId(); // ProtocolVersion version = ProtocolVersion.getById(id); // if (version != null) { // return version; // } else { // throw new IllegalStateException("Unsupported version: " + id); // } // } // // public ProtocolState getState(); // // public int getVersionId(); // // public void sendPacket(RawPacket rawPacket); // // public Channel getChannel(); // // public Server getServer(); // } // // Path: src/main/java/net/techcable/spudcompat/protocol/ProtocolDirection.java // public enum ProtocolDirection { // CLIENTBOUND(ProtocolConstants.Direction.TO_CLIENT), // SERVERBOUND(ProtocolConstants.Direction.TO_SERVER); // // private ProtocolDirection(ProtocolConstants.Direction bungee) { // this.bungee = checkNotNull(bungee, "Null bungee direction"); // } // // private final ProtocolConstants.Direction bungee; // // public ProtocolConstants.Direction asBungee() { // return bungee; // } // } // // Path: src/main/java/net/techcable/spudcompat/protocol/ProtocolState.java // @RequiredArgsConstructor // public enum ProtocolState { // HANDSHAKE(Protocol.HANDSHAKE), // LOGIN(Protocol.LOGIN), // PLAY(Protocol.GAME), // STATUS(Protocol.STATUS); // // private final Protocol bungee; // // public Protocol toBungee() { // return bungee; // } // } // Path: src/main/java/net/techcable/spudcompat/protocol/injector/PacketListener.java import lombok.*; import net.techcable.spudcompat.ProtocolVersion; import net.techcable.spudcompat.protocol.Packet; import net.techcable.spudcompat.protocol.PlayerConnection; import net.techcable.spudcompat.protocol.ProtocolDirection; import net.techcable.spudcompat.protocol.ProtocolState; import static com.google.common.base.Preconditions.checkNotNull; package net.techcable.spudcompat.protocol.injector; public interface PacketListener { public default Result onRawSend(PlayerConnection connection, RawPacket packet) { return Result.IGNORED; } public default Result onRawReceive(PlayerConnection connection, RawPacket packet) { return Result.IGNORED; } public Result onSend(PlayerConnection connection, Packet definedPacket); public Result onReceive(PlayerConnection connection, Packet definedPacket); @Getter @RequiredArgsConstructor(access = AccessLevel.PRIVATE) public static class Result { private final boolean canceled; private final RawPacket result; private final ProtocolVersion version; public Result(RawPacket result, ProtocolVersion version) { this(false, checkNotNull(result, "Null result"), checkNotNull(version, "Null version")); }
public Result(PlayerConnection connection, Packet packet, ProtocolVersion version, ProtocolState state, ProtocolDirection direction) {
SpudCompat/SpudCompat
src/main/java/net/techcable/spudcompat/protocol/injector/PacketListener.java
// Path: src/main/java/net/techcable/spudcompat/ProtocolVersion.java // @RequiredArgsConstructor // public enum ProtocolVersion { // v1_7_10(5), // v1_8(47); // // public boolean isBefore(ProtocolVersion other) { // return this.getId() < other.getId(); // } // // private final int versionNumber; // // public int getId() { // return versionNumber; // } // // public static final int MAX_ID; // private static final ProtocolVersion[] BY_ID; // // static { // int maxId = 0; // for (ProtocolVersion version : values()) { // if (version.getId() > maxId) { // maxId = version.getId(); // } // } // MAX_ID = maxId; // BY_ID = new ProtocolVersion[MAX_ID + 1]; // for (ProtocolVersion version : values()) { // int id = version.getId(); // if (BY_ID[id] != null) throw new AssertionError("Already a version with id: " + id); // BY_ID[id] = version; // } // } // // public static ProtocolVersion getById(int id) { // if (id < 0) { // throw new IllegalArgumentException("Negative id: " + id); // } else if (id < BY_ID.length) { // return BY_ID[id]; // } else { // return null; // } // } // } // // Path: src/main/java/net/techcable/spudcompat/protocol/Packet.java // public interface Packet { // public PacketType getType(); // // public void write(ByteBuf buf, ProtocolVersion version, ProtocolState state, ProtocolDirection direction); // // public default RawPacket toRaw(ByteBufAllocator allocator, ProtocolVersion version, ProtocolState state, ProtocolDirection direction) { // ByteBuf buf = allocator.buffer(); // write(buf, version, state, direction); // RawPacket raw = RawPacket.fromBuffer(buf, state, direction); // buf.release(); // assert buf.refCnt() != 0; // assert raw.getType() == this.getType(); // return raw; // } // } // // Path: src/main/java/net/techcable/spudcompat/protocol/PlayerConnection.java // public interface PlayerConnection { // // public default boolean isSupportedVersion() { // return ProtocolVersion.getById(getVersionId()) != null; // } // // public default ProtocolVersion getVersion() { // int id = getVersionId(); // ProtocolVersion version = ProtocolVersion.getById(id); // if (version != null) { // return version; // } else { // throw new IllegalStateException("Unsupported version: " + id); // } // } // // public ProtocolState getState(); // // public int getVersionId(); // // public void sendPacket(RawPacket rawPacket); // // public Channel getChannel(); // // public Server getServer(); // } // // Path: src/main/java/net/techcable/spudcompat/protocol/ProtocolDirection.java // public enum ProtocolDirection { // CLIENTBOUND(ProtocolConstants.Direction.TO_CLIENT), // SERVERBOUND(ProtocolConstants.Direction.TO_SERVER); // // private ProtocolDirection(ProtocolConstants.Direction bungee) { // this.bungee = checkNotNull(bungee, "Null bungee direction"); // } // // private final ProtocolConstants.Direction bungee; // // public ProtocolConstants.Direction asBungee() { // return bungee; // } // } // // Path: src/main/java/net/techcable/spudcompat/protocol/ProtocolState.java // @RequiredArgsConstructor // public enum ProtocolState { // HANDSHAKE(Protocol.HANDSHAKE), // LOGIN(Protocol.LOGIN), // PLAY(Protocol.GAME), // STATUS(Protocol.STATUS); // // private final Protocol bungee; // // public Protocol toBungee() { // return bungee; // } // }
import lombok.*; import net.techcable.spudcompat.ProtocolVersion; import net.techcable.spudcompat.protocol.Packet; import net.techcable.spudcompat.protocol.PlayerConnection; import net.techcable.spudcompat.protocol.ProtocolDirection; import net.techcable.spudcompat.protocol.ProtocolState; import static com.google.common.base.Preconditions.checkNotNull;
package net.techcable.spudcompat.protocol.injector; public interface PacketListener { public default Result onRawSend(PlayerConnection connection, RawPacket packet) { return Result.IGNORED; } public default Result onRawReceive(PlayerConnection connection, RawPacket packet) { return Result.IGNORED; } public Result onSend(PlayerConnection connection, Packet definedPacket); public Result onReceive(PlayerConnection connection, Packet definedPacket); @Getter @RequiredArgsConstructor(access = AccessLevel.PRIVATE) public static class Result { private final boolean canceled; private final RawPacket result; private final ProtocolVersion version; public Result(RawPacket result, ProtocolVersion version) { this(false, checkNotNull(result, "Null result"), checkNotNull(version, "Null version")); }
// Path: src/main/java/net/techcable/spudcompat/ProtocolVersion.java // @RequiredArgsConstructor // public enum ProtocolVersion { // v1_7_10(5), // v1_8(47); // // public boolean isBefore(ProtocolVersion other) { // return this.getId() < other.getId(); // } // // private final int versionNumber; // // public int getId() { // return versionNumber; // } // // public static final int MAX_ID; // private static final ProtocolVersion[] BY_ID; // // static { // int maxId = 0; // for (ProtocolVersion version : values()) { // if (version.getId() > maxId) { // maxId = version.getId(); // } // } // MAX_ID = maxId; // BY_ID = new ProtocolVersion[MAX_ID + 1]; // for (ProtocolVersion version : values()) { // int id = version.getId(); // if (BY_ID[id] != null) throw new AssertionError("Already a version with id: " + id); // BY_ID[id] = version; // } // } // // public static ProtocolVersion getById(int id) { // if (id < 0) { // throw new IllegalArgumentException("Negative id: " + id); // } else if (id < BY_ID.length) { // return BY_ID[id]; // } else { // return null; // } // } // } // // Path: src/main/java/net/techcable/spudcompat/protocol/Packet.java // public interface Packet { // public PacketType getType(); // // public void write(ByteBuf buf, ProtocolVersion version, ProtocolState state, ProtocolDirection direction); // // public default RawPacket toRaw(ByteBufAllocator allocator, ProtocolVersion version, ProtocolState state, ProtocolDirection direction) { // ByteBuf buf = allocator.buffer(); // write(buf, version, state, direction); // RawPacket raw = RawPacket.fromBuffer(buf, state, direction); // buf.release(); // assert buf.refCnt() != 0; // assert raw.getType() == this.getType(); // return raw; // } // } // // Path: src/main/java/net/techcable/spudcompat/protocol/PlayerConnection.java // public interface PlayerConnection { // // public default boolean isSupportedVersion() { // return ProtocolVersion.getById(getVersionId()) != null; // } // // public default ProtocolVersion getVersion() { // int id = getVersionId(); // ProtocolVersion version = ProtocolVersion.getById(id); // if (version != null) { // return version; // } else { // throw new IllegalStateException("Unsupported version: " + id); // } // } // // public ProtocolState getState(); // // public int getVersionId(); // // public void sendPacket(RawPacket rawPacket); // // public Channel getChannel(); // // public Server getServer(); // } // // Path: src/main/java/net/techcable/spudcompat/protocol/ProtocolDirection.java // public enum ProtocolDirection { // CLIENTBOUND(ProtocolConstants.Direction.TO_CLIENT), // SERVERBOUND(ProtocolConstants.Direction.TO_SERVER); // // private ProtocolDirection(ProtocolConstants.Direction bungee) { // this.bungee = checkNotNull(bungee, "Null bungee direction"); // } // // private final ProtocolConstants.Direction bungee; // // public ProtocolConstants.Direction asBungee() { // return bungee; // } // } // // Path: src/main/java/net/techcable/spudcompat/protocol/ProtocolState.java // @RequiredArgsConstructor // public enum ProtocolState { // HANDSHAKE(Protocol.HANDSHAKE), // LOGIN(Protocol.LOGIN), // PLAY(Protocol.GAME), // STATUS(Protocol.STATUS); // // private final Protocol bungee; // // public Protocol toBungee() { // return bungee; // } // } // Path: src/main/java/net/techcable/spudcompat/protocol/injector/PacketListener.java import lombok.*; import net.techcable.spudcompat.ProtocolVersion; import net.techcable.spudcompat.protocol.Packet; import net.techcable.spudcompat.protocol.PlayerConnection; import net.techcable.spudcompat.protocol.ProtocolDirection; import net.techcable.spudcompat.protocol.ProtocolState; import static com.google.common.base.Preconditions.checkNotNull; package net.techcable.spudcompat.protocol.injector; public interface PacketListener { public default Result onRawSend(PlayerConnection connection, RawPacket packet) { return Result.IGNORED; } public default Result onRawReceive(PlayerConnection connection, RawPacket packet) { return Result.IGNORED; } public Result onSend(PlayerConnection connection, Packet definedPacket); public Result onReceive(PlayerConnection connection, Packet definedPacket); @Getter @RequiredArgsConstructor(access = AccessLevel.PRIVATE) public static class Result { private final boolean canceled; private final RawPacket result; private final ProtocolVersion version; public Result(RawPacket result, ProtocolVersion version) { this(false, checkNotNull(result, "Null result"), checkNotNull(version, "Null version")); }
public Result(PlayerConnection connection, Packet packet, ProtocolVersion version, ProtocolState state, ProtocolDirection direction) {
SpudCompat/SpudCompat
src/main/java/net/techcable/spudcompat/protocol/Packet.java
// Path: src/main/java/net/techcable/spudcompat/ProtocolVersion.java // @RequiredArgsConstructor // public enum ProtocolVersion { // v1_7_10(5), // v1_8(47); // // public boolean isBefore(ProtocolVersion other) { // return this.getId() < other.getId(); // } // // private final int versionNumber; // // public int getId() { // return versionNumber; // } // // public static final int MAX_ID; // private static final ProtocolVersion[] BY_ID; // // static { // int maxId = 0; // for (ProtocolVersion version : values()) { // if (version.getId() > maxId) { // maxId = version.getId(); // } // } // MAX_ID = maxId; // BY_ID = new ProtocolVersion[MAX_ID + 1]; // for (ProtocolVersion version : values()) { // int id = version.getId(); // if (BY_ID[id] != null) throw new AssertionError("Already a version with id: " + id); // BY_ID[id] = version; // } // } // // public static ProtocolVersion getById(int id) { // if (id < 0) { // throw new IllegalArgumentException("Negative id: " + id); // } else if (id < BY_ID.length) { // return BY_ID[id]; // } else { // return null; // } // } // } // // Path: src/main/java/net/techcable/spudcompat/protocol/injector/RawPacket.java // @Getter // public class RawPacket extends AbstractReferenceCounted { // private final ByteBuf allData; // private final ByteBuf packetData; // private final int id; // private final ProtocolState protocolState; // private final ProtocolDirection direction; // private final PacketType type; // // private RawPacket(ByteBuf allData, ByteBuf packetData, int id, ProtocolState protocolState, ProtocolDirection direction) { // this.allData = allData.retain(); // this.packetData = packetData.retain(); // this.id = id; // this.protocolState = checkNotNull(protocolState, "Null state"); // this.direction = checkNotNull(direction, "Null direction"); // this.type = PacketType.getById(id, protocolState, direction); // } // // public ByteBuf getAllData() { // assertValid(); // return allData; // } // // public ByteBuf getPacketData() { // assertValid(); // return packetData; // } // // // public boolean isKnownType() { // return getType() != null; // } // // public static RawPacket fromWrapper(PacketWrapper wrapper, ProtocolState protocolState, ProtocolDirection direction) { // return fromBuffer(checkNotNull(wrapper, "Null wrapper").buf, protocolState, direction); // } // // public static RawPacket fromBuffer(ByteBuf buf, ProtocolState protocolState, ProtocolDirection direction) { // checkNotNull(buf, "Null buffer"); // checkNotNull(protocolState, "Null state"); // checkNotNull(direction, "Null direction"); // buf = Unpooled.unmodifiableBuffer(buf.duplicate()); // Read-only // ByteBuf allData = buf.duplicate(); // int id = DefinedPacket.readVarInt(buf); // return new RawPacket(allData, buf.slice(), id, protocolState, direction); // } // // @Override // protected void deallocate() { // allData.release(); // packetData.release(); // } // // private void assertValid() { // if (refCnt() <= 0) throw new IllegalReferenceCountException("Packet deallocated"); // } // }
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import net.md_5.bungee.api.connection.Connection; import net.techcable.spudcompat.ProtocolVersion; import net.techcable.spudcompat.protocol.injector.RawPacket;
package net.techcable.spudcompat.protocol; public interface Packet { public PacketType getType();
// Path: src/main/java/net/techcable/spudcompat/ProtocolVersion.java // @RequiredArgsConstructor // public enum ProtocolVersion { // v1_7_10(5), // v1_8(47); // // public boolean isBefore(ProtocolVersion other) { // return this.getId() < other.getId(); // } // // private final int versionNumber; // // public int getId() { // return versionNumber; // } // // public static final int MAX_ID; // private static final ProtocolVersion[] BY_ID; // // static { // int maxId = 0; // for (ProtocolVersion version : values()) { // if (version.getId() > maxId) { // maxId = version.getId(); // } // } // MAX_ID = maxId; // BY_ID = new ProtocolVersion[MAX_ID + 1]; // for (ProtocolVersion version : values()) { // int id = version.getId(); // if (BY_ID[id] != null) throw new AssertionError("Already a version with id: " + id); // BY_ID[id] = version; // } // } // // public static ProtocolVersion getById(int id) { // if (id < 0) { // throw new IllegalArgumentException("Negative id: " + id); // } else if (id < BY_ID.length) { // return BY_ID[id]; // } else { // return null; // } // } // } // // Path: src/main/java/net/techcable/spudcompat/protocol/injector/RawPacket.java // @Getter // public class RawPacket extends AbstractReferenceCounted { // private final ByteBuf allData; // private final ByteBuf packetData; // private final int id; // private final ProtocolState protocolState; // private final ProtocolDirection direction; // private final PacketType type; // // private RawPacket(ByteBuf allData, ByteBuf packetData, int id, ProtocolState protocolState, ProtocolDirection direction) { // this.allData = allData.retain(); // this.packetData = packetData.retain(); // this.id = id; // this.protocolState = checkNotNull(protocolState, "Null state"); // this.direction = checkNotNull(direction, "Null direction"); // this.type = PacketType.getById(id, protocolState, direction); // } // // public ByteBuf getAllData() { // assertValid(); // return allData; // } // // public ByteBuf getPacketData() { // assertValid(); // return packetData; // } // // // public boolean isKnownType() { // return getType() != null; // } // // public static RawPacket fromWrapper(PacketWrapper wrapper, ProtocolState protocolState, ProtocolDirection direction) { // return fromBuffer(checkNotNull(wrapper, "Null wrapper").buf, protocolState, direction); // } // // public static RawPacket fromBuffer(ByteBuf buf, ProtocolState protocolState, ProtocolDirection direction) { // checkNotNull(buf, "Null buffer"); // checkNotNull(protocolState, "Null state"); // checkNotNull(direction, "Null direction"); // buf = Unpooled.unmodifiableBuffer(buf.duplicate()); // Read-only // ByteBuf allData = buf.duplicate(); // int id = DefinedPacket.readVarInt(buf); // return new RawPacket(allData, buf.slice(), id, protocolState, direction); // } // // @Override // protected void deallocate() { // allData.release(); // packetData.release(); // } // // private void assertValid() { // if (refCnt() <= 0) throw new IllegalReferenceCountException("Packet deallocated"); // } // } // Path: src/main/java/net/techcable/spudcompat/protocol/Packet.java import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import net.md_5.bungee.api.connection.Connection; import net.techcable.spudcompat.ProtocolVersion; import net.techcable.spudcompat.protocol.injector.RawPacket; package net.techcable.spudcompat.protocol; public interface Packet { public PacketType getType();
public void write(ByteBuf buf, ProtocolVersion version, ProtocolState state, ProtocolDirection direction);
SpudCompat/SpudCompat
src/main/java/net/techcable/spudcompat/protocol/Packet.java
// Path: src/main/java/net/techcable/spudcompat/ProtocolVersion.java // @RequiredArgsConstructor // public enum ProtocolVersion { // v1_7_10(5), // v1_8(47); // // public boolean isBefore(ProtocolVersion other) { // return this.getId() < other.getId(); // } // // private final int versionNumber; // // public int getId() { // return versionNumber; // } // // public static final int MAX_ID; // private static final ProtocolVersion[] BY_ID; // // static { // int maxId = 0; // for (ProtocolVersion version : values()) { // if (version.getId() > maxId) { // maxId = version.getId(); // } // } // MAX_ID = maxId; // BY_ID = new ProtocolVersion[MAX_ID + 1]; // for (ProtocolVersion version : values()) { // int id = version.getId(); // if (BY_ID[id] != null) throw new AssertionError("Already a version with id: " + id); // BY_ID[id] = version; // } // } // // public static ProtocolVersion getById(int id) { // if (id < 0) { // throw new IllegalArgumentException("Negative id: " + id); // } else if (id < BY_ID.length) { // return BY_ID[id]; // } else { // return null; // } // } // } // // Path: src/main/java/net/techcable/spudcompat/protocol/injector/RawPacket.java // @Getter // public class RawPacket extends AbstractReferenceCounted { // private final ByteBuf allData; // private final ByteBuf packetData; // private final int id; // private final ProtocolState protocolState; // private final ProtocolDirection direction; // private final PacketType type; // // private RawPacket(ByteBuf allData, ByteBuf packetData, int id, ProtocolState protocolState, ProtocolDirection direction) { // this.allData = allData.retain(); // this.packetData = packetData.retain(); // this.id = id; // this.protocolState = checkNotNull(protocolState, "Null state"); // this.direction = checkNotNull(direction, "Null direction"); // this.type = PacketType.getById(id, protocolState, direction); // } // // public ByteBuf getAllData() { // assertValid(); // return allData; // } // // public ByteBuf getPacketData() { // assertValid(); // return packetData; // } // // // public boolean isKnownType() { // return getType() != null; // } // // public static RawPacket fromWrapper(PacketWrapper wrapper, ProtocolState protocolState, ProtocolDirection direction) { // return fromBuffer(checkNotNull(wrapper, "Null wrapper").buf, protocolState, direction); // } // // public static RawPacket fromBuffer(ByteBuf buf, ProtocolState protocolState, ProtocolDirection direction) { // checkNotNull(buf, "Null buffer"); // checkNotNull(protocolState, "Null state"); // checkNotNull(direction, "Null direction"); // buf = Unpooled.unmodifiableBuffer(buf.duplicate()); // Read-only // ByteBuf allData = buf.duplicate(); // int id = DefinedPacket.readVarInt(buf); // return new RawPacket(allData, buf.slice(), id, protocolState, direction); // } // // @Override // protected void deallocate() { // allData.release(); // packetData.release(); // } // // private void assertValid() { // if (refCnt() <= 0) throw new IllegalReferenceCountException("Packet deallocated"); // } // }
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import net.md_5.bungee.api.connection.Connection; import net.techcable.spudcompat.ProtocolVersion; import net.techcable.spudcompat.protocol.injector.RawPacket;
package net.techcable.spudcompat.protocol; public interface Packet { public PacketType getType(); public void write(ByteBuf buf, ProtocolVersion version, ProtocolState state, ProtocolDirection direction);
// Path: src/main/java/net/techcable/spudcompat/ProtocolVersion.java // @RequiredArgsConstructor // public enum ProtocolVersion { // v1_7_10(5), // v1_8(47); // // public boolean isBefore(ProtocolVersion other) { // return this.getId() < other.getId(); // } // // private final int versionNumber; // // public int getId() { // return versionNumber; // } // // public static final int MAX_ID; // private static final ProtocolVersion[] BY_ID; // // static { // int maxId = 0; // for (ProtocolVersion version : values()) { // if (version.getId() > maxId) { // maxId = version.getId(); // } // } // MAX_ID = maxId; // BY_ID = new ProtocolVersion[MAX_ID + 1]; // for (ProtocolVersion version : values()) { // int id = version.getId(); // if (BY_ID[id] != null) throw new AssertionError("Already a version with id: " + id); // BY_ID[id] = version; // } // } // // public static ProtocolVersion getById(int id) { // if (id < 0) { // throw new IllegalArgumentException("Negative id: " + id); // } else if (id < BY_ID.length) { // return BY_ID[id]; // } else { // return null; // } // } // } // // Path: src/main/java/net/techcable/spudcompat/protocol/injector/RawPacket.java // @Getter // public class RawPacket extends AbstractReferenceCounted { // private final ByteBuf allData; // private final ByteBuf packetData; // private final int id; // private final ProtocolState protocolState; // private final ProtocolDirection direction; // private final PacketType type; // // private RawPacket(ByteBuf allData, ByteBuf packetData, int id, ProtocolState protocolState, ProtocolDirection direction) { // this.allData = allData.retain(); // this.packetData = packetData.retain(); // this.id = id; // this.protocolState = checkNotNull(protocolState, "Null state"); // this.direction = checkNotNull(direction, "Null direction"); // this.type = PacketType.getById(id, protocolState, direction); // } // // public ByteBuf getAllData() { // assertValid(); // return allData; // } // // public ByteBuf getPacketData() { // assertValid(); // return packetData; // } // // // public boolean isKnownType() { // return getType() != null; // } // // public static RawPacket fromWrapper(PacketWrapper wrapper, ProtocolState protocolState, ProtocolDirection direction) { // return fromBuffer(checkNotNull(wrapper, "Null wrapper").buf, protocolState, direction); // } // // public static RawPacket fromBuffer(ByteBuf buf, ProtocolState protocolState, ProtocolDirection direction) { // checkNotNull(buf, "Null buffer"); // checkNotNull(protocolState, "Null state"); // checkNotNull(direction, "Null direction"); // buf = Unpooled.unmodifiableBuffer(buf.duplicate()); // Read-only // ByteBuf allData = buf.duplicate(); // int id = DefinedPacket.readVarInt(buf); // return new RawPacket(allData, buf.slice(), id, protocolState, direction); // } // // @Override // protected void deallocate() { // allData.release(); // packetData.release(); // } // // private void assertValid() { // if (refCnt() <= 0) throw new IllegalReferenceCountException("Packet deallocated"); // } // } // Path: src/main/java/net/techcable/spudcompat/protocol/Packet.java import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import net.md_5.bungee.api.connection.Connection; import net.techcable.spudcompat.ProtocolVersion; import net.techcable.spudcompat.protocol.injector.RawPacket; package net.techcable.spudcompat.protocol; public interface Packet { public PacketType getType(); public void write(ByteBuf buf, ProtocolVersion version, ProtocolState state, ProtocolDirection direction);
public default RawPacket toRaw(ByteBufAllocator allocator, ProtocolVersion version, ProtocolState state, ProtocolDirection direction) {
SpudCompat/SpudCompat
src/main/java/net/techcable/spudcompat/metadata/MetadataDataType.java
// Path: src/main/java/net/techcable/spudcompat/BlockPos.java // @RequiredArgsConstructor // @Getter // public final class BlockPos { // private final int x, y, z; // }
import lombok.*; import com.google.common.base.Preconditions; import net.techcable.spudcompat.BlockPos;
package net.techcable.spudcompat.metadata; @RequiredArgsConstructor public enum MetadataDataType { BYTE(Byte.class), SHORT(Short.class), INT(Integer.class), FLOAT(Float.class), STRING(String.class), STACK(null),
// Path: src/main/java/net/techcable/spudcompat/BlockPos.java // @RequiredArgsConstructor // @Getter // public final class BlockPos { // private final int x, y, z; // } // Path: src/main/java/net/techcable/spudcompat/metadata/MetadataDataType.java import lombok.*; import com.google.common.base.Preconditions; import net.techcable.spudcompat.BlockPos; package net.techcable.spudcompat.metadata; @RequiredArgsConstructor public enum MetadataDataType { BYTE(Byte.class), SHORT(Short.class), INT(Integer.class), FLOAT(Float.class), STRING(String.class), STACK(null),
BLOCK_POS(BlockPos.class);
SpudCompat/SpudCompat
src/main/java/net/techcable/spudcompat/metadata/ImmutableMetadataMap.java
// Path: src/main/java/net/techcable/spudcompat/ProtocolVersion.java // @RequiredArgsConstructor // public enum ProtocolVersion { // v1_7_10(5), // v1_8(47); // // public boolean isBefore(ProtocolVersion other) { // return this.getId() < other.getId(); // } // // private final int versionNumber; // // public int getId() { // return versionNumber; // } // // public static final int MAX_ID; // private static final ProtocolVersion[] BY_ID; // // static { // int maxId = 0; // for (ProtocolVersion version : values()) { // if (version.getId() > maxId) { // maxId = version.getId(); // } // } // MAX_ID = maxId; // BY_ID = new ProtocolVersion[MAX_ID + 1]; // for (ProtocolVersion version : values()) { // int id = version.getId(); // if (BY_ID[id] != null) throw new AssertionError("Already a version with id: " + id); // BY_ID[id] = version; // } // } // // public static ProtocolVersion getById(int id) { // if (id < 0) { // throw new IllegalArgumentException("Negative id: " + id); // } else if (id < BY_ID.length) { // return BY_ID[id]; // } else { // return null; // } // } // }
import org.apache.commons.lang3.ArrayUtils; import lombok.*; import java.util.Arrays; import net.techcable.spudcompat.ProtocolVersion;
package net.techcable.spudcompat.metadata; public final class ImmutableMetadataMap implements MetadataMap { @Getter
// Path: src/main/java/net/techcable/spudcompat/ProtocolVersion.java // @RequiredArgsConstructor // public enum ProtocolVersion { // v1_7_10(5), // v1_8(47); // // public boolean isBefore(ProtocolVersion other) { // return this.getId() < other.getId(); // } // // private final int versionNumber; // // public int getId() { // return versionNumber; // } // // public static final int MAX_ID; // private static final ProtocolVersion[] BY_ID; // // static { // int maxId = 0; // for (ProtocolVersion version : values()) { // if (version.getId() > maxId) { // maxId = version.getId(); // } // } // MAX_ID = maxId; // BY_ID = new ProtocolVersion[MAX_ID + 1]; // for (ProtocolVersion version : values()) { // int id = version.getId(); // if (BY_ID[id] != null) throw new AssertionError("Already a version with id: " + id); // BY_ID[id] = version; // } // } // // public static ProtocolVersion getById(int id) { // if (id < 0) { // throw new IllegalArgumentException("Negative id: " + id); // } else if (id < BY_ID.length) { // return BY_ID[id]; // } else { // return null; // } // } // } // Path: src/main/java/net/techcable/spudcompat/metadata/ImmutableMetadataMap.java import org.apache.commons.lang3.ArrayUtils; import lombok.*; import java.util.Arrays; import net.techcable.spudcompat.ProtocolVersion; package net.techcable.spudcompat.metadata; public final class ImmutableMetadataMap implements MetadataMap { @Getter
private final ProtocolVersion version;
SpudCompat/SpudCompat
src/main/java/net/techcable/spudcompat/entity/EntityType.java
// Path: src/main/java/net/techcable/spudcompat/ProtocolVersion.java // @RequiredArgsConstructor // public enum ProtocolVersion { // v1_7_10(5), // v1_8(47); // // public boolean isBefore(ProtocolVersion other) { // return this.getId() < other.getId(); // } // // private final int versionNumber; // // public int getId() { // return versionNumber; // } // // public static final int MAX_ID; // private static final ProtocolVersion[] BY_ID; // // static { // int maxId = 0; // for (ProtocolVersion version : values()) { // if (version.getId() > maxId) { // maxId = version.getId(); // } // } // MAX_ID = maxId; // BY_ID = new ProtocolVersion[MAX_ID + 1]; // for (ProtocolVersion version : values()) { // int id = version.getId(); // if (BY_ID[id] != null) throw new AssertionError("Already a version with id: " + id); // BY_ID[id] = version; // } // } // // public static ProtocolVersion getById(int id) { // if (id < 0) { // throw new IllegalArgumentException("Negative id: " + id); // } else if (id < BY_ID.length) { // return BY_ID[id]; // } else { // return null; // } // } // }
import lombok.*; import sun.nio.cs.ext.IBM037; import java.util.Arrays; import java.util.stream.Collectors; import com.google.common.collect.ImmutableSet; import net.techcable.spudcompat.ProtocolVersion;
package net.techcable.spudcompat.entity; @Getter @RequiredArgsConstructor public enum EntityType { // Mobs CREEPER(Sort.MOB, 50), SKELETON(Sort.MOB, 51), SPIDER(Sort.MOB, 52), GIANT_ZOMBIE(Sort.MOB, 53), ZOMBIE(Sort.MOB, 54), SLIME(Sort.MOB, 55), GHAST(Sort.MOB, 56), ZOMBIE_PIGMAN(Sort.MOB, 57), ENDERMAN(Sort.MOB, 58), CAVE_SPIDER(Sort.MOB, 59), SILVERFISH(Sort.MOB, 60), BLAZE(Sort.MOB, 61), MAGMA_CUBE(Sort.MOB, 62), ENDER_DRAGON(Sort.MOB, 63), WITHER(Sort.MOB, 64), BAT(Sort.MOB, 65), WITCH(Sort.MOB, 66), ENDERMITE(Sort.MOB, 67) { @Override
// Path: src/main/java/net/techcable/spudcompat/ProtocolVersion.java // @RequiredArgsConstructor // public enum ProtocolVersion { // v1_7_10(5), // v1_8(47); // // public boolean isBefore(ProtocolVersion other) { // return this.getId() < other.getId(); // } // // private final int versionNumber; // // public int getId() { // return versionNumber; // } // // public static final int MAX_ID; // private static final ProtocolVersion[] BY_ID; // // static { // int maxId = 0; // for (ProtocolVersion version : values()) { // if (version.getId() > maxId) { // maxId = version.getId(); // } // } // MAX_ID = maxId; // BY_ID = new ProtocolVersion[MAX_ID + 1]; // for (ProtocolVersion version : values()) { // int id = version.getId(); // if (BY_ID[id] != null) throw new AssertionError("Already a version with id: " + id); // BY_ID[id] = version; // } // } // // public static ProtocolVersion getById(int id) { // if (id < 0) { // throw new IllegalArgumentException("Negative id: " + id); // } else if (id < BY_ID.length) { // return BY_ID[id]; // } else { // return null; // } // } // } // Path: src/main/java/net/techcable/spudcompat/entity/EntityType.java import lombok.*; import sun.nio.cs.ext.IBM037; import java.util.Arrays; import java.util.stream.Collectors; import com.google.common.collect.ImmutableSet; import net.techcable.spudcompat.ProtocolVersion; package net.techcable.spudcompat.entity; @Getter @RequiredArgsConstructor public enum EntityType { // Mobs CREEPER(Sort.MOB, 50), SKELETON(Sort.MOB, 51), SPIDER(Sort.MOB, 52), GIANT_ZOMBIE(Sort.MOB, 53), ZOMBIE(Sort.MOB, 54), SLIME(Sort.MOB, 55), GHAST(Sort.MOB, 56), ZOMBIE_PIGMAN(Sort.MOB, 57), ENDERMAN(Sort.MOB, 58), CAVE_SPIDER(Sort.MOB, 59), SILVERFISH(Sort.MOB, 60), BLAZE(Sort.MOB, 61), MAGMA_CUBE(Sort.MOB, 62), ENDER_DRAGON(Sort.MOB, 63), WITHER(Sort.MOB, 64), BAT(Sort.MOB, 65), WITCH(Sort.MOB, 66), ENDERMITE(Sort.MOB, 67) { @Override
public int getId(ProtocolVersion version) {
SpudCompat/SpudCompat
src/main/java/net/techcable/spudcompat/protocol/injector/AbstractPlayerConnection.java
// Path: src/main/java/net/techcable/spudcompat/protocol/PlayerConnection.java // public interface PlayerConnection { // // public default boolean isSupportedVersion() { // return ProtocolVersion.getById(getVersionId()) != null; // } // // public default ProtocolVersion getVersion() { // int id = getVersionId(); // ProtocolVersion version = ProtocolVersion.getById(id); // if (version != null) { // return version; // } else { // throw new IllegalStateException("Unsupported version: " + id); // } // } // // public ProtocolState getState(); // // public int getVersionId(); // // public void sendPacket(RawPacket rawPacket); // // public Channel getChannel(); // // public Server getServer(); // } // // Path: src/main/java/net/techcable/spudcompat/protocol/ProtocolState.java // @RequiredArgsConstructor // public enum ProtocolState { // HANDSHAKE(Protocol.HANDSHAKE), // LOGIN(Protocol.LOGIN), // PLAY(Protocol.GAME), // STATUS(Protocol.STATUS); // // private final Protocol bungee; // // public Protocol toBungee() { // return bungee; // } // }
import java.lang.reflect.Field; import io.netty.channel.Channel; import net.md_5.bungee.netty.ChannelWrapper; import net.md_5.bungee.protocol.MinecraftDecoder; import net.md_5.bungee.protocol.Protocol; import net.techcable.spudcompat.protocol.PlayerConnection; import net.techcable.spudcompat.protocol.ProtocolState;
package net.techcable.spudcompat.protocol.injector; public abstract class AbstractPlayerConnection implements PlayerConnection { @Override public void sendPacket(RawPacket rawPacket) { getChannelWrapper().write(rawPacket.getAllData()); } @Override public Channel getChannel() { return getChannelWrapper().getHandle(); } private static final Field minecraftDecoderProtocolField; static { try { minecraftDecoderProtocolField = MinecraftDecoder.class.getDeclaredField("protocol"); minecraftDecoderProtocolField.setAccessible(true); } catch (NoSuchFieldException e) { throw new AssertionError("Couldn't find protocol field", e); } } @Override
// Path: src/main/java/net/techcable/spudcompat/protocol/PlayerConnection.java // public interface PlayerConnection { // // public default boolean isSupportedVersion() { // return ProtocolVersion.getById(getVersionId()) != null; // } // // public default ProtocolVersion getVersion() { // int id = getVersionId(); // ProtocolVersion version = ProtocolVersion.getById(id); // if (version != null) { // return version; // } else { // throw new IllegalStateException("Unsupported version: " + id); // } // } // // public ProtocolState getState(); // // public int getVersionId(); // // public void sendPacket(RawPacket rawPacket); // // public Channel getChannel(); // // public Server getServer(); // } // // Path: src/main/java/net/techcable/spudcompat/protocol/ProtocolState.java // @RequiredArgsConstructor // public enum ProtocolState { // HANDSHAKE(Protocol.HANDSHAKE), // LOGIN(Protocol.LOGIN), // PLAY(Protocol.GAME), // STATUS(Protocol.STATUS); // // private final Protocol bungee; // // public Protocol toBungee() { // return bungee; // } // } // Path: src/main/java/net/techcable/spudcompat/protocol/injector/AbstractPlayerConnection.java import java.lang.reflect.Field; import io.netty.channel.Channel; import net.md_5.bungee.netty.ChannelWrapper; import net.md_5.bungee.protocol.MinecraftDecoder; import net.md_5.bungee.protocol.Protocol; import net.techcable.spudcompat.protocol.PlayerConnection; import net.techcable.spudcompat.protocol.ProtocolState; package net.techcable.spudcompat.protocol.injector; public abstract class AbstractPlayerConnection implements PlayerConnection { @Override public void sendPacket(RawPacket rawPacket) { getChannelWrapper().write(rawPacket.getAllData()); } @Override public Channel getChannel() { return getChannelWrapper().getHandle(); } private static final Field minecraftDecoderProtocolField; static { try { minecraftDecoderProtocolField = MinecraftDecoder.class.getDeclaredField("protocol"); minecraftDecoderProtocolField.setAccessible(true); } catch (NoSuchFieldException e) { throw new AssertionError("Couldn't find protocol field", e); } } @Override
public ProtocolState getState() {
SpudCompat/SpudCompat
src/main/java/net/techcable/spudcompat/protocol/injector/BungeeProtocolInjector.java
// Path: src/main/java/net/techcable/spudcompat/protocol/PlayerConnection.java // public interface PlayerConnection { // // public default boolean isSupportedVersion() { // return ProtocolVersion.getById(getVersionId()) != null; // } // // public default ProtocolVersion getVersion() { // int id = getVersionId(); // ProtocolVersion version = ProtocolVersion.getById(id); // if (version != null) { // return version; // } else { // throw new IllegalStateException("Unsupported version: " + id); // } // } // // public ProtocolState getState(); // // public int getVersionId(); // // public void sendPacket(RawPacket rawPacket); // // public Channel getChannel(); // // public Server getServer(); // } // // Path: src/main/java/net/techcable/spudcompat/protocol/ProtocolDirection.java // public enum ProtocolDirection { // CLIENTBOUND(ProtocolConstants.Direction.TO_CLIENT), // SERVERBOUND(ProtocolConstants.Direction.TO_SERVER); // // private ProtocolDirection(ProtocolConstants.Direction bungee) { // this.bungee = checkNotNull(bungee, "Null bungee direction"); // } // // private final ProtocolConstants.Direction bungee; // // public ProtocolConstants.Direction asBungee() { // return bungee; // } // }
import lombok.*; import com.google.common.base.Preconditions; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelOutboundHandlerAdapter; import io.netty.channel.ChannelPromise; import net.md_5.bungee.UserConnection; import net.md_5.bungee.api.event.PostLoginEvent; import net.md_5.bungee.api.plugin.Listener; import net.md_5.bungee.event.EventHandler; import net.md_5.bungee.netty.PipelineUtils; import net.md_5.bungee.protocol.DefinedPacket; import net.md_5.bungee.protocol.PacketWrapper; import net.techcable.spudcompat.protocol.PlayerConnection; import net.techcable.spudcompat.protocol.ProtocolDirection;
package net.techcable.spudcompat.protocol.injector; @RequiredArgsConstructor public class BungeeProtocolInjector implements Listener { private final PacketListener listener; public static final String SPUD_INCOMING_TRANSFORMER = "spud-incoming-transformer"; public static final String SPUD_OUTGOING_TRANSFORMER = "spud-outgoing-transformer"; @EventHandler public void onPostLogin(PostLoginEvent event) {
// Path: src/main/java/net/techcable/spudcompat/protocol/PlayerConnection.java // public interface PlayerConnection { // // public default boolean isSupportedVersion() { // return ProtocolVersion.getById(getVersionId()) != null; // } // // public default ProtocolVersion getVersion() { // int id = getVersionId(); // ProtocolVersion version = ProtocolVersion.getById(id); // if (version != null) { // return version; // } else { // throw new IllegalStateException("Unsupported version: " + id); // } // } // // public ProtocolState getState(); // // public int getVersionId(); // // public void sendPacket(RawPacket rawPacket); // // public Channel getChannel(); // // public Server getServer(); // } // // Path: src/main/java/net/techcable/spudcompat/protocol/ProtocolDirection.java // public enum ProtocolDirection { // CLIENTBOUND(ProtocolConstants.Direction.TO_CLIENT), // SERVERBOUND(ProtocolConstants.Direction.TO_SERVER); // // private ProtocolDirection(ProtocolConstants.Direction bungee) { // this.bungee = checkNotNull(bungee, "Null bungee direction"); // } // // private final ProtocolConstants.Direction bungee; // // public ProtocolConstants.Direction asBungee() { // return bungee; // } // } // Path: src/main/java/net/techcable/spudcompat/protocol/injector/BungeeProtocolInjector.java import lombok.*; import com.google.common.base.Preconditions; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelOutboundHandlerAdapter; import io.netty.channel.ChannelPromise; import net.md_5.bungee.UserConnection; import net.md_5.bungee.api.event.PostLoginEvent; import net.md_5.bungee.api.plugin.Listener; import net.md_5.bungee.event.EventHandler; import net.md_5.bungee.netty.PipelineUtils; import net.md_5.bungee.protocol.DefinedPacket; import net.md_5.bungee.protocol.PacketWrapper; import net.techcable.spudcompat.protocol.PlayerConnection; import net.techcable.spudcompat.protocol.ProtocolDirection; package net.techcable.spudcompat.protocol.injector; @RequiredArgsConstructor public class BungeeProtocolInjector implements Listener { private final PacketListener listener; public static final String SPUD_INCOMING_TRANSFORMER = "spud-incoming-transformer"; public static final String SPUD_OUTGOING_TRANSFORMER = "spud-outgoing-transformer"; @EventHandler public void onPostLogin(PostLoginEvent event) {
PlayerConnection connection = new UserConnectionPlayerConnection((UserConnection) event.getPlayer());
SpudCompat/SpudCompat
src/main/java/net/techcable/spudcompat/protocol/injector/BungeeProtocolInjector.java
// Path: src/main/java/net/techcable/spudcompat/protocol/PlayerConnection.java // public interface PlayerConnection { // // public default boolean isSupportedVersion() { // return ProtocolVersion.getById(getVersionId()) != null; // } // // public default ProtocolVersion getVersion() { // int id = getVersionId(); // ProtocolVersion version = ProtocolVersion.getById(id); // if (version != null) { // return version; // } else { // throw new IllegalStateException("Unsupported version: " + id); // } // } // // public ProtocolState getState(); // // public int getVersionId(); // // public void sendPacket(RawPacket rawPacket); // // public Channel getChannel(); // // public Server getServer(); // } // // Path: src/main/java/net/techcable/spudcompat/protocol/ProtocolDirection.java // public enum ProtocolDirection { // CLIENTBOUND(ProtocolConstants.Direction.TO_CLIENT), // SERVERBOUND(ProtocolConstants.Direction.TO_SERVER); // // private ProtocolDirection(ProtocolConstants.Direction bungee) { // this.bungee = checkNotNull(bungee, "Null bungee direction"); // } // // private final ProtocolConstants.Direction bungee; // // public ProtocolConstants.Direction asBungee() { // return bungee; // } // }
import lombok.*; import com.google.common.base.Preconditions; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelOutboundHandlerAdapter; import io.netty.channel.ChannelPromise; import net.md_5.bungee.UserConnection; import net.md_5.bungee.api.event.PostLoginEvent; import net.md_5.bungee.api.plugin.Listener; import net.md_5.bungee.event.EventHandler; import net.md_5.bungee.netty.PipelineUtils; import net.md_5.bungee.protocol.DefinedPacket; import net.md_5.bungee.protocol.PacketWrapper; import net.techcable.spudcompat.protocol.PlayerConnection; import net.techcable.spudcompat.protocol.ProtocolDirection;
package net.techcable.spudcompat.protocol.injector; @RequiredArgsConstructor public class BungeeProtocolInjector implements Listener { private final PacketListener listener; public static final String SPUD_INCOMING_TRANSFORMER = "spud-incoming-transformer"; public static final String SPUD_OUTGOING_TRANSFORMER = "spud-outgoing-transformer"; @EventHandler public void onPostLogin(PostLoginEvent event) { PlayerConnection connection = new UserConnectionPlayerConnection((UserConnection) event.getPlayer()); if (!connection.isSupportedVersion()) return; inject(connection); } public void inject(PlayerConnection connection) { Preconditions.checkNotNull(connection, "Null connection"); Preconditions.checkArgument(connection.isSupportedVersion(), "Unsupported version %s", connection.getVersionId()); Channel channel = connection.getChannel(); channel.pipeline().addAfter(PipelineUtils.PACKET_DECODER, SPUD_INCOMING_TRANSFORMER, new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { PacketWrapper wrapper = (PacketWrapper) msg; PacketListener.Result result; if (wrapper.packet != null) { result = listener.onReceive(connection, new BungeePacket(wrapper.packet)); } else {
// Path: src/main/java/net/techcable/spudcompat/protocol/PlayerConnection.java // public interface PlayerConnection { // // public default boolean isSupportedVersion() { // return ProtocolVersion.getById(getVersionId()) != null; // } // // public default ProtocolVersion getVersion() { // int id = getVersionId(); // ProtocolVersion version = ProtocolVersion.getById(id); // if (version != null) { // return version; // } else { // throw new IllegalStateException("Unsupported version: " + id); // } // } // // public ProtocolState getState(); // // public int getVersionId(); // // public void sendPacket(RawPacket rawPacket); // // public Channel getChannel(); // // public Server getServer(); // } // // Path: src/main/java/net/techcable/spudcompat/protocol/ProtocolDirection.java // public enum ProtocolDirection { // CLIENTBOUND(ProtocolConstants.Direction.TO_CLIENT), // SERVERBOUND(ProtocolConstants.Direction.TO_SERVER); // // private ProtocolDirection(ProtocolConstants.Direction bungee) { // this.bungee = checkNotNull(bungee, "Null bungee direction"); // } // // private final ProtocolConstants.Direction bungee; // // public ProtocolConstants.Direction asBungee() { // return bungee; // } // } // Path: src/main/java/net/techcable/spudcompat/protocol/injector/BungeeProtocolInjector.java import lombok.*; import com.google.common.base.Preconditions; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelOutboundHandlerAdapter; import io.netty.channel.ChannelPromise; import net.md_5.bungee.UserConnection; import net.md_5.bungee.api.event.PostLoginEvent; import net.md_5.bungee.api.plugin.Listener; import net.md_5.bungee.event.EventHandler; import net.md_5.bungee.netty.PipelineUtils; import net.md_5.bungee.protocol.DefinedPacket; import net.md_5.bungee.protocol.PacketWrapper; import net.techcable.spudcompat.protocol.PlayerConnection; import net.techcable.spudcompat.protocol.ProtocolDirection; package net.techcable.spudcompat.protocol.injector; @RequiredArgsConstructor public class BungeeProtocolInjector implements Listener { private final PacketListener listener; public static final String SPUD_INCOMING_TRANSFORMER = "spud-incoming-transformer"; public static final String SPUD_OUTGOING_TRANSFORMER = "spud-outgoing-transformer"; @EventHandler public void onPostLogin(PostLoginEvent event) { PlayerConnection connection = new UserConnectionPlayerConnection((UserConnection) event.getPlayer()); if (!connection.isSupportedVersion()) return; inject(connection); } public void inject(PlayerConnection connection) { Preconditions.checkNotNull(connection, "Null connection"); Preconditions.checkArgument(connection.isSupportedVersion(), "Unsupported version %s", connection.getVersionId()); Channel channel = connection.getChannel(); channel.pipeline().addAfter(PipelineUtils.PACKET_DECODER, SPUD_INCOMING_TRANSFORMER, new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { PacketWrapper wrapper = (PacketWrapper) msg; PacketListener.Result result; if (wrapper.packet != null) { result = listener.onReceive(connection, new BungeePacket(wrapper.packet)); } else {
RawPacket rawPacket = RawPacket.fromBuffer(wrapper.buf, connection.getState(), ProtocolDirection.SERVERBOUND);
SpudCompat/SpudCompat
src/main/java/net/techcable/spudcompat/metadata/BasicMetadataTransformer.java
// Path: src/main/java/net/techcable/spudcompat/ProtocolVersion.java // @RequiredArgsConstructor // public enum ProtocolVersion { // v1_7_10(5), // v1_8(47); // // public boolean isBefore(ProtocolVersion other) { // return this.getId() < other.getId(); // } // // private final int versionNumber; // // public int getId() { // return versionNumber; // } // // public static final int MAX_ID; // private static final ProtocolVersion[] BY_ID; // // static { // int maxId = 0; // for (ProtocolVersion version : values()) { // if (version.getId() > maxId) { // maxId = version.getId(); // } // } // MAX_ID = maxId; // BY_ID = new ProtocolVersion[MAX_ID + 1]; // for (ProtocolVersion version : values()) { // int id = version.getId(); // if (BY_ID[id] != null) throw new AssertionError("Already a version with id: " + id); // BY_ID[id] = version; // } // } // // public static ProtocolVersion getById(int id) { // if (id < 0) { // throw new IllegalArgumentException("Negative id: " + id); // } else if (id < BY_ID.length) { // return BY_ID[id]; // } else { // return null; // } // } // }
import java.util.Arrays; import java.util.Map; import java.util.Optional; import java.util.OptionalInt; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import net.techcable.spudcompat.ProtocolVersion;
package net.techcable.spudcompat.metadata; /** * A {@link MetadataTransformer} that does basic transformations (like primitive casting) between metadata */ public class BasicMetadataTransformer implements MetadataTransformer { private final int[] indexes; private final MetadataDataType[] types; private BasicMetadataTransformer(int[] indexes, MetadataDataType[] types) { this.indexes = indexes; this.types = types;
// Path: src/main/java/net/techcable/spudcompat/ProtocolVersion.java // @RequiredArgsConstructor // public enum ProtocolVersion { // v1_7_10(5), // v1_8(47); // // public boolean isBefore(ProtocolVersion other) { // return this.getId() < other.getId(); // } // // private final int versionNumber; // // public int getId() { // return versionNumber; // } // // public static final int MAX_ID; // private static final ProtocolVersion[] BY_ID; // // static { // int maxId = 0; // for (ProtocolVersion version : values()) { // if (version.getId() > maxId) { // maxId = version.getId(); // } // } // MAX_ID = maxId; // BY_ID = new ProtocolVersion[MAX_ID + 1]; // for (ProtocolVersion version : values()) { // int id = version.getId(); // if (BY_ID[id] != null) throw new AssertionError("Already a version with id: " + id); // BY_ID[id] = version; // } // } // // public static ProtocolVersion getById(int id) { // if (id < 0) { // throw new IllegalArgumentException("Negative id: " + id); // } else if (id < BY_ID.length) { // return BY_ID[id]; // } else { // return null; // } // } // } // Path: src/main/java/net/techcable/spudcompat/metadata/BasicMetadataTransformer.java import java.util.Arrays; import java.util.Map; import java.util.Optional; import java.util.OptionalInt; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import net.techcable.spudcompat.ProtocolVersion; package net.techcable.spudcompat.metadata; /** * A {@link MetadataTransformer} that does basic transformations (like primitive casting) between metadata */ public class BasicMetadataTransformer implements MetadataTransformer { private final int[] indexes; private final MetadataDataType[] types; private BasicMetadataTransformer(int[] indexes, MetadataDataType[] types) { this.indexes = indexes; this.types = types;
for (ProtocolVersion version : ProtocolVersion.values()) {
ChenTianSaber/DailyZhiHu
MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/service/ThemeContentService.java
// Path: MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/been/ThemeContentBeen.java // public class ThemeContentBeen { // // private List<Stories> stories; // private String description; // private String background; // private int color; // private String name; // private String image; // private List<Editors> editors; // private String imageSource; // public void setStories(List<Stories> stories) { // this.stories = stories; // } // public List<Stories> getStories() { // return stories; // } // // public void setDescription(String description) { // this.description = description; // } // public String getDescription() { // return description; // } // // public void setBackground(String background) { // this.background = background; // } // public String getBackground() { // return background; // } // // public void setColor(int color) { // this.color = color; // } // public int getColor() { // return color; // } // // public void setName(String name) { // this.name = name; // } // public String getName() { // return name; // } // // public void setImage(String image) { // this.image = image; // } // public String getImage() { // return image; // } // // public void setEditors(List<Editors> editors) { // this.editors = editors; // } // public List<Editors> getEditors() { // return editors; // } // // public void setImageSource(String imageSource) { // this.imageSource = imageSource; // } // public String getImageSource() { // return imageSource; // } // // }
import com.example.chentian.myzhihudaily.been.ThemeContentBeen; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path;
package com.example.chentian.myzhihudaily.service; /** * Created by chentian on 16/04/2017. */ public interface ThemeContentService { @GET("{id}")
// Path: MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/been/ThemeContentBeen.java // public class ThemeContentBeen { // // private List<Stories> stories; // private String description; // private String background; // private int color; // private String name; // private String image; // private List<Editors> editors; // private String imageSource; // public void setStories(List<Stories> stories) { // this.stories = stories; // } // public List<Stories> getStories() { // return stories; // } // // public void setDescription(String description) { // this.description = description; // } // public String getDescription() { // return description; // } // // public void setBackground(String background) { // this.background = background; // } // public String getBackground() { // return background; // } // // public void setColor(int color) { // this.color = color; // } // public int getColor() { // return color; // } // // public void setName(String name) { // this.name = name; // } // public String getName() { // return name; // } // // public void setImage(String image) { // this.image = image; // } // public String getImage() { // return image; // } // // public void setEditors(List<Editors> editors) { // this.editors = editors; // } // public List<Editors> getEditors() { // return editors; // } // // public void setImageSource(String imageSource) { // this.imageSource = imageSource; // } // public String getImageSource() { // return imageSource; // } // // } // Path: MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/service/ThemeContentService.java import com.example.chentian.myzhihudaily.been.ThemeContentBeen; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; package com.example.chentian.myzhihudaily.service; /** * Created by chentian on 16/04/2017. */ public interface ThemeContentService { @GET("{id}")
Call<ThemeContentBeen> getThemeContent(@Path("id") String themeId);
ChenTianSaber/DailyZhiHu
MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/service/ContentListService.java
// Path: MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/been/ContentListBeen.java // public class ContentListBeen { // // private String date; // private List<Stories> stories; // public void setDate(String date) { // this.date = date; // } // public String getDate() { // return date; // } // // public void setStories(List<Stories> stories) { // this.stories = stories; // } // public List<Stories> getStories() { // return stories; // } // // }
import com.example.chentian.myzhihudaily.been.ContentListBeen; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path;
package com.example.chentian.myzhihudaily.service; /** * Created by chentian on 11/04/2017. */ public interface ContentListService { @GET("{date}")
// Path: MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/been/ContentListBeen.java // public class ContentListBeen { // // private String date; // private List<Stories> stories; // public void setDate(String date) { // this.date = date; // } // public String getDate() { // return date; // } // // public void setStories(List<Stories> stories) { // this.stories = stories; // } // public List<Stories> getStories() { // return stories; // } // // } // Path: MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/service/ContentListService.java import com.example.chentian.myzhihudaily.been.ContentListBeen; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; package com.example.chentian.myzhihudaily.service; /** * Created by chentian on 11/04/2017. */ public interface ContentListService { @GET("{date}")
Call<ContentListBeen> getContentList(@Path("date") String date);
ChenTianSaber/DailyZhiHu
MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/service/ContentService.java
// Path: MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/been/ContentBeen.java // public class ContentBeen { // // private String body; // private String image_source; // private String title; // private String image; // private String share_url; // private List<String> js; // private String gaPrefix; // private Section section; // // private List<String> images; // private int type; // private int id; // private List<String> css; // public void setBody(String body) { // this.body = body; // } // public String getBody() { // return body; // } // // public void setImageSource(String imageSource) { // this.image_source = imageSource; // } // public String getImageSource() { // return image_source; // } // // public void setTitle(String title) { // this.title = title; // } // public String getTitle() { // return title; // } // // public void setImage(String image) { // this.image = image; // } // public String getImage() { // return image; // } // // public void setShareUrl(String shareUrl) { // this.share_url = shareUrl; // } // public String getShareUrl() { // return share_url; // } // // public void setJs(List<String> js) { // this.js = js; // } // public List<String> getJs() { // return js; // } // // public void setGaPrefix(String gaPrefix) { // this.gaPrefix = gaPrefix; // } // public String getGaPrefix() { // return gaPrefix; // } // // public void setSection(Section section) { // this.section = section; // } // public Section getSection() { // return section; // } // // public void setImages(List<String> images) { // this.images = images; // } // public List<String> getImages() { // return images; // } // // public void setType(int type) { // this.type = type; // } // public int getType() { // return type; // } // // public void setId(int id) { // this.id = id; // } // public int getId() { // return id; // } // // public void setCss(List<String> css) { // this.css = css; // } // public List<String> getCss() { // return css; // } // // }
import com.example.chentian.myzhihudaily.been.ContentBeen; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path;
package com.example.chentian.myzhihudaily.service; /** * Created by chentian on 12/04/2017. */ public interface ContentService { @GET("{id}")
// Path: MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/been/ContentBeen.java // public class ContentBeen { // // private String body; // private String image_source; // private String title; // private String image; // private String share_url; // private List<String> js; // private String gaPrefix; // private Section section; // // private List<String> images; // private int type; // private int id; // private List<String> css; // public void setBody(String body) { // this.body = body; // } // public String getBody() { // return body; // } // // public void setImageSource(String imageSource) { // this.image_source = imageSource; // } // public String getImageSource() { // return image_source; // } // // public void setTitle(String title) { // this.title = title; // } // public String getTitle() { // return title; // } // // public void setImage(String image) { // this.image = image; // } // public String getImage() { // return image; // } // // public void setShareUrl(String shareUrl) { // this.share_url = shareUrl; // } // public String getShareUrl() { // return share_url; // } // // public void setJs(List<String> js) { // this.js = js; // } // public List<String> getJs() { // return js; // } // // public void setGaPrefix(String gaPrefix) { // this.gaPrefix = gaPrefix; // } // public String getGaPrefix() { // return gaPrefix; // } // // public void setSection(Section section) { // this.section = section; // } // public Section getSection() { // return section; // } // // public void setImages(List<String> images) { // this.images = images; // } // public List<String> getImages() { // return images; // } // // public void setType(int type) { // this.type = type; // } // public int getType() { // return type; // } // // public void setId(int id) { // this.id = id; // } // public int getId() { // return id; // } // // public void setCss(List<String> css) { // this.css = css; // } // public List<String> getCss() { // return css; // } // // } // Path: MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/service/ContentService.java import com.example.chentian.myzhihudaily.been.ContentBeen; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; package com.example.chentian.myzhihudaily.service; /** * Created by chentian on 12/04/2017. */ public interface ContentService { @GET("{id}")
Call<ContentBeen> getContent(@Path("id") String contentId);
ChenTianSaber/DailyZhiHu
MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/fragment/DownloadFragment.java
// Path: MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/adapter/DownloadAdapter.java // public class DownloadAdapter extends RecyclerView.Adapter { // // Context context; // ArrayList<String> titleData; // ArrayList<String> bodyData; // // public DownloadAdapter(Context context, ArrayList<String> titleData,ArrayList<String> bodyData) { // this.context = context; // this.titleData = titleData; // this.bodyData = bodyData; // } // // @Override // public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // View view = LayoutInflater.from(context) // .inflate(R.layout.recycler_item, parent, false); // ContentRecyclerViewHolder viewHolder = new ContentRecyclerViewHolder(view); // return viewHolder; // } // // @Override // public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { // ContentRecyclerViewHolder viewHolder = (ContentRecyclerViewHolder) holder; // viewHolder.textView.setText(titleData.get(position)); // Glide.with(context).load(R.mipmap.default_img).into(viewHolder.imageView); // viewHolder.bodyText.setText(bodyData.get(position)); // } // // @Override // public int getItemCount() { // return titleData.size(); // } // // class ContentRecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { // // TextView textView,bodyText; // ImageView imageView; // LinearLayout itemLayout; // // public ContentRecyclerViewHolder(View itemView) { // super(itemView); // textView = (TextView) itemView.findViewById(R.id.recycler_title); // bodyText = (TextView) itemView.findViewById(R.id.tv_content_id); // imageView = (ImageView) itemView.findViewById(R.id.recycler_img); // itemLayout = (LinearLayout) itemView.findViewById(R.id.recycler_item); // // itemLayout.setOnClickListener(this); // itemLayout.setOnLongClickListener(new View.OnLongClickListener() { // @Override // public boolean onLongClick(View v) { // titleData.remove(textView.getText().toString()); // notifyDataSetChanged(); // DataSupport.deleteAll(Artical.class, "articalTitle = ?" , textView.getText().toString()); // Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show(); // return true; // } // }); // } // // @Override // public void onClick(View v) { // Intent intent = new Intent(context,DownloadDetaiContentActivity.class); // intent.putExtra("body",bodyText.getText().toString()); // intent.putExtra("title",textView.getText().toString()); // context.startActivity(intent); // } // } // } // // Path: MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/database/Artical.java // public class Artical extends DataSupport { // // private String articalBody; // // @Column(unique = true) // private String articalTitle; // // public String getArticalBody() { // return articalBody; // } // // public void setArticalBody(String articalBody) { // this.articalBody = articalBody; // } // // public String getArticalTitle() { // return articalTitle; // } // // public void setArticalTitle(String articalTitle) { // this.articalTitle = articalTitle; // } // }
import android.content.res.Resources; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.example.chentian.myzhihudaily.R; import com.example.chentian.myzhihudaily.adapter.DownloadAdapter; import com.example.chentian.myzhihudaily.database.Artical; import org.litepal.crud.DataSupport; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List;
package com.example.chentian.myzhihudaily.fragment; /** * Created by chentian on 27/04/2017. */ public class DownloadFragment extends Fragment { View view; RecyclerView contentRecycler; ArrayList<String> titleData; ArrayList<String> bodyData;
// Path: MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/adapter/DownloadAdapter.java // public class DownloadAdapter extends RecyclerView.Adapter { // // Context context; // ArrayList<String> titleData; // ArrayList<String> bodyData; // // public DownloadAdapter(Context context, ArrayList<String> titleData,ArrayList<String> bodyData) { // this.context = context; // this.titleData = titleData; // this.bodyData = bodyData; // } // // @Override // public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // View view = LayoutInflater.from(context) // .inflate(R.layout.recycler_item, parent, false); // ContentRecyclerViewHolder viewHolder = new ContentRecyclerViewHolder(view); // return viewHolder; // } // // @Override // public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { // ContentRecyclerViewHolder viewHolder = (ContentRecyclerViewHolder) holder; // viewHolder.textView.setText(titleData.get(position)); // Glide.with(context).load(R.mipmap.default_img).into(viewHolder.imageView); // viewHolder.bodyText.setText(bodyData.get(position)); // } // // @Override // public int getItemCount() { // return titleData.size(); // } // // class ContentRecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { // // TextView textView,bodyText; // ImageView imageView; // LinearLayout itemLayout; // // public ContentRecyclerViewHolder(View itemView) { // super(itemView); // textView = (TextView) itemView.findViewById(R.id.recycler_title); // bodyText = (TextView) itemView.findViewById(R.id.tv_content_id); // imageView = (ImageView) itemView.findViewById(R.id.recycler_img); // itemLayout = (LinearLayout) itemView.findViewById(R.id.recycler_item); // // itemLayout.setOnClickListener(this); // itemLayout.setOnLongClickListener(new View.OnLongClickListener() { // @Override // public boolean onLongClick(View v) { // titleData.remove(textView.getText().toString()); // notifyDataSetChanged(); // DataSupport.deleteAll(Artical.class, "articalTitle = ?" , textView.getText().toString()); // Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show(); // return true; // } // }); // } // // @Override // public void onClick(View v) { // Intent intent = new Intent(context,DownloadDetaiContentActivity.class); // intent.putExtra("body",bodyText.getText().toString()); // intent.putExtra("title",textView.getText().toString()); // context.startActivity(intent); // } // } // } // // Path: MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/database/Artical.java // public class Artical extends DataSupport { // // private String articalBody; // // @Column(unique = true) // private String articalTitle; // // public String getArticalBody() { // return articalBody; // } // // public void setArticalBody(String articalBody) { // this.articalBody = articalBody; // } // // public String getArticalTitle() { // return articalTitle; // } // // public void setArticalTitle(String articalTitle) { // this.articalTitle = articalTitle; // } // } // Path: MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/fragment/DownloadFragment.java import android.content.res.Resources; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.example.chentian.myzhihudaily.R; import com.example.chentian.myzhihudaily.adapter.DownloadAdapter; import com.example.chentian.myzhihudaily.database.Artical; import org.litepal.crud.DataSupport; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; package com.example.chentian.myzhihudaily.fragment; /** * Created by chentian on 27/04/2017. */ public class DownloadFragment extends Fragment { View view; RecyclerView contentRecycler; ArrayList<String> titleData; ArrayList<String> bodyData;
DownloadAdapter contentAdapter;
ChenTianSaber/DailyZhiHu
MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/fragment/DownloadFragment.java
// Path: MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/adapter/DownloadAdapter.java // public class DownloadAdapter extends RecyclerView.Adapter { // // Context context; // ArrayList<String> titleData; // ArrayList<String> bodyData; // // public DownloadAdapter(Context context, ArrayList<String> titleData,ArrayList<String> bodyData) { // this.context = context; // this.titleData = titleData; // this.bodyData = bodyData; // } // // @Override // public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // View view = LayoutInflater.from(context) // .inflate(R.layout.recycler_item, parent, false); // ContentRecyclerViewHolder viewHolder = new ContentRecyclerViewHolder(view); // return viewHolder; // } // // @Override // public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { // ContentRecyclerViewHolder viewHolder = (ContentRecyclerViewHolder) holder; // viewHolder.textView.setText(titleData.get(position)); // Glide.with(context).load(R.mipmap.default_img).into(viewHolder.imageView); // viewHolder.bodyText.setText(bodyData.get(position)); // } // // @Override // public int getItemCount() { // return titleData.size(); // } // // class ContentRecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { // // TextView textView,bodyText; // ImageView imageView; // LinearLayout itemLayout; // // public ContentRecyclerViewHolder(View itemView) { // super(itemView); // textView = (TextView) itemView.findViewById(R.id.recycler_title); // bodyText = (TextView) itemView.findViewById(R.id.tv_content_id); // imageView = (ImageView) itemView.findViewById(R.id.recycler_img); // itemLayout = (LinearLayout) itemView.findViewById(R.id.recycler_item); // // itemLayout.setOnClickListener(this); // itemLayout.setOnLongClickListener(new View.OnLongClickListener() { // @Override // public boolean onLongClick(View v) { // titleData.remove(textView.getText().toString()); // notifyDataSetChanged(); // DataSupport.deleteAll(Artical.class, "articalTitle = ?" , textView.getText().toString()); // Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show(); // return true; // } // }); // } // // @Override // public void onClick(View v) { // Intent intent = new Intent(context,DownloadDetaiContentActivity.class); // intent.putExtra("body",bodyText.getText().toString()); // intent.putExtra("title",textView.getText().toString()); // context.startActivity(intent); // } // } // } // // Path: MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/database/Artical.java // public class Artical extends DataSupport { // // private String articalBody; // // @Column(unique = true) // private String articalTitle; // // public String getArticalBody() { // return articalBody; // } // // public void setArticalBody(String articalBody) { // this.articalBody = articalBody; // } // // public String getArticalTitle() { // return articalTitle; // } // // public void setArticalTitle(String articalTitle) { // this.articalTitle = articalTitle; // } // }
import android.content.res.Resources; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.example.chentian.myzhihudaily.R; import com.example.chentian.myzhihudaily.adapter.DownloadAdapter; import com.example.chentian.myzhihudaily.database.Artical; import org.litepal.crud.DataSupport; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List;
package com.example.chentian.myzhihudaily.fragment; /** * Created by chentian on 27/04/2017. */ public class DownloadFragment extends Fragment { View view; RecyclerView contentRecycler; ArrayList<String> titleData; ArrayList<String> bodyData; DownloadAdapter contentAdapter; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { if(view==null){ view = inflater.inflate(R.layout.activity_content,container,false); } init(); setHomeRecycler(); fillContent(); return view; } private void init() { contentRecycler = (RecyclerView) view.findViewById(R.id.content_recyler); titleData = new ArrayList<String>(); bodyData = new ArrayList<String>(); } private void fillContent() {
// Path: MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/adapter/DownloadAdapter.java // public class DownloadAdapter extends RecyclerView.Adapter { // // Context context; // ArrayList<String> titleData; // ArrayList<String> bodyData; // // public DownloadAdapter(Context context, ArrayList<String> titleData,ArrayList<String> bodyData) { // this.context = context; // this.titleData = titleData; // this.bodyData = bodyData; // } // // @Override // public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // View view = LayoutInflater.from(context) // .inflate(R.layout.recycler_item, parent, false); // ContentRecyclerViewHolder viewHolder = new ContentRecyclerViewHolder(view); // return viewHolder; // } // // @Override // public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { // ContentRecyclerViewHolder viewHolder = (ContentRecyclerViewHolder) holder; // viewHolder.textView.setText(titleData.get(position)); // Glide.with(context).load(R.mipmap.default_img).into(viewHolder.imageView); // viewHolder.bodyText.setText(bodyData.get(position)); // } // // @Override // public int getItemCount() { // return titleData.size(); // } // // class ContentRecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { // // TextView textView,bodyText; // ImageView imageView; // LinearLayout itemLayout; // // public ContentRecyclerViewHolder(View itemView) { // super(itemView); // textView = (TextView) itemView.findViewById(R.id.recycler_title); // bodyText = (TextView) itemView.findViewById(R.id.tv_content_id); // imageView = (ImageView) itemView.findViewById(R.id.recycler_img); // itemLayout = (LinearLayout) itemView.findViewById(R.id.recycler_item); // // itemLayout.setOnClickListener(this); // itemLayout.setOnLongClickListener(new View.OnLongClickListener() { // @Override // public boolean onLongClick(View v) { // titleData.remove(textView.getText().toString()); // notifyDataSetChanged(); // DataSupport.deleteAll(Artical.class, "articalTitle = ?" , textView.getText().toString()); // Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show(); // return true; // } // }); // } // // @Override // public void onClick(View v) { // Intent intent = new Intent(context,DownloadDetaiContentActivity.class); // intent.putExtra("body",bodyText.getText().toString()); // intent.putExtra("title",textView.getText().toString()); // context.startActivity(intent); // } // } // } // // Path: MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/database/Artical.java // public class Artical extends DataSupport { // // private String articalBody; // // @Column(unique = true) // private String articalTitle; // // public String getArticalBody() { // return articalBody; // } // // public void setArticalBody(String articalBody) { // this.articalBody = articalBody; // } // // public String getArticalTitle() { // return articalTitle; // } // // public void setArticalTitle(String articalTitle) { // this.articalTitle = articalTitle; // } // } // Path: MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/fragment/DownloadFragment.java import android.content.res.Resources; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.example.chentian.myzhihudaily.R; import com.example.chentian.myzhihudaily.adapter.DownloadAdapter; import com.example.chentian.myzhihudaily.database.Artical; import org.litepal.crud.DataSupport; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; package com.example.chentian.myzhihudaily.fragment; /** * Created by chentian on 27/04/2017. */ public class DownloadFragment extends Fragment { View view; RecyclerView contentRecycler; ArrayList<String> titleData; ArrayList<String> bodyData; DownloadAdapter contentAdapter; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { if(view==null){ view = inflater.inflate(R.layout.activity_content,container,false); } init(); setHomeRecycler(); fillContent(); return view; } private void init() { contentRecycler = (RecyclerView) view.findViewById(R.id.content_recyler); titleData = new ArrayList<String>(); bodyData = new ArrayList<String>(); } private void fillContent() {
List<Artical> allArticals = DataSupport.findAll(Artical.class);
ChenTianSaber/DailyZhiHu
MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/adapter/DownloadAdapter.java
// Path: MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/activity/DownloadDetaiContentActivity.java // public class DownloadDetaiContentActivity extends BaseActivity { // String body,title; // WebView contentView; // ImageView topImage; // TextView topTitle,topSource; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // supportRequestWindowFeature(Window.FEATURE_NO_TITLE); // initTheme(); // setContentView(R.layout.detail_layout); // //将状态栏透明 // if(Build.VERSION.SDK_INT>=21){ // View decorView = getWindow().getDecorView(); // int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN| // View.SYSTEM_UI_FLAG_LAYOUT_STABLE; // decorView.setSystemUiVisibility(option); // getWindow().setStatusBarColor(Color.TRANSPARENT); // } // // init(); // fillContent(); // } // // private void initTheme() { // setTheme(R.style.NightTheme); // } // // private void init(){ // LinearLayout layout = (LinearLayout) findViewById(R.id.Download_layout); // layout.setVisibility(View.GONE); // // Intent intent = getIntent(); // body = intent.getStringExtra("body"); // title = intent.getStringExtra("title"); // contentView = (WebView) findViewById(R.id.content_webview); // contentView.setHorizontalScrollBarEnabled(false);//水平不显示 // contentView.setVerticalScrollBarEnabled(false); //垂直不显示 // // contentView.setOnTouchListener(new View.OnTouchListener() { // @Override // public boolean onTouch(View v, MotionEvent event) { // return (event.getAction() == MotionEvent.ACTION_MOVE); // } // }); // contentView.setWebViewClient(new WebViewClient()); // // topImage = (ImageView) findViewById(R.id.top_image); // topTitle = (TextView) findViewById(R.id.top_titlt); // topSource = (TextView) findViewById(R.id.top_source); // } // // //进行网络请求,请求首页的详细内容 // private void fillContent() { // topTitle.setText(title); // topSource.setText("图片:"+"懒得获取~"); // topImage.setImageResource(R.mipmap.default_img); // // String css; // if(!isDay){ // css = "<link type=\"text/css\" href=\"" + // "file:///android_asset/zhihu_dark.css" + // "\" " + // "rel=\"stylesheet\" />\n"; // }else { // css = "<link type=\"text/css\" href=\"" + // "file:///android_asset/zhihu.css" + // "\" " + // "rel=\"stylesheet\" />\n"; // } // String html = "<!DOCTYPE html>\n" + // "<html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\">\n" + // "<head>\n" + // "\t<meta charset=\"utf-8\" />\n</head>\n" + // "<body>\n" + css + // body.replace("<div class=\"img-place-holder\">", "") + "\n<body>"; // contentView.loadDataWithBaseURL("x-data://base", html, "text/html", "utf-8", null); // } // } // // Path: MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/database/Artical.java // public class Artical extends DataSupport { // // private String articalBody; // // @Column(unique = true) // private String articalTitle; // // public String getArticalBody() { // return articalBody; // } // // public void setArticalBody(String articalBody) { // this.articalBody = articalBody; // } // // public String getArticalTitle() { // return articalTitle; // } // // public void setArticalTitle(String articalTitle) { // this.articalTitle = articalTitle; // } // }
import android.content.Context; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.example.chentian.myzhihudaily.R; import com.example.chentian.myzhihudaily.activity.DownloadDetaiContentActivity; import com.example.chentian.myzhihudaily.database.Artical; import org.litepal.crud.DataSupport; import java.util.ArrayList;
ContentRecyclerViewHolder viewHolder = (ContentRecyclerViewHolder) holder; viewHolder.textView.setText(titleData.get(position)); Glide.with(context).load(R.mipmap.default_img).into(viewHolder.imageView); viewHolder.bodyText.setText(bodyData.get(position)); } @Override public int getItemCount() { return titleData.size(); } class ContentRecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { TextView textView,bodyText; ImageView imageView; LinearLayout itemLayout; public ContentRecyclerViewHolder(View itemView) { super(itemView); textView = (TextView) itemView.findViewById(R.id.recycler_title); bodyText = (TextView) itemView.findViewById(R.id.tv_content_id); imageView = (ImageView) itemView.findViewById(R.id.recycler_img); itemLayout = (LinearLayout) itemView.findViewById(R.id.recycler_item); itemLayout.setOnClickListener(this); itemLayout.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { titleData.remove(textView.getText().toString()); notifyDataSetChanged();
// Path: MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/activity/DownloadDetaiContentActivity.java // public class DownloadDetaiContentActivity extends BaseActivity { // String body,title; // WebView contentView; // ImageView topImage; // TextView topTitle,topSource; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // supportRequestWindowFeature(Window.FEATURE_NO_TITLE); // initTheme(); // setContentView(R.layout.detail_layout); // //将状态栏透明 // if(Build.VERSION.SDK_INT>=21){ // View decorView = getWindow().getDecorView(); // int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN| // View.SYSTEM_UI_FLAG_LAYOUT_STABLE; // decorView.setSystemUiVisibility(option); // getWindow().setStatusBarColor(Color.TRANSPARENT); // } // // init(); // fillContent(); // } // // private void initTheme() { // setTheme(R.style.NightTheme); // } // // private void init(){ // LinearLayout layout = (LinearLayout) findViewById(R.id.Download_layout); // layout.setVisibility(View.GONE); // // Intent intent = getIntent(); // body = intent.getStringExtra("body"); // title = intent.getStringExtra("title"); // contentView = (WebView) findViewById(R.id.content_webview); // contentView.setHorizontalScrollBarEnabled(false);//水平不显示 // contentView.setVerticalScrollBarEnabled(false); //垂直不显示 // // contentView.setOnTouchListener(new View.OnTouchListener() { // @Override // public boolean onTouch(View v, MotionEvent event) { // return (event.getAction() == MotionEvent.ACTION_MOVE); // } // }); // contentView.setWebViewClient(new WebViewClient()); // // topImage = (ImageView) findViewById(R.id.top_image); // topTitle = (TextView) findViewById(R.id.top_titlt); // topSource = (TextView) findViewById(R.id.top_source); // } // // //进行网络请求,请求首页的详细内容 // private void fillContent() { // topTitle.setText(title); // topSource.setText("图片:"+"懒得获取~"); // topImage.setImageResource(R.mipmap.default_img); // // String css; // if(!isDay){ // css = "<link type=\"text/css\" href=\"" + // "file:///android_asset/zhihu_dark.css" + // "\" " + // "rel=\"stylesheet\" />\n"; // }else { // css = "<link type=\"text/css\" href=\"" + // "file:///android_asset/zhihu.css" + // "\" " + // "rel=\"stylesheet\" />\n"; // } // String html = "<!DOCTYPE html>\n" + // "<html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\">\n" + // "<head>\n" + // "\t<meta charset=\"utf-8\" />\n</head>\n" + // "<body>\n" + css + // body.replace("<div class=\"img-place-holder\">", "") + "\n<body>"; // contentView.loadDataWithBaseURL("x-data://base", html, "text/html", "utf-8", null); // } // } // // Path: MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/database/Artical.java // public class Artical extends DataSupport { // // private String articalBody; // // @Column(unique = true) // private String articalTitle; // // public String getArticalBody() { // return articalBody; // } // // public void setArticalBody(String articalBody) { // this.articalBody = articalBody; // } // // public String getArticalTitle() { // return articalTitle; // } // // public void setArticalTitle(String articalTitle) { // this.articalTitle = articalTitle; // } // } // Path: MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/adapter/DownloadAdapter.java import android.content.Context; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.example.chentian.myzhihudaily.R; import com.example.chentian.myzhihudaily.activity.DownloadDetaiContentActivity; import com.example.chentian.myzhihudaily.database.Artical; import org.litepal.crud.DataSupport; import java.util.ArrayList; ContentRecyclerViewHolder viewHolder = (ContentRecyclerViewHolder) holder; viewHolder.textView.setText(titleData.get(position)); Glide.with(context).load(R.mipmap.default_img).into(viewHolder.imageView); viewHolder.bodyText.setText(bodyData.get(position)); } @Override public int getItemCount() { return titleData.size(); } class ContentRecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { TextView textView,bodyText; ImageView imageView; LinearLayout itemLayout; public ContentRecyclerViewHolder(View itemView) { super(itemView); textView = (TextView) itemView.findViewById(R.id.recycler_title); bodyText = (TextView) itemView.findViewById(R.id.tv_content_id); imageView = (ImageView) itemView.findViewById(R.id.recycler_img); itemLayout = (LinearLayout) itemView.findViewById(R.id.recycler_item); itemLayout.setOnClickListener(this); itemLayout.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { titleData.remove(textView.getText().toString()); notifyDataSetChanged();
DataSupport.deleteAll(Artical.class, "articalTitle = ?" , textView.getText().toString());
ChenTianSaber/DailyZhiHu
MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/adapter/DownloadAdapter.java
// Path: MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/activity/DownloadDetaiContentActivity.java // public class DownloadDetaiContentActivity extends BaseActivity { // String body,title; // WebView contentView; // ImageView topImage; // TextView topTitle,topSource; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // supportRequestWindowFeature(Window.FEATURE_NO_TITLE); // initTheme(); // setContentView(R.layout.detail_layout); // //将状态栏透明 // if(Build.VERSION.SDK_INT>=21){ // View decorView = getWindow().getDecorView(); // int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN| // View.SYSTEM_UI_FLAG_LAYOUT_STABLE; // decorView.setSystemUiVisibility(option); // getWindow().setStatusBarColor(Color.TRANSPARENT); // } // // init(); // fillContent(); // } // // private void initTheme() { // setTheme(R.style.NightTheme); // } // // private void init(){ // LinearLayout layout = (LinearLayout) findViewById(R.id.Download_layout); // layout.setVisibility(View.GONE); // // Intent intent = getIntent(); // body = intent.getStringExtra("body"); // title = intent.getStringExtra("title"); // contentView = (WebView) findViewById(R.id.content_webview); // contentView.setHorizontalScrollBarEnabled(false);//水平不显示 // contentView.setVerticalScrollBarEnabled(false); //垂直不显示 // // contentView.setOnTouchListener(new View.OnTouchListener() { // @Override // public boolean onTouch(View v, MotionEvent event) { // return (event.getAction() == MotionEvent.ACTION_MOVE); // } // }); // contentView.setWebViewClient(new WebViewClient()); // // topImage = (ImageView) findViewById(R.id.top_image); // topTitle = (TextView) findViewById(R.id.top_titlt); // topSource = (TextView) findViewById(R.id.top_source); // } // // //进行网络请求,请求首页的详细内容 // private void fillContent() { // topTitle.setText(title); // topSource.setText("图片:"+"懒得获取~"); // topImage.setImageResource(R.mipmap.default_img); // // String css; // if(!isDay){ // css = "<link type=\"text/css\" href=\"" + // "file:///android_asset/zhihu_dark.css" + // "\" " + // "rel=\"stylesheet\" />\n"; // }else { // css = "<link type=\"text/css\" href=\"" + // "file:///android_asset/zhihu.css" + // "\" " + // "rel=\"stylesheet\" />\n"; // } // String html = "<!DOCTYPE html>\n" + // "<html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\">\n" + // "<head>\n" + // "\t<meta charset=\"utf-8\" />\n</head>\n" + // "<body>\n" + css + // body.replace("<div class=\"img-place-holder\">", "") + "\n<body>"; // contentView.loadDataWithBaseURL("x-data://base", html, "text/html", "utf-8", null); // } // } // // Path: MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/database/Artical.java // public class Artical extends DataSupport { // // private String articalBody; // // @Column(unique = true) // private String articalTitle; // // public String getArticalBody() { // return articalBody; // } // // public void setArticalBody(String articalBody) { // this.articalBody = articalBody; // } // // public String getArticalTitle() { // return articalTitle; // } // // public void setArticalTitle(String articalTitle) { // this.articalTitle = articalTitle; // } // }
import android.content.Context; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.example.chentian.myzhihudaily.R; import com.example.chentian.myzhihudaily.activity.DownloadDetaiContentActivity; import com.example.chentian.myzhihudaily.database.Artical; import org.litepal.crud.DataSupport; import java.util.ArrayList;
} class ContentRecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { TextView textView,bodyText; ImageView imageView; LinearLayout itemLayout; public ContentRecyclerViewHolder(View itemView) { super(itemView); textView = (TextView) itemView.findViewById(R.id.recycler_title); bodyText = (TextView) itemView.findViewById(R.id.tv_content_id); imageView = (ImageView) itemView.findViewById(R.id.recycler_img); itemLayout = (LinearLayout) itemView.findViewById(R.id.recycler_item); itemLayout.setOnClickListener(this); itemLayout.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { titleData.remove(textView.getText().toString()); notifyDataSetChanged(); DataSupport.deleteAll(Artical.class, "articalTitle = ?" , textView.getText().toString()); Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show(); return true; } }); } @Override public void onClick(View v) {
// Path: MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/activity/DownloadDetaiContentActivity.java // public class DownloadDetaiContentActivity extends BaseActivity { // String body,title; // WebView contentView; // ImageView topImage; // TextView topTitle,topSource; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // supportRequestWindowFeature(Window.FEATURE_NO_TITLE); // initTheme(); // setContentView(R.layout.detail_layout); // //将状态栏透明 // if(Build.VERSION.SDK_INT>=21){ // View decorView = getWindow().getDecorView(); // int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN| // View.SYSTEM_UI_FLAG_LAYOUT_STABLE; // decorView.setSystemUiVisibility(option); // getWindow().setStatusBarColor(Color.TRANSPARENT); // } // // init(); // fillContent(); // } // // private void initTheme() { // setTheme(R.style.NightTheme); // } // // private void init(){ // LinearLayout layout = (LinearLayout) findViewById(R.id.Download_layout); // layout.setVisibility(View.GONE); // // Intent intent = getIntent(); // body = intent.getStringExtra("body"); // title = intent.getStringExtra("title"); // contentView = (WebView) findViewById(R.id.content_webview); // contentView.setHorizontalScrollBarEnabled(false);//水平不显示 // contentView.setVerticalScrollBarEnabled(false); //垂直不显示 // // contentView.setOnTouchListener(new View.OnTouchListener() { // @Override // public boolean onTouch(View v, MotionEvent event) { // return (event.getAction() == MotionEvent.ACTION_MOVE); // } // }); // contentView.setWebViewClient(new WebViewClient()); // // topImage = (ImageView) findViewById(R.id.top_image); // topTitle = (TextView) findViewById(R.id.top_titlt); // topSource = (TextView) findViewById(R.id.top_source); // } // // //进行网络请求,请求首页的详细内容 // private void fillContent() { // topTitle.setText(title); // topSource.setText("图片:"+"懒得获取~"); // topImage.setImageResource(R.mipmap.default_img); // // String css; // if(!isDay){ // css = "<link type=\"text/css\" href=\"" + // "file:///android_asset/zhihu_dark.css" + // "\" " + // "rel=\"stylesheet\" />\n"; // }else { // css = "<link type=\"text/css\" href=\"" + // "file:///android_asset/zhihu.css" + // "\" " + // "rel=\"stylesheet\" />\n"; // } // String html = "<!DOCTYPE html>\n" + // "<html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\">\n" + // "<head>\n" + // "\t<meta charset=\"utf-8\" />\n</head>\n" + // "<body>\n" + css + // body.replace("<div class=\"img-place-holder\">", "") + "\n<body>"; // contentView.loadDataWithBaseURL("x-data://base", html, "text/html", "utf-8", null); // } // } // // Path: MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/database/Artical.java // public class Artical extends DataSupport { // // private String articalBody; // // @Column(unique = true) // private String articalTitle; // // public String getArticalBody() { // return articalBody; // } // // public void setArticalBody(String articalBody) { // this.articalBody = articalBody; // } // // public String getArticalTitle() { // return articalTitle; // } // // public void setArticalTitle(String articalTitle) { // this.articalTitle = articalTitle; // } // } // Path: MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/adapter/DownloadAdapter.java import android.content.Context; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.example.chentian.myzhihudaily.R; import com.example.chentian.myzhihudaily.activity.DownloadDetaiContentActivity; import com.example.chentian.myzhihudaily.database.Artical; import org.litepal.crud.DataSupport; import java.util.ArrayList; } class ContentRecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { TextView textView,bodyText; ImageView imageView; LinearLayout itemLayout; public ContentRecyclerViewHolder(View itemView) { super(itemView); textView = (TextView) itemView.findViewById(R.id.recycler_title); bodyText = (TextView) itemView.findViewById(R.id.tv_content_id); imageView = (ImageView) itemView.findViewById(R.id.recycler_img); itemLayout = (LinearLayout) itemView.findViewById(R.id.recycler_item); itemLayout.setOnClickListener(this); itemLayout.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { titleData.remove(textView.getText().toString()); notifyDataSetChanged(); DataSupport.deleteAll(Artical.class, "articalTitle = ?" , textView.getText().toString()); Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show(); return true; } }); } @Override public void onClick(View v) {
Intent intent = new Intent(context,DownloadDetaiContentActivity.class);
ChenTianSaber/DailyZhiHu
MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/service/HotNewsService.java
// Path: MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/been/HotNewsBeen.java // public class HotNewsBeen { // // private List<Recent> recent; // public void setRecent(List<Recent> recent) { // this.recent = recent; // } // public List<Recent> getRecent() { // return recent; // } // // }
import com.example.chentian.myzhihudaily.been.HotNewsBeen; import retrofit2.Call; import retrofit2.http.GET;
package com.example.chentian.myzhihudaily.service; /** * Created by chentian on 15/04/2017. */ public interface HotNewsService { @GET("hot")
// Path: MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/been/HotNewsBeen.java // public class HotNewsBeen { // // private List<Recent> recent; // public void setRecent(List<Recent> recent) { // this.recent = recent; // } // public List<Recent> getRecent() { // return recent; // } // // } // Path: MyZhiHuDaily/app/src/main/java/com/example/chentian/myzhihudaily/service/HotNewsService.java import com.example.chentian.myzhihudaily.been.HotNewsBeen; import retrofit2.Call; import retrofit2.http.GET; package com.example.chentian.myzhihudaily.service; /** * Created by chentian on 15/04/2017. */ public interface HotNewsService { @GET("hot")
Call<HotNewsBeen> getHotNews();
talenguyen/PrettyBundle
app/src/main/java/com/tale/prettybundle/sample/TestParcelableActivity.java
// Path: prettybundle/src/main/java/com/tale/prettybundle/PrettyBundle.java // public final class PrettyBundle { // public static final String INJECTOR_SUFFIX = "$$BundleInjector"; // public static final String ANDROID_PREFIX = "android."; // public static final String JAVA_PREFIX = "java."; // // private PrettyBundle() { // throw new AssertionError("No instances."); // } // // private static final String TAG = "PrettyBundle"; // private static boolean debug = false; // // static final Map<Class<?>, Injector<Object>> INJECTORS = // new LinkedHashMap<Class<?>, Injector<Object>>(); // // private static final Injector<Object> NOP_INJECTOR = new Injector<Object>() { // @Override public void inject(Object target, Bundle extras) { // // } // }; // // /** // * Control whether debug logging is enabled. // */ // public static void setDebug(boolean debug) { // PrettyBundle.debug = debug; // } // // public static void inject(Activity activity) { // if (activity == null) { // return; // } // // inject(activity, activity.getIntent().getExtras()); // } // // public static void inject(Fragment fragment) { // if (fragment == null) { // return; // } // // inject(fragment, fragment.getArguments()); // } // // public static void inject(android.support.v4.app.Fragment fragment) { // if (fragment == null) { // return; // } // // inject(fragment, fragment.getArguments()); // } // // public static void inject(Service service, Intent intent) { // if (service == null) { // return; // } // // inject(service, intent == null ? null : intent.getExtras()); // } // // private static void inject(Object target, Bundle extras) { // Class<?> targetClass = target.getClass(); // try { // if (debug) Log.d(TAG, "Looking up view injector for " + targetClass.getName()); // Injector<Object> injector = findInjectorForClass(targetClass); // if (injector != null) { // injector.inject(target, extras); // } // } catch (RuntimeException e) { // throw e; // } catch (Exception e) { // throw new RuntimeException("Unable to inject views for " + target, e); // } // } // // private static Injector<Object> findInjectorForClass(Class<?> cls) // throws IllegalAccessException, InstantiationException { // Injector<Object> injector = INJECTORS.get(cls); // if (injector != null) { // if (debug) Log.d(TAG, "HIT: Cached in injector map."); // return injector; // } // String clsName = cls.getName(); // if (clsName.startsWith(ANDROID_PREFIX) || clsName.startsWith(JAVA_PREFIX)) { // if (debug) Log.d(TAG, "MISS: Reached framework class. Abandoning search."); // return NOP_INJECTOR; // } // // try { // Class<?> injectorClass = Class.forName(clsName + INJECTOR_SUFFIX); // //noinspection unchecked // injector = (Injector<Object>) injectorClass.newInstance(); // if (debug) Log.d(TAG, "HIT: Class loaded injection class."); // } catch (ClassNotFoundException e) { // if (debug) Log.d(TAG, "Not found. Trying superclass " + cls.getSuperclass().getName()); // injector = findInjectorForClass(cls.getSuperclass()); // } // INJECTORS.put(cls, injector); // return injector; // } // // } // // Path: app/src/main/java/com/tale/prettybundle/sample/data/Person.java // public class Person implements Parcelable { // public String name; // public int age; // // public Person(String name, int age) { // this.name = name; // this.age = age; // } // // @Override public int describeContents() { // return 0; // } // // @Override public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.name); // dest.writeInt(this.age); // } // // public Person() { // } // // private Person(Parcel in) { // this.name = in.readString(); // this.age = in.readInt(); // } // // public static final Creator<Person> CREATOR = new Creator<Person>() { // public Person createFromParcel(Parcel source) { // return new Person(source); // } // // public Person[] newArray(int size) { // return new Person[size]; // } // }; // // @Override public String toString() { // return "{" + // "name='" + name + '\'' + // ",age=" + age + // '}'; // } // }
import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.widget.TextView; import com.tale.prettybundle.Extra; import com.tale.prettybundle.PrettyBundle; import com.tale.prettybundle.sample.data.Person; import butterknife.ButterKnife; import butterknife.InjectView;
package com.tale.prettybundle.sample; public class TestParcelableActivity extends ActionBarActivity { @Extra Person person; @InjectView(R.id.tvName) TextView tvName; @InjectView(R.id.tvAge) TextView tvAge; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_parcelable); ButterKnife.inject(this);
// Path: prettybundle/src/main/java/com/tale/prettybundle/PrettyBundle.java // public final class PrettyBundle { // public static final String INJECTOR_SUFFIX = "$$BundleInjector"; // public static final String ANDROID_PREFIX = "android."; // public static final String JAVA_PREFIX = "java."; // // private PrettyBundle() { // throw new AssertionError("No instances."); // } // // private static final String TAG = "PrettyBundle"; // private static boolean debug = false; // // static final Map<Class<?>, Injector<Object>> INJECTORS = // new LinkedHashMap<Class<?>, Injector<Object>>(); // // private static final Injector<Object> NOP_INJECTOR = new Injector<Object>() { // @Override public void inject(Object target, Bundle extras) { // // } // }; // // /** // * Control whether debug logging is enabled. // */ // public static void setDebug(boolean debug) { // PrettyBundle.debug = debug; // } // // public static void inject(Activity activity) { // if (activity == null) { // return; // } // // inject(activity, activity.getIntent().getExtras()); // } // // public static void inject(Fragment fragment) { // if (fragment == null) { // return; // } // // inject(fragment, fragment.getArguments()); // } // // public static void inject(android.support.v4.app.Fragment fragment) { // if (fragment == null) { // return; // } // // inject(fragment, fragment.getArguments()); // } // // public static void inject(Service service, Intent intent) { // if (service == null) { // return; // } // // inject(service, intent == null ? null : intent.getExtras()); // } // // private static void inject(Object target, Bundle extras) { // Class<?> targetClass = target.getClass(); // try { // if (debug) Log.d(TAG, "Looking up view injector for " + targetClass.getName()); // Injector<Object> injector = findInjectorForClass(targetClass); // if (injector != null) { // injector.inject(target, extras); // } // } catch (RuntimeException e) { // throw e; // } catch (Exception e) { // throw new RuntimeException("Unable to inject views for " + target, e); // } // } // // private static Injector<Object> findInjectorForClass(Class<?> cls) // throws IllegalAccessException, InstantiationException { // Injector<Object> injector = INJECTORS.get(cls); // if (injector != null) { // if (debug) Log.d(TAG, "HIT: Cached in injector map."); // return injector; // } // String clsName = cls.getName(); // if (clsName.startsWith(ANDROID_PREFIX) || clsName.startsWith(JAVA_PREFIX)) { // if (debug) Log.d(TAG, "MISS: Reached framework class. Abandoning search."); // return NOP_INJECTOR; // } // // try { // Class<?> injectorClass = Class.forName(clsName + INJECTOR_SUFFIX); // //noinspection unchecked // injector = (Injector<Object>) injectorClass.newInstance(); // if (debug) Log.d(TAG, "HIT: Class loaded injection class."); // } catch (ClassNotFoundException e) { // if (debug) Log.d(TAG, "Not found. Trying superclass " + cls.getSuperclass().getName()); // injector = findInjectorForClass(cls.getSuperclass()); // } // INJECTORS.put(cls, injector); // return injector; // } // // } // // Path: app/src/main/java/com/tale/prettybundle/sample/data/Person.java // public class Person implements Parcelable { // public String name; // public int age; // // public Person(String name, int age) { // this.name = name; // this.age = age; // } // // @Override public int describeContents() { // return 0; // } // // @Override public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.name); // dest.writeInt(this.age); // } // // public Person() { // } // // private Person(Parcel in) { // this.name = in.readString(); // this.age = in.readInt(); // } // // public static final Creator<Person> CREATOR = new Creator<Person>() { // public Person createFromParcel(Parcel source) { // return new Person(source); // } // // public Person[] newArray(int size) { // return new Person[size]; // } // }; // // @Override public String toString() { // return "{" + // "name='" + name + '\'' + // ",age=" + age + // '}'; // } // } // Path: app/src/main/java/com/tale/prettybundle/sample/TestParcelableActivity.java import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.widget.TextView; import com.tale.prettybundle.Extra; import com.tale.prettybundle.PrettyBundle; import com.tale.prettybundle.sample.data.Person; import butterknife.ButterKnife; import butterknife.InjectView; package com.tale.prettybundle.sample; public class TestParcelableActivity extends ActionBarActivity { @Extra Person person; @InjectView(R.id.tvName) TextView tvName; @InjectView(R.id.tvAge) TextView tvAge; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_parcelable); ButterKnife.inject(this);
PrettyBundle.inject(this);
talenguyen/PrettyBundle
app/src/androidTest/java/com/tale/prettybundle/sample/InjectPrimaryTypeExtrasTest.java
// Path: app/src/androidTest/java/com/tale/prettybundle/sample/espresso/ExtViewActions.java // public class ExtViewActions { // // /** // * Perform action of waiting for a specific view id. // * <p/> // * E.g.: // * onView(isRoot()).perform(waitId(R.id.dialogEditor, Sampling.SECONDS_15)); // * // * @param viewId // * @param millis // * @return // */ // public static ViewAction waitId(final int viewId, final long millis) { // return new ViewAction() { // @Override // public Matcher<View> getConstraints() { // return isRoot(); // } // // @Override // public String getDescription() { // return "wait for a specific view with id <" + viewId + "> during " + millis + " millis."; // } // // @Override // public void perform(final UiController uiController, final View view) { // uiController.loopMainThreadUntilIdle(); // final long startTime = System.currentTimeMillis(); // final long endTime = startTime + millis; // final Matcher<View> viewMatcher = withId(viewId); // // do { // for (View child : TreeIterables.breadthFirstViewTraversal(view)) { // // found view with required ID // if (viewMatcher.matches(child)) { // return; // } // } // // uiController.loopMainThreadForAtLeast(50); // } // while (System.currentTimeMillis() < endTime); // // // timeout happens // throw new PerformException.Builder() // .withActionDescription(this.getDescription()) // .withViewDescription(HumanReadables.describe(view)) // .withCause(new TimeoutException()) // .build(); // } // }; // } // // /** // * Perform action of waiting for a specific time. Useful when you need // * to wait for animations to end and Espresso fails at waiting. // * <p/> // * E.g.: // * onView(isRoot()).perform(waitAtLeast(Sampling.SECONDS_15)); // * // * @param millis // * @return // */ // public static ViewAction waitAtLeast(final long millis) { // return new ViewAction() { // @Override // public Matcher<View> getConstraints() { // return anything(); // } // // @Override // public String getDescription() { // return "wait for at least " + millis + " millis."; // } // // @Override // public void perform(final UiController uiController, final View view) { // uiController.loopMainThreadUntilIdle(); // uiController.loopMainThreadForAtLeast(millis); // } // }; // } // // public static ViewAction waitForSoftKeyboard() { // return waitAtLeast(500); // } // // public static ViewAction swipeTop() { // return new GeneralSwipeAction(Swipe.FAST, GeneralLocation.BOTTOM_CENTER, GeneralLocation.TOP_CENTER, Press.FINGER); // } // // public static ViewAction swipeBottom() { // return new GeneralSwipeAction(Swipe.FAST, GeneralLocation.TOP_CENTER, GeneralLocation.BOTTOM_CENTER, Press.FINGER); // } // // /** // * Perform action of waiting until UI thread is free. // * <p/> // * E.g.: // * onView(isRoot()).perform(waitUntilIdle()); // * // * @return // */ // public static ViewAction waitUntilIdle() { // return new ViewAction() { // @Override // public Matcher<View> getConstraints() { // return anything(); // } // // @Override // public String getDescription() { // return "wait until UI thread is free"; // } // // @Override // public void perform(final UiController uiController, final View view) { // uiController.loopMainThreadUntilIdle(); // } // }; // } // // }
import android.support.test.espresso.Espresso; import android.support.test.espresso.action.ViewActions; import android.support.test.espresso.assertion.ViewAssertions; import android.support.test.espresso.matcher.ViewMatchers; import android.test.ActivityInstrumentationTestCase2; import android.widget.CheckBox; import com.tale.prettybundle.sample.espresso.ExtViewActions;
package com.tale.prettybundle.sample; /** * Created by tale on 2/18/15. */ public class InjectPrimaryTypeExtrasTest extends ActivityInstrumentationTestCase2<TestPrimaryTypeSetterActivity> { private TestPrimaryTypeSetterActivity activity; public InjectPrimaryTypeExtrasTest() { super(TestPrimaryTypeSetterActivity.class); } @Override public void setUp() throws Exception { super.setUp(); activity = getActivity(); } public void testStartPrimaryTypeDisplayWithExtras() throws Exception { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { ((CheckBox) activity.findViewById(R.id.cbBoolean)).setChecked(true); } }); final String integerExtra = "1"; Espresso.onView(ViewMatchers.withHint(R.string.hint_int)).perform(ViewActions.typeText(integerExtra), ViewActions.pressImeActionButton()); final String longExtra = "2"; Espresso.onView(ViewMatchers.withHint(R.string.hint_long)).perform(ViewActions.typeText(longExtra), ViewActions.pressImeActionButton()); final String floatExtra = "3.4"; Espresso.onView(ViewMatchers.withHint(R.string.hint_float)).perform(ViewActions.typeText(floatExtra), ViewActions.pressImeActionButton()); final String doubleExtra = "5.6"; Espresso.onView(ViewMatchers.withHint(R.string.hint_double)).perform(ViewActions.typeText(doubleExtra), ViewActions.pressImeActionButton()); final String stringExtra = "String value"; Espresso.onView(ViewMatchers.withHint(R.string.hint_string)).perform(ViewActions.typeText(stringExtra), ViewActions.pressImeActionButton()); final String charSequenceExtra = "CharSequence value"; Espresso.onView(ViewMatchers.withHint(R.string.hint_char_sequence)).perform(ViewActions.typeText(charSequenceExtra), ViewActions.pressImeActionButton()); Espresso.closeSoftKeyboard();
// Path: app/src/androidTest/java/com/tale/prettybundle/sample/espresso/ExtViewActions.java // public class ExtViewActions { // // /** // * Perform action of waiting for a specific view id. // * <p/> // * E.g.: // * onView(isRoot()).perform(waitId(R.id.dialogEditor, Sampling.SECONDS_15)); // * // * @param viewId // * @param millis // * @return // */ // public static ViewAction waitId(final int viewId, final long millis) { // return new ViewAction() { // @Override // public Matcher<View> getConstraints() { // return isRoot(); // } // // @Override // public String getDescription() { // return "wait for a specific view with id <" + viewId + "> during " + millis + " millis."; // } // // @Override // public void perform(final UiController uiController, final View view) { // uiController.loopMainThreadUntilIdle(); // final long startTime = System.currentTimeMillis(); // final long endTime = startTime + millis; // final Matcher<View> viewMatcher = withId(viewId); // // do { // for (View child : TreeIterables.breadthFirstViewTraversal(view)) { // // found view with required ID // if (viewMatcher.matches(child)) { // return; // } // } // // uiController.loopMainThreadForAtLeast(50); // } // while (System.currentTimeMillis() < endTime); // // // timeout happens // throw new PerformException.Builder() // .withActionDescription(this.getDescription()) // .withViewDescription(HumanReadables.describe(view)) // .withCause(new TimeoutException()) // .build(); // } // }; // } // // /** // * Perform action of waiting for a specific time. Useful when you need // * to wait for animations to end and Espresso fails at waiting. // * <p/> // * E.g.: // * onView(isRoot()).perform(waitAtLeast(Sampling.SECONDS_15)); // * // * @param millis // * @return // */ // public static ViewAction waitAtLeast(final long millis) { // return new ViewAction() { // @Override // public Matcher<View> getConstraints() { // return anything(); // } // // @Override // public String getDescription() { // return "wait for at least " + millis + " millis."; // } // // @Override // public void perform(final UiController uiController, final View view) { // uiController.loopMainThreadUntilIdle(); // uiController.loopMainThreadForAtLeast(millis); // } // }; // } // // public static ViewAction waitForSoftKeyboard() { // return waitAtLeast(500); // } // // public static ViewAction swipeTop() { // return new GeneralSwipeAction(Swipe.FAST, GeneralLocation.BOTTOM_CENTER, GeneralLocation.TOP_CENTER, Press.FINGER); // } // // public static ViewAction swipeBottom() { // return new GeneralSwipeAction(Swipe.FAST, GeneralLocation.TOP_CENTER, GeneralLocation.BOTTOM_CENTER, Press.FINGER); // } // // /** // * Perform action of waiting until UI thread is free. // * <p/> // * E.g.: // * onView(isRoot()).perform(waitUntilIdle()); // * // * @return // */ // public static ViewAction waitUntilIdle() { // return new ViewAction() { // @Override // public Matcher<View> getConstraints() { // return anything(); // } // // @Override // public String getDescription() { // return "wait until UI thread is free"; // } // // @Override // public void perform(final UiController uiController, final View view) { // uiController.loopMainThreadUntilIdle(); // } // }; // } // // } // Path: app/src/androidTest/java/com/tale/prettybundle/sample/InjectPrimaryTypeExtrasTest.java import android.support.test.espresso.Espresso; import android.support.test.espresso.action.ViewActions; import android.support.test.espresso.assertion.ViewAssertions; import android.support.test.espresso.matcher.ViewMatchers; import android.test.ActivityInstrumentationTestCase2; import android.widget.CheckBox; import com.tale.prettybundle.sample.espresso.ExtViewActions; package com.tale.prettybundle.sample; /** * Created by tale on 2/18/15. */ public class InjectPrimaryTypeExtrasTest extends ActivityInstrumentationTestCase2<TestPrimaryTypeSetterActivity> { private TestPrimaryTypeSetterActivity activity; public InjectPrimaryTypeExtrasTest() { super(TestPrimaryTypeSetterActivity.class); } @Override public void setUp() throws Exception { super.setUp(); activity = getActivity(); } public void testStartPrimaryTypeDisplayWithExtras() throws Exception { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { ((CheckBox) activity.findViewById(R.id.cbBoolean)).setChecked(true); } }); final String integerExtra = "1"; Espresso.onView(ViewMatchers.withHint(R.string.hint_int)).perform(ViewActions.typeText(integerExtra), ViewActions.pressImeActionButton()); final String longExtra = "2"; Espresso.onView(ViewMatchers.withHint(R.string.hint_long)).perform(ViewActions.typeText(longExtra), ViewActions.pressImeActionButton()); final String floatExtra = "3.4"; Espresso.onView(ViewMatchers.withHint(R.string.hint_float)).perform(ViewActions.typeText(floatExtra), ViewActions.pressImeActionButton()); final String doubleExtra = "5.6"; Espresso.onView(ViewMatchers.withHint(R.string.hint_double)).perform(ViewActions.typeText(doubleExtra), ViewActions.pressImeActionButton()); final String stringExtra = "String value"; Espresso.onView(ViewMatchers.withHint(R.string.hint_string)).perform(ViewActions.typeText(stringExtra), ViewActions.pressImeActionButton()); final String charSequenceExtra = "CharSequence value"; Espresso.onView(ViewMatchers.withHint(R.string.hint_char_sequence)).perform(ViewActions.typeText(charSequenceExtra), ViewActions.pressImeActionButton()); Espresso.closeSoftKeyboard();
Espresso.onView(ViewMatchers.withText(R.string.submit)).perform(ExtViewActions.waitForSoftKeyboard(), ViewActions.scrollTo(), ViewActions.click());
talenguyen/PrettyBundle
app/src/main/java/com/tale/prettybundle/sample/fragments/TestPrimaryExtraFragment4.java
// Path: prettybundle/src/main/java/com/tale/prettybundle/PrettyBundle.java // public final class PrettyBundle { // public static final String INJECTOR_SUFFIX = "$$BundleInjector"; // public static final String ANDROID_PREFIX = "android."; // public static final String JAVA_PREFIX = "java."; // // private PrettyBundle() { // throw new AssertionError("No instances."); // } // // private static final String TAG = "PrettyBundle"; // private static boolean debug = false; // // static final Map<Class<?>, Injector<Object>> INJECTORS = // new LinkedHashMap<Class<?>, Injector<Object>>(); // // private static final Injector<Object> NOP_INJECTOR = new Injector<Object>() { // @Override public void inject(Object target, Bundle extras) { // // } // }; // // /** // * Control whether debug logging is enabled. // */ // public static void setDebug(boolean debug) { // PrettyBundle.debug = debug; // } // // public static void inject(Activity activity) { // if (activity == null) { // return; // } // // inject(activity, activity.getIntent().getExtras()); // } // // public static void inject(Fragment fragment) { // if (fragment == null) { // return; // } // // inject(fragment, fragment.getArguments()); // } // // public static void inject(android.support.v4.app.Fragment fragment) { // if (fragment == null) { // return; // } // // inject(fragment, fragment.getArguments()); // } // // public static void inject(Service service, Intent intent) { // if (service == null) { // return; // } // // inject(service, intent == null ? null : intent.getExtras()); // } // // private static void inject(Object target, Bundle extras) { // Class<?> targetClass = target.getClass(); // try { // if (debug) Log.d(TAG, "Looking up view injector for " + targetClass.getName()); // Injector<Object> injector = findInjectorForClass(targetClass); // if (injector != null) { // injector.inject(target, extras); // } // } catch (RuntimeException e) { // throw e; // } catch (Exception e) { // throw new RuntimeException("Unable to inject views for " + target, e); // } // } // // private static Injector<Object> findInjectorForClass(Class<?> cls) // throws IllegalAccessException, InstantiationException { // Injector<Object> injector = INJECTORS.get(cls); // if (injector != null) { // if (debug) Log.d(TAG, "HIT: Cached in injector map."); // return injector; // } // String clsName = cls.getName(); // if (clsName.startsWith(ANDROID_PREFIX) || clsName.startsWith(JAVA_PREFIX)) { // if (debug) Log.d(TAG, "MISS: Reached framework class. Abandoning search."); // return NOP_INJECTOR; // } // // try { // Class<?> injectorClass = Class.forName(clsName + INJECTOR_SUFFIX); // //noinspection unchecked // injector = (Injector<Object>) injectorClass.newInstance(); // if (debug) Log.d(TAG, "HIT: Class loaded injection class."); // } catch (ClassNotFoundException e) { // if (debug) Log.d(TAG, "Not found. Trying superclass " + cls.getSuperclass().getName()); // injector = findInjectorForClass(cls.getSuperclass()); // } // INJECTORS.put(cls, injector); // return injector; // } // // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.tale.prettybundle.Extra; import com.tale.prettybundle.PrettyBundle; import com.tale.prettybundle.sample.R; import butterknife.ButterKnife; import butterknife.InjectView;
long longVal = 0; @Extra float floatVal = 0; @Extra double doubleVal = 0; @Extra boolean booleanVal = false; @Extra String stringVal = "Default"; @Extra CharSequence charSequenceVal = "Default"; @InjectView(R.id.tvInt) TextView tvInt; @InjectView(R.id.tvLong) TextView tvLong; @InjectView(R.id.tvFloat) TextView tvFloat; @InjectView(R.id.tvDouble) TextView tvDouble; @InjectView(R.id.tvBoolean) TextView tvBoolean; @InjectView(R.id.tvString) TextView tvString; @InjectView(R.id.tvCharSequence) TextView tvCharSequence; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
// Path: prettybundle/src/main/java/com/tale/prettybundle/PrettyBundle.java // public final class PrettyBundle { // public static final String INJECTOR_SUFFIX = "$$BundleInjector"; // public static final String ANDROID_PREFIX = "android."; // public static final String JAVA_PREFIX = "java."; // // private PrettyBundle() { // throw new AssertionError("No instances."); // } // // private static final String TAG = "PrettyBundle"; // private static boolean debug = false; // // static final Map<Class<?>, Injector<Object>> INJECTORS = // new LinkedHashMap<Class<?>, Injector<Object>>(); // // private static final Injector<Object> NOP_INJECTOR = new Injector<Object>() { // @Override public void inject(Object target, Bundle extras) { // // } // }; // // /** // * Control whether debug logging is enabled. // */ // public static void setDebug(boolean debug) { // PrettyBundle.debug = debug; // } // // public static void inject(Activity activity) { // if (activity == null) { // return; // } // // inject(activity, activity.getIntent().getExtras()); // } // // public static void inject(Fragment fragment) { // if (fragment == null) { // return; // } // // inject(fragment, fragment.getArguments()); // } // // public static void inject(android.support.v4.app.Fragment fragment) { // if (fragment == null) { // return; // } // // inject(fragment, fragment.getArguments()); // } // // public static void inject(Service service, Intent intent) { // if (service == null) { // return; // } // // inject(service, intent == null ? null : intent.getExtras()); // } // // private static void inject(Object target, Bundle extras) { // Class<?> targetClass = target.getClass(); // try { // if (debug) Log.d(TAG, "Looking up view injector for " + targetClass.getName()); // Injector<Object> injector = findInjectorForClass(targetClass); // if (injector != null) { // injector.inject(target, extras); // } // } catch (RuntimeException e) { // throw e; // } catch (Exception e) { // throw new RuntimeException("Unable to inject views for " + target, e); // } // } // // private static Injector<Object> findInjectorForClass(Class<?> cls) // throws IllegalAccessException, InstantiationException { // Injector<Object> injector = INJECTORS.get(cls); // if (injector != null) { // if (debug) Log.d(TAG, "HIT: Cached in injector map."); // return injector; // } // String clsName = cls.getName(); // if (clsName.startsWith(ANDROID_PREFIX) || clsName.startsWith(JAVA_PREFIX)) { // if (debug) Log.d(TAG, "MISS: Reached framework class. Abandoning search."); // return NOP_INJECTOR; // } // // try { // Class<?> injectorClass = Class.forName(clsName + INJECTOR_SUFFIX); // //noinspection unchecked // injector = (Injector<Object>) injectorClass.newInstance(); // if (debug) Log.d(TAG, "HIT: Class loaded injection class."); // } catch (ClassNotFoundException e) { // if (debug) Log.d(TAG, "Not found. Trying superclass " + cls.getSuperclass().getName()); // injector = findInjectorForClass(cls.getSuperclass()); // } // INJECTORS.put(cls, injector); // return injector; // } // // } // Path: app/src/main/java/com/tale/prettybundle/sample/fragments/TestPrimaryExtraFragment4.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.tale.prettybundle.Extra; import com.tale.prettybundle.PrettyBundle; import com.tale.prettybundle.sample.R; import butterknife.ButterKnife; import butterknife.InjectView; long longVal = 0; @Extra float floatVal = 0; @Extra double doubleVal = 0; @Extra boolean booleanVal = false; @Extra String stringVal = "Default"; @Extra CharSequence charSequenceVal = "Default"; @InjectView(R.id.tvInt) TextView tvInt; @InjectView(R.id.tvLong) TextView tvLong; @InjectView(R.id.tvFloat) TextView tvFloat; @InjectView(R.id.tvDouble) TextView tvDouble; @InjectView(R.id.tvBoolean) TextView tvBoolean; @InjectView(R.id.tvString) TextView tvString; @InjectView(R.id.tvCharSequence) TextView tvCharSequence; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
PrettyBundle.inject(this);
talenguyen/PrettyBundle
app/src/main/java/com/tale/prettybundle/sample/TestStringExtra2Activity.java
// Path: prettybundle/src/main/java/com/tale/prettybundle/PrettyBundle.java // public final class PrettyBundle { // public static final String INJECTOR_SUFFIX = "$$BundleInjector"; // public static final String ANDROID_PREFIX = "android."; // public static final String JAVA_PREFIX = "java."; // // private PrettyBundle() { // throw new AssertionError("No instances."); // } // // private static final String TAG = "PrettyBundle"; // private static boolean debug = false; // // static final Map<Class<?>, Injector<Object>> INJECTORS = // new LinkedHashMap<Class<?>, Injector<Object>>(); // // private static final Injector<Object> NOP_INJECTOR = new Injector<Object>() { // @Override public void inject(Object target, Bundle extras) { // // } // }; // // /** // * Control whether debug logging is enabled. // */ // public static void setDebug(boolean debug) { // PrettyBundle.debug = debug; // } // // public static void inject(Activity activity) { // if (activity == null) { // return; // } // // inject(activity, activity.getIntent().getExtras()); // } // // public static void inject(Fragment fragment) { // if (fragment == null) { // return; // } // // inject(fragment, fragment.getArguments()); // } // // public static void inject(android.support.v4.app.Fragment fragment) { // if (fragment == null) { // return; // } // // inject(fragment, fragment.getArguments()); // } // // public static void inject(Service service, Intent intent) { // if (service == null) { // return; // } // // inject(service, intent == null ? null : intent.getExtras()); // } // // private static void inject(Object target, Bundle extras) { // Class<?> targetClass = target.getClass(); // try { // if (debug) Log.d(TAG, "Looking up view injector for " + targetClass.getName()); // Injector<Object> injector = findInjectorForClass(targetClass); // if (injector != null) { // injector.inject(target, extras); // } // } catch (RuntimeException e) { // throw e; // } catch (Exception e) { // throw new RuntimeException("Unable to inject views for " + target, e); // } // } // // private static Injector<Object> findInjectorForClass(Class<?> cls) // throws IllegalAccessException, InstantiationException { // Injector<Object> injector = INJECTORS.get(cls); // if (injector != null) { // if (debug) Log.d(TAG, "HIT: Cached in injector map."); // return injector; // } // String clsName = cls.getName(); // if (clsName.startsWith(ANDROID_PREFIX) || clsName.startsWith(JAVA_PREFIX)) { // if (debug) Log.d(TAG, "MISS: Reached framework class. Abandoning search."); // return NOP_INJECTOR; // } // // try { // Class<?> injectorClass = Class.forName(clsName + INJECTOR_SUFFIX); // //noinspection unchecked // injector = (Injector<Object>) injectorClass.newInstance(); // if (debug) Log.d(TAG, "HIT: Class loaded injection class."); // } catch (ClassNotFoundException e) { // if (debug) Log.d(TAG, "Not found. Trying superclass " + cls.getSuperclass().getName()); // injector = findInjectorForClass(cls.getSuperclass()); // } // INJECTORS.put(cls, injector); // return injector; // } // // }
import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.text.TextUtils; import android.widget.TextView; import com.tale.prettybundle.Extra; import com.tale.prettybundle.PrettyBundle; import butterknife.ButterKnife; import butterknife.InjectView;
package com.tale.prettybundle.sample; /** * Created by tale on 2/1/15. */ public class TestStringExtra2Activity extends ActionBarActivity { @Extra String stringExtra1 = "Default"; @Extra String stringExtra2; @InjectView(R.id.tvStringExtra1) TextView tvStringExtra1; @InjectView(R.id.tvStringExtra2) TextView tvStringExtra2; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_extra); ButterKnife.inject(this);
// Path: prettybundle/src/main/java/com/tale/prettybundle/PrettyBundle.java // public final class PrettyBundle { // public static final String INJECTOR_SUFFIX = "$$BundleInjector"; // public static final String ANDROID_PREFIX = "android."; // public static final String JAVA_PREFIX = "java."; // // private PrettyBundle() { // throw new AssertionError("No instances."); // } // // private static final String TAG = "PrettyBundle"; // private static boolean debug = false; // // static final Map<Class<?>, Injector<Object>> INJECTORS = // new LinkedHashMap<Class<?>, Injector<Object>>(); // // private static final Injector<Object> NOP_INJECTOR = new Injector<Object>() { // @Override public void inject(Object target, Bundle extras) { // // } // }; // // /** // * Control whether debug logging is enabled. // */ // public static void setDebug(boolean debug) { // PrettyBundle.debug = debug; // } // // public static void inject(Activity activity) { // if (activity == null) { // return; // } // // inject(activity, activity.getIntent().getExtras()); // } // // public static void inject(Fragment fragment) { // if (fragment == null) { // return; // } // // inject(fragment, fragment.getArguments()); // } // // public static void inject(android.support.v4.app.Fragment fragment) { // if (fragment == null) { // return; // } // // inject(fragment, fragment.getArguments()); // } // // public static void inject(Service service, Intent intent) { // if (service == null) { // return; // } // // inject(service, intent == null ? null : intent.getExtras()); // } // // private static void inject(Object target, Bundle extras) { // Class<?> targetClass = target.getClass(); // try { // if (debug) Log.d(TAG, "Looking up view injector for " + targetClass.getName()); // Injector<Object> injector = findInjectorForClass(targetClass); // if (injector != null) { // injector.inject(target, extras); // } // } catch (RuntimeException e) { // throw e; // } catch (Exception e) { // throw new RuntimeException("Unable to inject views for " + target, e); // } // } // // private static Injector<Object> findInjectorForClass(Class<?> cls) // throws IllegalAccessException, InstantiationException { // Injector<Object> injector = INJECTORS.get(cls); // if (injector != null) { // if (debug) Log.d(TAG, "HIT: Cached in injector map."); // return injector; // } // String clsName = cls.getName(); // if (clsName.startsWith(ANDROID_PREFIX) || clsName.startsWith(JAVA_PREFIX)) { // if (debug) Log.d(TAG, "MISS: Reached framework class. Abandoning search."); // return NOP_INJECTOR; // } // // try { // Class<?> injectorClass = Class.forName(clsName + INJECTOR_SUFFIX); // //noinspection unchecked // injector = (Injector<Object>) injectorClass.newInstance(); // if (debug) Log.d(TAG, "HIT: Class loaded injection class."); // } catch (ClassNotFoundException e) { // if (debug) Log.d(TAG, "Not found. Trying superclass " + cls.getSuperclass().getName()); // injector = findInjectorForClass(cls.getSuperclass()); // } // INJECTORS.put(cls, injector); // return injector; // } // // } // Path: app/src/main/java/com/tale/prettybundle/sample/TestStringExtra2Activity.java import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.text.TextUtils; import android.widget.TextView; import com.tale.prettybundle.Extra; import com.tale.prettybundle.PrettyBundle; import butterknife.ButterKnife; import butterknife.InjectView; package com.tale.prettybundle.sample; /** * Created by tale on 2/1/15. */ public class TestStringExtra2Activity extends ActionBarActivity { @Extra String stringExtra1 = "Default"; @Extra String stringExtra2; @InjectView(R.id.tvStringExtra1) TextView tvStringExtra1; @InjectView(R.id.tvStringExtra2) TextView tvStringExtra2; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_extra); ButterKnife.inject(this);
PrettyBundle.inject(this);
talenguyen/PrettyBundle
app/src/main/java/com/tale/prettybundle/sample/TestArrayExtrasActivity.java
// Path: prettybundle/src/main/java/com/tale/prettybundle/PrettyBundle.java // public final class PrettyBundle { // public static final String INJECTOR_SUFFIX = "$$BundleInjector"; // public static final String ANDROID_PREFIX = "android."; // public static final String JAVA_PREFIX = "java."; // // private PrettyBundle() { // throw new AssertionError("No instances."); // } // // private static final String TAG = "PrettyBundle"; // private static boolean debug = false; // // static final Map<Class<?>, Injector<Object>> INJECTORS = // new LinkedHashMap<Class<?>, Injector<Object>>(); // // private static final Injector<Object> NOP_INJECTOR = new Injector<Object>() { // @Override public void inject(Object target, Bundle extras) { // // } // }; // // /** // * Control whether debug logging is enabled. // */ // public static void setDebug(boolean debug) { // PrettyBundle.debug = debug; // } // // public static void inject(Activity activity) { // if (activity == null) { // return; // } // // inject(activity, activity.getIntent().getExtras()); // } // // public static void inject(Fragment fragment) { // if (fragment == null) { // return; // } // // inject(fragment, fragment.getArguments()); // } // // public static void inject(android.support.v4.app.Fragment fragment) { // if (fragment == null) { // return; // } // // inject(fragment, fragment.getArguments()); // } // // public static void inject(Service service, Intent intent) { // if (service == null) { // return; // } // // inject(service, intent == null ? null : intent.getExtras()); // } // // private static void inject(Object target, Bundle extras) { // Class<?> targetClass = target.getClass(); // try { // if (debug) Log.d(TAG, "Looking up view injector for " + targetClass.getName()); // Injector<Object> injector = findInjectorForClass(targetClass); // if (injector != null) { // injector.inject(target, extras); // } // } catch (RuntimeException e) { // throw e; // } catch (Exception e) { // throw new RuntimeException("Unable to inject views for " + target, e); // } // } // // private static Injector<Object> findInjectorForClass(Class<?> cls) // throws IllegalAccessException, InstantiationException { // Injector<Object> injector = INJECTORS.get(cls); // if (injector != null) { // if (debug) Log.d(TAG, "HIT: Cached in injector map."); // return injector; // } // String clsName = cls.getName(); // if (clsName.startsWith(ANDROID_PREFIX) || clsName.startsWith(JAVA_PREFIX)) { // if (debug) Log.d(TAG, "MISS: Reached framework class. Abandoning search."); // return NOP_INJECTOR; // } // // try { // Class<?> injectorClass = Class.forName(clsName + INJECTOR_SUFFIX); // //noinspection unchecked // injector = (Injector<Object>) injectorClass.newInstance(); // if (debug) Log.d(TAG, "HIT: Class loaded injection class."); // } catch (ClassNotFoundException e) { // if (debug) Log.d(TAG, "Not found. Trying superclass " + cls.getSuperclass().getName()); // injector = findInjectorForClass(cls.getSuperclass()); // } // INJECTORS.put(cls, injector); // return injector; // } // // }
import android.app.Activity; import android.os.Bundle; import android.os.Parcelable; import android.widget.TextView; import com.tale.prettybundle.Extra; import com.tale.prettybundle.PrettyBundle; import butterknife.ButterKnife; import butterknife.InjectView;
package com.tale.prettybundle.sample; /** * Created by giang on 2/25/15. */ public class TestArrayExtrasActivity extends Activity { @Extra int[] ints; @Extra long[] longs; @Extra float[] floats; @Extra double[] doubles; @Extra boolean[] booleans; @Extra String[] strings; @Extra Parcelable[] people; @InjectView(R.id.tvInts) TextView tvInts; @InjectView(R.id.tvLongs) TextView tvLongs; @InjectView(R.id.tvFloats) TextView tvFloats; @InjectView(R.id.tvDoubles) TextView tvDoubles; @InjectView(R.id.tvBooleans) TextView tvBooleans; @InjectView(R.id.tvStrings) TextView tvStrings; @InjectView(R.id.tvPeople) TextView tvPeople; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_array_extras); ButterKnife.inject(this);
// Path: prettybundle/src/main/java/com/tale/prettybundle/PrettyBundle.java // public final class PrettyBundle { // public static final String INJECTOR_SUFFIX = "$$BundleInjector"; // public static final String ANDROID_PREFIX = "android."; // public static final String JAVA_PREFIX = "java."; // // private PrettyBundle() { // throw new AssertionError("No instances."); // } // // private static final String TAG = "PrettyBundle"; // private static boolean debug = false; // // static final Map<Class<?>, Injector<Object>> INJECTORS = // new LinkedHashMap<Class<?>, Injector<Object>>(); // // private static final Injector<Object> NOP_INJECTOR = new Injector<Object>() { // @Override public void inject(Object target, Bundle extras) { // // } // }; // // /** // * Control whether debug logging is enabled. // */ // public static void setDebug(boolean debug) { // PrettyBundle.debug = debug; // } // // public static void inject(Activity activity) { // if (activity == null) { // return; // } // // inject(activity, activity.getIntent().getExtras()); // } // // public static void inject(Fragment fragment) { // if (fragment == null) { // return; // } // // inject(fragment, fragment.getArguments()); // } // // public static void inject(android.support.v4.app.Fragment fragment) { // if (fragment == null) { // return; // } // // inject(fragment, fragment.getArguments()); // } // // public static void inject(Service service, Intent intent) { // if (service == null) { // return; // } // // inject(service, intent == null ? null : intent.getExtras()); // } // // private static void inject(Object target, Bundle extras) { // Class<?> targetClass = target.getClass(); // try { // if (debug) Log.d(TAG, "Looking up view injector for " + targetClass.getName()); // Injector<Object> injector = findInjectorForClass(targetClass); // if (injector != null) { // injector.inject(target, extras); // } // } catch (RuntimeException e) { // throw e; // } catch (Exception e) { // throw new RuntimeException("Unable to inject views for " + target, e); // } // } // // private static Injector<Object> findInjectorForClass(Class<?> cls) // throws IllegalAccessException, InstantiationException { // Injector<Object> injector = INJECTORS.get(cls); // if (injector != null) { // if (debug) Log.d(TAG, "HIT: Cached in injector map."); // return injector; // } // String clsName = cls.getName(); // if (clsName.startsWith(ANDROID_PREFIX) || clsName.startsWith(JAVA_PREFIX)) { // if (debug) Log.d(TAG, "MISS: Reached framework class. Abandoning search."); // return NOP_INJECTOR; // } // // try { // Class<?> injectorClass = Class.forName(clsName + INJECTOR_SUFFIX); // //noinspection unchecked // injector = (Injector<Object>) injectorClass.newInstance(); // if (debug) Log.d(TAG, "HIT: Class loaded injection class."); // } catch (ClassNotFoundException e) { // if (debug) Log.d(TAG, "Not found. Trying superclass " + cls.getSuperclass().getName()); // injector = findInjectorForClass(cls.getSuperclass()); // } // INJECTORS.put(cls, injector); // return injector; // } // // } // Path: app/src/main/java/com/tale/prettybundle/sample/TestArrayExtrasActivity.java import android.app.Activity; import android.os.Bundle; import android.os.Parcelable; import android.widget.TextView; import com.tale.prettybundle.Extra; import com.tale.prettybundle.PrettyBundle; import butterknife.ButterKnife; import butterknife.InjectView; package com.tale.prettybundle.sample; /** * Created by giang on 2/25/15. */ public class TestArrayExtrasActivity extends Activity { @Extra int[] ints; @Extra long[] longs; @Extra float[] floats; @Extra double[] doubles; @Extra boolean[] booleans; @Extra String[] strings; @Extra Parcelable[] people; @InjectView(R.id.tvInts) TextView tvInts; @InjectView(R.id.tvLongs) TextView tvLongs; @InjectView(R.id.tvFloats) TextView tvFloats; @InjectView(R.id.tvDoubles) TextView tvDoubles; @InjectView(R.id.tvBooleans) TextView tvBooleans; @InjectView(R.id.tvStrings) TextView tvStrings; @InjectView(R.id.tvPeople) TextView tvPeople; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_array_extras); ButterKnife.inject(this);
PrettyBundle.inject(this);
talenguyen/PrettyBundle
app/src/main/java/com/tale/prettybundle/sample/MenuActivity.java
// Path: app/src/main/java/com/tale/prettybundle/sample/data/Person.java // public class Person implements Parcelable { // public String name; // public int age; // // public Person(String name, int age) { // this.name = name; // this.age = age; // } // // @Override public int describeContents() { // return 0; // } // // @Override public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.name); // dest.writeInt(this.age); // } // // public Person() { // } // // private Person(Parcel in) { // this.name = in.readString(); // this.age = in.readInt(); // } // // public static final Creator<Person> CREATOR = new Creator<Person>() { // public Person createFromParcel(Parcel source) { // return new Person(source); // } // // public Person[] newArray(int size) { // return new Person[size]; // } // }; // // @Override public String toString() { // return "{" + // "name='" + name + '\'' + // ",age=" + age + // '}'; // } // }
import android.app.Activity; import android.content.Intent; import android.os.Bundle; import com.tale.prettybundle.Activities; import com.tale.prettybundle.sample.data.Person; import butterknife.ButterKnife; import butterknife.OnClick;
package com.tale.prettybundle.sample; /** * Created by giang on 2/24/15. */ public class MenuActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_menu); ButterKnife.inject(this); } @OnClick(R.id.btTestStringExtras) public void testStringExtras() { startActivity(new Intent(this, MainActivity.class)); } @OnClick(R.id.btTestPrimaryTypeExtras) public void testPrimaryTypeExtras() { startActivity(new Intent(this, TestPrimaryTypeSetterActivity.class)); } @OnClick(R.id.btTestParcelableExtras) public void testTestParcelableExtras() {
// Path: app/src/main/java/com/tale/prettybundle/sample/data/Person.java // public class Person implements Parcelable { // public String name; // public int age; // // public Person(String name, int age) { // this.name = name; // this.age = age; // } // // @Override public int describeContents() { // return 0; // } // // @Override public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.name); // dest.writeInt(this.age); // } // // public Person() { // } // // private Person(Parcel in) { // this.name = in.readString(); // this.age = in.readInt(); // } // // public static final Creator<Person> CREATOR = new Creator<Person>() { // public Person createFromParcel(Parcel source) { // return new Person(source); // } // // public Person[] newArray(int size) { // return new Person[size]; // } // }; // // @Override public String toString() { // return "{" + // "name='" + name + '\'' + // ",age=" + age + // '}'; // } // } // Path: app/src/main/java/com/tale/prettybundle/sample/MenuActivity.java import android.app.Activity; import android.content.Intent; import android.os.Bundle; import com.tale.prettybundle.Activities; import com.tale.prettybundle.sample.data.Person; import butterknife.ButterKnife; import butterknife.OnClick; package com.tale.prettybundle.sample; /** * Created by giang on 2/24/15. */ public class MenuActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_menu); ButterKnife.inject(this); } @OnClick(R.id.btTestStringExtras) public void testStringExtras() { startActivity(new Intent(this, MainActivity.class)); } @OnClick(R.id.btTestPrimaryTypeExtras) public void testPrimaryTypeExtras() { startActivity(new Intent(this, TestPrimaryTypeSetterActivity.class)); } @OnClick(R.id.btTestParcelableExtras) public void testTestParcelableExtras() {
startActivity(Activities.createTestParcelableActivityIntent(this, new Person("Giang", 26)));
talenguyen/PrettyBundle
app/src/main/java/com/tale/prettybundle/sample/fragments/TestPrimaryExtraFragment.java
// Path: prettybundle/src/main/java/com/tale/prettybundle/PrettyBundle.java // public final class PrettyBundle { // public static final String INJECTOR_SUFFIX = "$$BundleInjector"; // public static final String ANDROID_PREFIX = "android."; // public static final String JAVA_PREFIX = "java."; // // private PrettyBundle() { // throw new AssertionError("No instances."); // } // // private static final String TAG = "PrettyBundle"; // private static boolean debug = false; // // static final Map<Class<?>, Injector<Object>> INJECTORS = // new LinkedHashMap<Class<?>, Injector<Object>>(); // // private static final Injector<Object> NOP_INJECTOR = new Injector<Object>() { // @Override public void inject(Object target, Bundle extras) { // // } // }; // // /** // * Control whether debug logging is enabled. // */ // public static void setDebug(boolean debug) { // PrettyBundle.debug = debug; // } // // public static void inject(Activity activity) { // if (activity == null) { // return; // } // // inject(activity, activity.getIntent().getExtras()); // } // // public static void inject(Fragment fragment) { // if (fragment == null) { // return; // } // // inject(fragment, fragment.getArguments()); // } // // public static void inject(android.support.v4.app.Fragment fragment) { // if (fragment == null) { // return; // } // // inject(fragment, fragment.getArguments()); // } // // public static void inject(Service service, Intent intent) { // if (service == null) { // return; // } // // inject(service, intent == null ? null : intent.getExtras()); // } // // private static void inject(Object target, Bundle extras) { // Class<?> targetClass = target.getClass(); // try { // if (debug) Log.d(TAG, "Looking up view injector for " + targetClass.getName()); // Injector<Object> injector = findInjectorForClass(targetClass); // if (injector != null) { // injector.inject(target, extras); // } // } catch (RuntimeException e) { // throw e; // } catch (Exception e) { // throw new RuntimeException("Unable to inject views for " + target, e); // } // } // // private static Injector<Object> findInjectorForClass(Class<?> cls) // throws IllegalAccessException, InstantiationException { // Injector<Object> injector = INJECTORS.get(cls); // if (injector != null) { // if (debug) Log.d(TAG, "HIT: Cached in injector map."); // return injector; // } // String clsName = cls.getName(); // if (clsName.startsWith(ANDROID_PREFIX) || clsName.startsWith(JAVA_PREFIX)) { // if (debug) Log.d(TAG, "MISS: Reached framework class. Abandoning search."); // return NOP_INJECTOR; // } // // try { // Class<?> injectorClass = Class.forName(clsName + INJECTOR_SUFFIX); // //noinspection unchecked // injector = (Injector<Object>) injectorClass.newInstance(); // if (debug) Log.d(TAG, "HIT: Class loaded injection class."); // } catch (ClassNotFoundException e) { // if (debug) Log.d(TAG, "Not found. Trying superclass " + cls.getSuperclass().getName()); // injector = findInjectorForClass(cls.getSuperclass()); // } // INJECTORS.put(cls, injector); // return injector; // } // // }
import android.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.tale.prettybundle.Extra; import com.tale.prettybundle.PrettyBundle; import com.tale.prettybundle.sample.R; import butterknife.ButterKnife; import butterknife.InjectView;
package com.tale.prettybundle.sample.fragments; /** * Created by giang on 2/26/15. */ public class TestPrimaryExtraFragment extends Fragment { @Extra int intVal = 0; @Extra long longVal = 0; @Extra float floatVal = 0; @Extra double doubleVal = 0; @Extra boolean booleanVal = false; @Extra String stringVal = "Default"; @Extra CharSequence charSequenceVal = "Default"; @InjectView(R.id.tvInt) TextView tvInt; @InjectView(R.id.tvLong) TextView tvLong; @InjectView(R.id.tvFloat) TextView tvFloat; @InjectView(R.id.tvDouble) TextView tvDouble; @InjectView(R.id.tvBoolean) TextView tvBoolean; @InjectView(R.id.tvString) TextView tvString; @InjectView(R.id.tvCharSequence) TextView tvCharSequence; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
// Path: prettybundle/src/main/java/com/tale/prettybundle/PrettyBundle.java // public final class PrettyBundle { // public static final String INJECTOR_SUFFIX = "$$BundleInjector"; // public static final String ANDROID_PREFIX = "android."; // public static final String JAVA_PREFIX = "java."; // // private PrettyBundle() { // throw new AssertionError("No instances."); // } // // private static final String TAG = "PrettyBundle"; // private static boolean debug = false; // // static final Map<Class<?>, Injector<Object>> INJECTORS = // new LinkedHashMap<Class<?>, Injector<Object>>(); // // private static final Injector<Object> NOP_INJECTOR = new Injector<Object>() { // @Override public void inject(Object target, Bundle extras) { // // } // }; // // /** // * Control whether debug logging is enabled. // */ // public static void setDebug(boolean debug) { // PrettyBundle.debug = debug; // } // // public static void inject(Activity activity) { // if (activity == null) { // return; // } // // inject(activity, activity.getIntent().getExtras()); // } // // public static void inject(Fragment fragment) { // if (fragment == null) { // return; // } // // inject(fragment, fragment.getArguments()); // } // // public static void inject(android.support.v4.app.Fragment fragment) { // if (fragment == null) { // return; // } // // inject(fragment, fragment.getArguments()); // } // // public static void inject(Service service, Intent intent) { // if (service == null) { // return; // } // // inject(service, intent == null ? null : intent.getExtras()); // } // // private static void inject(Object target, Bundle extras) { // Class<?> targetClass = target.getClass(); // try { // if (debug) Log.d(TAG, "Looking up view injector for " + targetClass.getName()); // Injector<Object> injector = findInjectorForClass(targetClass); // if (injector != null) { // injector.inject(target, extras); // } // } catch (RuntimeException e) { // throw e; // } catch (Exception e) { // throw new RuntimeException("Unable to inject views for " + target, e); // } // } // // private static Injector<Object> findInjectorForClass(Class<?> cls) // throws IllegalAccessException, InstantiationException { // Injector<Object> injector = INJECTORS.get(cls); // if (injector != null) { // if (debug) Log.d(TAG, "HIT: Cached in injector map."); // return injector; // } // String clsName = cls.getName(); // if (clsName.startsWith(ANDROID_PREFIX) || clsName.startsWith(JAVA_PREFIX)) { // if (debug) Log.d(TAG, "MISS: Reached framework class. Abandoning search."); // return NOP_INJECTOR; // } // // try { // Class<?> injectorClass = Class.forName(clsName + INJECTOR_SUFFIX); // //noinspection unchecked // injector = (Injector<Object>) injectorClass.newInstance(); // if (debug) Log.d(TAG, "HIT: Class loaded injection class."); // } catch (ClassNotFoundException e) { // if (debug) Log.d(TAG, "Not found. Trying superclass " + cls.getSuperclass().getName()); // injector = findInjectorForClass(cls.getSuperclass()); // } // INJECTORS.put(cls, injector); // return injector; // } // // } // Path: app/src/main/java/com/tale/prettybundle/sample/fragments/TestPrimaryExtraFragment.java import android.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.tale.prettybundle.Extra; import com.tale.prettybundle.PrettyBundle; import com.tale.prettybundle.sample.R; import butterknife.ButterKnife; import butterknife.InjectView; package com.tale.prettybundle.sample.fragments; /** * Created by giang on 2/26/15. */ public class TestPrimaryExtraFragment extends Fragment { @Extra int intVal = 0; @Extra long longVal = 0; @Extra float floatVal = 0; @Extra double doubleVal = 0; @Extra boolean booleanVal = false; @Extra String stringVal = "Default"; @Extra CharSequence charSequenceVal = "Default"; @InjectView(R.id.tvInt) TextView tvInt; @InjectView(R.id.tvLong) TextView tvLong; @InjectView(R.id.tvFloat) TextView tvFloat; @InjectView(R.id.tvDouble) TextView tvDouble; @InjectView(R.id.tvBoolean) TextView tvBoolean; @InjectView(R.id.tvString) TextView tvString; @InjectView(R.id.tvCharSequence) TextView tvCharSequence; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
PrettyBundle.inject(this);
talenguyen/PrettyBundle
app/src/androidTest/java/com/tale/prettybundle/sample/InjectStringExtrasTest.java
// Path: app/src/androidTest/java/com/tale/prettybundle/sample/espresso/ExtViewActions.java // public class ExtViewActions { // // /** // * Perform action of waiting for a specific view id. // * <p/> // * E.g.: // * onView(isRoot()).perform(waitId(R.id.dialogEditor, Sampling.SECONDS_15)); // * // * @param viewId // * @param millis // * @return // */ // public static ViewAction waitId(final int viewId, final long millis) { // return new ViewAction() { // @Override // public Matcher<View> getConstraints() { // return isRoot(); // } // // @Override // public String getDescription() { // return "wait for a specific view with id <" + viewId + "> during " + millis + " millis."; // } // // @Override // public void perform(final UiController uiController, final View view) { // uiController.loopMainThreadUntilIdle(); // final long startTime = System.currentTimeMillis(); // final long endTime = startTime + millis; // final Matcher<View> viewMatcher = withId(viewId); // // do { // for (View child : TreeIterables.breadthFirstViewTraversal(view)) { // // found view with required ID // if (viewMatcher.matches(child)) { // return; // } // } // // uiController.loopMainThreadForAtLeast(50); // } // while (System.currentTimeMillis() < endTime); // // // timeout happens // throw new PerformException.Builder() // .withActionDescription(this.getDescription()) // .withViewDescription(HumanReadables.describe(view)) // .withCause(new TimeoutException()) // .build(); // } // }; // } // // /** // * Perform action of waiting for a specific time. Useful when you need // * to wait for animations to end and Espresso fails at waiting. // * <p/> // * E.g.: // * onView(isRoot()).perform(waitAtLeast(Sampling.SECONDS_15)); // * // * @param millis // * @return // */ // public static ViewAction waitAtLeast(final long millis) { // return new ViewAction() { // @Override // public Matcher<View> getConstraints() { // return anything(); // } // // @Override // public String getDescription() { // return "wait for at least " + millis + " millis."; // } // // @Override // public void perform(final UiController uiController, final View view) { // uiController.loopMainThreadUntilIdle(); // uiController.loopMainThreadForAtLeast(millis); // } // }; // } // // public static ViewAction waitForSoftKeyboard() { // return waitAtLeast(500); // } // // public static ViewAction swipeTop() { // return new GeneralSwipeAction(Swipe.FAST, GeneralLocation.BOTTOM_CENTER, GeneralLocation.TOP_CENTER, Press.FINGER); // } // // public static ViewAction swipeBottom() { // return new GeneralSwipeAction(Swipe.FAST, GeneralLocation.TOP_CENTER, GeneralLocation.BOTTOM_CENTER, Press.FINGER); // } // // /** // * Perform action of waiting until UI thread is free. // * <p/> // * E.g.: // * onView(isRoot()).perform(waitUntilIdle()); // * // * @return // */ // public static ViewAction waitUntilIdle() { // return new ViewAction() { // @Override // public Matcher<View> getConstraints() { // return anything(); // } // // @Override // public String getDescription() { // return "wait until UI thread is free"; // } // // @Override // public void perform(final UiController uiController, final View view) { // uiController.loopMainThreadUntilIdle(); // } // }; // } // // }
import android.support.test.espresso.Espresso; import android.support.test.espresso.action.ViewActions; import android.support.test.espresso.assertion.ViewAssertions; import android.support.test.espresso.matcher.ViewMatchers; import android.test.ActivityInstrumentationTestCase2; import com.tale.prettybundle.sample.espresso.ExtViewActions;
package com.tale.prettybundle.sample; /** * Created by tale on 2/18/15. */ public class InjectStringExtrasTest extends ActivityInstrumentationTestCase2<MainActivity> { public InjectStringExtrasTest() { super(MainActivity.class); } @Override public void setUp() throws Exception { super.setUp(); getActivity(); } public void testStartActivityTestStringExtra2WithExtras() throws Exception { final String extra1 = "Giang"; final String extra2 = "Nguyen"; Espresso.onView(ViewMatchers.withHint(R.string.string_extra_1)).perform(ViewActions.typeText(extra1), ViewActions.pressImeActionButton()); Espresso.onView(ViewMatchers.withHint(R.string.string_extra_2)).perform(ViewActions.typeText(extra2), ViewActions.pressImeActionButton());
// Path: app/src/androidTest/java/com/tale/prettybundle/sample/espresso/ExtViewActions.java // public class ExtViewActions { // // /** // * Perform action of waiting for a specific view id. // * <p/> // * E.g.: // * onView(isRoot()).perform(waitId(R.id.dialogEditor, Sampling.SECONDS_15)); // * // * @param viewId // * @param millis // * @return // */ // public static ViewAction waitId(final int viewId, final long millis) { // return new ViewAction() { // @Override // public Matcher<View> getConstraints() { // return isRoot(); // } // // @Override // public String getDescription() { // return "wait for a specific view with id <" + viewId + "> during " + millis + " millis."; // } // // @Override // public void perform(final UiController uiController, final View view) { // uiController.loopMainThreadUntilIdle(); // final long startTime = System.currentTimeMillis(); // final long endTime = startTime + millis; // final Matcher<View> viewMatcher = withId(viewId); // // do { // for (View child : TreeIterables.breadthFirstViewTraversal(view)) { // // found view with required ID // if (viewMatcher.matches(child)) { // return; // } // } // // uiController.loopMainThreadForAtLeast(50); // } // while (System.currentTimeMillis() < endTime); // // // timeout happens // throw new PerformException.Builder() // .withActionDescription(this.getDescription()) // .withViewDescription(HumanReadables.describe(view)) // .withCause(new TimeoutException()) // .build(); // } // }; // } // // /** // * Perform action of waiting for a specific time. Useful when you need // * to wait for animations to end and Espresso fails at waiting. // * <p/> // * E.g.: // * onView(isRoot()).perform(waitAtLeast(Sampling.SECONDS_15)); // * // * @param millis // * @return // */ // public static ViewAction waitAtLeast(final long millis) { // return new ViewAction() { // @Override // public Matcher<View> getConstraints() { // return anything(); // } // // @Override // public String getDescription() { // return "wait for at least " + millis + " millis."; // } // // @Override // public void perform(final UiController uiController, final View view) { // uiController.loopMainThreadUntilIdle(); // uiController.loopMainThreadForAtLeast(millis); // } // }; // } // // public static ViewAction waitForSoftKeyboard() { // return waitAtLeast(500); // } // // public static ViewAction swipeTop() { // return new GeneralSwipeAction(Swipe.FAST, GeneralLocation.BOTTOM_CENTER, GeneralLocation.TOP_CENTER, Press.FINGER); // } // // public static ViewAction swipeBottom() { // return new GeneralSwipeAction(Swipe.FAST, GeneralLocation.TOP_CENTER, GeneralLocation.BOTTOM_CENTER, Press.FINGER); // } // // /** // * Perform action of waiting until UI thread is free. // * <p/> // * E.g.: // * onView(isRoot()).perform(waitUntilIdle()); // * // * @return // */ // public static ViewAction waitUntilIdle() { // return new ViewAction() { // @Override // public Matcher<View> getConstraints() { // return anything(); // } // // @Override // public String getDescription() { // return "wait until UI thread is free"; // } // // @Override // public void perform(final UiController uiController, final View view) { // uiController.loopMainThreadUntilIdle(); // } // }; // } // // } // Path: app/src/androidTest/java/com/tale/prettybundle/sample/InjectStringExtrasTest.java import android.support.test.espresso.Espresso; import android.support.test.espresso.action.ViewActions; import android.support.test.espresso.assertion.ViewAssertions; import android.support.test.espresso.matcher.ViewMatchers; import android.test.ActivityInstrumentationTestCase2; import com.tale.prettybundle.sample.espresso.ExtViewActions; package com.tale.prettybundle.sample; /** * Created by tale on 2/18/15. */ public class InjectStringExtrasTest extends ActivityInstrumentationTestCase2<MainActivity> { public InjectStringExtrasTest() { super(MainActivity.class); } @Override public void setUp() throws Exception { super.setUp(); getActivity(); } public void testStartActivityTestStringExtra2WithExtras() throws Exception { final String extra1 = "Giang"; final String extra2 = "Nguyen"; Espresso.onView(ViewMatchers.withHint(R.string.string_extra_1)).perform(ViewActions.typeText(extra1), ViewActions.pressImeActionButton()); Espresso.onView(ViewMatchers.withHint(R.string.string_extra_2)).perform(ViewActions.typeText(extra2), ViewActions.pressImeActionButton());
Espresso.onView(ViewMatchers.withText(R.string.submit)).perform(ExtViewActions.waitForSoftKeyboard(), ViewActions.click());
talenguyen/PrettyBundle
app/src/main/java/com/tale/prettybundle/sample/TestPrimaryTypeDisplayActivity.java
// Path: prettybundle/src/main/java/com/tale/prettybundle/PrettyBundle.java // public final class PrettyBundle { // public static final String INJECTOR_SUFFIX = "$$BundleInjector"; // public static final String ANDROID_PREFIX = "android."; // public static final String JAVA_PREFIX = "java."; // // private PrettyBundle() { // throw new AssertionError("No instances."); // } // // private static final String TAG = "PrettyBundle"; // private static boolean debug = false; // // static final Map<Class<?>, Injector<Object>> INJECTORS = // new LinkedHashMap<Class<?>, Injector<Object>>(); // // private static final Injector<Object> NOP_INJECTOR = new Injector<Object>() { // @Override public void inject(Object target, Bundle extras) { // // } // }; // // /** // * Control whether debug logging is enabled. // */ // public static void setDebug(boolean debug) { // PrettyBundle.debug = debug; // } // // public static void inject(Activity activity) { // if (activity == null) { // return; // } // // inject(activity, activity.getIntent().getExtras()); // } // // public static void inject(Fragment fragment) { // if (fragment == null) { // return; // } // // inject(fragment, fragment.getArguments()); // } // // public static void inject(android.support.v4.app.Fragment fragment) { // if (fragment == null) { // return; // } // // inject(fragment, fragment.getArguments()); // } // // public static void inject(Service service, Intent intent) { // if (service == null) { // return; // } // // inject(service, intent == null ? null : intent.getExtras()); // } // // private static void inject(Object target, Bundle extras) { // Class<?> targetClass = target.getClass(); // try { // if (debug) Log.d(TAG, "Looking up view injector for " + targetClass.getName()); // Injector<Object> injector = findInjectorForClass(targetClass); // if (injector != null) { // injector.inject(target, extras); // } // } catch (RuntimeException e) { // throw e; // } catch (Exception e) { // throw new RuntimeException("Unable to inject views for " + target, e); // } // } // // private static Injector<Object> findInjectorForClass(Class<?> cls) // throws IllegalAccessException, InstantiationException { // Injector<Object> injector = INJECTORS.get(cls); // if (injector != null) { // if (debug) Log.d(TAG, "HIT: Cached in injector map."); // return injector; // } // String clsName = cls.getName(); // if (clsName.startsWith(ANDROID_PREFIX) || clsName.startsWith(JAVA_PREFIX)) { // if (debug) Log.d(TAG, "MISS: Reached framework class. Abandoning search."); // return NOP_INJECTOR; // } // // try { // Class<?> injectorClass = Class.forName(clsName + INJECTOR_SUFFIX); // //noinspection unchecked // injector = (Injector<Object>) injectorClass.newInstance(); // if (debug) Log.d(TAG, "HIT: Class loaded injection class."); // } catch (ClassNotFoundException e) { // if (debug) Log.d(TAG, "Not found. Trying superclass " + cls.getSuperclass().getName()); // injector = findInjectorForClass(cls.getSuperclass()); // } // INJECTORS.put(cls, injector); // return injector; // } // // }
import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.widget.TextView; import com.tale.prettybundle.Extra; import com.tale.prettybundle.PrettyBundle; import butterknife.ButterKnife; import butterknife.InjectView;
package com.tale.prettybundle.sample; /** * Created by giang on 2/24/15. */ public class TestPrimaryTypeDisplayActivity extends FragmentActivity { @Extra int intVal = 0; @Extra long longVal = 0; @Extra float floatVal = 0; @Extra double doubleVal = 0; @Extra boolean booleanVal = false; @Extra String stringVal = "Default"; @Extra CharSequence charSequenceVal = "Default"; @InjectView(R.id.tvInt) TextView tvInt; @InjectView(R.id.tvLong) TextView tvLong; @InjectView(R.id.tvFloat) TextView tvFloat; @InjectView(R.id.tvDouble) TextView tvDouble; @InjectView(R.id.tvBoolean) TextView tvBoolean; @InjectView(R.id.tvString) TextView tvString; @InjectView(R.id.tvCharSequence) TextView tvCharSequence; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_test_primary_type_display); ButterKnife.inject(this);
// Path: prettybundle/src/main/java/com/tale/prettybundle/PrettyBundle.java // public final class PrettyBundle { // public static final String INJECTOR_SUFFIX = "$$BundleInjector"; // public static final String ANDROID_PREFIX = "android."; // public static final String JAVA_PREFIX = "java."; // // private PrettyBundle() { // throw new AssertionError("No instances."); // } // // private static final String TAG = "PrettyBundle"; // private static boolean debug = false; // // static final Map<Class<?>, Injector<Object>> INJECTORS = // new LinkedHashMap<Class<?>, Injector<Object>>(); // // private static final Injector<Object> NOP_INJECTOR = new Injector<Object>() { // @Override public void inject(Object target, Bundle extras) { // // } // }; // // /** // * Control whether debug logging is enabled. // */ // public static void setDebug(boolean debug) { // PrettyBundle.debug = debug; // } // // public static void inject(Activity activity) { // if (activity == null) { // return; // } // // inject(activity, activity.getIntent().getExtras()); // } // // public static void inject(Fragment fragment) { // if (fragment == null) { // return; // } // // inject(fragment, fragment.getArguments()); // } // // public static void inject(android.support.v4.app.Fragment fragment) { // if (fragment == null) { // return; // } // // inject(fragment, fragment.getArguments()); // } // // public static void inject(Service service, Intent intent) { // if (service == null) { // return; // } // // inject(service, intent == null ? null : intent.getExtras()); // } // // private static void inject(Object target, Bundle extras) { // Class<?> targetClass = target.getClass(); // try { // if (debug) Log.d(TAG, "Looking up view injector for " + targetClass.getName()); // Injector<Object> injector = findInjectorForClass(targetClass); // if (injector != null) { // injector.inject(target, extras); // } // } catch (RuntimeException e) { // throw e; // } catch (Exception e) { // throw new RuntimeException("Unable to inject views for " + target, e); // } // } // // private static Injector<Object> findInjectorForClass(Class<?> cls) // throws IllegalAccessException, InstantiationException { // Injector<Object> injector = INJECTORS.get(cls); // if (injector != null) { // if (debug) Log.d(TAG, "HIT: Cached in injector map."); // return injector; // } // String clsName = cls.getName(); // if (clsName.startsWith(ANDROID_PREFIX) || clsName.startsWith(JAVA_PREFIX)) { // if (debug) Log.d(TAG, "MISS: Reached framework class. Abandoning search."); // return NOP_INJECTOR; // } // // try { // Class<?> injectorClass = Class.forName(clsName + INJECTOR_SUFFIX); // //noinspection unchecked // injector = (Injector<Object>) injectorClass.newInstance(); // if (debug) Log.d(TAG, "HIT: Class loaded injection class."); // } catch (ClassNotFoundException e) { // if (debug) Log.d(TAG, "Not found. Trying superclass " + cls.getSuperclass().getName()); // injector = findInjectorForClass(cls.getSuperclass()); // } // INJECTORS.put(cls, injector); // return injector; // } // // } // Path: app/src/main/java/com/tale/prettybundle/sample/TestPrimaryTypeDisplayActivity.java import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.widget.TextView; import com.tale.prettybundle.Extra; import com.tale.prettybundle.PrettyBundle; import butterknife.ButterKnife; import butterknife.InjectView; package com.tale.prettybundle.sample; /** * Created by giang on 2/24/15. */ public class TestPrimaryTypeDisplayActivity extends FragmentActivity { @Extra int intVal = 0; @Extra long longVal = 0; @Extra float floatVal = 0; @Extra double doubleVal = 0; @Extra boolean booleanVal = false; @Extra String stringVal = "Default"; @Extra CharSequence charSequenceVal = "Default"; @InjectView(R.id.tvInt) TextView tvInt; @InjectView(R.id.tvLong) TextView tvLong; @InjectView(R.id.tvFloat) TextView tvFloat; @InjectView(R.id.tvDouble) TextView tvDouble; @InjectView(R.id.tvBoolean) TextView tvBoolean; @InjectView(R.id.tvString) TextView tvString; @InjectView(R.id.tvCharSequence) TextView tvCharSequence; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_test_primary_type_display); ButterKnife.inject(this);
PrettyBundle.inject(this);
talenguyen/PrettyBundle
app/src/main/java/com/tale/prettybundle/sample/services/TestPrimaryTypeService.java
// Path: prettybundle/src/main/java/com/tale/prettybundle/PrettyBundle.java // public final class PrettyBundle { // public static final String INJECTOR_SUFFIX = "$$BundleInjector"; // public static final String ANDROID_PREFIX = "android."; // public static final String JAVA_PREFIX = "java."; // // private PrettyBundle() { // throw new AssertionError("No instances."); // } // // private static final String TAG = "PrettyBundle"; // private static boolean debug = false; // // static final Map<Class<?>, Injector<Object>> INJECTORS = // new LinkedHashMap<Class<?>, Injector<Object>>(); // // private static final Injector<Object> NOP_INJECTOR = new Injector<Object>() { // @Override public void inject(Object target, Bundle extras) { // // } // }; // // /** // * Control whether debug logging is enabled. // */ // public static void setDebug(boolean debug) { // PrettyBundle.debug = debug; // } // // public static void inject(Activity activity) { // if (activity == null) { // return; // } // // inject(activity, activity.getIntent().getExtras()); // } // // public static void inject(Fragment fragment) { // if (fragment == null) { // return; // } // // inject(fragment, fragment.getArguments()); // } // // public static void inject(android.support.v4.app.Fragment fragment) { // if (fragment == null) { // return; // } // // inject(fragment, fragment.getArguments()); // } // // public static void inject(Service service, Intent intent) { // if (service == null) { // return; // } // // inject(service, intent == null ? null : intent.getExtras()); // } // // private static void inject(Object target, Bundle extras) { // Class<?> targetClass = target.getClass(); // try { // if (debug) Log.d(TAG, "Looking up view injector for " + targetClass.getName()); // Injector<Object> injector = findInjectorForClass(targetClass); // if (injector != null) { // injector.inject(target, extras); // } // } catch (RuntimeException e) { // throw e; // } catch (Exception e) { // throw new RuntimeException("Unable to inject views for " + target, e); // } // } // // private static Injector<Object> findInjectorForClass(Class<?> cls) // throws IllegalAccessException, InstantiationException { // Injector<Object> injector = INJECTORS.get(cls); // if (injector != null) { // if (debug) Log.d(TAG, "HIT: Cached in injector map."); // return injector; // } // String clsName = cls.getName(); // if (clsName.startsWith(ANDROID_PREFIX) || clsName.startsWith(JAVA_PREFIX)) { // if (debug) Log.d(TAG, "MISS: Reached framework class. Abandoning search."); // return NOP_INJECTOR; // } // // try { // Class<?> injectorClass = Class.forName(clsName + INJECTOR_SUFFIX); // //noinspection unchecked // injector = (Injector<Object>) injectorClass.newInstance(); // if (debug) Log.d(TAG, "HIT: Class loaded injection class."); // } catch (ClassNotFoundException e) { // if (debug) Log.d(TAG, "Not found. Trying superclass " + cls.getSuperclass().getName()); // injector = findInjectorForClass(cls.getSuperclass()); // } // INJECTORS.put(cls, injector); // return injector; // } // // }
import android.app.Service; import android.content.Intent; import android.os.IBinder; import com.tale.prettybundle.Extra; import com.tale.prettybundle.PrettyBundle;
package com.tale.prettybundle.sample.services; /** * Created by giang on 2/27/15. */ public class TestPrimaryTypeService extends Service { @Extra int requestId; @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) {
// Path: prettybundle/src/main/java/com/tale/prettybundle/PrettyBundle.java // public final class PrettyBundle { // public static final String INJECTOR_SUFFIX = "$$BundleInjector"; // public static final String ANDROID_PREFIX = "android."; // public static final String JAVA_PREFIX = "java."; // // private PrettyBundle() { // throw new AssertionError("No instances."); // } // // private static final String TAG = "PrettyBundle"; // private static boolean debug = false; // // static final Map<Class<?>, Injector<Object>> INJECTORS = // new LinkedHashMap<Class<?>, Injector<Object>>(); // // private static final Injector<Object> NOP_INJECTOR = new Injector<Object>() { // @Override public void inject(Object target, Bundle extras) { // // } // }; // // /** // * Control whether debug logging is enabled. // */ // public static void setDebug(boolean debug) { // PrettyBundle.debug = debug; // } // // public static void inject(Activity activity) { // if (activity == null) { // return; // } // // inject(activity, activity.getIntent().getExtras()); // } // // public static void inject(Fragment fragment) { // if (fragment == null) { // return; // } // // inject(fragment, fragment.getArguments()); // } // // public static void inject(android.support.v4.app.Fragment fragment) { // if (fragment == null) { // return; // } // // inject(fragment, fragment.getArguments()); // } // // public static void inject(Service service, Intent intent) { // if (service == null) { // return; // } // // inject(service, intent == null ? null : intent.getExtras()); // } // // private static void inject(Object target, Bundle extras) { // Class<?> targetClass = target.getClass(); // try { // if (debug) Log.d(TAG, "Looking up view injector for " + targetClass.getName()); // Injector<Object> injector = findInjectorForClass(targetClass); // if (injector != null) { // injector.inject(target, extras); // } // } catch (RuntimeException e) { // throw e; // } catch (Exception e) { // throw new RuntimeException("Unable to inject views for " + target, e); // } // } // // private static Injector<Object> findInjectorForClass(Class<?> cls) // throws IllegalAccessException, InstantiationException { // Injector<Object> injector = INJECTORS.get(cls); // if (injector != null) { // if (debug) Log.d(TAG, "HIT: Cached in injector map."); // return injector; // } // String clsName = cls.getName(); // if (clsName.startsWith(ANDROID_PREFIX) || clsName.startsWith(JAVA_PREFIX)) { // if (debug) Log.d(TAG, "MISS: Reached framework class. Abandoning search."); // return NOP_INJECTOR; // } // // try { // Class<?> injectorClass = Class.forName(clsName + INJECTOR_SUFFIX); // //noinspection unchecked // injector = (Injector<Object>) injectorClass.newInstance(); // if (debug) Log.d(TAG, "HIT: Class loaded injection class."); // } catch (ClassNotFoundException e) { // if (debug) Log.d(TAG, "Not found. Trying superclass " + cls.getSuperclass().getName()); // injector = findInjectorForClass(cls.getSuperclass()); // } // INJECTORS.put(cls, injector); // return injector; // } // // } // Path: app/src/main/java/com/tale/prettybundle/sample/services/TestPrimaryTypeService.java import android.app.Service; import android.content.Intent; import android.os.IBinder; import com.tale.prettybundle.Extra; import com.tale.prettybundle.PrettyBundle; package com.tale.prettybundle.sample.services; /** * Created by giang on 2/27/15. */ public class TestPrimaryTypeService extends Service { @Extra int requestId; @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) {
PrettyBundle.inject(this, intent);
RefineriaWeb/base_app_android
presentation/src/main/java/presentation/foundation/BasePresenterFragment.java
// Path: domain/src/main/java/domain/foundation/BaseView.java // public interface BaseView { // } // // Path: domain/src/main/java/domain/foundation/Presenter.java // public abstract class Presenter<V extends BaseView> { // protected V view; // protected final Wireframe wireframe; // private final SubscribeOn subscribeOn; // private final ObserveOn observeOn; // private final ParserException parserException; // protected final UI ui; // private final CompositeSubscription subscriptions; // // public Presenter(Wireframe wireframe, SubscribeOn subscribeOn, ObserveOn observeOn, ParserException parserException, UI ui) { // this.wireframe = wireframe; // this.subscribeOn = subscribeOn; // this.observeOn = observeOn; // this.parserException = parserException; // this.ui = ui; // this.subscriptions = new CompositeSubscription(); // } // // /** // * Called when view is required to initialize. On the Android lifecycle ecosystem, it would be onCreated. // */ // public void attachView(V view) { // this.view = view; // } // // /** // * Called when view is required to resume. On the Android lifecycle ecosystem, it would be onResume. // */ // public void resumeView() {} // // /** // * Handles observable subscriptions, not throw any exception and report it using feedback. // */ // protected <T> Disposing<T> safetyReportError(Observable<T> observable) { // Observable<T> configured = schedulers(observable) // .doOnError(throwable -> ui.showFeedback(parserException.with(throwable).react())) // .onErrorResumeNext(throwable -> Observable.empty()); // // return new Disposing(configured, subscriptions); // } // // /** // * Handles observable subscriptions, not throw any exception and report it using anchoredScreenFeedback. // */ // protected <T> Disposing<T> safetyReportErrorAnchored(Observable<T> observable) { // Observable<T> configured = schedulers(observable) // .doOnError(throwable -> ui.showAnchoredScreenFeedback(parserException.with(throwable).react())) // .onErrorResumeNext(throwable -> Observable.empty()); // // return new Disposing(configured, subscriptions); // } // // /** // * Handles observable subscriptions and not throw any exception. // */ // protected <T> Disposing<T> safety(Observable<T> observable) { // Observable<T> configured = schedulers(observable) // .onErrorResumeNext(throwable -> Observable.empty()); // // return new Disposing(configured, subscriptions); // } // // /** // * Handles observable schedulers. // */ // private <T> Observable<T> schedulers(Observable<T> observable) { // return observable.subscribeOn(subscribeOn.getScheduler()) // .observeOn(observeOn.getScheduler()); // } // // public void dispose() { // if (!subscriptions.isUnsubscribed()) { // subscriptions.clear(); // } // } // // /** // * Wrapper to hold a reference to the observable and the expected subscription. // */ // protected static class Disposing<T> { // private Observable<T> observable; // private final CompositeSubscription subscriptions; // // private Disposing(Observable<T> observable, CompositeSubscription subscriptions) { // this.observable = observable; // this.subscriptions = subscriptions; // } // // public void disposable(Disposable<T> disposable) { // subscriptions.add(disposable.subscription(observable)); // } // // public interface Disposable<T> { // Subscription subscription(Observable<T> observable); // } // } // } // // Path: presentation/src/main/java/presentation/internal/di/ApplicationComponent.java // @Singleton @Component(modules = {DomainPresentationModule.class, DataPresentationModule.class, ApplicationModule.class}) // public interface ApplicationComponent { // void inject(LaunchActivity launchActivity); // // void inject(DashBoardActivity dashBoardActivity); // void inject(UserFragment userFragment); // void inject(UsersFragment usersFragment); // void inject(SearchUserFragment searchUserFragment); // }
import domain.foundation.Presenter; import presentation.internal.di.ApplicationComponent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import javax.inject.Inject; import butterknife.ButterKnife; import domain.foundation.BaseView;
/* * Copyright 2015 RefineriaWeb * * 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 presentation.foundation; public abstract class BasePresenterFragment<P extends Presenter> extends Fragment implements BaseView { @Inject protected P presenter; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(layoutRes(), container, false); ButterKnife.bind(this, view); injectDagger(); return view; } private Integer layoutRes() { LayoutResFragment layoutRes = this.getClass().getAnnotation(LayoutResFragment.class); return layoutRes != null ? layoutRes.value() : null; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initViews(); presenter.attachView(this); } protected abstract void injectDagger(); protected void initViews() {} @Override public void onDestroyView() { super.onDestroyView(); presenter.dispose(); ButterKnife.unbind(this); } @Override public void onResume() { super.onResume(); presenter.resumeView(); }
// Path: domain/src/main/java/domain/foundation/BaseView.java // public interface BaseView { // } // // Path: domain/src/main/java/domain/foundation/Presenter.java // public abstract class Presenter<V extends BaseView> { // protected V view; // protected final Wireframe wireframe; // private final SubscribeOn subscribeOn; // private final ObserveOn observeOn; // private final ParserException parserException; // protected final UI ui; // private final CompositeSubscription subscriptions; // // public Presenter(Wireframe wireframe, SubscribeOn subscribeOn, ObserveOn observeOn, ParserException parserException, UI ui) { // this.wireframe = wireframe; // this.subscribeOn = subscribeOn; // this.observeOn = observeOn; // this.parserException = parserException; // this.ui = ui; // this.subscriptions = new CompositeSubscription(); // } // // /** // * Called when view is required to initialize. On the Android lifecycle ecosystem, it would be onCreated. // */ // public void attachView(V view) { // this.view = view; // } // // /** // * Called when view is required to resume. On the Android lifecycle ecosystem, it would be onResume. // */ // public void resumeView() {} // // /** // * Handles observable subscriptions, not throw any exception and report it using feedback. // */ // protected <T> Disposing<T> safetyReportError(Observable<T> observable) { // Observable<T> configured = schedulers(observable) // .doOnError(throwable -> ui.showFeedback(parserException.with(throwable).react())) // .onErrorResumeNext(throwable -> Observable.empty()); // // return new Disposing(configured, subscriptions); // } // // /** // * Handles observable subscriptions, not throw any exception and report it using anchoredScreenFeedback. // */ // protected <T> Disposing<T> safetyReportErrorAnchored(Observable<T> observable) { // Observable<T> configured = schedulers(observable) // .doOnError(throwable -> ui.showAnchoredScreenFeedback(parserException.with(throwable).react())) // .onErrorResumeNext(throwable -> Observable.empty()); // // return new Disposing(configured, subscriptions); // } // // /** // * Handles observable subscriptions and not throw any exception. // */ // protected <T> Disposing<T> safety(Observable<T> observable) { // Observable<T> configured = schedulers(observable) // .onErrorResumeNext(throwable -> Observable.empty()); // // return new Disposing(configured, subscriptions); // } // // /** // * Handles observable schedulers. // */ // private <T> Observable<T> schedulers(Observable<T> observable) { // return observable.subscribeOn(subscribeOn.getScheduler()) // .observeOn(observeOn.getScheduler()); // } // // public void dispose() { // if (!subscriptions.isUnsubscribed()) { // subscriptions.clear(); // } // } // // /** // * Wrapper to hold a reference to the observable and the expected subscription. // */ // protected static class Disposing<T> { // private Observable<T> observable; // private final CompositeSubscription subscriptions; // // private Disposing(Observable<T> observable, CompositeSubscription subscriptions) { // this.observable = observable; // this.subscriptions = subscriptions; // } // // public void disposable(Disposable<T> disposable) { // subscriptions.add(disposable.subscription(observable)); // } // // public interface Disposable<T> { // Subscription subscription(Observable<T> observable); // } // } // } // // Path: presentation/src/main/java/presentation/internal/di/ApplicationComponent.java // @Singleton @Component(modules = {DomainPresentationModule.class, DataPresentationModule.class, ApplicationModule.class}) // public interface ApplicationComponent { // void inject(LaunchActivity launchActivity); // // void inject(DashBoardActivity dashBoardActivity); // void inject(UserFragment userFragment); // void inject(UsersFragment usersFragment); // void inject(SearchUserFragment searchUserFragment); // } // Path: presentation/src/main/java/presentation/foundation/BasePresenterFragment.java import domain.foundation.Presenter; import presentation.internal.di.ApplicationComponent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import javax.inject.Inject; import butterknife.ButterKnife; import domain.foundation.BaseView; /* * Copyright 2015 RefineriaWeb * * 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 presentation.foundation; public abstract class BasePresenterFragment<P extends Presenter> extends Fragment implements BaseView { @Inject protected P presenter; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(layoutRes(), container, false); ButterKnife.bind(this, view); injectDagger(); return view; } private Integer layoutRes() { LayoutResFragment layoutRes = this.getClass().getAnnotation(LayoutResFragment.class); return layoutRes != null ? layoutRes.value() : null; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initViews(); presenter.attachView(this); } protected abstract void injectDagger(); protected void initViews() {} @Override public void onDestroyView() { super.onDestroyView(); presenter.dispose(); ButterKnife.unbind(this); } @Override public void onResume() { super.onResume(); presenter.resumeView(); }
protected ApplicationComponent getApplicationComponent() {
RefineriaWeb/base_app_android
domain/src/test/java/domain/sections/user_demo/detail/GetSelectedDemoUserListUseCaseTest.java
// Path: domain/src/test/java/domain/common/BaseTest.java // public abstract class BaseTest { // protected final static int WAIT = 50; // @Mock protected UI UIMock; // @Mock protected ObserveOn observeOnMock; // @Mock protected SubscribeOn subscribeOnMock; // // @Before public void setUp() { // MockitoAnnotations.initMocks(this); // when(observeOnMock.getScheduler()).thenReturn(Schedulers.newThread()); // when(subscribeOnMock.getScheduler()).thenReturn(Schedulers.newThread()); // } // } // // Path: domain/src/main/java/domain/sections/user_demo/UserDemoRepository.java // public interface UserDemoRepository extends Repository { // Observable<UserDemoEntity> searchByUserName(String nameUser); // Observable<List<UserDemoEntity>> askForUsers(); // Observable<UserDemoEntity> getSelectedUserDemoList(); // Observable<Boolean> saveSelectedUserDemoList(UserDemoEntity user); // } // // Path: domain/src/main/java/domain/sections/user_demo/entities/UserDemoEntity.java // @AllArgsConstructor(access = AccessLevel.PROTECTED) // @Data // public class UserDemoEntity { // private final int id; // private final String login; // private String avatar_url = ""; // // public String getAvatarUrl() { // if (avatar_url.isEmpty()) return avatar_url; // return avatar_url.split("\\?")[0]; // } // }
import org.junit.Test; import org.mockito.Mock; import domain.common.BaseTest; import domain.sections.user_demo.UserDemoRepository; import domain.sections.user_demo.entities.UserDemoEntity; import rx.Observable; import rx.observers.TestSubscriber; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.when;
/* * Copyright 2015 RefineriaWeb * * 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 domain.sections.user_demo.detail; public class GetSelectedDemoUserListUseCaseTest extends BaseTest { private GetSelectedDemoUserListUseCase getSelectedDemoUserListUseCaseUT;
// Path: domain/src/test/java/domain/common/BaseTest.java // public abstract class BaseTest { // protected final static int WAIT = 50; // @Mock protected UI UIMock; // @Mock protected ObserveOn observeOnMock; // @Mock protected SubscribeOn subscribeOnMock; // // @Before public void setUp() { // MockitoAnnotations.initMocks(this); // when(observeOnMock.getScheduler()).thenReturn(Schedulers.newThread()); // when(subscribeOnMock.getScheduler()).thenReturn(Schedulers.newThread()); // } // } // // Path: domain/src/main/java/domain/sections/user_demo/UserDemoRepository.java // public interface UserDemoRepository extends Repository { // Observable<UserDemoEntity> searchByUserName(String nameUser); // Observable<List<UserDemoEntity>> askForUsers(); // Observable<UserDemoEntity> getSelectedUserDemoList(); // Observable<Boolean> saveSelectedUserDemoList(UserDemoEntity user); // } // // Path: domain/src/main/java/domain/sections/user_demo/entities/UserDemoEntity.java // @AllArgsConstructor(access = AccessLevel.PROTECTED) // @Data // public class UserDemoEntity { // private final int id; // private final String login; // private String avatar_url = ""; // // public String getAvatarUrl() { // if (avatar_url.isEmpty()) return avatar_url; // return avatar_url.split("\\?")[0]; // } // } // Path: domain/src/test/java/domain/sections/user_demo/detail/GetSelectedDemoUserListUseCaseTest.java import org.junit.Test; import org.mockito.Mock; import domain.common.BaseTest; import domain.sections.user_demo.UserDemoRepository; import domain.sections.user_demo.entities.UserDemoEntity; import rx.Observable; import rx.observers.TestSubscriber; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.when; /* * Copyright 2015 RefineriaWeb * * 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 domain.sections.user_demo.detail; public class GetSelectedDemoUserListUseCaseTest extends BaseTest { private GetSelectedDemoUserListUseCase getSelectedDemoUserListUseCaseUT;
@Mock protected UserDemoRepository userDemoRepositoryMock;
RefineriaWeb/base_app_android
domain/src/test/java/domain/sections/user_demo/detail/GetSelectedDemoUserListUseCaseTest.java
// Path: domain/src/test/java/domain/common/BaseTest.java // public abstract class BaseTest { // protected final static int WAIT = 50; // @Mock protected UI UIMock; // @Mock protected ObserveOn observeOnMock; // @Mock protected SubscribeOn subscribeOnMock; // // @Before public void setUp() { // MockitoAnnotations.initMocks(this); // when(observeOnMock.getScheduler()).thenReturn(Schedulers.newThread()); // when(subscribeOnMock.getScheduler()).thenReturn(Schedulers.newThread()); // } // } // // Path: domain/src/main/java/domain/sections/user_demo/UserDemoRepository.java // public interface UserDemoRepository extends Repository { // Observable<UserDemoEntity> searchByUserName(String nameUser); // Observable<List<UserDemoEntity>> askForUsers(); // Observable<UserDemoEntity> getSelectedUserDemoList(); // Observable<Boolean> saveSelectedUserDemoList(UserDemoEntity user); // } // // Path: domain/src/main/java/domain/sections/user_demo/entities/UserDemoEntity.java // @AllArgsConstructor(access = AccessLevel.PROTECTED) // @Data // public class UserDemoEntity { // private final int id; // private final String login; // private String avatar_url = ""; // // public String getAvatarUrl() { // if (avatar_url.isEmpty()) return avatar_url; // return avatar_url.split("\\?")[0]; // } // }
import org.junit.Test; import org.mockito.Mock; import domain.common.BaseTest; import domain.sections.user_demo.UserDemoRepository; import domain.sections.user_demo.entities.UserDemoEntity; import rx.Observable; import rx.observers.TestSubscriber; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.when;
/* * Copyright 2015 RefineriaWeb * * 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 domain.sections.user_demo.detail; public class GetSelectedDemoUserListUseCaseTest extends BaseTest { private GetSelectedDemoUserListUseCase getSelectedDemoUserListUseCaseUT; @Mock protected UserDemoRepository userDemoRepositoryMock;
// Path: domain/src/test/java/domain/common/BaseTest.java // public abstract class BaseTest { // protected final static int WAIT = 50; // @Mock protected UI UIMock; // @Mock protected ObserveOn observeOnMock; // @Mock protected SubscribeOn subscribeOnMock; // // @Before public void setUp() { // MockitoAnnotations.initMocks(this); // when(observeOnMock.getScheduler()).thenReturn(Schedulers.newThread()); // when(subscribeOnMock.getScheduler()).thenReturn(Schedulers.newThread()); // } // } // // Path: domain/src/main/java/domain/sections/user_demo/UserDemoRepository.java // public interface UserDemoRepository extends Repository { // Observable<UserDemoEntity> searchByUserName(String nameUser); // Observable<List<UserDemoEntity>> askForUsers(); // Observable<UserDemoEntity> getSelectedUserDemoList(); // Observable<Boolean> saveSelectedUserDemoList(UserDemoEntity user); // } // // Path: domain/src/main/java/domain/sections/user_demo/entities/UserDemoEntity.java // @AllArgsConstructor(access = AccessLevel.PROTECTED) // @Data // public class UserDemoEntity { // private final int id; // private final String login; // private String avatar_url = ""; // // public String getAvatarUrl() { // if (avatar_url.isEmpty()) return avatar_url; // return avatar_url.split("\\?")[0]; // } // } // Path: domain/src/test/java/domain/sections/user_demo/detail/GetSelectedDemoUserListUseCaseTest.java import org.junit.Test; import org.mockito.Mock; import domain.common.BaseTest; import domain.sections.user_demo.UserDemoRepository; import domain.sections.user_demo.entities.UserDemoEntity; import rx.Observable; import rx.observers.TestSubscriber; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.when; /* * Copyright 2015 RefineriaWeb * * 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 domain.sections.user_demo.detail; public class GetSelectedDemoUserListUseCaseTest extends BaseTest { private GetSelectedDemoUserListUseCase getSelectedDemoUserListUseCaseUT; @Mock protected UserDemoRepository userDemoRepositoryMock;
@Mock protected UserDemoEntity userDemoEntityMock;
RefineriaWeb/base_app_android
domain/src/main/java/domain/internal/di/DomainModule.java
// Path: domain/src/main/java/domain/foundation/schedulers/SubscribeOn.java // public interface SubscribeOn { // Scheduler getScheduler(); // }
import javax.inject.Singleton; import domain.foundation.schedulers.SubscribeOn; import dagger.Module; import dagger.Provides; import rx.schedulers.Schedulers;
/* * Copyright 2015 RefineriaWeb * * 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 domain.internal.di; /** * Dagger module for domain layer. */ @Module public class DomainModule { /** * Provides the Scheduler to be used by any subscriber on subscribing. * The operation will be executed in a new thread, this way the ui won't be block */
// Path: domain/src/main/java/domain/foundation/schedulers/SubscribeOn.java // public interface SubscribeOn { // Scheduler getScheduler(); // } // Path: domain/src/main/java/domain/internal/di/DomainModule.java import javax.inject.Singleton; import domain.foundation.schedulers.SubscribeOn; import dagger.Module; import dagger.Provides; import rx.schedulers.Schedulers; /* * Copyright 2015 RefineriaWeb * * 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 domain.internal.di; /** * Dagger module for domain layer. */ @Module public class DomainModule { /** * Provides the Scheduler to be used by any subscriber on subscribing. * The operation will be executed in a new thread, this way the ui won't be block */
@Singleton @Provides SubscribeOn provideSubscribeOn() {
RefineriaWeb/base_app_android
data/src/main/java/data/sections/user_demo/UserDemoDataRepository.java
// Path: data/src/main/java/data/cache/RxProviders.java // public interface RxProviders { // Observable<UserDemoEntity> getSelectedUserDemoList(Observable<UserDemoEntity> oUserSelected, EvictProvider evictProvider); // } // // Path: data/src/main/java/data/net/RestApi.java // public interface RestApi { // String URL_BASE = "https://api.github.com"; // String HEADER_API_VERSION = "Accept: application/vnd.github.v3+json"; // // @Headers({HEADER_API_VERSION}) // @GET("/users/{username}") Observable<Response<UserDemoEntity>> getUser(@Path("username") String username); // // @Headers({HEADER_API_VERSION}) // @GET("/users") Observable<Response<List<UserDemoEntity>>> getUsers(); // } // // Path: data/src/main/java/data/sections/DataRepository.java // public abstract class DataRepository implements Repository { // protected final RestApi restApi; // protected final RxProviders rxProviders; // protected final UI UI; // // public DataRepository(RestApi restApi, RxProviders rxProviders, UI ui) { // this.restApi = restApi; // this.rxProviders = rxProviders; // this.UI = ui; // } // // protected void handleError(Response response) { // if (response.isSuccess()) return; // // try { // ResponseError responseError = new Gson().fromJson(response.errorBody().string(), ResponseError.class); // throw new RuntimeException(responseError.getMessage()); // } catch (JsonParseException |IOException exception) { // throw new RuntimeException(); // } // } // // @Data private static class ResponseError { // private final String message; // } // // protected Observable buildObservableError(String message) { // return Observable.create(subscriber -> subscriber.onError(new RuntimeException(message))); // } // } // // Path: data/src/main/java/data/sections/UI.java // public interface UI { // Observable<String> genericError(); // } // // Path: domain/src/main/java/domain/sections/user_demo/UserDemoRepository.java // public interface UserDemoRepository extends Repository { // Observable<UserDemoEntity> searchByUserName(String nameUser); // Observable<List<UserDemoEntity>> askForUsers(); // Observable<UserDemoEntity> getSelectedUserDemoList(); // Observable<Boolean> saveSelectedUserDemoList(UserDemoEntity user); // } // // Path: domain/src/main/java/domain/sections/user_demo/entities/UserDemoEntity.java // @AllArgsConstructor(access = AccessLevel.PROTECTED) // @Data // public class UserDemoEntity { // private final int id; // private final String login; // private String avatar_url = ""; // // public String getAvatarUrl() { // if (avatar_url.isEmpty()) return avatar_url; // return avatar_url.split("\\?")[0]; // } // }
import java.util.List; import javax.inject.Inject; import data.cache.RxProviders; import data.net.RestApi; import data.sections.DataRepository; import data.sections.UI; import domain.sections.user_demo.UserDemoRepository; import domain.sections.user_demo.entities.UserDemoEntity; import io.rx_cache.EvictProvider; import rx.Observable;
/* * Copyright 2015 RefineriaWeb * * 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 data.sections.user_demo; public class UserDemoDataRepository extends DataRepository implements UserDemoRepository { @Inject public UserDemoDataRepository(RestApi restApi, RxProviders rxProviders, UI ui) { super(restApi, rxProviders, ui); }
// Path: data/src/main/java/data/cache/RxProviders.java // public interface RxProviders { // Observable<UserDemoEntity> getSelectedUserDemoList(Observable<UserDemoEntity> oUserSelected, EvictProvider evictProvider); // } // // Path: data/src/main/java/data/net/RestApi.java // public interface RestApi { // String URL_BASE = "https://api.github.com"; // String HEADER_API_VERSION = "Accept: application/vnd.github.v3+json"; // // @Headers({HEADER_API_VERSION}) // @GET("/users/{username}") Observable<Response<UserDemoEntity>> getUser(@Path("username") String username); // // @Headers({HEADER_API_VERSION}) // @GET("/users") Observable<Response<List<UserDemoEntity>>> getUsers(); // } // // Path: data/src/main/java/data/sections/DataRepository.java // public abstract class DataRepository implements Repository { // protected final RestApi restApi; // protected final RxProviders rxProviders; // protected final UI UI; // // public DataRepository(RestApi restApi, RxProviders rxProviders, UI ui) { // this.restApi = restApi; // this.rxProviders = rxProviders; // this.UI = ui; // } // // protected void handleError(Response response) { // if (response.isSuccess()) return; // // try { // ResponseError responseError = new Gson().fromJson(response.errorBody().string(), ResponseError.class); // throw new RuntimeException(responseError.getMessage()); // } catch (JsonParseException |IOException exception) { // throw new RuntimeException(); // } // } // // @Data private static class ResponseError { // private final String message; // } // // protected Observable buildObservableError(String message) { // return Observable.create(subscriber -> subscriber.onError(new RuntimeException(message))); // } // } // // Path: data/src/main/java/data/sections/UI.java // public interface UI { // Observable<String> genericError(); // } // // Path: domain/src/main/java/domain/sections/user_demo/UserDemoRepository.java // public interface UserDemoRepository extends Repository { // Observable<UserDemoEntity> searchByUserName(String nameUser); // Observable<List<UserDemoEntity>> askForUsers(); // Observable<UserDemoEntity> getSelectedUserDemoList(); // Observable<Boolean> saveSelectedUserDemoList(UserDemoEntity user); // } // // Path: domain/src/main/java/domain/sections/user_demo/entities/UserDemoEntity.java // @AllArgsConstructor(access = AccessLevel.PROTECTED) // @Data // public class UserDemoEntity { // private final int id; // private final String login; // private String avatar_url = ""; // // public String getAvatarUrl() { // if (avatar_url.isEmpty()) return avatar_url; // return avatar_url.split("\\?")[0]; // } // } // Path: data/src/main/java/data/sections/user_demo/UserDemoDataRepository.java import java.util.List; import javax.inject.Inject; import data.cache.RxProviders; import data.net.RestApi; import data.sections.DataRepository; import data.sections.UI; import domain.sections.user_demo.UserDemoRepository; import domain.sections.user_demo.entities.UserDemoEntity; import io.rx_cache.EvictProvider; import rx.Observable; /* * Copyright 2015 RefineriaWeb * * 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 data.sections.user_demo; public class UserDemoDataRepository extends DataRepository implements UserDemoRepository { @Inject public UserDemoDataRepository(RestApi restApi, RxProviders rxProviders, UI ui) { super(restApi, rxProviders, ui); }
@Override public Observable<UserDemoEntity> searchByUserName(final String username) {
RefineriaWeb/base_app_android
domain/src/test/java/domain/foundation/PresenterSubscriptionsTest.java
// Path: domain/src/test/java/domain/common/BaseTest.java // public abstract class BaseTest { // protected final static int WAIT = 50; // @Mock protected UI UIMock; // @Mock protected ObserveOn observeOnMock; // @Mock protected SubscribeOn subscribeOnMock; // // @Before public void setUp() { // MockitoAnnotations.initMocks(this); // when(observeOnMock.getScheduler()).thenReturn(Schedulers.newThread()); // when(subscribeOnMock.getScheduler()).thenReturn(Schedulers.newThread()); // } // } // // Path: domain/src/main/java/domain/foundation/helpers/ParserException.java // public class ParserException extends UseCase<String> { // private Throwable throwable; // // @Inject public ParserException(UI ui) { // super(ui); // } // // public ParserException with(Throwable throwable) { // this.throwable = throwable; // return this; // } // // @Override public Observable<String> react() { // String message = throwable.getMessage(); // // if (throwable instanceof CompositeException) { // message += System.getProperty("line.separator"); // CompositeException compositeException = (CompositeException) throwable; // // for (Throwable exception : compositeException.getExceptions()) { // String exceptionName = exception.getClass().getSimpleName(); // String exceptionMessage = exception.getMessage() != null ? exception.getMessage() : ""; // message += exceptionName + " -> " + exceptionMessage + System.getProperty("line.separator"); // } // } // // return Observable.just(message); // } // }
import org.junit.Test; import domain.common.BaseTest; import domain.foundation.helpers.ParserException; import rx.Observable; import rx.observers.TestSubscriber; import rx.schedulers.Schedulers;
package domain.foundation; /** * Created by victor on 01/02/16. */ public class PresenterSubscriptionsTest extends BaseTest { private Presenter presenterUT; @Override public void setUp() { super.setUp();
// Path: domain/src/test/java/domain/common/BaseTest.java // public abstract class BaseTest { // protected final static int WAIT = 50; // @Mock protected UI UIMock; // @Mock protected ObserveOn observeOnMock; // @Mock protected SubscribeOn subscribeOnMock; // // @Before public void setUp() { // MockitoAnnotations.initMocks(this); // when(observeOnMock.getScheduler()).thenReturn(Schedulers.newThread()); // when(subscribeOnMock.getScheduler()).thenReturn(Schedulers.newThread()); // } // } // // Path: domain/src/main/java/domain/foundation/helpers/ParserException.java // public class ParserException extends UseCase<String> { // private Throwable throwable; // // @Inject public ParserException(UI ui) { // super(ui); // } // // public ParserException with(Throwable throwable) { // this.throwable = throwable; // return this; // } // // @Override public Observable<String> react() { // String message = throwable.getMessage(); // // if (throwable instanceof CompositeException) { // message += System.getProperty("line.separator"); // CompositeException compositeException = (CompositeException) throwable; // // for (Throwable exception : compositeException.getExceptions()) { // String exceptionName = exception.getClass().getSimpleName(); // String exceptionMessage = exception.getMessage() != null ? exception.getMessage() : ""; // message += exceptionName + " -> " + exceptionMessage + System.getProperty("line.separator"); // } // } // // return Observable.just(message); // } // } // Path: domain/src/test/java/domain/foundation/PresenterSubscriptionsTest.java import org.junit.Test; import domain.common.BaseTest; import domain.foundation.helpers.ParserException; import rx.Observable; import rx.observers.TestSubscriber; import rx.schedulers.Schedulers; package domain.foundation; /** * Created by victor on 01/02/16. */ public class PresenterSubscriptionsTest extends BaseTest { private Presenter presenterUT; @Override public void setUp() { super.setUp();
presenterUT = new Presenter(null, subscribeOnMock, observeOnMock, new ParserException(UIMock), UIMock) {};
RefineriaWeb/base_app_android
domain/src/main/java/domain/sections/user_demo/list/SaveUserDemoSelectedListUseCase.java
// Path: domain/src/main/java/domain/foundation/UseCase.java // public abstract class UseCase<D> { // protected final UI ui; // // public UseCase(UI ui) { // this.ui = ui; // } // // /** // * Observable built for every use case // */ // public abstract Observable<D> react(); // } // // Path: domain/src/main/java/domain/sections/UI.java // public interface UI { // Observable<String> errorNonEmptyFields(); // Subscription showFeedback(Observable<String> oFeedback); // Subscription showAnchoredScreenFeedback(Observable<String> oFeedback); // // void showLoading(); // void hideLoading(); // } // // Path: domain/src/main/java/domain/sections/user_demo/UserDemoRepository.java // public interface UserDemoRepository extends Repository { // Observable<UserDemoEntity> searchByUserName(String nameUser); // Observable<List<UserDemoEntity>> askForUsers(); // Observable<UserDemoEntity> getSelectedUserDemoList(); // Observable<Boolean> saveSelectedUserDemoList(UserDemoEntity user); // } // // Path: domain/src/main/java/domain/sections/user_demo/entities/UserDemoEntity.java // @AllArgsConstructor(access = AccessLevel.PROTECTED) // @Data // public class UserDemoEntity { // private final int id; // private final String login; // private String avatar_url = ""; // // public String getAvatarUrl() { // if (avatar_url.isEmpty()) return avatar_url; // return avatar_url.split("\\?")[0]; // } // }
import javax.inject.Inject; import domain.foundation.UseCase; import domain.sections.UI; import domain.sections.user_demo.UserDemoRepository; import domain.sections.user_demo.entities.UserDemoEntity; import rx.Observable;
/* * Copyright 2015 RefineriaWeb * * 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 domain.sections.user_demo.list; public class SaveUserDemoSelectedListUseCase extends UseCase<Boolean> { private final UserDemoRepository repository;
// Path: domain/src/main/java/domain/foundation/UseCase.java // public abstract class UseCase<D> { // protected final UI ui; // // public UseCase(UI ui) { // this.ui = ui; // } // // /** // * Observable built for every use case // */ // public abstract Observable<D> react(); // } // // Path: domain/src/main/java/domain/sections/UI.java // public interface UI { // Observable<String> errorNonEmptyFields(); // Subscription showFeedback(Observable<String> oFeedback); // Subscription showAnchoredScreenFeedback(Observable<String> oFeedback); // // void showLoading(); // void hideLoading(); // } // // Path: domain/src/main/java/domain/sections/user_demo/UserDemoRepository.java // public interface UserDemoRepository extends Repository { // Observable<UserDemoEntity> searchByUserName(String nameUser); // Observable<List<UserDemoEntity>> askForUsers(); // Observable<UserDemoEntity> getSelectedUserDemoList(); // Observable<Boolean> saveSelectedUserDemoList(UserDemoEntity user); // } // // Path: domain/src/main/java/domain/sections/user_demo/entities/UserDemoEntity.java // @AllArgsConstructor(access = AccessLevel.PROTECTED) // @Data // public class UserDemoEntity { // private final int id; // private final String login; // private String avatar_url = ""; // // public String getAvatarUrl() { // if (avatar_url.isEmpty()) return avatar_url; // return avatar_url.split("\\?")[0]; // } // } // Path: domain/src/main/java/domain/sections/user_demo/list/SaveUserDemoSelectedListUseCase.java import javax.inject.Inject; import domain.foundation.UseCase; import domain.sections.UI; import domain.sections.user_demo.UserDemoRepository; import domain.sections.user_demo.entities.UserDemoEntity; import rx.Observable; /* * Copyright 2015 RefineriaWeb * * 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 domain.sections.user_demo.list; public class SaveUserDemoSelectedListUseCase extends UseCase<Boolean> { private final UserDemoRepository repository;
private UserDemoEntity userDemoEntity;
RefineriaWeb/base_app_android
domain/src/main/java/domain/sections/user_demo/list/SaveUserDemoSelectedListUseCase.java
// Path: domain/src/main/java/domain/foundation/UseCase.java // public abstract class UseCase<D> { // protected final UI ui; // // public UseCase(UI ui) { // this.ui = ui; // } // // /** // * Observable built for every use case // */ // public abstract Observable<D> react(); // } // // Path: domain/src/main/java/domain/sections/UI.java // public interface UI { // Observable<String> errorNonEmptyFields(); // Subscription showFeedback(Observable<String> oFeedback); // Subscription showAnchoredScreenFeedback(Observable<String> oFeedback); // // void showLoading(); // void hideLoading(); // } // // Path: domain/src/main/java/domain/sections/user_demo/UserDemoRepository.java // public interface UserDemoRepository extends Repository { // Observable<UserDemoEntity> searchByUserName(String nameUser); // Observable<List<UserDemoEntity>> askForUsers(); // Observable<UserDemoEntity> getSelectedUserDemoList(); // Observable<Boolean> saveSelectedUserDemoList(UserDemoEntity user); // } // // Path: domain/src/main/java/domain/sections/user_demo/entities/UserDemoEntity.java // @AllArgsConstructor(access = AccessLevel.PROTECTED) // @Data // public class UserDemoEntity { // private final int id; // private final String login; // private String avatar_url = ""; // // public String getAvatarUrl() { // if (avatar_url.isEmpty()) return avatar_url; // return avatar_url.split("\\?")[0]; // } // }
import javax.inject.Inject; import domain.foundation.UseCase; import domain.sections.UI; import domain.sections.user_demo.UserDemoRepository; import domain.sections.user_demo.entities.UserDemoEntity; import rx.Observable;
/* * Copyright 2015 RefineriaWeb * * 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 domain.sections.user_demo.list; public class SaveUserDemoSelectedListUseCase extends UseCase<Boolean> { private final UserDemoRepository repository; private UserDemoEntity userDemoEntity;
// Path: domain/src/main/java/domain/foundation/UseCase.java // public abstract class UseCase<D> { // protected final UI ui; // // public UseCase(UI ui) { // this.ui = ui; // } // // /** // * Observable built for every use case // */ // public abstract Observable<D> react(); // } // // Path: domain/src/main/java/domain/sections/UI.java // public interface UI { // Observable<String> errorNonEmptyFields(); // Subscription showFeedback(Observable<String> oFeedback); // Subscription showAnchoredScreenFeedback(Observable<String> oFeedback); // // void showLoading(); // void hideLoading(); // } // // Path: domain/src/main/java/domain/sections/user_demo/UserDemoRepository.java // public interface UserDemoRepository extends Repository { // Observable<UserDemoEntity> searchByUserName(String nameUser); // Observable<List<UserDemoEntity>> askForUsers(); // Observable<UserDemoEntity> getSelectedUserDemoList(); // Observable<Boolean> saveSelectedUserDemoList(UserDemoEntity user); // } // // Path: domain/src/main/java/domain/sections/user_demo/entities/UserDemoEntity.java // @AllArgsConstructor(access = AccessLevel.PROTECTED) // @Data // public class UserDemoEntity { // private final int id; // private final String login; // private String avatar_url = ""; // // public String getAvatarUrl() { // if (avatar_url.isEmpty()) return avatar_url; // return avatar_url.split("\\?")[0]; // } // } // Path: domain/src/main/java/domain/sections/user_demo/list/SaveUserDemoSelectedListUseCase.java import javax.inject.Inject; import domain.foundation.UseCase; import domain.sections.UI; import domain.sections.user_demo.UserDemoRepository; import domain.sections.user_demo.entities.UserDemoEntity; import rx.Observable; /* * Copyright 2015 RefineriaWeb * * 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 domain.sections.user_demo.list; public class SaveUserDemoSelectedListUseCase extends UseCase<Boolean> { private final UserDemoRepository repository; private UserDemoEntity userDemoEntity;
@Inject public SaveUserDemoSelectedListUseCase(UI ui, UserDemoRepository repository) {