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 |
|---|---|---|---|---|---|---|
guigarage/ObserverPattern | impl/src/main/java/com/guigarage/examples/SwingBindingExample.java | // Path: impl/src/main/java/com/guigarage/binding/SwingBinding.java
// public class SwingBinding {
//
// private static Executor backgroundExecutor = Executors.newSingleThreadExecutor();
//
// public static <T> ConvertableBidirectionalBindable<T> bind(final Component component, final String attribute) {
// return new ConvertableBidirectionalBindable<T>() {
//
// private AtomicBoolean bindingCalled = new AtomicBoolean(false);
//
// private Consumer<Throwable> errorHandler = e -> e.printStackTrace();
//
// private Lock bindingLock = new ReentrantLock();
//
// private <U> U callLocked(Supplier<U> supplier) {
// bindingLock.lock();
// try {
// return supplier.get();
// } finally {
// bindingLock.unlock();
// }
// }
//
// private void callLocked(Runnable runnable) {
// callLocked(() -> {
// runnable.run();
// return null;
// });
// }
//
// @Override
// public <U> Subscription bidirectionalTo(Property<U> property, Function<U, T> converter, Function<T, U> converter2) {
// try {
// final PropertyDescriptor propertyDescriptor = new PropertyDescriptor(attribute, component.getClass());
// final PropertyEditor propertyEditor = propertyDescriptor.createPropertyEditor(component);
// Subscription subscription = bind(property, converter, propertyEditor);
//
// PropertyChangeListener listener = e -> {
// if (!bindingCalled.get()) {
// bindingCalled.set(true);
// try {
// backgroundExecutor.execute(() -> {
// callLocked(() -> {
// try {
// property.setValue(converter2.apply((T) e.getNewValue()));
// } catch (Exception ex) {
// SwingUtilities.invokeLater(() -> {
// errorHandler.accept(ex);
// });
// }
// });
// });
// } catch (Exception e1) {
// errorHandler.accept(e1);
// } finally {
// bindingCalled.set(false);
// }
// }
// };
//
// component.addPropertyChangeListener(listener);
//
// return () -> {
// component.removePropertyChangeListener(listener);
// subscription.unsubscribe();
// };
// } catch (Exception e1) {
// throw new RuntimeException("Can not bind!", e1);
// }
// }
//
// @Override
// public <U> Subscription to(Observable<U> observable, Function<U, T> converter) {
// try {
// final PropertyDescriptor propertyDescriptor = new PropertyDescriptor(attribute, component.getClass());
// final PropertyEditor propertyEditor = propertyDescriptor.createPropertyEditor(component);
// return bind(observable, converter, propertyEditor);
// } catch (Exception e1) {
// throw new RuntimeException("Can not bind!", e1);
// }
// }
//
// private <U> Subscription bind(Observable<U> observable, Function<U, T> converter, PropertyEditor propertyEditor) {
// return observable.onChanged(e -> {
// callLocked(() -> {
// try {
// SwingUtilities.invokeAndWait(() -> {
// if (!bindingCalled.get()) {
// bindingCalled.set(true);
// try {
// propertyEditor.setValue(converter.apply(e.getValue()));
// } catch (Exception e1) {
// errorHandler.accept(e1);
// } finally {
// bindingCalled.set(false);
// }
// }
// });
// } catch (Exception e1) {
// SwingUtilities.invokeLater(() -> {
// errorHandler.accept(e1);
// });
// }
// });
// });
// }
//
// @Override
// public ConvertableBindable<T> withErrorHandler(Consumer<Throwable> handler) {
// this.errorHandler = handler;
// return this;
// }
//
// };
// }
// }
//
// Path: impl/src/main/java/com/guigarage/observer/BasicProperty.java
// public class BasicProperty<V> extends BasicObservable<V> implements Property<V> {
//
// @Override
// public void setValue(V value) {
// updateValue(value);
// }
// }
//
// Path: api/src/main/java/javax/observer/Property.java
// public interface Property<V> extends Observable<V> {
//
// /**
// * Replaces the internal value with the given new value. This should end in calling the
// * {@link ValueChangeListener#valueChanged(ValueChangeEvent)} method on all registered
// * listeners.
// * @param value the new value
// */
// void setValue(V value);
// }
| import com.guigarage.binding.SwingBinding;
import com.guigarage.observer.BasicProperty;
import javax.observer.Property;
import javax.swing.JTextField; | package com.guigarage.examples;
public class SwingBindingExample {
public static void main(String[] args) {
| // Path: impl/src/main/java/com/guigarage/binding/SwingBinding.java
// public class SwingBinding {
//
// private static Executor backgroundExecutor = Executors.newSingleThreadExecutor();
//
// public static <T> ConvertableBidirectionalBindable<T> bind(final Component component, final String attribute) {
// return new ConvertableBidirectionalBindable<T>() {
//
// private AtomicBoolean bindingCalled = new AtomicBoolean(false);
//
// private Consumer<Throwable> errorHandler = e -> e.printStackTrace();
//
// private Lock bindingLock = new ReentrantLock();
//
// private <U> U callLocked(Supplier<U> supplier) {
// bindingLock.lock();
// try {
// return supplier.get();
// } finally {
// bindingLock.unlock();
// }
// }
//
// private void callLocked(Runnable runnable) {
// callLocked(() -> {
// runnable.run();
// return null;
// });
// }
//
// @Override
// public <U> Subscription bidirectionalTo(Property<U> property, Function<U, T> converter, Function<T, U> converter2) {
// try {
// final PropertyDescriptor propertyDescriptor = new PropertyDescriptor(attribute, component.getClass());
// final PropertyEditor propertyEditor = propertyDescriptor.createPropertyEditor(component);
// Subscription subscription = bind(property, converter, propertyEditor);
//
// PropertyChangeListener listener = e -> {
// if (!bindingCalled.get()) {
// bindingCalled.set(true);
// try {
// backgroundExecutor.execute(() -> {
// callLocked(() -> {
// try {
// property.setValue(converter2.apply((T) e.getNewValue()));
// } catch (Exception ex) {
// SwingUtilities.invokeLater(() -> {
// errorHandler.accept(ex);
// });
// }
// });
// });
// } catch (Exception e1) {
// errorHandler.accept(e1);
// } finally {
// bindingCalled.set(false);
// }
// }
// };
//
// component.addPropertyChangeListener(listener);
//
// return () -> {
// component.removePropertyChangeListener(listener);
// subscription.unsubscribe();
// };
// } catch (Exception e1) {
// throw new RuntimeException("Can not bind!", e1);
// }
// }
//
// @Override
// public <U> Subscription to(Observable<U> observable, Function<U, T> converter) {
// try {
// final PropertyDescriptor propertyDescriptor = new PropertyDescriptor(attribute, component.getClass());
// final PropertyEditor propertyEditor = propertyDescriptor.createPropertyEditor(component);
// return bind(observable, converter, propertyEditor);
// } catch (Exception e1) {
// throw new RuntimeException("Can not bind!", e1);
// }
// }
//
// private <U> Subscription bind(Observable<U> observable, Function<U, T> converter, PropertyEditor propertyEditor) {
// return observable.onChanged(e -> {
// callLocked(() -> {
// try {
// SwingUtilities.invokeAndWait(() -> {
// if (!bindingCalled.get()) {
// bindingCalled.set(true);
// try {
// propertyEditor.setValue(converter.apply(e.getValue()));
// } catch (Exception e1) {
// errorHandler.accept(e1);
// } finally {
// bindingCalled.set(false);
// }
// }
// });
// } catch (Exception e1) {
// SwingUtilities.invokeLater(() -> {
// errorHandler.accept(e1);
// });
// }
// });
// });
// }
//
// @Override
// public ConvertableBindable<T> withErrorHandler(Consumer<Throwable> handler) {
// this.errorHandler = handler;
// return this;
// }
//
// };
// }
// }
//
// Path: impl/src/main/java/com/guigarage/observer/BasicProperty.java
// public class BasicProperty<V> extends BasicObservable<V> implements Property<V> {
//
// @Override
// public void setValue(V value) {
// updateValue(value);
// }
// }
//
// Path: api/src/main/java/javax/observer/Property.java
// public interface Property<V> extends Observable<V> {
//
// /**
// * Replaces the internal value with the given new value. This should end in calling the
// * {@link ValueChangeListener#valueChanged(ValueChangeEvent)} method on all registered
// * listeners.
// * @param value the new value
// */
// void setValue(V value);
// }
// Path: impl/src/main/java/com/guigarage/examples/SwingBindingExample.java
import com.guigarage.binding.SwingBinding;
import com.guigarage.observer.BasicProperty;
import javax.observer.Property;
import javax.swing.JTextField;
package com.guigarage.examples;
public class SwingBindingExample {
public static void main(String[] args) {
| Property<String> databaseBackgroundProperty = new BasicProperty<>(); |
guigarage/ObserverPattern | impl/src/main/java/com/guigarage/examples/SwingBindingExample.java | // Path: impl/src/main/java/com/guigarage/binding/SwingBinding.java
// public class SwingBinding {
//
// private static Executor backgroundExecutor = Executors.newSingleThreadExecutor();
//
// public static <T> ConvertableBidirectionalBindable<T> bind(final Component component, final String attribute) {
// return new ConvertableBidirectionalBindable<T>() {
//
// private AtomicBoolean bindingCalled = new AtomicBoolean(false);
//
// private Consumer<Throwable> errorHandler = e -> e.printStackTrace();
//
// private Lock bindingLock = new ReentrantLock();
//
// private <U> U callLocked(Supplier<U> supplier) {
// bindingLock.lock();
// try {
// return supplier.get();
// } finally {
// bindingLock.unlock();
// }
// }
//
// private void callLocked(Runnable runnable) {
// callLocked(() -> {
// runnable.run();
// return null;
// });
// }
//
// @Override
// public <U> Subscription bidirectionalTo(Property<U> property, Function<U, T> converter, Function<T, U> converter2) {
// try {
// final PropertyDescriptor propertyDescriptor = new PropertyDescriptor(attribute, component.getClass());
// final PropertyEditor propertyEditor = propertyDescriptor.createPropertyEditor(component);
// Subscription subscription = bind(property, converter, propertyEditor);
//
// PropertyChangeListener listener = e -> {
// if (!bindingCalled.get()) {
// bindingCalled.set(true);
// try {
// backgroundExecutor.execute(() -> {
// callLocked(() -> {
// try {
// property.setValue(converter2.apply((T) e.getNewValue()));
// } catch (Exception ex) {
// SwingUtilities.invokeLater(() -> {
// errorHandler.accept(ex);
// });
// }
// });
// });
// } catch (Exception e1) {
// errorHandler.accept(e1);
// } finally {
// bindingCalled.set(false);
// }
// }
// };
//
// component.addPropertyChangeListener(listener);
//
// return () -> {
// component.removePropertyChangeListener(listener);
// subscription.unsubscribe();
// };
// } catch (Exception e1) {
// throw new RuntimeException("Can not bind!", e1);
// }
// }
//
// @Override
// public <U> Subscription to(Observable<U> observable, Function<U, T> converter) {
// try {
// final PropertyDescriptor propertyDescriptor = new PropertyDescriptor(attribute, component.getClass());
// final PropertyEditor propertyEditor = propertyDescriptor.createPropertyEditor(component);
// return bind(observable, converter, propertyEditor);
// } catch (Exception e1) {
// throw new RuntimeException("Can not bind!", e1);
// }
// }
//
// private <U> Subscription bind(Observable<U> observable, Function<U, T> converter, PropertyEditor propertyEditor) {
// return observable.onChanged(e -> {
// callLocked(() -> {
// try {
// SwingUtilities.invokeAndWait(() -> {
// if (!bindingCalled.get()) {
// bindingCalled.set(true);
// try {
// propertyEditor.setValue(converter.apply(e.getValue()));
// } catch (Exception e1) {
// errorHandler.accept(e1);
// } finally {
// bindingCalled.set(false);
// }
// }
// });
// } catch (Exception e1) {
// SwingUtilities.invokeLater(() -> {
// errorHandler.accept(e1);
// });
// }
// });
// });
// }
//
// @Override
// public ConvertableBindable<T> withErrorHandler(Consumer<Throwable> handler) {
// this.errorHandler = handler;
// return this;
// }
//
// };
// }
// }
//
// Path: impl/src/main/java/com/guigarage/observer/BasicProperty.java
// public class BasicProperty<V> extends BasicObservable<V> implements Property<V> {
//
// @Override
// public void setValue(V value) {
// updateValue(value);
// }
// }
//
// Path: api/src/main/java/javax/observer/Property.java
// public interface Property<V> extends Observable<V> {
//
// /**
// * Replaces the internal value with the given new value. This should end in calling the
// * {@link ValueChangeListener#valueChanged(ValueChangeEvent)} method on all registered
// * listeners.
// * @param value the new value
// */
// void setValue(V value);
// }
| import com.guigarage.binding.SwingBinding;
import com.guigarage.observer.BasicProperty;
import javax.observer.Property;
import javax.swing.JTextField; | package com.guigarage.examples;
public class SwingBindingExample {
public static void main(String[] args) {
| // Path: impl/src/main/java/com/guigarage/binding/SwingBinding.java
// public class SwingBinding {
//
// private static Executor backgroundExecutor = Executors.newSingleThreadExecutor();
//
// public static <T> ConvertableBidirectionalBindable<T> bind(final Component component, final String attribute) {
// return new ConvertableBidirectionalBindable<T>() {
//
// private AtomicBoolean bindingCalled = new AtomicBoolean(false);
//
// private Consumer<Throwable> errorHandler = e -> e.printStackTrace();
//
// private Lock bindingLock = new ReentrantLock();
//
// private <U> U callLocked(Supplier<U> supplier) {
// bindingLock.lock();
// try {
// return supplier.get();
// } finally {
// bindingLock.unlock();
// }
// }
//
// private void callLocked(Runnable runnable) {
// callLocked(() -> {
// runnable.run();
// return null;
// });
// }
//
// @Override
// public <U> Subscription bidirectionalTo(Property<U> property, Function<U, T> converter, Function<T, U> converter2) {
// try {
// final PropertyDescriptor propertyDescriptor = new PropertyDescriptor(attribute, component.getClass());
// final PropertyEditor propertyEditor = propertyDescriptor.createPropertyEditor(component);
// Subscription subscription = bind(property, converter, propertyEditor);
//
// PropertyChangeListener listener = e -> {
// if (!bindingCalled.get()) {
// bindingCalled.set(true);
// try {
// backgroundExecutor.execute(() -> {
// callLocked(() -> {
// try {
// property.setValue(converter2.apply((T) e.getNewValue()));
// } catch (Exception ex) {
// SwingUtilities.invokeLater(() -> {
// errorHandler.accept(ex);
// });
// }
// });
// });
// } catch (Exception e1) {
// errorHandler.accept(e1);
// } finally {
// bindingCalled.set(false);
// }
// }
// };
//
// component.addPropertyChangeListener(listener);
//
// return () -> {
// component.removePropertyChangeListener(listener);
// subscription.unsubscribe();
// };
// } catch (Exception e1) {
// throw new RuntimeException("Can not bind!", e1);
// }
// }
//
// @Override
// public <U> Subscription to(Observable<U> observable, Function<U, T> converter) {
// try {
// final PropertyDescriptor propertyDescriptor = new PropertyDescriptor(attribute, component.getClass());
// final PropertyEditor propertyEditor = propertyDescriptor.createPropertyEditor(component);
// return bind(observable, converter, propertyEditor);
// } catch (Exception e1) {
// throw new RuntimeException("Can not bind!", e1);
// }
// }
//
// private <U> Subscription bind(Observable<U> observable, Function<U, T> converter, PropertyEditor propertyEditor) {
// return observable.onChanged(e -> {
// callLocked(() -> {
// try {
// SwingUtilities.invokeAndWait(() -> {
// if (!bindingCalled.get()) {
// bindingCalled.set(true);
// try {
// propertyEditor.setValue(converter.apply(e.getValue()));
// } catch (Exception e1) {
// errorHandler.accept(e1);
// } finally {
// bindingCalled.set(false);
// }
// }
// });
// } catch (Exception e1) {
// SwingUtilities.invokeLater(() -> {
// errorHandler.accept(e1);
// });
// }
// });
// });
// }
//
// @Override
// public ConvertableBindable<T> withErrorHandler(Consumer<Throwable> handler) {
// this.errorHandler = handler;
// return this;
// }
//
// };
// }
// }
//
// Path: impl/src/main/java/com/guigarage/observer/BasicProperty.java
// public class BasicProperty<V> extends BasicObservable<V> implements Property<V> {
//
// @Override
// public void setValue(V value) {
// updateValue(value);
// }
// }
//
// Path: api/src/main/java/javax/observer/Property.java
// public interface Property<V> extends Observable<V> {
//
// /**
// * Replaces the internal value with the given new value. This should end in calling the
// * {@link ValueChangeListener#valueChanged(ValueChangeEvent)} method on all registered
// * listeners.
// * @param value the new value
// */
// void setValue(V value);
// }
// Path: impl/src/main/java/com/guigarage/examples/SwingBindingExample.java
import com.guigarage.binding.SwingBinding;
import com.guigarage.observer.BasicProperty;
import javax.observer.Property;
import javax.swing.JTextField;
package com.guigarage.examples;
public class SwingBindingExample {
public static void main(String[] args) {
| Property<String> databaseBackgroundProperty = new BasicProperty<>(); |
guigarage/ObserverPattern | impl/src/main/java/com/guigarage/examples/SwingBindingExample.java | // Path: impl/src/main/java/com/guigarage/binding/SwingBinding.java
// public class SwingBinding {
//
// private static Executor backgroundExecutor = Executors.newSingleThreadExecutor();
//
// public static <T> ConvertableBidirectionalBindable<T> bind(final Component component, final String attribute) {
// return new ConvertableBidirectionalBindable<T>() {
//
// private AtomicBoolean bindingCalled = new AtomicBoolean(false);
//
// private Consumer<Throwable> errorHandler = e -> e.printStackTrace();
//
// private Lock bindingLock = new ReentrantLock();
//
// private <U> U callLocked(Supplier<U> supplier) {
// bindingLock.lock();
// try {
// return supplier.get();
// } finally {
// bindingLock.unlock();
// }
// }
//
// private void callLocked(Runnable runnable) {
// callLocked(() -> {
// runnable.run();
// return null;
// });
// }
//
// @Override
// public <U> Subscription bidirectionalTo(Property<U> property, Function<U, T> converter, Function<T, U> converter2) {
// try {
// final PropertyDescriptor propertyDescriptor = new PropertyDescriptor(attribute, component.getClass());
// final PropertyEditor propertyEditor = propertyDescriptor.createPropertyEditor(component);
// Subscription subscription = bind(property, converter, propertyEditor);
//
// PropertyChangeListener listener = e -> {
// if (!bindingCalled.get()) {
// bindingCalled.set(true);
// try {
// backgroundExecutor.execute(() -> {
// callLocked(() -> {
// try {
// property.setValue(converter2.apply((T) e.getNewValue()));
// } catch (Exception ex) {
// SwingUtilities.invokeLater(() -> {
// errorHandler.accept(ex);
// });
// }
// });
// });
// } catch (Exception e1) {
// errorHandler.accept(e1);
// } finally {
// bindingCalled.set(false);
// }
// }
// };
//
// component.addPropertyChangeListener(listener);
//
// return () -> {
// component.removePropertyChangeListener(listener);
// subscription.unsubscribe();
// };
// } catch (Exception e1) {
// throw new RuntimeException("Can not bind!", e1);
// }
// }
//
// @Override
// public <U> Subscription to(Observable<U> observable, Function<U, T> converter) {
// try {
// final PropertyDescriptor propertyDescriptor = new PropertyDescriptor(attribute, component.getClass());
// final PropertyEditor propertyEditor = propertyDescriptor.createPropertyEditor(component);
// return bind(observable, converter, propertyEditor);
// } catch (Exception e1) {
// throw new RuntimeException("Can not bind!", e1);
// }
// }
//
// private <U> Subscription bind(Observable<U> observable, Function<U, T> converter, PropertyEditor propertyEditor) {
// return observable.onChanged(e -> {
// callLocked(() -> {
// try {
// SwingUtilities.invokeAndWait(() -> {
// if (!bindingCalled.get()) {
// bindingCalled.set(true);
// try {
// propertyEditor.setValue(converter.apply(e.getValue()));
// } catch (Exception e1) {
// errorHandler.accept(e1);
// } finally {
// bindingCalled.set(false);
// }
// }
// });
// } catch (Exception e1) {
// SwingUtilities.invokeLater(() -> {
// errorHandler.accept(e1);
// });
// }
// });
// });
// }
//
// @Override
// public ConvertableBindable<T> withErrorHandler(Consumer<Throwable> handler) {
// this.errorHandler = handler;
// return this;
// }
//
// };
// }
// }
//
// Path: impl/src/main/java/com/guigarage/observer/BasicProperty.java
// public class BasicProperty<V> extends BasicObservable<V> implements Property<V> {
//
// @Override
// public void setValue(V value) {
// updateValue(value);
// }
// }
//
// Path: api/src/main/java/javax/observer/Property.java
// public interface Property<V> extends Observable<V> {
//
// /**
// * Replaces the internal value with the given new value. This should end in calling the
// * {@link ValueChangeListener#valueChanged(ValueChangeEvent)} method on all registered
// * listeners.
// * @param value the new value
// */
// void setValue(V value);
// }
| import com.guigarage.binding.SwingBinding;
import com.guigarage.observer.BasicProperty;
import javax.observer.Property;
import javax.swing.JTextField; | package com.guigarage.examples;
public class SwingBindingExample {
public static void main(String[] args) {
Property<String> databaseBackgroundProperty = new BasicProperty<>();
JTextField textField = new JTextField();
| // Path: impl/src/main/java/com/guigarage/binding/SwingBinding.java
// public class SwingBinding {
//
// private static Executor backgroundExecutor = Executors.newSingleThreadExecutor();
//
// public static <T> ConvertableBidirectionalBindable<T> bind(final Component component, final String attribute) {
// return new ConvertableBidirectionalBindable<T>() {
//
// private AtomicBoolean bindingCalled = new AtomicBoolean(false);
//
// private Consumer<Throwable> errorHandler = e -> e.printStackTrace();
//
// private Lock bindingLock = new ReentrantLock();
//
// private <U> U callLocked(Supplier<U> supplier) {
// bindingLock.lock();
// try {
// return supplier.get();
// } finally {
// bindingLock.unlock();
// }
// }
//
// private void callLocked(Runnable runnable) {
// callLocked(() -> {
// runnable.run();
// return null;
// });
// }
//
// @Override
// public <U> Subscription bidirectionalTo(Property<U> property, Function<U, T> converter, Function<T, U> converter2) {
// try {
// final PropertyDescriptor propertyDescriptor = new PropertyDescriptor(attribute, component.getClass());
// final PropertyEditor propertyEditor = propertyDescriptor.createPropertyEditor(component);
// Subscription subscription = bind(property, converter, propertyEditor);
//
// PropertyChangeListener listener = e -> {
// if (!bindingCalled.get()) {
// bindingCalled.set(true);
// try {
// backgroundExecutor.execute(() -> {
// callLocked(() -> {
// try {
// property.setValue(converter2.apply((T) e.getNewValue()));
// } catch (Exception ex) {
// SwingUtilities.invokeLater(() -> {
// errorHandler.accept(ex);
// });
// }
// });
// });
// } catch (Exception e1) {
// errorHandler.accept(e1);
// } finally {
// bindingCalled.set(false);
// }
// }
// };
//
// component.addPropertyChangeListener(listener);
//
// return () -> {
// component.removePropertyChangeListener(listener);
// subscription.unsubscribe();
// };
// } catch (Exception e1) {
// throw new RuntimeException("Can not bind!", e1);
// }
// }
//
// @Override
// public <U> Subscription to(Observable<U> observable, Function<U, T> converter) {
// try {
// final PropertyDescriptor propertyDescriptor = new PropertyDescriptor(attribute, component.getClass());
// final PropertyEditor propertyEditor = propertyDescriptor.createPropertyEditor(component);
// return bind(observable, converter, propertyEditor);
// } catch (Exception e1) {
// throw new RuntimeException("Can not bind!", e1);
// }
// }
//
// private <U> Subscription bind(Observable<U> observable, Function<U, T> converter, PropertyEditor propertyEditor) {
// return observable.onChanged(e -> {
// callLocked(() -> {
// try {
// SwingUtilities.invokeAndWait(() -> {
// if (!bindingCalled.get()) {
// bindingCalled.set(true);
// try {
// propertyEditor.setValue(converter.apply(e.getValue()));
// } catch (Exception e1) {
// errorHandler.accept(e1);
// } finally {
// bindingCalled.set(false);
// }
// }
// });
// } catch (Exception e1) {
// SwingUtilities.invokeLater(() -> {
// errorHandler.accept(e1);
// });
// }
// });
// });
// }
//
// @Override
// public ConvertableBindable<T> withErrorHandler(Consumer<Throwable> handler) {
// this.errorHandler = handler;
// return this;
// }
//
// };
// }
// }
//
// Path: impl/src/main/java/com/guigarage/observer/BasicProperty.java
// public class BasicProperty<V> extends BasicObservable<V> implements Property<V> {
//
// @Override
// public void setValue(V value) {
// updateValue(value);
// }
// }
//
// Path: api/src/main/java/javax/observer/Property.java
// public interface Property<V> extends Observable<V> {
//
// /**
// * Replaces the internal value with the given new value. This should end in calling the
// * {@link ValueChangeListener#valueChanged(ValueChangeEvent)} method on all registered
// * listeners.
// * @param value the new value
// */
// void setValue(V value);
// }
// Path: impl/src/main/java/com/guigarage/examples/SwingBindingExample.java
import com.guigarage.binding.SwingBinding;
import com.guigarage.observer.BasicProperty;
import javax.observer.Property;
import javax.swing.JTextField;
package com.guigarage.examples;
public class SwingBindingExample {
public static void main(String[] args) {
Property<String> databaseBackgroundProperty = new BasicProperty<>();
JTextField textField = new JTextField();
| SwingBinding.<String>bind(textField, "text").bidirectionalTo(databaseBackgroundProperty); |
cckevincyh/SafeChatRoom | SafeChat_Server/src/chat_server/server/backstage/Server_Connect_Database.java | // Path: SafeChat_Server/src/chat/common/User.java
// public class User implements Serializable{
// private String Name;
// private String PassWords;
// private String Type; //注册或是登陆
//
// public User(){
//
// }
//
// public User(String Name,String PassWords){
// this.Name = Name;
// this.PassWords = PassWords;
// }
//
// public String getType() {
// return Type;
// }
//
// public void setType(String type) {
// Type = type;
// }
//
// public String getName() {
// return Name;
// }
//
// public void setName(String name) {
// Name = name;
// }
//
// public String getPassWords() {
// return PassWords;
// }
//
// public void setPassWords(String passWords) {
// PassWords = passWords;
// }
//
//
// }
| import java.sql.ResultSet;
import java.sql.SQLException;
import chat.common.User; | package chat_server.server.backstage;
/**
* 服务器端与数据库通信的后台类
* @author c
*
*/
public class Server_Connect_Database {
private ResultSet rs = null;
private DatabaseManage databaseManage = null;
/**
* 检查是否登陆成功的方法
* @param user 用户对象
* @return 返回是否登陆成功
*/ | // Path: SafeChat_Server/src/chat/common/User.java
// public class User implements Serializable{
// private String Name;
// private String PassWords;
// private String Type; //注册或是登陆
//
// public User(){
//
// }
//
// public User(String Name,String PassWords){
// this.Name = Name;
// this.PassWords = PassWords;
// }
//
// public String getType() {
// return Type;
// }
//
// public void setType(String type) {
// Type = type;
// }
//
// public String getName() {
// return Name;
// }
//
// public void setName(String name) {
// Name = name;
// }
//
// public String getPassWords() {
// return PassWords;
// }
//
// public void setPassWords(String passWords) {
// PassWords = passWords;
// }
//
//
// }
// Path: SafeChat_Server/src/chat_server/server/backstage/Server_Connect_Database.java
import java.sql.ResultSet;
import java.sql.SQLException;
import chat.common.User;
package chat_server.server.backstage;
/**
* 服务器端与数据库通信的后台类
* @author c
*
*/
public class Server_Connect_Database {
private ResultSet rs = null;
private DatabaseManage databaseManage = null;
/**
* 检查是否登陆成功的方法
* @param user 用户对象
* @return 返回是否登陆成功
*/ | public boolean CheckLogin(User user){ |
cckevincyh/SafeChatRoom | SafeChat_Server/src/chat/utils/DecryptionUtils.java | // Path: SafeChat_Server/src/chat/common/Message.java
// public class Message implements Serializable{
// private String MessageType;
// private String Content;
// private String Time;
// private String Sender;
// private String Getter;
// private byte[] Key; //秘钥
//
//
//
// public Message(String messageType, String sender, byte[] key) {
// super();
// MessageType = messageType;
// Sender = sender;
// Key = key;
// }
//
//
//
//
//
//
//
//
// public Message(Message message){
// this.setContent(message.getContent());
// this.setGetter(message.getGetter());
// this.setSender(message.getSender());
// this.setMessageType(message.getMessageType());
// this.setTime(message.getTime());
// this.setKey(message.getKey());
// }
//
//
//
//
//
//
//
//
// public byte[] getKey() {
// return Key;
// }
//
//
//
//
//
//
// public void setKey(byte[] key) {
// Key = key;
// }
//
//
//
//
//
//
// public Message(){
//
// }
//
// public Message(String MessageType,String Content,String Time,String Sender,String Getter){
// this.MessageType = MessageType;
// this.Content = Content;
// this.Time = Time;
// this.Sender = Sender;
// this.Getter = Getter;
// }
//
// public String getMessageType() {
// return MessageType;
// }
//
// public void setMessageType(String messageType) {
// MessageType = messageType;
// }
//
// public String getContent() {
// return Content;
// }
//
// public void setContent(String content) {
// Content = content;
// }
//
// public String getTime() {
// return Time;
// }
//
// public void setTime(String time) {
// Time = time;
// }
//
// public String getSender() {
// return Sender;
// }
//
// public void setSender(String sender) {
// Sender = sender;
// }
//
// public String getGetter() {
// return Getter;
// }
//
// public void setGetter(String getter) {
// Getter = getter;
// }
//
//
// }
| import java.io.IOException;
import java.util.UUID;
import chat.common.Message; | package chat.utils;
public class DecryptionUtils {
/**
* RSA解密
* @param filePrivateKeyName 要使用的私钥的文件路径
* @param data 要解密的数据
* @return 返回解密后的数据
*/
public static byte[] decryptByPrivateKey(String filePrivateKeyName,byte[] data){
//1.读取文件名为:filePrivateKeyName的密钥文件
String key = IOUtils.ReadKeyFile(filePrivateKeyName);
try {
//2.用读取出来的密钥对数据进行解密
byte[] decodedData = RSAUtils.decryptByPrivateKey(data, key);
return decodedData;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 服务器解密消息
* @param filePrivateKeyName 要使用的私钥的文件路径
* @param message 接受的消息
*/ | // Path: SafeChat_Server/src/chat/common/Message.java
// public class Message implements Serializable{
// private String MessageType;
// private String Content;
// private String Time;
// private String Sender;
// private String Getter;
// private byte[] Key; //秘钥
//
//
//
// public Message(String messageType, String sender, byte[] key) {
// super();
// MessageType = messageType;
// Sender = sender;
// Key = key;
// }
//
//
//
//
//
//
//
//
// public Message(Message message){
// this.setContent(message.getContent());
// this.setGetter(message.getGetter());
// this.setSender(message.getSender());
// this.setMessageType(message.getMessageType());
// this.setTime(message.getTime());
// this.setKey(message.getKey());
// }
//
//
//
//
//
//
//
//
// public byte[] getKey() {
// return Key;
// }
//
//
//
//
//
//
// public void setKey(byte[] key) {
// Key = key;
// }
//
//
//
//
//
//
// public Message(){
//
// }
//
// public Message(String MessageType,String Content,String Time,String Sender,String Getter){
// this.MessageType = MessageType;
// this.Content = Content;
// this.Time = Time;
// this.Sender = Sender;
// this.Getter = Getter;
// }
//
// public String getMessageType() {
// return MessageType;
// }
//
// public void setMessageType(String messageType) {
// MessageType = messageType;
// }
//
// public String getContent() {
// return Content;
// }
//
// public void setContent(String content) {
// Content = content;
// }
//
// public String getTime() {
// return Time;
// }
//
// public void setTime(String time) {
// Time = time;
// }
//
// public String getSender() {
// return Sender;
// }
//
// public void setSender(String sender) {
// Sender = sender;
// }
//
// public String getGetter() {
// return Getter;
// }
//
// public void setGetter(String getter) {
// Getter = getter;
// }
//
//
// }
// Path: SafeChat_Server/src/chat/utils/DecryptionUtils.java
import java.io.IOException;
import java.util.UUID;
import chat.common.Message;
package chat.utils;
public class DecryptionUtils {
/**
* RSA解密
* @param filePrivateKeyName 要使用的私钥的文件路径
* @param data 要解密的数据
* @return 返回解密后的数据
*/
public static byte[] decryptByPrivateKey(String filePrivateKeyName,byte[] data){
//1.读取文件名为:filePrivateKeyName的密钥文件
String key = IOUtils.ReadKeyFile(filePrivateKeyName);
try {
//2.用读取出来的密钥对数据进行解密
byte[] decodedData = RSAUtils.decryptByPrivateKey(data, key);
return decodedData;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 服务器解密消息
* @param filePrivateKeyName 要使用的私钥的文件路径
* @param message 接受的消息
*/ | public static void decryptMessage(String filePrivateKeyName,Message message) throws IOException{ |
cckevincyh/SafeChatRoom | SafeChat_Room/src/chat/utils/DecryptionUtils.java | // Path: SafeChat_Server/src/chat/common/Message.java
// public class Message implements Serializable{
// private String MessageType;
// private String Content;
// private String Time;
// private String Sender;
// private String Getter;
// private byte[] Key; //秘钥
//
//
//
// public Message(String messageType, String sender, byte[] key) {
// super();
// MessageType = messageType;
// Sender = sender;
// Key = key;
// }
//
//
//
//
//
//
//
//
// public Message(Message message){
// this.setContent(message.getContent());
// this.setGetter(message.getGetter());
// this.setSender(message.getSender());
// this.setMessageType(message.getMessageType());
// this.setTime(message.getTime());
// this.setKey(message.getKey());
// }
//
//
//
//
//
//
//
//
// public byte[] getKey() {
// return Key;
// }
//
//
//
//
//
//
// public void setKey(byte[] key) {
// Key = key;
// }
//
//
//
//
//
//
// public Message(){
//
// }
//
// public Message(String MessageType,String Content,String Time,String Sender,String Getter){
// this.MessageType = MessageType;
// this.Content = Content;
// this.Time = Time;
// this.Sender = Sender;
// this.Getter = Getter;
// }
//
// public String getMessageType() {
// return MessageType;
// }
//
// public void setMessageType(String messageType) {
// MessageType = messageType;
// }
//
// public String getContent() {
// return Content;
// }
//
// public void setContent(String content) {
// Content = content;
// }
//
// public String getTime() {
// return Time;
// }
//
// public void setTime(String time) {
// Time = time;
// }
//
// public String getSender() {
// return Sender;
// }
//
// public void setSender(String sender) {
// Sender = sender;
// }
//
// public String getGetter() {
// return Getter;
// }
//
// public void setGetter(String getter) {
// Getter = getter;
// }
//
//
// }
//
// Path: SafeChat_Room/src/chat/common/MessageType.java
// public interface MessageType {
//
// public String UserLogin = "@UsersLogin"; //用户登陆信息
// public String UserRegister = "@UserRegister"; //用户注册信息
// public String Login_Success = "@Login_Success";//登陆成功
// public String Login_Fail = "@Login_Fail";//登陆失败
// public String Register_Success = "@Register_Success"; //注册成功
// public String Register_Fail = "Register_Fail"; //注册失败
// public String Common_Message_ToAll ="@Common_Message_ToAll";//发送普通消息给所有人
// public String Common_Message_ToPerson ="@Common_Message_ToPerson" ;//发送普通消息给个人
// public String Send_FileToAll = "@Send_FileToAll";//发送文件给所有人
// public String Send_FileToPerson = "@Send_FileToPerson";//发送文件给个人
// public String Get_Online = "@Get_Online";//获得在线人员
// public String Send_Online = "@Send_Online";//返回在线人员
// public String SendUser = "@Send_User";//发送用户信息
// public String CommonMessage ="@CommonMessage"; //普通消息
// public String System_Messages = "@System_Messages"; //系统消息
// public String Login = "@Login"; //登陆过了
// public String NoLogin = "@NoLogin"; //没登陆过
// public String Recive = "@Recive"; //接收
// public String NoRecive = "@NoRevice"; //拒绝接收
// public String Send_Public_Key = "@Send_Public_Key"; //发送客户端生成的公钥
//
// }
| import java.io.IOException;
import chat.common.Message;
import chat.common.MessageType; | package chat.utils;
public class DecryptionUtils {
/**
* RSA解密
* @param filePrivateKeyName 要使用的私钥的文件路径
* @param data 要解密的数据
* @return 返回解密后的数据
*/
public static byte[] decryptByPrivateKey(String filePrivateKeyName,byte[] data){
//1.读取文件名为:filePrivateKeyName的密钥文件
String key = IOUtils.ReadKeyFile(filePrivateKeyName);
try {
//2.用读取出来的密钥对数据进行解密
byte[] decodedData = RSAUtils.decryptByPrivateKey(data, key);
return decodedData;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 客户端解密服务器发送文件消息的KEY
* @param message 对message设置加密后的KEY
* @return 返回KEY
*/ | // Path: SafeChat_Server/src/chat/common/Message.java
// public class Message implements Serializable{
// private String MessageType;
// private String Content;
// private String Time;
// private String Sender;
// private String Getter;
// private byte[] Key; //秘钥
//
//
//
// public Message(String messageType, String sender, byte[] key) {
// super();
// MessageType = messageType;
// Sender = sender;
// Key = key;
// }
//
//
//
//
//
//
//
//
// public Message(Message message){
// this.setContent(message.getContent());
// this.setGetter(message.getGetter());
// this.setSender(message.getSender());
// this.setMessageType(message.getMessageType());
// this.setTime(message.getTime());
// this.setKey(message.getKey());
// }
//
//
//
//
//
//
//
//
// public byte[] getKey() {
// return Key;
// }
//
//
//
//
//
//
// public void setKey(byte[] key) {
// Key = key;
// }
//
//
//
//
//
//
// public Message(){
//
// }
//
// public Message(String MessageType,String Content,String Time,String Sender,String Getter){
// this.MessageType = MessageType;
// this.Content = Content;
// this.Time = Time;
// this.Sender = Sender;
// this.Getter = Getter;
// }
//
// public String getMessageType() {
// return MessageType;
// }
//
// public void setMessageType(String messageType) {
// MessageType = messageType;
// }
//
// public String getContent() {
// return Content;
// }
//
// public void setContent(String content) {
// Content = content;
// }
//
// public String getTime() {
// return Time;
// }
//
// public void setTime(String time) {
// Time = time;
// }
//
// public String getSender() {
// return Sender;
// }
//
// public void setSender(String sender) {
// Sender = sender;
// }
//
// public String getGetter() {
// return Getter;
// }
//
// public void setGetter(String getter) {
// Getter = getter;
// }
//
//
// }
//
// Path: SafeChat_Room/src/chat/common/MessageType.java
// public interface MessageType {
//
// public String UserLogin = "@UsersLogin"; //用户登陆信息
// public String UserRegister = "@UserRegister"; //用户注册信息
// public String Login_Success = "@Login_Success";//登陆成功
// public String Login_Fail = "@Login_Fail";//登陆失败
// public String Register_Success = "@Register_Success"; //注册成功
// public String Register_Fail = "Register_Fail"; //注册失败
// public String Common_Message_ToAll ="@Common_Message_ToAll";//发送普通消息给所有人
// public String Common_Message_ToPerson ="@Common_Message_ToPerson" ;//发送普通消息给个人
// public String Send_FileToAll = "@Send_FileToAll";//发送文件给所有人
// public String Send_FileToPerson = "@Send_FileToPerson";//发送文件给个人
// public String Get_Online = "@Get_Online";//获得在线人员
// public String Send_Online = "@Send_Online";//返回在线人员
// public String SendUser = "@Send_User";//发送用户信息
// public String CommonMessage ="@CommonMessage"; //普通消息
// public String System_Messages = "@System_Messages"; //系统消息
// public String Login = "@Login"; //登陆过了
// public String NoLogin = "@NoLogin"; //没登陆过
// public String Recive = "@Recive"; //接收
// public String NoRecive = "@NoRevice"; //拒绝接收
// public String Send_Public_Key = "@Send_Public_Key"; //发送客户端生成的公钥
//
// }
// Path: SafeChat_Room/src/chat/utils/DecryptionUtils.java
import java.io.IOException;
import chat.common.Message;
import chat.common.MessageType;
package chat.utils;
public class DecryptionUtils {
/**
* RSA解密
* @param filePrivateKeyName 要使用的私钥的文件路径
* @param data 要解密的数据
* @return 返回解密后的数据
*/
public static byte[] decryptByPrivateKey(String filePrivateKeyName,byte[] data){
//1.读取文件名为:filePrivateKeyName的密钥文件
String key = IOUtils.ReadKeyFile(filePrivateKeyName);
try {
//2.用读取出来的密钥对数据进行解密
byte[] decodedData = RSAUtils.decryptByPrivateKey(data, key);
return decodedData;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 客户端解密服务器发送文件消息的KEY
* @param message 对message设置加密后的KEY
* @return 返回KEY
*/ | public static void decryptFileKey(Message message){ |
cckevincyh/SafeChatRoom | SafeChat_Server/src/chat_server/server/backstage/DatabaseManage.java | // Path: SafeChat_Server/src/chat/common/User.java
// public class User implements Serializable{
// private String Name;
// private String PassWords;
// private String Type; //注册或是登陆
//
// public User(){
//
// }
//
// public User(String Name,String PassWords){
// this.Name = Name;
// this.PassWords = PassWords;
// }
//
// public String getType() {
// return Type;
// }
//
// public void setType(String type) {
// Type = type;
// }
//
// public String getName() {
// return Name;
// }
//
// public void setName(String name) {
// Name = name;
// }
//
// public String getPassWords() {
// return PassWords;
// }
//
// public void setPassWords(String passWords) {
// PassWords = passWords;
// }
//
//
// }
| import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import chat.common.User; | package chat_server.server.backstage;
// _ooOoo_
// o8888888o
// 88" . "88
// (| -_- |)
// O\ = /O
// ____/`---'\____
// . ' \\| |// `.
// / \\||| : |||// \
// / _||||| -:- |||||- \
// | | \\\ - /// | |
// | \_| ''\---/'' | |
// \ .-\__ `-` ___/-. /
// ___`. .' /--.--\ `. . __
// ."" '< `.___\_<|>_/___.' >'"".
// | | : `- \`.;`\ _ /`;.`/ - ` : | |
// \ \ `-. \_ __\ /__ _/ .-` / /
// ======`-.____`-.___\_____/___.-`____.-'======
// `=---='
//
// .............................................
// 佛祖保佑 永无BUG
// 佛曰:
// 写字楼里写字间,写字间里程序员;
// 程序人员写程序,又拿程序换酒钱。
// 酒醒只在网上坐,酒醉还来网下眠;
// 酒醉酒醒日复日,网上网下年复年。
// 但愿老死电脑间,不愿鞠躬老板前;
// 奔驰宝马贵者趣,公交自行程序员。
// 别人笑我忒疯癫,我笑自己命太贱;
// 不见满街漂亮妹,哪个归得程序员?
/**
* 服务器后台的数据库处理类
* @author Administrator
*
*/
public class DatabaseManage {
//定义连接数据库所需要的对象
private PreparedStatement ps = null;
private ResultSet rs = null;
private Connection ct = null;
public void init(){
//加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
//得到连接
ct = DriverManager.getConnection("jdbc:mysql://localhost:3306/ChatRoomDao","root","123");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (SQLException e) {
e.printStackTrace();
}
}
public DatabaseManage(){
this.init();
}
//取得用户信息
public ResultSet GetUser(String Name){
try {
ps = ct.prepareStatement("select * from Users where Name=?");
ps.setString(1, Name);
rs = ps.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rs;
}
//注册用户信息 | // Path: SafeChat_Server/src/chat/common/User.java
// public class User implements Serializable{
// private String Name;
// private String PassWords;
// private String Type; //注册或是登陆
//
// public User(){
//
// }
//
// public User(String Name,String PassWords){
// this.Name = Name;
// this.PassWords = PassWords;
// }
//
// public String getType() {
// return Type;
// }
//
// public void setType(String type) {
// Type = type;
// }
//
// public String getName() {
// return Name;
// }
//
// public void setName(String name) {
// Name = name;
// }
//
// public String getPassWords() {
// return PassWords;
// }
//
// public void setPassWords(String passWords) {
// PassWords = passWords;
// }
//
//
// }
// Path: SafeChat_Server/src/chat_server/server/backstage/DatabaseManage.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import chat.common.User;
package chat_server.server.backstage;
// _ooOoo_
// o8888888o
// 88" . "88
// (| -_- |)
// O\ = /O
// ____/`---'\____
// . ' \\| |// `.
// / \\||| : |||// \
// / _||||| -:- |||||- \
// | | \\\ - /// | |
// | \_| ''\---/'' | |
// \ .-\__ `-` ___/-. /
// ___`. .' /--.--\ `. . __
// ."" '< `.___\_<|>_/___.' >'"".
// | | : `- \`.;`\ _ /`;.`/ - ` : | |
// \ \ `-. \_ __\ /__ _/ .-` / /
// ======`-.____`-.___\_____/___.-`____.-'======
// `=---='
//
// .............................................
// 佛祖保佑 永无BUG
// 佛曰:
// 写字楼里写字间,写字间里程序员;
// 程序人员写程序,又拿程序换酒钱。
// 酒醒只在网上坐,酒醉还来网下眠;
// 酒醉酒醒日复日,网上网下年复年。
// 但愿老死电脑间,不愿鞠躬老板前;
// 奔驰宝马贵者趣,公交自行程序员。
// 别人笑我忒疯癫,我笑自己命太贱;
// 不见满街漂亮妹,哪个归得程序员?
/**
* 服务器后台的数据库处理类
* @author Administrator
*
*/
public class DatabaseManage {
//定义连接数据库所需要的对象
private PreparedStatement ps = null;
private ResultSet rs = null;
private Connection ct = null;
public void init(){
//加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
//得到连接
ct = DriverManager.getConnection("jdbc:mysql://localhost:3306/ChatRoomDao","root","123");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (SQLException e) {
e.printStackTrace();
}
}
public DatabaseManage(){
this.init();
}
//取得用户信息
public ResultSet GetUser(String Name){
try {
ps = ct.prepareStatement("select * from Users where Name=?");
ps.setString(1, Name);
rs = ps.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rs;
}
//注册用户信息 | public boolean Register(User user){ |
jprante/elasticsearch-skywalker | src/main/java/org/xbib/elasticsearch/rest/action/skywalker/RestConsistencyCheckAction.java | // Path: src/main/java/org/xbib/elasticsearch/action/admin/cluster/state/ConsistencyCheckAction.java
// public class ConsistencyCheckAction extends ClusterAction<ConsistencyCheckRequest, ConsistencyCheckResponse, ConsistencyCheckRequestBuilder> {
//
// public static final ConsistencyCheckAction INSTANCE = new ConsistencyCheckAction();
// public static final String NAME = "cluster/state/consistencycheck";
//
// private ConsistencyCheckAction() {
// super(NAME);
// }
//
// @Override
// public ConsistencyCheckResponse newResponse() {
// return new ConsistencyCheckResponse();
// }
//
// @Override
// public ConsistencyCheckRequestBuilder newRequestBuilder(ClusterAdminClient client) {
// return new ConsistencyCheckRequestBuilder(client);
// }
// }
//
// Path: src/main/java/org/xbib/elasticsearch/action/admin/cluster/state/ConsistencyCheckRequest.java
// public class ConsistencyCheckRequest extends MasterNodeOperationRequest<ConsistencyCheckRequest> {
//
// public ConsistencyCheckRequest() {
// }
//
// @Override
// public ActionRequestValidationException validate() {
// return null;
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// }
// }
//
// Path: src/main/java/org/xbib/elasticsearch/action/admin/cluster/state/ConsistencyCheckResponse.java
// public class ConsistencyCheckResponse extends ActionResponse {
//
// private ClusterName clusterName;
//
// private ClusterState clusterState;
//
// private List<File> files;
//
// public ConsistencyCheckResponse() {
// }
//
// ConsistencyCheckResponse(ClusterName clusterName, ClusterState clusterState, List<File> files) {
// this.clusterName = clusterName;
// this.clusterState = clusterState;
// this.files = files;
// }
//
// public ClusterState getState() {
// return this.clusterState;
// }
//
// public ClusterName getClusterName() {
// return this.clusterName;
// }
//
// public List<File> getFiles() {
// return this.files;
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// clusterName = ClusterName.readClusterName(in);
// clusterState = ClusterState.Builder.readFrom(in, null);
// int n = in.read();
// files = new ArrayList();
// for (int i = 0; i < n; i++) {
// files.set(i, new File(in.readString()));
// }
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// clusterName.writeTo(out);
// ClusterState.Builder.writeTo(clusterState, out);
// out.write(files.size());
// for (File file : files) {
// out.writeString(file.getAbsolutePath());
// }
// }
// }
| import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.joda.time.Instant;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.SizeUnit;
import org.elasticsearch.common.unit.SizeValue;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestResponseListener;
import org.xbib.elasticsearch.action.admin.cluster.state.ConsistencyCheckAction;
import org.xbib.elasticsearch.action.admin.cluster.state.ConsistencyCheckRequest;
import org.xbib.elasticsearch.action.admin.cluster.state.ConsistencyCheckResponse;
import java.io.File;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestStatus.OK; |
package org.xbib.elasticsearch.rest.action.skywalker;
/**
* REST consistency check action
*/
public class RestConsistencyCheckAction extends BaseRestHandler {
@Inject
public RestConsistencyCheckAction(Settings settings, Client client, RestController controller) {
super(settings, client);
controller.registerHandler(GET, "/_skywalker/consistencycheck", this);
}
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) throws Exception { | // Path: src/main/java/org/xbib/elasticsearch/action/admin/cluster/state/ConsistencyCheckAction.java
// public class ConsistencyCheckAction extends ClusterAction<ConsistencyCheckRequest, ConsistencyCheckResponse, ConsistencyCheckRequestBuilder> {
//
// public static final ConsistencyCheckAction INSTANCE = new ConsistencyCheckAction();
// public static final String NAME = "cluster/state/consistencycheck";
//
// private ConsistencyCheckAction() {
// super(NAME);
// }
//
// @Override
// public ConsistencyCheckResponse newResponse() {
// return new ConsistencyCheckResponse();
// }
//
// @Override
// public ConsistencyCheckRequestBuilder newRequestBuilder(ClusterAdminClient client) {
// return new ConsistencyCheckRequestBuilder(client);
// }
// }
//
// Path: src/main/java/org/xbib/elasticsearch/action/admin/cluster/state/ConsistencyCheckRequest.java
// public class ConsistencyCheckRequest extends MasterNodeOperationRequest<ConsistencyCheckRequest> {
//
// public ConsistencyCheckRequest() {
// }
//
// @Override
// public ActionRequestValidationException validate() {
// return null;
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// }
// }
//
// Path: src/main/java/org/xbib/elasticsearch/action/admin/cluster/state/ConsistencyCheckResponse.java
// public class ConsistencyCheckResponse extends ActionResponse {
//
// private ClusterName clusterName;
//
// private ClusterState clusterState;
//
// private List<File> files;
//
// public ConsistencyCheckResponse() {
// }
//
// ConsistencyCheckResponse(ClusterName clusterName, ClusterState clusterState, List<File> files) {
// this.clusterName = clusterName;
// this.clusterState = clusterState;
// this.files = files;
// }
//
// public ClusterState getState() {
// return this.clusterState;
// }
//
// public ClusterName getClusterName() {
// return this.clusterName;
// }
//
// public List<File> getFiles() {
// return this.files;
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// clusterName = ClusterName.readClusterName(in);
// clusterState = ClusterState.Builder.readFrom(in, null);
// int n = in.read();
// files = new ArrayList();
// for (int i = 0; i < n; i++) {
// files.set(i, new File(in.readString()));
// }
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// clusterName.writeTo(out);
// ClusterState.Builder.writeTo(clusterState, out);
// out.write(files.size());
// for (File file : files) {
// out.writeString(file.getAbsolutePath());
// }
// }
// }
// Path: src/main/java/org/xbib/elasticsearch/rest/action/skywalker/RestConsistencyCheckAction.java
import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.joda.time.Instant;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.SizeUnit;
import org.elasticsearch.common.unit.SizeValue;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestResponseListener;
import org.xbib.elasticsearch.action.admin.cluster.state.ConsistencyCheckAction;
import org.xbib.elasticsearch.action.admin.cluster.state.ConsistencyCheckRequest;
import org.xbib.elasticsearch.action.admin.cluster.state.ConsistencyCheckResponse;
import java.io.File;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestStatus.OK;
package org.xbib.elasticsearch.rest.action.skywalker;
/**
* REST consistency check action
*/
public class RestConsistencyCheckAction extends BaseRestHandler {
@Inject
public RestConsistencyCheckAction(Settings settings, Client client, RestController controller) {
super(settings, client);
controller.registerHandler(GET, "/_skywalker/consistencycheck", this);
}
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) throws Exception { | ConsistencyCheckRequest r = new ConsistencyCheckRequest(); |
jprante/elasticsearch-skywalker | src/main/java/org/xbib/elasticsearch/rest/action/skywalker/RestConsistencyCheckAction.java | // Path: src/main/java/org/xbib/elasticsearch/action/admin/cluster/state/ConsistencyCheckAction.java
// public class ConsistencyCheckAction extends ClusterAction<ConsistencyCheckRequest, ConsistencyCheckResponse, ConsistencyCheckRequestBuilder> {
//
// public static final ConsistencyCheckAction INSTANCE = new ConsistencyCheckAction();
// public static final String NAME = "cluster/state/consistencycheck";
//
// private ConsistencyCheckAction() {
// super(NAME);
// }
//
// @Override
// public ConsistencyCheckResponse newResponse() {
// return new ConsistencyCheckResponse();
// }
//
// @Override
// public ConsistencyCheckRequestBuilder newRequestBuilder(ClusterAdminClient client) {
// return new ConsistencyCheckRequestBuilder(client);
// }
// }
//
// Path: src/main/java/org/xbib/elasticsearch/action/admin/cluster/state/ConsistencyCheckRequest.java
// public class ConsistencyCheckRequest extends MasterNodeOperationRequest<ConsistencyCheckRequest> {
//
// public ConsistencyCheckRequest() {
// }
//
// @Override
// public ActionRequestValidationException validate() {
// return null;
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// }
// }
//
// Path: src/main/java/org/xbib/elasticsearch/action/admin/cluster/state/ConsistencyCheckResponse.java
// public class ConsistencyCheckResponse extends ActionResponse {
//
// private ClusterName clusterName;
//
// private ClusterState clusterState;
//
// private List<File> files;
//
// public ConsistencyCheckResponse() {
// }
//
// ConsistencyCheckResponse(ClusterName clusterName, ClusterState clusterState, List<File> files) {
// this.clusterName = clusterName;
// this.clusterState = clusterState;
// this.files = files;
// }
//
// public ClusterState getState() {
// return this.clusterState;
// }
//
// public ClusterName getClusterName() {
// return this.clusterName;
// }
//
// public List<File> getFiles() {
// return this.files;
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// clusterName = ClusterName.readClusterName(in);
// clusterState = ClusterState.Builder.readFrom(in, null);
// int n = in.read();
// files = new ArrayList();
// for (int i = 0; i < n; i++) {
// files.set(i, new File(in.readString()));
// }
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// clusterName.writeTo(out);
// ClusterState.Builder.writeTo(clusterState, out);
// out.write(files.size());
// for (File file : files) {
// out.writeString(file.getAbsolutePath());
// }
// }
// }
| import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.joda.time.Instant;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.SizeUnit;
import org.elasticsearch.common.unit.SizeValue;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestResponseListener;
import org.xbib.elasticsearch.action.admin.cluster.state.ConsistencyCheckAction;
import org.xbib.elasticsearch.action.admin.cluster.state.ConsistencyCheckRequest;
import org.xbib.elasticsearch.action.admin.cluster.state.ConsistencyCheckResponse;
import java.io.File;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestStatus.OK; |
package org.xbib.elasticsearch.rest.action.skywalker;
/**
* REST consistency check action
*/
public class RestConsistencyCheckAction extends BaseRestHandler {
@Inject
public RestConsistencyCheckAction(Settings settings, Client client, RestController controller) {
super(settings, client);
controller.registerHandler(GET, "/_skywalker/consistencycheck", this);
}
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) throws Exception {
ConsistencyCheckRequest r = new ConsistencyCheckRequest(); | // Path: src/main/java/org/xbib/elasticsearch/action/admin/cluster/state/ConsistencyCheckAction.java
// public class ConsistencyCheckAction extends ClusterAction<ConsistencyCheckRequest, ConsistencyCheckResponse, ConsistencyCheckRequestBuilder> {
//
// public static final ConsistencyCheckAction INSTANCE = new ConsistencyCheckAction();
// public static final String NAME = "cluster/state/consistencycheck";
//
// private ConsistencyCheckAction() {
// super(NAME);
// }
//
// @Override
// public ConsistencyCheckResponse newResponse() {
// return new ConsistencyCheckResponse();
// }
//
// @Override
// public ConsistencyCheckRequestBuilder newRequestBuilder(ClusterAdminClient client) {
// return new ConsistencyCheckRequestBuilder(client);
// }
// }
//
// Path: src/main/java/org/xbib/elasticsearch/action/admin/cluster/state/ConsistencyCheckRequest.java
// public class ConsistencyCheckRequest extends MasterNodeOperationRequest<ConsistencyCheckRequest> {
//
// public ConsistencyCheckRequest() {
// }
//
// @Override
// public ActionRequestValidationException validate() {
// return null;
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// }
// }
//
// Path: src/main/java/org/xbib/elasticsearch/action/admin/cluster/state/ConsistencyCheckResponse.java
// public class ConsistencyCheckResponse extends ActionResponse {
//
// private ClusterName clusterName;
//
// private ClusterState clusterState;
//
// private List<File> files;
//
// public ConsistencyCheckResponse() {
// }
//
// ConsistencyCheckResponse(ClusterName clusterName, ClusterState clusterState, List<File> files) {
// this.clusterName = clusterName;
// this.clusterState = clusterState;
// this.files = files;
// }
//
// public ClusterState getState() {
// return this.clusterState;
// }
//
// public ClusterName getClusterName() {
// return this.clusterName;
// }
//
// public List<File> getFiles() {
// return this.files;
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// clusterName = ClusterName.readClusterName(in);
// clusterState = ClusterState.Builder.readFrom(in, null);
// int n = in.read();
// files = new ArrayList();
// for (int i = 0; i < n; i++) {
// files.set(i, new File(in.readString()));
// }
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// clusterName.writeTo(out);
// ClusterState.Builder.writeTo(clusterState, out);
// out.write(files.size());
// for (File file : files) {
// out.writeString(file.getAbsolutePath());
// }
// }
// }
// Path: src/main/java/org/xbib/elasticsearch/rest/action/skywalker/RestConsistencyCheckAction.java
import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.joda.time.Instant;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.SizeUnit;
import org.elasticsearch.common.unit.SizeValue;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestResponseListener;
import org.xbib.elasticsearch.action.admin.cluster.state.ConsistencyCheckAction;
import org.xbib.elasticsearch.action.admin.cluster.state.ConsistencyCheckRequest;
import org.xbib.elasticsearch.action.admin.cluster.state.ConsistencyCheckResponse;
import java.io.File;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestStatus.OK;
package org.xbib.elasticsearch.rest.action.skywalker;
/**
* REST consistency check action
*/
public class RestConsistencyCheckAction extends BaseRestHandler {
@Inject
public RestConsistencyCheckAction(Settings settings, Client client, RestController controller) {
super(settings, client);
controller.registerHandler(GET, "/_skywalker/consistencycheck", this);
}
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) throws Exception {
ConsistencyCheckRequest r = new ConsistencyCheckRequest(); | client.admin().cluster().execute(ConsistencyCheckAction.INSTANCE, r, new RestResponseListener<ConsistencyCheckResponse>(channel) { |
jprante/elasticsearch-skywalker | src/main/java/org/xbib/elasticsearch/rest/action/skywalker/RestConsistencyCheckAction.java | // Path: src/main/java/org/xbib/elasticsearch/action/admin/cluster/state/ConsistencyCheckAction.java
// public class ConsistencyCheckAction extends ClusterAction<ConsistencyCheckRequest, ConsistencyCheckResponse, ConsistencyCheckRequestBuilder> {
//
// public static final ConsistencyCheckAction INSTANCE = new ConsistencyCheckAction();
// public static final String NAME = "cluster/state/consistencycheck";
//
// private ConsistencyCheckAction() {
// super(NAME);
// }
//
// @Override
// public ConsistencyCheckResponse newResponse() {
// return new ConsistencyCheckResponse();
// }
//
// @Override
// public ConsistencyCheckRequestBuilder newRequestBuilder(ClusterAdminClient client) {
// return new ConsistencyCheckRequestBuilder(client);
// }
// }
//
// Path: src/main/java/org/xbib/elasticsearch/action/admin/cluster/state/ConsistencyCheckRequest.java
// public class ConsistencyCheckRequest extends MasterNodeOperationRequest<ConsistencyCheckRequest> {
//
// public ConsistencyCheckRequest() {
// }
//
// @Override
// public ActionRequestValidationException validate() {
// return null;
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// }
// }
//
// Path: src/main/java/org/xbib/elasticsearch/action/admin/cluster/state/ConsistencyCheckResponse.java
// public class ConsistencyCheckResponse extends ActionResponse {
//
// private ClusterName clusterName;
//
// private ClusterState clusterState;
//
// private List<File> files;
//
// public ConsistencyCheckResponse() {
// }
//
// ConsistencyCheckResponse(ClusterName clusterName, ClusterState clusterState, List<File> files) {
// this.clusterName = clusterName;
// this.clusterState = clusterState;
// this.files = files;
// }
//
// public ClusterState getState() {
// return this.clusterState;
// }
//
// public ClusterName getClusterName() {
// return this.clusterName;
// }
//
// public List<File> getFiles() {
// return this.files;
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// clusterName = ClusterName.readClusterName(in);
// clusterState = ClusterState.Builder.readFrom(in, null);
// int n = in.read();
// files = new ArrayList();
// for (int i = 0; i < n; i++) {
// files.set(i, new File(in.readString()));
// }
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// clusterName.writeTo(out);
// ClusterState.Builder.writeTo(clusterState, out);
// out.write(files.size());
// for (File file : files) {
// out.writeString(file.getAbsolutePath());
// }
// }
// }
| import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.joda.time.Instant;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.SizeUnit;
import org.elasticsearch.common.unit.SizeValue;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestResponseListener;
import org.xbib.elasticsearch.action.admin.cluster.state.ConsistencyCheckAction;
import org.xbib.elasticsearch.action.admin.cluster.state.ConsistencyCheckRequest;
import org.xbib.elasticsearch.action.admin.cluster.state.ConsistencyCheckResponse;
import java.io.File;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestStatus.OK; |
package org.xbib.elasticsearch.rest.action.skywalker;
/**
* REST consistency check action
*/
public class RestConsistencyCheckAction extends BaseRestHandler {
@Inject
public RestConsistencyCheckAction(Settings settings, Client client, RestController controller) {
super(settings, client);
controller.registerHandler(GET, "/_skywalker/consistencycheck", this);
}
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) throws Exception {
ConsistencyCheckRequest r = new ConsistencyCheckRequest(); | // Path: src/main/java/org/xbib/elasticsearch/action/admin/cluster/state/ConsistencyCheckAction.java
// public class ConsistencyCheckAction extends ClusterAction<ConsistencyCheckRequest, ConsistencyCheckResponse, ConsistencyCheckRequestBuilder> {
//
// public static final ConsistencyCheckAction INSTANCE = new ConsistencyCheckAction();
// public static final String NAME = "cluster/state/consistencycheck";
//
// private ConsistencyCheckAction() {
// super(NAME);
// }
//
// @Override
// public ConsistencyCheckResponse newResponse() {
// return new ConsistencyCheckResponse();
// }
//
// @Override
// public ConsistencyCheckRequestBuilder newRequestBuilder(ClusterAdminClient client) {
// return new ConsistencyCheckRequestBuilder(client);
// }
// }
//
// Path: src/main/java/org/xbib/elasticsearch/action/admin/cluster/state/ConsistencyCheckRequest.java
// public class ConsistencyCheckRequest extends MasterNodeOperationRequest<ConsistencyCheckRequest> {
//
// public ConsistencyCheckRequest() {
// }
//
// @Override
// public ActionRequestValidationException validate() {
// return null;
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// }
// }
//
// Path: src/main/java/org/xbib/elasticsearch/action/admin/cluster/state/ConsistencyCheckResponse.java
// public class ConsistencyCheckResponse extends ActionResponse {
//
// private ClusterName clusterName;
//
// private ClusterState clusterState;
//
// private List<File> files;
//
// public ConsistencyCheckResponse() {
// }
//
// ConsistencyCheckResponse(ClusterName clusterName, ClusterState clusterState, List<File> files) {
// this.clusterName = clusterName;
// this.clusterState = clusterState;
// this.files = files;
// }
//
// public ClusterState getState() {
// return this.clusterState;
// }
//
// public ClusterName getClusterName() {
// return this.clusterName;
// }
//
// public List<File> getFiles() {
// return this.files;
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// clusterName = ClusterName.readClusterName(in);
// clusterState = ClusterState.Builder.readFrom(in, null);
// int n = in.read();
// files = new ArrayList();
// for (int i = 0; i < n; i++) {
// files.set(i, new File(in.readString()));
// }
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// clusterName.writeTo(out);
// ClusterState.Builder.writeTo(clusterState, out);
// out.write(files.size());
// for (File file : files) {
// out.writeString(file.getAbsolutePath());
// }
// }
// }
// Path: src/main/java/org/xbib/elasticsearch/rest/action/skywalker/RestConsistencyCheckAction.java
import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.joda.time.Instant;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.SizeUnit;
import org.elasticsearch.common.unit.SizeValue;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestResponseListener;
import org.xbib.elasticsearch.action.admin.cluster.state.ConsistencyCheckAction;
import org.xbib.elasticsearch.action.admin.cluster.state.ConsistencyCheckRequest;
import org.xbib.elasticsearch.action.admin.cluster.state.ConsistencyCheckResponse;
import java.io.File;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestStatus.OK;
package org.xbib.elasticsearch.rest.action.skywalker;
/**
* REST consistency check action
*/
public class RestConsistencyCheckAction extends BaseRestHandler {
@Inject
public RestConsistencyCheckAction(Settings settings, Client client, RestController controller) {
super(settings, client);
controller.registerHandler(GET, "/_skywalker/consistencycheck", this);
}
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) throws Exception {
ConsistencyCheckRequest r = new ConsistencyCheckRequest(); | client.admin().cluster().execute(ConsistencyCheckAction.INSTANCE, r, new RestResponseListener<ConsistencyCheckResponse>(channel) { |
jprante/elasticsearch-skywalker | src/main/java/org/xbib/elasticsearch/skywalker/Skywalker.java | // Path: src/main/java/org/xbib/elasticsearch/skywalker/stats/FieldTermCount.java
// public class FieldTermCount implements Comparable<FieldTermCount> {
//
// private String fieldname;
//
// private long termCount;
//
// public FieldTermCount(String fieldname, long termCount) {
// this.fieldname = fieldname;
// this.termCount = termCount;
// }
//
// public String getFieldname() {
// return fieldname;
// }
//
// public long getTermCount() {
// return termCount;
// }
//
// public int compareTo(FieldTermCount f2) {
// if (termCount > f2.termCount) {
// return -1;
// } else if (termCount < f2.termCount) {
// return 1;
// } else {
// return 0;
// }
// }
// }
//
// Path: src/main/java/org/xbib/elasticsearch/skywalker/stats/TermStatsQueue.java
// public class TermStatsQueue extends PriorityQueue<TermStats> {
//
// public TermStatsQueue(int size) {
// super(size);
// }
//
// @Override
// protected boolean lessThan(TermStats termInfoA, TermStats termInfoB) {
// return termInfoA.docFreq() < termInfoB.docFreq();
// }
// }
| import org.apache.lucene.codecs.CodecUtil;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.index.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.IOContext;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.io.Streams;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.env.NodeEnvironment;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.codec.postingsformat.PostingsFormatProvider;
import org.elasticsearch.index.fielddata.FieldDataType;
import org.elasticsearch.index.mapper.FieldMapper;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.similarity.SimilarityProvider;
import org.elasticsearch.index.store.Store;
import org.elasticsearch.index.store.StoreFileMetaData;
import org.xbib.elasticsearch.skywalker.stats.FieldTermCount;
import org.xbib.elasticsearch.skywalker.stats.TermStats;
import org.xbib.elasticsearch.skywalker.stats.TermStatsQueue;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*; | if (!stateFile.getName().startsWith("global-")) {
continue;
}
files.add(stateFile);
try {
long version = Long.parseLong(stateFile.getName().substring("global-".length()));
if (version > highestVersion) {
byte[] data = Streams.copyToByteArray(new FileInputStream(stateFile));
if (data.length == 0) {
continue;
}
XContentParser parser = null;
try {
parser = XContentHelper.createParser(data, 0, data.length);
metaData = MetaData.Builder.fromXContent(parser);
highestVersion = version;
} finally {
if (parser != null) {
parser.close();
}
}
}
} catch (Exception e) {
continue;
}
}
}
return metaData;
}
| // Path: src/main/java/org/xbib/elasticsearch/skywalker/stats/FieldTermCount.java
// public class FieldTermCount implements Comparable<FieldTermCount> {
//
// private String fieldname;
//
// private long termCount;
//
// public FieldTermCount(String fieldname, long termCount) {
// this.fieldname = fieldname;
// this.termCount = termCount;
// }
//
// public String getFieldname() {
// return fieldname;
// }
//
// public long getTermCount() {
// return termCount;
// }
//
// public int compareTo(FieldTermCount f2) {
// if (termCount > f2.termCount) {
// return -1;
// } else if (termCount < f2.termCount) {
// return 1;
// } else {
// return 0;
// }
// }
// }
//
// Path: src/main/java/org/xbib/elasticsearch/skywalker/stats/TermStatsQueue.java
// public class TermStatsQueue extends PriorityQueue<TermStats> {
//
// public TermStatsQueue(int size) {
// super(size);
// }
//
// @Override
// protected boolean lessThan(TermStats termInfoA, TermStats termInfoB) {
// return termInfoA.docFreq() < termInfoB.docFreq();
// }
// }
// Path: src/main/java/org/xbib/elasticsearch/skywalker/Skywalker.java
import org.apache.lucene.codecs.CodecUtil;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.index.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.IOContext;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.io.Streams;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.env.NodeEnvironment;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.codec.postingsformat.PostingsFormatProvider;
import org.elasticsearch.index.fielddata.FieldDataType;
import org.elasticsearch.index.mapper.FieldMapper;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.similarity.SimilarityProvider;
import org.elasticsearch.index.store.Store;
import org.elasticsearch.index.store.StoreFileMetaData;
import org.xbib.elasticsearch.skywalker.stats.FieldTermCount;
import org.xbib.elasticsearch.skywalker.stats.TermStats;
import org.xbib.elasticsearch.skywalker.stats.TermStatsQueue;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
if (!stateFile.getName().startsWith("global-")) {
continue;
}
files.add(stateFile);
try {
long version = Long.parseLong(stateFile.getName().substring("global-".length()));
if (version > highestVersion) {
byte[] data = Streams.copyToByteArray(new FileInputStream(stateFile));
if (data.length == 0) {
continue;
}
XContentParser parser = null;
try {
parser = XContentHelper.createParser(data, 0, data.length);
metaData = MetaData.Builder.fromXContent(parser);
highestVersion = version;
} finally {
if (parser != null) {
parser.close();
}
}
}
} catch (Exception e) {
continue;
}
}
}
return metaData;
}
| public Set<FieldTermCount> getFieldTermCounts() throws IOException { |
jprante/elasticsearch-skywalker | src/main/java/org/xbib/elasticsearch/skywalker/Skywalker.java | // Path: src/main/java/org/xbib/elasticsearch/skywalker/stats/FieldTermCount.java
// public class FieldTermCount implements Comparable<FieldTermCount> {
//
// private String fieldname;
//
// private long termCount;
//
// public FieldTermCount(String fieldname, long termCount) {
// this.fieldname = fieldname;
// this.termCount = termCount;
// }
//
// public String getFieldname() {
// return fieldname;
// }
//
// public long getTermCount() {
// return termCount;
// }
//
// public int compareTo(FieldTermCount f2) {
// if (termCount > f2.termCount) {
// return -1;
// } else if (termCount < f2.termCount) {
// return 1;
// } else {
// return 0;
// }
// }
// }
//
// Path: src/main/java/org/xbib/elasticsearch/skywalker/stats/TermStatsQueue.java
// public class TermStatsQueue extends PriorityQueue<TermStats> {
//
// public TermStatsQueue(int size) {
// super(size);
// }
//
// @Override
// protected boolean lessThan(TermStats termInfoA, TermStats termInfoB) {
// return termInfoA.docFreq() < termInfoB.docFreq();
// }
// }
| import org.apache.lucene.codecs.CodecUtil;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.index.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.IOContext;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.io.Streams;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.env.NodeEnvironment;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.codec.postingsformat.PostingsFormatProvider;
import org.elasticsearch.index.fielddata.FieldDataType;
import org.elasticsearch.index.mapper.FieldMapper;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.similarity.SimilarityProvider;
import org.elasticsearch.index.store.Store;
import org.elasticsearch.index.store.StoreFileMetaData;
import org.xbib.elasticsearch.skywalker.stats.FieldTermCount;
import org.xbib.elasticsearch.skywalker.stats.TermStats;
import org.xbib.elasticsearch.skywalker.stats.TermStatsQueue;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*; | fld = fe.next();
long termCount = 0L;
Terms terms = fields.terms(fld);
if (terms != null) {
te = terms.iterator(te);
while (te.next() != null) {
termCount++;
numTerms++;
}
}
termCounts.add(new FieldTermCount(fld, termCount));
}
}
return termCounts;
}
public int getNumTerms() {
return numTerms;
}
public TermStats[] getTopTerms(int num) {
if (topTerms == null) {
topTerms = getHighFreqTerms(num, null);
}
return topTerms;
}
private static final TermStats[] EMPTY_STATS = new TermStats[0];
public TermStats[] getHighFreqTerms(int numTerms, String[] fieldNames) { | // Path: src/main/java/org/xbib/elasticsearch/skywalker/stats/FieldTermCount.java
// public class FieldTermCount implements Comparable<FieldTermCount> {
//
// private String fieldname;
//
// private long termCount;
//
// public FieldTermCount(String fieldname, long termCount) {
// this.fieldname = fieldname;
// this.termCount = termCount;
// }
//
// public String getFieldname() {
// return fieldname;
// }
//
// public long getTermCount() {
// return termCount;
// }
//
// public int compareTo(FieldTermCount f2) {
// if (termCount > f2.termCount) {
// return -1;
// } else if (termCount < f2.termCount) {
// return 1;
// } else {
// return 0;
// }
// }
// }
//
// Path: src/main/java/org/xbib/elasticsearch/skywalker/stats/TermStatsQueue.java
// public class TermStatsQueue extends PriorityQueue<TermStats> {
//
// public TermStatsQueue(int size) {
// super(size);
// }
//
// @Override
// protected boolean lessThan(TermStats termInfoA, TermStats termInfoB) {
// return termInfoA.docFreq() < termInfoB.docFreq();
// }
// }
// Path: src/main/java/org/xbib/elasticsearch/skywalker/Skywalker.java
import org.apache.lucene.codecs.CodecUtil;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.index.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.IOContext;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.io.Streams;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.env.NodeEnvironment;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.codec.postingsformat.PostingsFormatProvider;
import org.elasticsearch.index.fielddata.FieldDataType;
import org.elasticsearch.index.mapper.FieldMapper;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.similarity.SimilarityProvider;
import org.elasticsearch.index.store.Store;
import org.elasticsearch.index.store.StoreFileMetaData;
import org.xbib.elasticsearch.skywalker.stats.FieldTermCount;
import org.xbib.elasticsearch.skywalker.stats.TermStats;
import org.xbib.elasticsearch.skywalker.stats.TermStatsQueue;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
fld = fe.next();
long termCount = 0L;
Terms terms = fields.terms(fld);
if (terms != null) {
te = terms.iterator(te);
while (te.next() != null) {
termCount++;
numTerms++;
}
}
termCounts.add(new FieldTermCount(fld, termCount));
}
}
return termCounts;
}
public int getNumTerms() {
return numTerms;
}
public TermStats[] getTopTerms(int num) {
if (topTerms == null) {
topTerms = getHighFreqTerms(num, null);
}
return topTerms;
}
private static final TermStats[] EMPTY_STATS = new TermStats[0];
public TermStats[] getHighFreqTerms(int numTerms, String[] fieldNames) { | TermStatsQueue tiq = new TermStatsQueue(numTerms); |
jprante/elasticsearch-skywalker | src/main/java/org/xbib/elasticsearch/rest/action/skywalker/RestReconstructIndexAction.java | // Path: src/main/java/org/xbib/elasticsearch/action/admin/indices/reconstruct/ReconstructIndexAction.java
// public class ReconstructIndexAction extends IndicesAction<ReconstructIndexRequest, ReconstructIndexResponse, ReconstructIndexRequestBuilder> {
//
// public static final ReconstructIndexAction INSTANCE = new ReconstructIndexAction();
// public static final String NAME = "indices/reconstruct";
//
// private ReconstructIndexAction() {
// super(NAME);
// }
//
// @Override
// public ReconstructIndexResponse newResponse() {
// return new ReconstructIndexResponse();
// }
//
// @Override
// public ReconstructIndexRequestBuilder newRequestBuilder(IndicesAdminClient client) {
// return new ReconstructIndexRequestBuilder(client);
// }
// }
//
// Path: src/main/java/org/xbib/elasticsearch/action/admin/indices/reconstruct/ReconstructIndexRequest.java
// public class ReconstructIndexRequest extends BroadcastOperationRequest<ReconstructIndexRequest> {
//
// private String index;
//
// ReconstructIndexRequest() {
// }
//
// public ReconstructIndexRequest(String index) {
// this.index = index;
// }
//
// public String index() {
// return index;
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// this.index = in.readString();
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// out.writeString(index);
// }
// }
//
// Path: src/main/java/org/xbib/elasticsearch/action/admin/indices/reconstruct/ReconstructIndexResponse.java
// public class ReconstructIndexResponse extends BroadcastOperationResponse {
//
// protected List<ShardReconstructIndexResponse> shards;
//
// ReconstructIndexResponse() {
// }
//
// ReconstructIndexResponse(List<ShardReconstructIndexResponse> shards, int totalShards, int successfulShards, int failedShards, List<ShardOperationFailedException> shardFailures) {
// super(totalShards, successfulShards, failedShards, shardFailures);
// this.shards = shards;
// }
//
// public List<ShardReconstructIndexResponse> shards() {
// return shards;
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// int n = in.readVInt();
// shards = newArrayList();
// for (int i = 0; i < n; i++) {
// ShardReconstructIndexResponse r = new ShardReconstructIndexResponse();
// r.readFrom(in);
// shards.add(r);
// }
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// out.writeVInt(shards.size());
// for (ShardReconstructIndexResponse r : shards) {
// r.writeTo(out);
// }
// }
// }
| import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestResponseListener;
import org.xbib.elasticsearch.action.admin.indices.reconstruct.ReconstructIndexAction;
import org.xbib.elasticsearch.action.admin.indices.reconstruct.ReconstructIndexRequest;
import org.xbib.elasticsearch.action.admin.indices.reconstruct.ReconstructIndexResponse;
import org.xbib.elasticsearch.action.admin.indices.reconstruct.ShardReconstructIndexResponse;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestStatus.OK; |
package org.xbib.elasticsearch.rest.action.skywalker;
/**
* REST action for reconstructing an index
*/
public class RestReconstructIndexAction extends BaseRestHandler {
@Inject
public RestReconstructIndexAction(Settings settings, Client client, RestController controller) {
super(settings, client);
controller.registerHandler(GET, "/{index}/_skywalker/reconstruct", this);
}
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) { | // Path: src/main/java/org/xbib/elasticsearch/action/admin/indices/reconstruct/ReconstructIndexAction.java
// public class ReconstructIndexAction extends IndicesAction<ReconstructIndexRequest, ReconstructIndexResponse, ReconstructIndexRequestBuilder> {
//
// public static final ReconstructIndexAction INSTANCE = new ReconstructIndexAction();
// public static final String NAME = "indices/reconstruct";
//
// private ReconstructIndexAction() {
// super(NAME);
// }
//
// @Override
// public ReconstructIndexResponse newResponse() {
// return new ReconstructIndexResponse();
// }
//
// @Override
// public ReconstructIndexRequestBuilder newRequestBuilder(IndicesAdminClient client) {
// return new ReconstructIndexRequestBuilder(client);
// }
// }
//
// Path: src/main/java/org/xbib/elasticsearch/action/admin/indices/reconstruct/ReconstructIndexRequest.java
// public class ReconstructIndexRequest extends BroadcastOperationRequest<ReconstructIndexRequest> {
//
// private String index;
//
// ReconstructIndexRequest() {
// }
//
// public ReconstructIndexRequest(String index) {
// this.index = index;
// }
//
// public String index() {
// return index;
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// this.index = in.readString();
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// out.writeString(index);
// }
// }
//
// Path: src/main/java/org/xbib/elasticsearch/action/admin/indices/reconstruct/ReconstructIndexResponse.java
// public class ReconstructIndexResponse extends BroadcastOperationResponse {
//
// protected List<ShardReconstructIndexResponse> shards;
//
// ReconstructIndexResponse() {
// }
//
// ReconstructIndexResponse(List<ShardReconstructIndexResponse> shards, int totalShards, int successfulShards, int failedShards, List<ShardOperationFailedException> shardFailures) {
// super(totalShards, successfulShards, failedShards, shardFailures);
// this.shards = shards;
// }
//
// public List<ShardReconstructIndexResponse> shards() {
// return shards;
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// int n = in.readVInt();
// shards = newArrayList();
// for (int i = 0; i < n; i++) {
// ShardReconstructIndexResponse r = new ShardReconstructIndexResponse();
// r.readFrom(in);
// shards.add(r);
// }
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// out.writeVInt(shards.size());
// for (ShardReconstructIndexResponse r : shards) {
// r.writeTo(out);
// }
// }
// }
// Path: src/main/java/org/xbib/elasticsearch/rest/action/skywalker/RestReconstructIndexAction.java
import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestResponseListener;
import org.xbib.elasticsearch.action.admin.indices.reconstruct.ReconstructIndexAction;
import org.xbib.elasticsearch.action.admin.indices.reconstruct.ReconstructIndexRequest;
import org.xbib.elasticsearch.action.admin.indices.reconstruct.ReconstructIndexResponse;
import org.xbib.elasticsearch.action.admin.indices.reconstruct.ShardReconstructIndexResponse;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestStatus.OK;
package org.xbib.elasticsearch.rest.action.skywalker;
/**
* REST action for reconstructing an index
*/
public class RestReconstructIndexAction extends BaseRestHandler {
@Inject
public RestReconstructIndexAction(Settings settings, Client client, RestController controller) {
super(settings, client);
controller.registerHandler(GET, "/{index}/_skywalker/reconstruct", this);
}
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) { | ReconstructIndexRequest r = new ReconstructIndexRequest(request.param("index")); |
jprante/elasticsearch-skywalker | src/main/java/org/xbib/elasticsearch/rest/action/skywalker/RestReconstructIndexAction.java | // Path: src/main/java/org/xbib/elasticsearch/action/admin/indices/reconstruct/ReconstructIndexAction.java
// public class ReconstructIndexAction extends IndicesAction<ReconstructIndexRequest, ReconstructIndexResponse, ReconstructIndexRequestBuilder> {
//
// public static final ReconstructIndexAction INSTANCE = new ReconstructIndexAction();
// public static final String NAME = "indices/reconstruct";
//
// private ReconstructIndexAction() {
// super(NAME);
// }
//
// @Override
// public ReconstructIndexResponse newResponse() {
// return new ReconstructIndexResponse();
// }
//
// @Override
// public ReconstructIndexRequestBuilder newRequestBuilder(IndicesAdminClient client) {
// return new ReconstructIndexRequestBuilder(client);
// }
// }
//
// Path: src/main/java/org/xbib/elasticsearch/action/admin/indices/reconstruct/ReconstructIndexRequest.java
// public class ReconstructIndexRequest extends BroadcastOperationRequest<ReconstructIndexRequest> {
//
// private String index;
//
// ReconstructIndexRequest() {
// }
//
// public ReconstructIndexRequest(String index) {
// this.index = index;
// }
//
// public String index() {
// return index;
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// this.index = in.readString();
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// out.writeString(index);
// }
// }
//
// Path: src/main/java/org/xbib/elasticsearch/action/admin/indices/reconstruct/ReconstructIndexResponse.java
// public class ReconstructIndexResponse extends BroadcastOperationResponse {
//
// protected List<ShardReconstructIndexResponse> shards;
//
// ReconstructIndexResponse() {
// }
//
// ReconstructIndexResponse(List<ShardReconstructIndexResponse> shards, int totalShards, int successfulShards, int failedShards, List<ShardOperationFailedException> shardFailures) {
// super(totalShards, successfulShards, failedShards, shardFailures);
// this.shards = shards;
// }
//
// public List<ShardReconstructIndexResponse> shards() {
// return shards;
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// int n = in.readVInt();
// shards = newArrayList();
// for (int i = 0; i < n; i++) {
// ShardReconstructIndexResponse r = new ShardReconstructIndexResponse();
// r.readFrom(in);
// shards.add(r);
// }
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// out.writeVInt(shards.size());
// for (ShardReconstructIndexResponse r : shards) {
// r.writeTo(out);
// }
// }
// }
| import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestResponseListener;
import org.xbib.elasticsearch.action.admin.indices.reconstruct.ReconstructIndexAction;
import org.xbib.elasticsearch.action.admin.indices.reconstruct.ReconstructIndexRequest;
import org.xbib.elasticsearch.action.admin.indices.reconstruct.ReconstructIndexResponse;
import org.xbib.elasticsearch.action.admin.indices.reconstruct.ShardReconstructIndexResponse;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestStatus.OK; |
package org.xbib.elasticsearch.rest.action.skywalker;
/**
* REST action for reconstructing an index
*/
public class RestReconstructIndexAction extends BaseRestHandler {
@Inject
public RestReconstructIndexAction(Settings settings, Client client, RestController controller) {
super(settings, client);
controller.registerHandler(GET, "/{index}/_skywalker/reconstruct", this);
}
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
ReconstructIndexRequest r = new ReconstructIndexRequest(request.param("index")); | // Path: src/main/java/org/xbib/elasticsearch/action/admin/indices/reconstruct/ReconstructIndexAction.java
// public class ReconstructIndexAction extends IndicesAction<ReconstructIndexRequest, ReconstructIndexResponse, ReconstructIndexRequestBuilder> {
//
// public static final ReconstructIndexAction INSTANCE = new ReconstructIndexAction();
// public static final String NAME = "indices/reconstruct";
//
// private ReconstructIndexAction() {
// super(NAME);
// }
//
// @Override
// public ReconstructIndexResponse newResponse() {
// return new ReconstructIndexResponse();
// }
//
// @Override
// public ReconstructIndexRequestBuilder newRequestBuilder(IndicesAdminClient client) {
// return new ReconstructIndexRequestBuilder(client);
// }
// }
//
// Path: src/main/java/org/xbib/elasticsearch/action/admin/indices/reconstruct/ReconstructIndexRequest.java
// public class ReconstructIndexRequest extends BroadcastOperationRequest<ReconstructIndexRequest> {
//
// private String index;
//
// ReconstructIndexRequest() {
// }
//
// public ReconstructIndexRequest(String index) {
// this.index = index;
// }
//
// public String index() {
// return index;
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// this.index = in.readString();
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// out.writeString(index);
// }
// }
//
// Path: src/main/java/org/xbib/elasticsearch/action/admin/indices/reconstruct/ReconstructIndexResponse.java
// public class ReconstructIndexResponse extends BroadcastOperationResponse {
//
// protected List<ShardReconstructIndexResponse> shards;
//
// ReconstructIndexResponse() {
// }
//
// ReconstructIndexResponse(List<ShardReconstructIndexResponse> shards, int totalShards, int successfulShards, int failedShards, List<ShardOperationFailedException> shardFailures) {
// super(totalShards, successfulShards, failedShards, shardFailures);
// this.shards = shards;
// }
//
// public List<ShardReconstructIndexResponse> shards() {
// return shards;
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// int n = in.readVInt();
// shards = newArrayList();
// for (int i = 0; i < n; i++) {
// ShardReconstructIndexResponse r = new ShardReconstructIndexResponse();
// r.readFrom(in);
// shards.add(r);
// }
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// out.writeVInt(shards.size());
// for (ShardReconstructIndexResponse r : shards) {
// r.writeTo(out);
// }
// }
// }
// Path: src/main/java/org/xbib/elasticsearch/rest/action/skywalker/RestReconstructIndexAction.java
import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestResponseListener;
import org.xbib.elasticsearch.action.admin.indices.reconstruct.ReconstructIndexAction;
import org.xbib.elasticsearch.action.admin.indices.reconstruct.ReconstructIndexRequest;
import org.xbib.elasticsearch.action.admin.indices.reconstruct.ReconstructIndexResponse;
import org.xbib.elasticsearch.action.admin.indices.reconstruct.ShardReconstructIndexResponse;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestStatus.OK;
package org.xbib.elasticsearch.rest.action.skywalker;
/**
* REST action for reconstructing an index
*/
public class RestReconstructIndexAction extends BaseRestHandler {
@Inject
public RestReconstructIndexAction(Settings settings, Client client, RestController controller) {
super(settings, client);
controller.registerHandler(GET, "/{index}/_skywalker/reconstruct", this);
}
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
ReconstructIndexRequest r = new ReconstructIndexRequest(request.param("index")); | client.admin().indices().execute(ReconstructIndexAction.INSTANCE, r, new RestResponseListener<ReconstructIndexResponse>(channel) { |
jprante/elasticsearch-skywalker | src/main/java/org/xbib/elasticsearch/rest/action/skywalker/RestReconstructIndexAction.java | // Path: src/main/java/org/xbib/elasticsearch/action/admin/indices/reconstruct/ReconstructIndexAction.java
// public class ReconstructIndexAction extends IndicesAction<ReconstructIndexRequest, ReconstructIndexResponse, ReconstructIndexRequestBuilder> {
//
// public static final ReconstructIndexAction INSTANCE = new ReconstructIndexAction();
// public static final String NAME = "indices/reconstruct";
//
// private ReconstructIndexAction() {
// super(NAME);
// }
//
// @Override
// public ReconstructIndexResponse newResponse() {
// return new ReconstructIndexResponse();
// }
//
// @Override
// public ReconstructIndexRequestBuilder newRequestBuilder(IndicesAdminClient client) {
// return new ReconstructIndexRequestBuilder(client);
// }
// }
//
// Path: src/main/java/org/xbib/elasticsearch/action/admin/indices/reconstruct/ReconstructIndexRequest.java
// public class ReconstructIndexRequest extends BroadcastOperationRequest<ReconstructIndexRequest> {
//
// private String index;
//
// ReconstructIndexRequest() {
// }
//
// public ReconstructIndexRequest(String index) {
// this.index = index;
// }
//
// public String index() {
// return index;
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// this.index = in.readString();
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// out.writeString(index);
// }
// }
//
// Path: src/main/java/org/xbib/elasticsearch/action/admin/indices/reconstruct/ReconstructIndexResponse.java
// public class ReconstructIndexResponse extends BroadcastOperationResponse {
//
// protected List<ShardReconstructIndexResponse> shards;
//
// ReconstructIndexResponse() {
// }
//
// ReconstructIndexResponse(List<ShardReconstructIndexResponse> shards, int totalShards, int successfulShards, int failedShards, List<ShardOperationFailedException> shardFailures) {
// super(totalShards, successfulShards, failedShards, shardFailures);
// this.shards = shards;
// }
//
// public List<ShardReconstructIndexResponse> shards() {
// return shards;
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// int n = in.readVInt();
// shards = newArrayList();
// for (int i = 0; i < n; i++) {
// ShardReconstructIndexResponse r = new ShardReconstructIndexResponse();
// r.readFrom(in);
// shards.add(r);
// }
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// out.writeVInt(shards.size());
// for (ShardReconstructIndexResponse r : shards) {
// r.writeTo(out);
// }
// }
// }
| import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestResponseListener;
import org.xbib.elasticsearch.action.admin.indices.reconstruct.ReconstructIndexAction;
import org.xbib.elasticsearch.action.admin.indices.reconstruct.ReconstructIndexRequest;
import org.xbib.elasticsearch.action.admin.indices.reconstruct.ReconstructIndexResponse;
import org.xbib.elasticsearch.action.admin.indices.reconstruct.ShardReconstructIndexResponse;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestStatus.OK; |
package org.xbib.elasticsearch.rest.action.skywalker;
/**
* REST action for reconstructing an index
*/
public class RestReconstructIndexAction extends BaseRestHandler {
@Inject
public RestReconstructIndexAction(Settings settings, Client client, RestController controller) {
super(settings, client);
controller.registerHandler(GET, "/{index}/_skywalker/reconstruct", this);
}
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
ReconstructIndexRequest r = new ReconstructIndexRequest(request.param("index")); | // Path: src/main/java/org/xbib/elasticsearch/action/admin/indices/reconstruct/ReconstructIndexAction.java
// public class ReconstructIndexAction extends IndicesAction<ReconstructIndexRequest, ReconstructIndexResponse, ReconstructIndexRequestBuilder> {
//
// public static final ReconstructIndexAction INSTANCE = new ReconstructIndexAction();
// public static final String NAME = "indices/reconstruct";
//
// private ReconstructIndexAction() {
// super(NAME);
// }
//
// @Override
// public ReconstructIndexResponse newResponse() {
// return new ReconstructIndexResponse();
// }
//
// @Override
// public ReconstructIndexRequestBuilder newRequestBuilder(IndicesAdminClient client) {
// return new ReconstructIndexRequestBuilder(client);
// }
// }
//
// Path: src/main/java/org/xbib/elasticsearch/action/admin/indices/reconstruct/ReconstructIndexRequest.java
// public class ReconstructIndexRequest extends BroadcastOperationRequest<ReconstructIndexRequest> {
//
// private String index;
//
// ReconstructIndexRequest() {
// }
//
// public ReconstructIndexRequest(String index) {
// this.index = index;
// }
//
// public String index() {
// return index;
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// this.index = in.readString();
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// out.writeString(index);
// }
// }
//
// Path: src/main/java/org/xbib/elasticsearch/action/admin/indices/reconstruct/ReconstructIndexResponse.java
// public class ReconstructIndexResponse extends BroadcastOperationResponse {
//
// protected List<ShardReconstructIndexResponse> shards;
//
// ReconstructIndexResponse() {
// }
//
// ReconstructIndexResponse(List<ShardReconstructIndexResponse> shards, int totalShards, int successfulShards, int failedShards, List<ShardOperationFailedException> shardFailures) {
// super(totalShards, successfulShards, failedShards, shardFailures);
// this.shards = shards;
// }
//
// public List<ShardReconstructIndexResponse> shards() {
// return shards;
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// int n = in.readVInt();
// shards = newArrayList();
// for (int i = 0; i < n; i++) {
// ShardReconstructIndexResponse r = new ShardReconstructIndexResponse();
// r.readFrom(in);
// shards.add(r);
// }
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// out.writeVInt(shards.size());
// for (ShardReconstructIndexResponse r : shards) {
// r.writeTo(out);
// }
// }
// }
// Path: src/main/java/org/xbib/elasticsearch/rest/action/skywalker/RestReconstructIndexAction.java
import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestResponseListener;
import org.xbib.elasticsearch.action.admin.indices.reconstruct.ReconstructIndexAction;
import org.xbib.elasticsearch.action.admin.indices.reconstruct.ReconstructIndexRequest;
import org.xbib.elasticsearch.action.admin.indices.reconstruct.ReconstructIndexResponse;
import org.xbib.elasticsearch.action.admin.indices.reconstruct.ShardReconstructIndexResponse;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestStatus.OK;
package org.xbib.elasticsearch.rest.action.skywalker;
/**
* REST action for reconstructing an index
*/
public class RestReconstructIndexAction extends BaseRestHandler {
@Inject
public RestReconstructIndexAction(Settings settings, Client client, RestController controller) {
super(settings, client);
controller.registerHandler(GET, "/{index}/_skywalker/reconstruct", this);
}
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
ReconstructIndexRequest r = new ReconstructIndexRequest(request.param("index")); | client.admin().indices().execute(ReconstructIndexAction.INSTANCE, r, new RestResponseListener<ReconstructIndexResponse>(channel) { |
jprante/elasticsearch-skywalker | src/main/java/org/xbib/elasticsearch/rest/action/skywalker/RestSkywalkerAction.java | // Path: src/main/java/org/xbib/elasticsearch/action/skywalker/SkywalkerAction.java
// public class SkywalkerAction extends ClusterAction<SkywalkerRequest, SkywalkerResponse, SkywalkerRequestBuilder> {
//
// public static final SkywalkerAction INSTANCE = new SkywalkerAction();
//
// public static final String NAME = "indices/skywalker";
//
// private SkywalkerAction() {
// super(NAME);
// }
//
// @Override
// public SkywalkerResponse newResponse() {
// return new SkywalkerResponse();
// }
//
// @Override
// public SkywalkerRequestBuilder newRequestBuilder(ClusterAdminClient client) {
// return new SkywalkerRequestBuilder(client);
// }
// }
//
// Path: src/main/java/org/xbib/elasticsearch/action/skywalker/SkywalkerRequest.java
// public class SkywalkerRequest extends BroadcastOperationRequest<SkywalkerRequest> {
//
// SkywalkerRequest() {
// }
//
// public SkywalkerRequest(String... indices) {
// super(indices);
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// }
// }
| import org.elasticsearch.common.Strings;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestResponseListener;
import org.xbib.elasticsearch.action.skywalker.SkywalkerAction;
import org.xbib.elasticsearch.action.skywalker.SkywalkerRequest;
import org.xbib.elasticsearch.action.skywalker.SkywalkerResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.POST;
import static org.elasticsearch.rest.RestStatus.OK;
import static org.elasticsearch.rest.action.support.RestActions.buildBroadcastShardsHeader; |
package org.xbib.elasticsearch.rest.action.skywalker;
/**
* REST skywalker action
*/
public class RestSkywalkerAction extends BaseRestHandler {
@Inject
public RestSkywalkerAction(Settings settings, Client client, RestController controller) {
super(settings, client);
controller.registerHandler(POST, "/_skywalker", this);
controller.registerHandler(POST, "/{index}/_skywalker", this);
controller.registerHandler(GET, "/_skywalker", this);
controller.registerHandler(GET, "/{index}/_skywalker", this);
}
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) { | // Path: src/main/java/org/xbib/elasticsearch/action/skywalker/SkywalkerAction.java
// public class SkywalkerAction extends ClusterAction<SkywalkerRequest, SkywalkerResponse, SkywalkerRequestBuilder> {
//
// public static final SkywalkerAction INSTANCE = new SkywalkerAction();
//
// public static final String NAME = "indices/skywalker";
//
// private SkywalkerAction() {
// super(NAME);
// }
//
// @Override
// public SkywalkerResponse newResponse() {
// return new SkywalkerResponse();
// }
//
// @Override
// public SkywalkerRequestBuilder newRequestBuilder(ClusterAdminClient client) {
// return new SkywalkerRequestBuilder(client);
// }
// }
//
// Path: src/main/java/org/xbib/elasticsearch/action/skywalker/SkywalkerRequest.java
// public class SkywalkerRequest extends BroadcastOperationRequest<SkywalkerRequest> {
//
// SkywalkerRequest() {
// }
//
// public SkywalkerRequest(String... indices) {
// super(indices);
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// }
// }
// Path: src/main/java/org/xbib/elasticsearch/rest/action/skywalker/RestSkywalkerAction.java
import org.elasticsearch.common.Strings;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestResponseListener;
import org.xbib.elasticsearch.action.skywalker.SkywalkerAction;
import org.xbib.elasticsearch.action.skywalker.SkywalkerRequest;
import org.xbib.elasticsearch.action.skywalker.SkywalkerResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.POST;
import static org.elasticsearch.rest.RestStatus.OK;
import static org.elasticsearch.rest.action.support.RestActions.buildBroadcastShardsHeader;
package org.xbib.elasticsearch.rest.action.skywalker;
/**
* REST skywalker action
*/
public class RestSkywalkerAction extends BaseRestHandler {
@Inject
public RestSkywalkerAction(Settings settings, Client client, RestController controller) {
super(settings, client);
controller.registerHandler(POST, "/_skywalker", this);
controller.registerHandler(POST, "/{index}/_skywalker", this);
controller.registerHandler(GET, "/_skywalker", this);
controller.registerHandler(GET, "/{index}/_skywalker", this);
}
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) { | SkywalkerRequest r = new SkywalkerRequest(Strings.splitStringByCommaToArray(request.param("index"))); |
jprante/elasticsearch-skywalker | src/main/java/org/xbib/elasticsearch/rest/action/skywalker/RestSkywalkerAction.java | // Path: src/main/java/org/xbib/elasticsearch/action/skywalker/SkywalkerAction.java
// public class SkywalkerAction extends ClusterAction<SkywalkerRequest, SkywalkerResponse, SkywalkerRequestBuilder> {
//
// public static final SkywalkerAction INSTANCE = new SkywalkerAction();
//
// public static final String NAME = "indices/skywalker";
//
// private SkywalkerAction() {
// super(NAME);
// }
//
// @Override
// public SkywalkerResponse newResponse() {
// return new SkywalkerResponse();
// }
//
// @Override
// public SkywalkerRequestBuilder newRequestBuilder(ClusterAdminClient client) {
// return new SkywalkerRequestBuilder(client);
// }
// }
//
// Path: src/main/java/org/xbib/elasticsearch/action/skywalker/SkywalkerRequest.java
// public class SkywalkerRequest extends BroadcastOperationRequest<SkywalkerRequest> {
//
// SkywalkerRequest() {
// }
//
// public SkywalkerRequest(String... indices) {
// super(indices);
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// }
// }
| import org.elasticsearch.common.Strings;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestResponseListener;
import org.xbib.elasticsearch.action.skywalker.SkywalkerAction;
import org.xbib.elasticsearch.action.skywalker.SkywalkerRequest;
import org.xbib.elasticsearch.action.skywalker.SkywalkerResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.POST;
import static org.elasticsearch.rest.RestStatus.OK;
import static org.elasticsearch.rest.action.support.RestActions.buildBroadcastShardsHeader; |
package org.xbib.elasticsearch.rest.action.skywalker;
/**
* REST skywalker action
*/
public class RestSkywalkerAction extends BaseRestHandler {
@Inject
public RestSkywalkerAction(Settings settings, Client client, RestController controller) {
super(settings, client);
controller.registerHandler(POST, "/_skywalker", this);
controller.registerHandler(POST, "/{index}/_skywalker", this);
controller.registerHandler(GET, "/_skywalker", this);
controller.registerHandler(GET, "/{index}/_skywalker", this);
}
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
SkywalkerRequest r = new SkywalkerRequest(Strings.splitStringByCommaToArray(request.param("index"))); | // Path: src/main/java/org/xbib/elasticsearch/action/skywalker/SkywalkerAction.java
// public class SkywalkerAction extends ClusterAction<SkywalkerRequest, SkywalkerResponse, SkywalkerRequestBuilder> {
//
// public static final SkywalkerAction INSTANCE = new SkywalkerAction();
//
// public static final String NAME = "indices/skywalker";
//
// private SkywalkerAction() {
// super(NAME);
// }
//
// @Override
// public SkywalkerResponse newResponse() {
// return new SkywalkerResponse();
// }
//
// @Override
// public SkywalkerRequestBuilder newRequestBuilder(ClusterAdminClient client) {
// return new SkywalkerRequestBuilder(client);
// }
// }
//
// Path: src/main/java/org/xbib/elasticsearch/action/skywalker/SkywalkerRequest.java
// public class SkywalkerRequest extends BroadcastOperationRequest<SkywalkerRequest> {
//
// SkywalkerRequest() {
// }
//
// public SkywalkerRequest(String... indices) {
// super(indices);
// }
//
// @Override
// public void readFrom(StreamInput in) throws IOException {
// super.readFrom(in);
// }
//
// @Override
// public void writeTo(StreamOutput out) throws IOException {
// super.writeTo(out);
// }
// }
// Path: src/main/java/org/xbib/elasticsearch/rest/action/skywalker/RestSkywalkerAction.java
import org.elasticsearch.common.Strings;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestResponseListener;
import org.xbib.elasticsearch.action.skywalker.SkywalkerAction;
import org.xbib.elasticsearch.action.skywalker.SkywalkerRequest;
import org.xbib.elasticsearch.action.skywalker.SkywalkerResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.POST;
import static org.elasticsearch.rest.RestStatus.OK;
import static org.elasticsearch.rest.action.support.RestActions.buildBroadcastShardsHeader;
package org.xbib.elasticsearch.rest.action.skywalker;
/**
* REST skywalker action
*/
public class RestSkywalkerAction extends BaseRestHandler {
@Inject
public RestSkywalkerAction(Settings settings, Client client, RestController controller) {
super(settings, client);
controller.registerHandler(POST, "/_skywalker", this);
controller.registerHandler(POST, "/{index}/_skywalker", this);
controller.registerHandler(GET, "/_skywalker", this);
controller.registerHandler(GET, "/{index}/_skywalker", this);
}
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
SkywalkerRequest r = new SkywalkerRequest(Strings.splitStringByCommaToArray(request.param("index"))); | client.admin().cluster().execute(SkywalkerAction.INSTANCE, r, new RestResponseListener<SkywalkerResponse>(channel) { |
a750183047/MobileSafe | app/src/main/java/com/yan/mobilesafe/adapter/AppManagerAdapter.java | // Path: app/src/main/java/com/yan/mobilesafe/Bean/AppInfo.java
// public class AppInfo {
// private Drawable icon; //图片
// private String apkName; //app名字
// private long apkSize; //app大小
// private boolean isRom; //安装位置
//
// public boolean isRom() {
// return isRom;
// }
//
// public void setIsRom(boolean isRom) {
// this.isRom = isRom;
// }
//
// /**
// * 判断是否为用户app,如果是true,就是用户app否则,就是系统的
// */
// private boolean userApp; //
// private String apkPackageName; //包名
//
// public Drawable getIcon() {
// return icon;
// }
//
// public void setIcon(Drawable icon) {
// this.icon = icon;
// }
//
// public String getApkName() {
// return apkName;
// }
//
// public void setApkName(String apkName) {
// this.apkName = apkName;
// }
//
// public long getApkSize() {
// return apkSize;
// }
//
// public void setApkSize(long apkSize) {
// this.apkSize = apkSize;
// }
//
// public boolean isUserApp() {
// return userApp;
// }
//
// public void setUserApp(boolean userApp) {
// this.userApp = userApp;
// }
//
// public String getApkPackageName() {
// return apkPackageName;
// }
//
// public void setApkPackageName(String apkPackageName) {
// this.apkPackageName = apkPackageName;
// }
//
// @Override
// public String toString() {
// return "AppInfo{" +
// "icon=" + icon +
// ", apkName='" + apkName + '\'' +
// ", apkSize=" + apkSize +
// ", userApp=" + userApp +
// ", apkPackageName='" + apkPackageName + '\'' +
// '}';
// }
// }
| import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.RecyclerView;
import android.text.format.Formatter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.yan.mobilesafe.Bean.AppInfo;
import com.yan.mobilesafe.R;
import java.util.List; | package com.yan.mobilesafe.adapter;
/**
* AppManagerAdapter
* Created by a7501 on 2015/12/12.
*/
public class AppManagerAdapter extends RecyclerView.Adapter<AppManagerAdapter.SimpleViewHolder> {
private Context context; | // Path: app/src/main/java/com/yan/mobilesafe/Bean/AppInfo.java
// public class AppInfo {
// private Drawable icon; //图片
// private String apkName; //app名字
// private long apkSize; //app大小
// private boolean isRom; //安装位置
//
// public boolean isRom() {
// return isRom;
// }
//
// public void setIsRom(boolean isRom) {
// this.isRom = isRom;
// }
//
// /**
// * 判断是否为用户app,如果是true,就是用户app否则,就是系统的
// */
// private boolean userApp; //
// private String apkPackageName; //包名
//
// public Drawable getIcon() {
// return icon;
// }
//
// public void setIcon(Drawable icon) {
// this.icon = icon;
// }
//
// public String getApkName() {
// return apkName;
// }
//
// public void setApkName(String apkName) {
// this.apkName = apkName;
// }
//
// public long getApkSize() {
// return apkSize;
// }
//
// public void setApkSize(long apkSize) {
// this.apkSize = apkSize;
// }
//
// public boolean isUserApp() {
// return userApp;
// }
//
// public void setUserApp(boolean userApp) {
// this.userApp = userApp;
// }
//
// public String getApkPackageName() {
// return apkPackageName;
// }
//
// public void setApkPackageName(String apkPackageName) {
// this.apkPackageName = apkPackageName;
// }
//
// @Override
// public String toString() {
// return "AppInfo{" +
// "icon=" + icon +
// ", apkName='" + apkName + '\'' +
// ", apkSize=" + apkSize +
// ", userApp=" + userApp +
// ", apkPackageName='" + apkPackageName + '\'' +
// '}';
// }
// }
// Path: app/src/main/java/com/yan/mobilesafe/adapter/AppManagerAdapter.java
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.RecyclerView;
import android.text.format.Formatter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.yan.mobilesafe.Bean.AppInfo;
import com.yan.mobilesafe.R;
import java.util.List;
package com.yan.mobilesafe.adapter;
/**
* AppManagerAdapter
* Created by a7501 on 2015/12/12.
*/
public class AppManagerAdapter extends RecyclerView.Adapter<AppManagerAdapter.SimpleViewHolder> {
private Context context; | private List<AppInfo> appInfoList; |
a750183047/MobileSafe | app/src/main/java/com/yan/mobilesafe/adapter/AppTaskManagerHeadersAdapter.java | // Path: app/src/main/java/com/yan/mobilesafe/Bean/TaskInfo.java
// public class TaskInfo {
// private Drawable drawable;
// private String packageName;
// private String appName;
// private long memorySize;
// private boolean isUserApp; //是否为用户进程
// private boolean isChickde; //是否勾选
//
// public boolean isChickde() {
// return isChickde;
// }
//
// public void setIsChickde(boolean isChickde) {
// this.isChickde = isChickde;
// }
//
// public Drawable getDrawable() {
// return drawable;
// }
//
// public void setDrawable(Drawable drawable) {
// this.drawable = drawable;
// }
//
// public String getAppName() {
// return appName;
// }
//
// public void setAppName(String appName) {
// this.appName = appName;
// }
//
// public String getPackageName() {
// return packageName;
// }
//
// public void setPackageName(String packageName) {
// this.packageName = packageName;
// }
//
// public long getMemorySize() {
// return memorySize;
// }
//
// public void setMemorySize(long memorySize) {
// this.memorySize = memorySize;
// }
//
// public boolean isUserApp() {
// return isUserApp;
// }
//
// public void setIsUserApp(boolean isUserApp) {
// this.isUserApp = isUserApp;
// }
//
// @Override
// public String toString() {
// return "TaskInfo{" +
// "drawable=" + drawable +
// ", packageName='" + packageName + '\'' +
// ", appName='" + appName + '\'' +
// ", memorySize=" + memorySize +
// ", isUserApp=" + isUserApp +
// '}';
// }
// }
//
// Path: app/src/main/java/com/yan/mobilesafe/adapter/listentr/MyItemClickListener.java
// public interface MyItemClickListener {
// public void onItemClick(View view,int position);
// }
| import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.RecyclerView;
import android.text.format.Formatter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersAdapter;
import com.yan.mobilesafe.Bean.TaskInfo;
import com.yan.mobilesafe.R;
import com.yan.mobilesafe.adapter.listentr.MyItemClickListener;
import java.util.List; | package com.yan.mobilesafe.adapter;
/**
* 软件内存信息adapter
* Created by a7501 on 2015/12/21.
*/
public class AppTaskManagerHeadersAdapter extends
RecyclerView.Adapter<AppTaskManagerHeadersAdapter.SimpleViewHolder> implements
StickyRecyclerHeadersAdapter<AppTaskManagerHeadersAdapter.ViewHeadersHolder> {
private Context context; | // Path: app/src/main/java/com/yan/mobilesafe/Bean/TaskInfo.java
// public class TaskInfo {
// private Drawable drawable;
// private String packageName;
// private String appName;
// private long memorySize;
// private boolean isUserApp; //是否为用户进程
// private boolean isChickde; //是否勾选
//
// public boolean isChickde() {
// return isChickde;
// }
//
// public void setIsChickde(boolean isChickde) {
// this.isChickde = isChickde;
// }
//
// public Drawable getDrawable() {
// return drawable;
// }
//
// public void setDrawable(Drawable drawable) {
// this.drawable = drawable;
// }
//
// public String getAppName() {
// return appName;
// }
//
// public void setAppName(String appName) {
// this.appName = appName;
// }
//
// public String getPackageName() {
// return packageName;
// }
//
// public void setPackageName(String packageName) {
// this.packageName = packageName;
// }
//
// public long getMemorySize() {
// return memorySize;
// }
//
// public void setMemorySize(long memorySize) {
// this.memorySize = memorySize;
// }
//
// public boolean isUserApp() {
// return isUserApp;
// }
//
// public void setIsUserApp(boolean isUserApp) {
// this.isUserApp = isUserApp;
// }
//
// @Override
// public String toString() {
// return "TaskInfo{" +
// "drawable=" + drawable +
// ", packageName='" + packageName + '\'' +
// ", appName='" + appName + '\'' +
// ", memorySize=" + memorySize +
// ", isUserApp=" + isUserApp +
// '}';
// }
// }
//
// Path: app/src/main/java/com/yan/mobilesafe/adapter/listentr/MyItemClickListener.java
// public interface MyItemClickListener {
// public void onItemClick(View view,int position);
// }
// Path: app/src/main/java/com/yan/mobilesafe/adapter/AppTaskManagerHeadersAdapter.java
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.RecyclerView;
import android.text.format.Formatter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersAdapter;
import com.yan.mobilesafe.Bean.TaskInfo;
import com.yan.mobilesafe.R;
import com.yan.mobilesafe.adapter.listentr.MyItemClickListener;
import java.util.List;
package com.yan.mobilesafe.adapter;
/**
* 软件内存信息adapter
* Created by a7501 on 2015/12/21.
*/
public class AppTaskManagerHeadersAdapter extends
RecyclerView.Adapter<AppTaskManagerHeadersAdapter.SimpleViewHolder> implements
StickyRecyclerHeadersAdapter<AppTaskManagerHeadersAdapter.ViewHeadersHolder> {
private Context context; | private List<TaskInfo> taskInfos; |
a750183047/MobileSafe | app/src/main/java/com/yan/mobilesafe/adapter/AppTaskManagerHeadersAdapter.java | // Path: app/src/main/java/com/yan/mobilesafe/Bean/TaskInfo.java
// public class TaskInfo {
// private Drawable drawable;
// private String packageName;
// private String appName;
// private long memorySize;
// private boolean isUserApp; //是否为用户进程
// private boolean isChickde; //是否勾选
//
// public boolean isChickde() {
// return isChickde;
// }
//
// public void setIsChickde(boolean isChickde) {
// this.isChickde = isChickde;
// }
//
// public Drawable getDrawable() {
// return drawable;
// }
//
// public void setDrawable(Drawable drawable) {
// this.drawable = drawable;
// }
//
// public String getAppName() {
// return appName;
// }
//
// public void setAppName(String appName) {
// this.appName = appName;
// }
//
// public String getPackageName() {
// return packageName;
// }
//
// public void setPackageName(String packageName) {
// this.packageName = packageName;
// }
//
// public long getMemorySize() {
// return memorySize;
// }
//
// public void setMemorySize(long memorySize) {
// this.memorySize = memorySize;
// }
//
// public boolean isUserApp() {
// return isUserApp;
// }
//
// public void setIsUserApp(boolean isUserApp) {
// this.isUserApp = isUserApp;
// }
//
// @Override
// public String toString() {
// return "TaskInfo{" +
// "drawable=" + drawable +
// ", packageName='" + packageName + '\'' +
// ", appName='" + appName + '\'' +
// ", memorySize=" + memorySize +
// ", isUserApp=" + isUserApp +
// '}';
// }
// }
//
// Path: app/src/main/java/com/yan/mobilesafe/adapter/listentr/MyItemClickListener.java
// public interface MyItemClickListener {
// public void onItemClick(View view,int position);
// }
| import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.RecyclerView;
import android.text.format.Formatter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersAdapter;
import com.yan.mobilesafe.Bean.TaskInfo;
import com.yan.mobilesafe.R;
import com.yan.mobilesafe.adapter.listentr.MyItemClickListener;
import java.util.List; | package com.yan.mobilesafe.adapter;
/**
* 软件内存信息adapter
* Created by a7501 on 2015/12/21.
*/
public class AppTaskManagerHeadersAdapter extends
RecyclerView.Adapter<AppTaskManagerHeadersAdapter.SimpleViewHolder> implements
StickyRecyclerHeadersAdapter<AppTaskManagerHeadersAdapter.ViewHeadersHolder> {
private Context context;
private List<TaskInfo> taskInfos;
private List<TaskInfo> userInfos;
private List<TaskInfo> systemInfos;
private String appName;
private Drawable icon;
private String appSize; | // Path: app/src/main/java/com/yan/mobilesafe/Bean/TaskInfo.java
// public class TaskInfo {
// private Drawable drawable;
// private String packageName;
// private String appName;
// private long memorySize;
// private boolean isUserApp; //是否为用户进程
// private boolean isChickde; //是否勾选
//
// public boolean isChickde() {
// return isChickde;
// }
//
// public void setIsChickde(boolean isChickde) {
// this.isChickde = isChickde;
// }
//
// public Drawable getDrawable() {
// return drawable;
// }
//
// public void setDrawable(Drawable drawable) {
// this.drawable = drawable;
// }
//
// public String getAppName() {
// return appName;
// }
//
// public void setAppName(String appName) {
// this.appName = appName;
// }
//
// public String getPackageName() {
// return packageName;
// }
//
// public void setPackageName(String packageName) {
// this.packageName = packageName;
// }
//
// public long getMemorySize() {
// return memorySize;
// }
//
// public void setMemorySize(long memorySize) {
// this.memorySize = memorySize;
// }
//
// public boolean isUserApp() {
// return isUserApp;
// }
//
// public void setIsUserApp(boolean isUserApp) {
// this.isUserApp = isUserApp;
// }
//
// @Override
// public String toString() {
// return "TaskInfo{" +
// "drawable=" + drawable +
// ", packageName='" + packageName + '\'' +
// ", appName='" + appName + '\'' +
// ", memorySize=" + memorySize +
// ", isUserApp=" + isUserApp +
// '}';
// }
// }
//
// Path: app/src/main/java/com/yan/mobilesafe/adapter/listentr/MyItemClickListener.java
// public interface MyItemClickListener {
// public void onItemClick(View view,int position);
// }
// Path: app/src/main/java/com/yan/mobilesafe/adapter/AppTaskManagerHeadersAdapter.java
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.RecyclerView;
import android.text.format.Formatter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersAdapter;
import com.yan.mobilesafe.Bean.TaskInfo;
import com.yan.mobilesafe.R;
import com.yan.mobilesafe.adapter.listentr.MyItemClickListener;
import java.util.List;
package com.yan.mobilesafe.adapter;
/**
* 软件内存信息adapter
* Created by a7501 on 2015/12/21.
*/
public class AppTaskManagerHeadersAdapter extends
RecyclerView.Adapter<AppTaskManagerHeadersAdapter.SimpleViewHolder> implements
StickyRecyclerHeadersAdapter<AppTaskManagerHeadersAdapter.ViewHeadersHolder> {
private Context context;
private List<TaskInfo> taskInfos;
private List<TaskInfo> userInfos;
private List<TaskInfo> systemInfos;
private String appName;
private Drawable icon;
private String appSize; | private MyItemClickListener listener; |
a750183047/MobileSafe | app/src/main/java/com/yan/mobilesafe/Service/AddressService.java | // Path: app/src/main/java/com/yan/mobilesafe/DataBase/AddressDB.java
// public class AddressDB {
// private static final String PATH = "data/data/com.yan.mobilesafe/files/address.db";
//
// public static String getAddress(String number){
// String address = "未知号码";
//
// //获取数据库对象
// SQLiteDatabase database = SQLiteDatabase.openDatabase(PATH,null,SQLiteDatabase.OPEN_READONLY);
//
// //手机号正则表达式匹配
// //1 + (3.4.5.6.7.8)+(9位数字)
// //^1[3-8]\d{9}$
//
// if (number.matches("^1[3-8]\\d{9}$")){
// Cursor cursor = database.rawQuery("select location from data2 where id = (select outkey from data1 where id = ?)"
// ,new String[]{number.substring(0,7)});
// if (cursor.moveToNext()){
// address = cursor.getString(0);
// }
// cursor.close();
// }else if (number.matches("^\\d+$")){ //匹配数字
// switch (number.length()){
// case 3:
// address = "报警电话";
// break;
// case 4:
// address = "模拟器电话";
// break;
// case 5:
// address = "客服电话";
// break;
// case 7:
// case 8:
// address = "本地电话";
// break;
// default:
// //03154011111
// //01055225525
// if (number.startsWith("0") && number.length()>10){ //可能是长途电话
// //先查询3位区号
// Cursor cursor = database.rawQuery("select location from data2 where area = ?",
// new String[]{number.substring(1,3)});
// if (cursor.moveToNext()){
// address = cursor.getString(0);
// address = address.substring(0,address.length()-2);
// }else {
// cursor.close();
// //查询4位区号
// cursor = database.rawQuery("select location from data2 where area = ?",
// new String[]{number.substring(1,4)});
// if (cursor.moveToNext()){
// address = cursor.getString(0);
// address = address.substring(0,address.length()-2);
// }
// cursor.close();
// }
// }
// break;
// }
// }
//
// database.close();
// return address;
// }
// }
//
// Path: app/src/main/java/com/yan/mobilesafe/utils/ToastUtils.java
// public class ToastUtils {
// public static void showToast(final Activity context, final String string){
// if ("main".equals(Thread.currentThread().getName())){ //判断是否为主线程
// Toast.makeText(context,string,Toast.LENGTH_SHORT).show();
// }else {
// context.runOnUiThread(new Runnable() { //如果不是,就用该方法使其在ui线程中运行
// @Override
// public void run() {
// Toast.makeText(context, string, Toast.LENGTH_SHORT).show();
// }
// });
// }
//
// }
// }
| import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import com.yan.mobilesafe.DataBase.AddressDB;
import com.yan.mobilesafe.R;
import com.yan.mobilesafe.utils.ToastUtils; | package com.yan.mobilesafe.Service;
/**
* 监听电话服务
* Created by a7501 on 2015/11/30.
*/
public class AddressService extends Service {
private TelephonyManager telephonyManager;
private MyListener listener;
private OutCallReceiver receiver;
private WindowManager windowManager;
private View view;
private int startY;
private int startX;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
listener = new MyListener();
telephonyManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE); //监听来电状态
receiver = new OutCallReceiver();
IntentFilter filter = new IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL);
registerReceiver(receiver, filter); //动态注册广播
}
class MyListener extends PhoneStateListener {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING: //电话响了
Log.e("AddressService", "来电话了"); | // Path: app/src/main/java/com/yan/mobilesafe/DataBase/AddressDB.java
// public class AddressDB {
// private static final String PATH = "data/data/com.yan.mobilesafe/files/address.db";
//
// public static String getAddress(String number){
// String address = "未知号码";
//
// //获取数据库对象
// SQLiteDatabase database = SQLiteDatabase.openDatabase(PATH,null,SQLiteDatabase.OPEN_READONLY);
//
// //手机号正则表达式匹配
// //1 + (3.4.5.6.7.8)+(9位数字)
// //^1[3-8]\d{9}$
//
// if (number.matches("^1[3-8]\\d{9}$")){
// Cursor cursor = database.rawQuery("select location from data2 where id = (select outkey from data1 where id = ?)"
// ,new String[]{number.substring(0,7)});
// if (cursor.moveToNext()){
// address = cursor.getString(0);
// }
// cursor.close();
// }else if (number.matches("^\\d+$")){ //匹配数字
// switch (number.length()){
// case 3:
// address = "报警电话";
// break;
// case 4:
// address = "模拟器电话";
// break;
// case 5:
// address = "客服电话";
// break;
// case 7:
// case 8:
// address = "本地电话";
// break;
// default:
// //03154011111
// //01055225525
// if (number.startsWith("0") && number.length()>10){ //可能是长途电话
// //先查询3位区号
// Cursor cursor = database.rawQuery("select location from data2 where area = ?",
// new String[]{number.substring(1,3)});
// if (cursor.moveToNext()){
// address = cursor.getString(0);
// address = address.substring(0,address.length()-2);
// }else {
// cursor.close();
// //查询4位区号
// cursor = database.rawQuery("select location from data2 where area = ?",
// new String[]{number.substring(1,4)});
// if (cursor.moveToNext()){
// address = cursor.getString(0);
// address = address.substring(0,address.length()-2);
// }
// cursor.close();
// }
// }
// break;
// }
// }
//
// database.close();
// return address;
// }
// }
//
// Path: app/src/main/java/com/yan/mobilesafe/utils/ToastUtils.java
// public class ToastUtils {
// public static void showToast(final Activity context, final String string){
// if ("main".equals(Thread.currentThread().getName())){ //判断是否为主线程
// Toast.makeText(context,string,Toast.LENGTH_SHORT).show();
// }else {
// context.runOnUiThread(new Runnable() { //如果不是,就用该方法使其在ui线程中运行
// @Override
// public void run() {
// Toast.makeText(context, string, Toast.LENGTH_SHORT).show();
// }
// });
// }
//
// }
// }
// Path: app/src/main/java/com/yan/mobilesafe/Service/AddressService.java
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import com.yan.mobilesafe.DataBase.AddressDB;
import com.yan.mobilesafe.R;
import com.yan.mobilesafe.utils.ToastUtils;
package com.yan.mobilesafe.Service;
/**
* 监听电话服务
* Created by a7501 on 2015/11/30.
*/
public class AddressService extends Service {
private TelephonyManager telephonyManager;
private MyListener listener;
private OutCallReceiver receiver;
private WindowManager windowManager;
private View view;
private int startY;
private int startX;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
listener = new MyListener();
telephonyManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE); //监听来电状态
receiver = new OutCallReceiver();
IntentFilter filter = new IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL);
registerReceiver(receiver, filter); //动态注册广播
}
class MyListener extends PhoneStateListener {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING: //电话响了
Log.e("AddressService", "来电话了"); | String address = AddressDB.getAddress(incomingNumber); |
a750183047/MobileSafe | app/src/main/java/com/yan/mobilesafe/activity/Simguard.java | // Path: app/src/main/java/com/yan/mobilesafe/activity/Setup/SetupActivity1.java
// public class SetupActivity1 extends AppCompatActivity {
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_setup1);
// Button next = (Button) findViewById(R.id.next);
//
// next.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
//
// startActivity(new Intent(getApplicationContext(), SetupActivity2.class));
// finish();
// overridePendingTransition(R.anim.tran_in, R.anim.tran_out);//进入动画和退出动画
//
// }
// });
// }
// }
//
// Path: app/src/main/java/com/yan/mobilesafe/utils/MD5utils.java
// public class MD5utils {
// /**
// * Md5加密
// */
// public static String encode(String password) {
// MessageDigest messageDigest = null;
// try {
// messageDigest = MessageDigest.getInstance("MD5");
// } catch (NoSuchAlgorithmException e) {
// e.printStackTrace();
// }
// byte[] digest = messageDigest.digest(password.getBytes());
//
// StringBuffer stringBuffer = new StringBuffer();
// for (byte b : digest) {
// int i = b & 0xff; //获取字节的低八位
// String hexString = Integer.toHexString(i); //转换成16进制
//
// if (hexString.length() < 2) {
// hexString = "0" + hexString;
// }
// stringBuffer.append(hexString);
// }
// return stringBuffer.toString();
// }
// }
| import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.yan.mobilesafe.R;
import com.yan.mobilesafe.activity.Setup.SetupActivity1;
import com.yan.mobilesafe.utils.MD5utils; | String savePassword = sharedPreferences.getString("password", null);
if (!TextUtils.isEmpty(savePassword)) {
showPasswordInputDialog();
} else {
showPasswordSetDialog();
}
}
/**
* 弹出输入密码框
*/
private void showPasswordInputDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final AlertDialog dialog = builder.create();
dialog.setView(viewInput);
dialog.setCancelable(false);
Button btnOk = (Button) viewInput.findViewById(R.id.btn_ok);
Button btnCancel = (Button) viewInput.findViewById(R.id.btn_cancel);
passwordInput = (EditText) viewInput.findViewById(R.id.et_password);
btnOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String password = passwordInput.getText().toString();
if (!TextUtils.isEmpty(password)) {
String savePassword = sharedPreferences.getString("password", null);
//校验密码 | // Path: app/src/main/java/com/yan/mobilesafe/activity/Setup/SetupActivity1.java
// public class SetupActivity1 extends AppCompatActivity {
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_setup1);
// Button next = (Button) findViewById(R.id.next);
//
// next.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
//
// startActivity(new Intent(getApplicationContext(), SetupActivity2.class));
// finish();
// overridePendingTransition(R.anim.tran_in, R.anim.tran_out);//进入动画和退出动画
//
// }
// });
// }
// }
//
// Path: app/src/main/java/com/yan/mobilesafe/utils/MD5utils.java
// public class MD5utils {
// /**
// * Md5加密
// */
// public static String encode(String password) {
// MessageDigest messageDigest = null;
// try {
// messageDigest = MessageDigest.getInstance("MD5");
// } catch (NoSuchAlgorithmException e) {
// e.printStackTrace();
// }
// byte[] digest = messageDigest.digest(password.getBytes());
//
// StringBuffer stringBuffer = new StringBuffer();
// for (byte b : digest) {
// int i = b & 0xff; //获取字节的低八位
// String hexString = Integer.toHexString(i); //转换成16进制
//
// if (hexString.length() < 2) {
// hexString = "0" + hexString;
// }
// stringBuffer.append(hexString);
// }
// return stringBuffer.toString();
// }
// }
// Path: app/src/main/java/com/yan/mobilesafe/activity/Simguard.java
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.yan.mobilesafe.R;
import com.yan.mobilesafe.activity.Setup.SetupActivity1;
import com.yan.mobilesafe.utils.MD5utils;
String savePassword = sharedPreferences.getString("password", null);
if (!TextUtils.isEmpty(savePassword)) {
showPasswordInputDialog();
} else {
showPasswordSetDialog();
}
}
/**
* 弹出输入密码框
*/
private void showPasswordInputDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final AlertDialog dialog = builder.create();
dialog.setView(viewInput);
dialog.setCancelable(false);
Button btnOk = (Button) viewInput.findViewById(R.id.btn_ok);
Button btnCancel = (Button) viewInput.findViewById(R.id.btn_cancel);
passwordInput = (EditText) viewInput.findViewById(R.id.et_password);
btnOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String password = passwordInput.getText().toString();
if (!TextUtils.isEmpty(password)) {
String savePassword = sharedPreferences.getString("password", null);
//校验密码 | if (MD5utils.encode(password).equals(savePassword)) { |
a750183047/MobileSafe | app/src/main/java/com/yan/mobilesafe/activity/Simguard.java | // Path: app/src/main/java/com/yan/mobilesafe/activity/Setup/SetupActivity1.java
// public class SetupActivity1 extends AppCompatActivity {
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_setup1);
// Button next = (Button) findViewById(R.id.next);
//
// next.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
//
// startActivity(new Intent(getApplicationContext(), SetupActivity2.class));
// finish();
// overridePendingTransition(R.anim.tran_in, R.anim.tran_out);//进入动画和退出动画
//
// }
// });
// }
// }
//
// Path: app/src/main/java/com/yan/mobilesafe/utils/MD5utils.java
// public class MD5utils {
// /**
// * Md5加密
// */
// public static String encode(String password) {
// MessageDigest messageDigest = null;
// try {
// messageDigest = MessageDigest.getInstance("MD5");
// } catch (NoSuchAlgorithmException e) {
// e.printStackTrace();
// }
// byte[] digest = messageDigest.digest(password.getBytes());
//
// StringBuffer stringBuffer = new StringBuffer();
// for (byte b : digest) {
// int i = b & 0xff; //获取字节的低八位
// String hexString = Integer.toHexString(i); //转换成16进制
//
// if (hexString.length() < 2) {
// hexString = "0" + hexString;
// }
// stringBuffer.append(hexString);
// }
// return stringBuffer.toString();
// }
// }
| import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.yan.mobilesafe.R;
import com.yan.mobilesafe.activity.Setup.SetupActivity1;
import com.yan.mobilesafe.utils.MD5utils; | @Override
public void afterTextChanged(Editable s) {
if (TextUtils.isEmpty(etPassword.getText().toString())
&& TextUtils.isEmpty(etPasswordConfirm.getText().toString())) {
btnOk.setEnabled(false);
} else {
btnOk.setEnabled(true);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
finish();
}
/**
* 判断是否进入引导页进入引导页
*/
private void isFirstIn() {
if (configed) {
setContentView(R.layout.sim_guard_layout);
intosetting = (TextView) findViewById(R.id.into_setting);
safeNumber = (TextView) findViewById(R.id.safe_number);
lockioc = (ImageView) findViewById(R.id.lock);
intosetting.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { | // Path: app/src/main/java/com/yan/mobilesafe/activity/Setup/SetupActivity1.java
// public class SetupActivity1 extends AppCompatActivity {
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_setup1);
// Button next = (Button) findViewById(R.id.next);
//
// next.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
//
// startActivity(new Intent(getApplicationContext(), SetupActivity2.class));
// finish();
// overridePendingTransition(R.anim.tran_in, R.anim.tran_out);//进入动画和退出动画
//
// }
// });
// }
// }
//
// Path: app/src/main/java/com/yan/mobilesafe/utils/MD5utils.java
// public class MD5utils {
// /**
// * Md5加密
// */
// public static String encode(String password) {
// MessageDigest messageDigest = null;
// try {
// messageDigest = MessageDigest.getInstance("MD5");
// } catch (NoSuchAlgorithmException e) {
// e.printStackTrace();
// }
// byte[] digest = messageDigest.digest(password.getBytes());
//
// StringBuffer stringBuffer = new StringBuffer();
// for (byte b : digest) {
// int i = b & 0xff; //获取字节的低八位
// String hexString = Integer.toHexString(i); //转换成16进制
//
// if (hexString.length() < 2) {
// hexString = "0" + hexString;
// }
// stringBuffer.append(hexString);
// }
// return stringBuffer.toString();
// }
// }
// Path: app/src/main/java/com/yan/mobilesafe/activity/Simguard.java
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.yan.mobilesafe.R;
import com.yan.mobilesafe.activity.Setup.SetupActivity1;
import com.yan.mobilesafe.utils.MD5utils;
@Override
public void afterTextChanged(Editable s) {
if (TextUtils.isEmpty(etPassword.getText().toString())
&& TextUtils.isEmpty(etPasswordConfirm.getText().toString())) {
btnOk.setEnabled(false);
} else {
btnOk.setEnabled(true);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
finish();
}
/**
* 判断是否进入引导页进入引导页
*/
private void isFirstIn() {
if (configed) {
setContentView(R.layout.sim_guard_layout);
intosetting = (TextView) findViewById(R.id.into_setting);
safeNumber = (TextView) findViewById(R.id.safe_number);
lockioc = (ImageView) findViewById(R.id.lock);
intosetting.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { | startActivity(new Intent(SimGuard.this, SetupActivity1.class)); |
a750183047/MobileSafe | app/src/main/java/com/yan/mobilesafe/DataBase/BlackNumberDb.java | // Path: app/src/main/java/com/yan/mobilesafe/Bean/BlackNumberInfo.java
// public class BlackNumberInfo {
// private String number; //黑名单号码
//
// /**
// * 1全部拦截,电话+短信
// * 2电话拦截
// * 3短信拦截
// */
// private String mode; //模式
//
// public String getMode() {
// return mode;
// }
//
// public void setMode(String mode) {
// this.mode = mode;
// }
//
// public String getNumber() {
//
// return number;
// }
//
// public void setNumber(String number) {
// this.number = number;
// }
// }
| import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.SystemClock;
import com.yan.mobilesafe.Bean.BlackNumberInfo;
import java.util.ArrayList;
import java.util.List; | public boolean changeNumberMode(String number, String mode) {
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("mode", mode);
int update = db.update(TABLENAME, contentValues, "number = ?", new String[]{number});
return update != 0;
}
/**
* 查找号码的拦截模式
*
* @param number 号码
* @return 模式
*/
public String findNumber(String number) {
SQLiteDatabase db = helper.getWritableDatabase();
Cursor cursor = db.query(TABLENAME, new String[]{"mode"}, "number = ?", new String[]{number}, null, null, null);
if (cursor.moveToNext()) {
mode = cursor.getString(cursor.getColumnIndex("mode"));
}
cursor.close();
db.close();
return mode;
}
/**
* 查询所有黑名单
*
* @return
*/ | // Path: app/src/main/java/com/yan/mobilesafe/Bean/BlackNumberInfo.java
// public class BlackNumberInfo {
// private String number; //黑名单号码
//
// /**
// * 1全部拦截,电话+短信
// * 2电话拦截
// * 3短信拦截
// */
// private String mode; //模式
//
// public String getMode() {
// return mode;
// }
//
// public void setMode(String mode) {
// this.mode = mode;
// }
//
// public String getNumber() {
//
// return number;
// }
//
// public void setNumber(String number) {
// this.number = number;
// }
// }
// Path: app/src/main/java/com/yan/mobilesafe/DataBase/BlackNumberDb.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.SystemClock;
import com.yan.mobilesafe.Bean.BlackNumberInfo;
import java.util.ArrayList;
import java.util.List;
public boolean changeNumberMode(String number, String mode) {
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("mode", mode);
int update = db.update(TABLENAME, contentValues, "number = ?", new String[]{number});
return update != 0;
}
/**
* 查找号码的拦截模式
*
* @param number 号码
* @return 模式
*/
public String findNumber(String number) {
SQLiteDatabase db = helper.getWritableDatabase();
Cursor cursor = db.query(TABLENAME, new String[]{"mode"}, "number = ?", new String[]{number}, null, null, null);
if (cursor.moveToNext()) {
mode = cursor.getString(cursor.getColumnIndex("mode"));
}
cursor.close();
db.close();
return mode;
}
/**
* 查询所有黑名单
*
* @return
*/ | public List<BlackNumberInfo> findAll() { |
a750183047/MobileSafe | app/src/main/java/com/yan/mobilesafe/activity/MainActivity.java | // Path: app/src/main/java/com/yan/mobilesafe/utils/StreamUtils.java
// public class StreamUtils {
//
// /**
// * 转换成字符串
// * **/
// public static String readFromStream(InputStream stream) throws IOException {
// ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//
// int len = 0;
// byte[] bytes = new byte[1024];
//
// while((len = stream.read(bytes))!= -1){
// outputStream.write(bytes,0,len);
// }
// String result = outputStream.toString();
// stream.close();
// outputStream.close();
// return result;
//
// }
// }
| import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.yan.mobilesafe.R;
import com.yan.mobilesafe.utils.StreamUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import android.os.Handler; | } else {
handler.sendEmptyMessageDelayed(CODE_NO_UP_UPDATE, 1000);
}
}
/**
* 从服务器获取版本信息进行校验
*/
private void checkVersion() {
final long startTime = System.currentTimeMillis(); //获取当前时间
new Thread() {
@Override
public void run() {
message = Message.obtain();
HttpURLConnection connection = null;
try {
URL url = new URL(UPDATEURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");//设置请求方法
connection.setConnectTimeout(5000); //设置连接超时
connection.setReadTimeout(5000); //设置响应超时
connection.connect(); //连接服务器
int responseCode = connection.getResponseCode(); //获得响应码
if (responseCode == 200) {
InputStream inputStream = connection.getInputStream(); //获取输入流 | // Path: app/src/main/java/com/yan/mobilesafe/utils/StreamUtils.java
// public class StreamUtils {
//
// /**
// * 转换成字符串
// * **/
// public static String readFromStream(InputStream stream) throws IOException {
// ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//
// int len = 0;
// byte[] bytes = new byte[1024];
//
// while((len = stream.read(bytes))!= -1){
// outputStream.write(bytes,0,len);
// }
// String result = outputStream.toString();
// stream.close();
// outputStream.close();
// return result;
//
// }
// }
// Path: app/src/main/java/com/yan/mobilesafe/activity/MainActivity.java
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.yan.mobilesafe.R;
import com.yan.mobilesafe.utils.StreamUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import android.os.Handler;
} else {
handler.sendEmptyMessageDelayed(CODE_NO_UP_UPDATE, 1000);
}
}
/**
* 从服务器获取版本信息进行校验
*/
private void checkVersion() {
final long startTime = System.currentTimeMillis(); //获取当前时间
new Thread() {
@Override
public void run() {
message = Message.obtain();
HttpURLConnection connection = null;
try {
URL url = new URL(UPDATEURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");//设置请求方法
connection.setConnectTimeout(5000); //设置连接超时
connection.setReadTimeout(5000); //设置响应超时
connection.connect(); //连接服务器
int responseCode = connection.getResponseCode(); //获得响应码
if (responseCode == 200) {
InputStream inputStream = connection.getInputStream(); //获取输入流 | String result = StreamUtils.readFromStream(inputStream); //把输入流转成字符串 |
a750183047/MobileSafe | app/src/main/java/com/yan/mobilesafe/adapter/AppManagerHeadersAdapter.java | // Path: app/src/main/java/com/yan/mobilesafe/Bean/AppInfo.java
// public class AppInfo {
// private Drawable icon; //图片
// private String apkName; //app名字
// private long apkSize; //app大小
// private boolean isRom; //安装位置
//
// public boolean isRom() {
// return isRom;
// }
//
// public void setIsRom(boolean isRom) {
// this.isRom = isRom;
// }
//
// /**
// * 判断是否为用户app,如果是true,就是用户app否则,就是系统的
// */
// private boolean userApp; //
// private String apkPackageName; //包名
//
// public Drawable getIcon() {
// return icon;
// }
//
// public void setIcon(Drawable icon) {
// this.icon = icon;
// }
//
// public String getApkName() {
// return apkName;
// }
//
// public void setApkName(String apkName) {
// this.apkName = apkName;
// }
//
// public long getApkSize() {
// return apkSize;
// }
//
// public void setApkSize(long apkSize) {
// this.apkSize = apkSize;
// }
//
// public boolean isUserApp() {
// return userApp;
// }
//
// public void setUserApp(boolean userApp) {
// this.userApp = userApp;
// }
//
// public String getApkPackageName() {
// return apkPackageName;
// }
//
// public void setApkPackageName(String apkPackageName) {
// this.apkPackageName = apkPackageName;
// }
//
// @Override
// public String toString() {
// return "AppInfo{" +
// "icon=" + icon +
// ", apkName='" + apkName + '\'' +
// ", apkSize=" + apkSize +
// ", userApp=" + userApp +
// ", apkPackageName='" + apkPackageName + '\'' +
// '}';
// }
// }
//
// Path: app/src/main/java/com/yan/mobilesafe/adapter/listentr/MyItemClickListener.java
// public interface MyItemClickListener {
// public void onItemClick(View view,int position);
// }
//
// Path: app/src/main/java/com/yan/mobilesafe/utils/ToastUtils.java
// public class ToastUtils {
// public static void showToast(final Activity context, final String string){
// if ("main".equals(Thread.currentThread().getName())){ //判断是否为主线程
// Toast.makeText(context,string,Toast.LENGTH_SHORT).show();
// }else {
// context.runOnUiThread(new Runnable() { //如果不是,就用该方法使其在ui线程中运行
// @Override
// public void run() {
// Toast.makeText(context, string, Toast.LENGTH_SHORT).show();
// }
// });
// }
//
// }
// }
| import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.text.format.Formatter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersAdapter;
import com.yan.mobilesafe.Bean.AppInfo;
import com.yan.mobilesafe.R;
import com.yan.mobilesafe.adapter.listentr.MyItemClickListener;
import com.yan.mobilesafe.utils.ToastUtils;
import java.util.List; | package com.yan.mobilesafe.adapter;
/**
* AppManagerAdapter
* Created by a7501 on 2015/12/12.
*/
public class AppManagerHeadersAdapter extends RecyclerView.Adapter<AppManagerHeadersAdapter.SimpleViewHolder>
implements StickyRecyclerHeadersAdapter<AppManagerHeadersAdapter.ViewHeadersHolder> {
private Context context; | // Path: app/src/main/java/com/yan/mobilesafe/Bean/AppInfo.java
// public class AppInfo {
// private Drawable icon; //图片
// private String apkName; //app名字
// private long apkSize; //app大小
// private boolean isRom; //安装位置
//
// public boolean isRom() {
// return isRom;
// }
//
// public void setIsRom(boolean isRom) {
// this.isRom = isRom;
// }
//
// /**
// * 判断是否为用户app,如果是true,就是用户app否则,就是系统的
// */
// private boolean userApp; //
// private String apkPackageName; //包名
//
// public Drawable getIcon() {
// return icon;
// }
//
// public void setIcon(Drawable icon) {
// this.icon = icon;
// }
//
// public String getApkName() {
// return apkName;
// }
//
// public void setApkName(String apkName) {
// this.apkName = apkName;
// }
//
// public long getApkSize() {
// return apkSize;
// }
//
// public void setApkSize(long apkSize) {
// this.apkSize = apkSize;
// }
//
// public boolean isUserApp() {
// return userApp;
// }
//
// public void setUserApp(boolean userApp) {
// this.userApp = userApp;
// }
//
// public String getApkPackageName() {
// return apkPackageName;
// }
//
// public void setApkPackageName(String apkPackageName) {
// this.apkPackageName = apkPackageName;
// }
//
// @Override
// public String toString() {
// return "AppInfo{" +
// "icon=" + icon +
// ", apkName='" + apkName + '\'' +
// ", apkSize=" + apkSize +
// ", userApp=" + userApp +
// ", apkPackageName='" + apkPackageName + '\'' +
// '}';
// }
// }
//
// Path: app/src/main/java/com/yan/mobilesafe/adapter/listentr/MyItemClickListener.java
// public interface MyItemClickListener {
// public void onItemClick(View view,int position);
// }
//
// Path: app/src/main/java/com/yan/mobilesafe/utils/ToastUtils.java
// public class ToastUtils {
// public static void showToast(final Activity context, final String string){
// if ("main".equals(Thread.currentThread().getName())){ //判断是否为主线程
// Toast.makeText(context,string,Toast.LENGTH_SHORT).show();
// }else {
// context.runOnUiThread(new Runnable() { //如果不是,就用该方法使其在ui线程中运行
// @Override
// public void run() {
// Toast.makeText(context, string, Toast.LENGTH_SHORT).show();
// }
// });
// }
//
// }
// }
// Path: app/src/main/java/com/yan/mobilesafe/adapter/AppManagerHeadersAdapter.java
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.text.format.Formatter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersAdapter;
import com.yan.mobilesafe.Bean.AppInfo;
import com.yan.mobilesafe.R;
import com.yan.mobilesafe.adapter.listentr.MyItemClickListener;
import com.yan.mobilesafe.utils.ToastUtils;
import java.util.List;
package com.yan.mobilesafe.adapter;
/**
* AppManagerAdapter
* Created by a7501 on 2015/12/12.
*/
public class AppManagerHeadersAdapter extends RecyclerView.Adapter<AppManagerHeadersAdapter.SimpleViewHolder>
implements StickyRecyclerHeadersAdapter<AppManagerHeadersAdapter.ViewHeadersHolder> {
private Context context; | private List<AppInfo> appInfoList = null; |
a750183047/MobileSafe | app/src/main/java/com/yan/mobilesafe/adapter/AppManagerHeadersAdapter.java | // Path: app/src/main/java/com/yan/mobilesafe/Bean/AppInfo.java
// public class AppInfo {
// private Drawable icon; //图片
// private String apkName; //app名字
// private long apkSize; //app大小
// private boolean isRom; //安装位置
//
// public boolean isRom() {
// return isRom;
// }
//
// public void setIsRom(boolean isRom) {
// this.isRom = isRom;
// }
//
// /**
// * 判断是否为用户app,如果是true,就是用户app否则,就是系统的
// */
// private boolean userApp; //
// private String apkPackageName; //包名
//
// public Drawable getIcon() {
// return icon;
// }
//
// public void setIcon(Drawable icon) {
// this.icon = icon;
// }
//
// public String getApkName() {
// return apkName;
// }
//
// public void setApkName(String apkName) {
// this.apkName = apkName;
// }
//
// public long getApkSize() {
// return apkSize;
// }
//
// public void setApkSize(long apkSize) {
// this.apkSize = apkSize;
// }
//
// public boolean isUserApp() {
// return userApp;
// }
//
// public void setUserApp(boolean userApp) {
// this.userApp = userApp;
// }
//
// public String getApkPackageName() {
// return apkPackageName;
// }
//
// public void setApkPackageName(String apkPackageName) {
// this.apkPackageName = apkPackageName;
// }
//
// @Override
// public String toString() {
// return "AppInfo{" +
// "icon=" + icon +
// ", apkName='" + apkName + '\'' +
// ", apkSize=" + apkSize +
// ", userApp=" + userApp +
// ", apkPackageName='" + apkPackageName + '\'' +
// '}';
// }
// }
//
// Path: app/src/main/java/com/yan/mobilesafe/adapter/listentr/MyItemClickListener.java
// public interface MyItemClickListener {
// public void onItemClick(View view,int position);
// }
//
// Path: app/src/main/java/com/yan/mobilesafe/utils/ToastUtils.java
// public class ToastUtils {
// public static void showToast(final Activity context, final String string){
// if ("main".equals(Thread.currentThread().getName())){ //判断是否为主线程
// Toast.makeText(context,string,Toast.LENGTH_SHORT).show();
// }else {
// context.runOnUiThread(new Runnable() { //如果不是,就用该方法使其在ui线程中运行
// @Override
// public void run() {
// Toast.makeText(context, string, Toast.LENGTH_SHORT).show();
// }
// });
// }
//
// }
// }
| import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.text.format.Formatter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersAdapter;
import com.yan.mobilesafe.Bean.AppInfo;
import com.yan.mobilesafe.R;
import com.yan.mobilesafe.adapter.listentr.MyItemClickListener;
import com.yan.mobilesafe.utils.ToastUtils;
import java.util.List; | package com.yan.mobilesafe.adapter;
/**
* AppManagerAdapter
* Created by a7501 on 2015/12/12.
*/
public class AppManagerHeadersAdapter extends RecyclerView.Adapter<AppManagerHeadersAdapter.SimpleViewHolder>
implements StickyRecyclerHeadersAdapter<AppManagerHeadersAdapter.ViewHeadersHolder> {
private Context context;
private List<AppInfo> appInfoList = null;
private List<AppInfo> userAppInfos;
private List<AppInfo> systemAppInfos;
private String appName;
private Drawable appIcon;
private long apkSize;
private String apkPackageName; | // Path: app/src/main/java/com/yan/mobilesafe/Bean/AppInfo.java
// public class AppInfo {
// private Drawable icon; //图片
// private String apkName; //app名字
// private long apkSize; //app大小
// private boolean isRom; //安装位置
//
// public boolean isRom() {
// return isRom;
// }
//
// public void setIsRom(boolean isRom) {
// this.isRom = isRom;
// }
//
// /**
// * 判断是否为用户app,如果是true,就是用户app否则,就是系统的
// */
// private boolean userApp; //
// private String apkPackageName; //包名
//
// public Drawable getIcon() {
// return icon;
// }
//
// public void setIcon(Drawable icon) {
// this.icon = icon;
// }
//
// public String getApkName() {
// return apkName;
// }
//
// public void setApkName(String apkName) {
// this.apkName = apkName;
// }
//
// public long getApkSize() {
// return apkSize;
// }
//
// public void setApkSize(long apkSize) {
// this.apkSize = apkSize;
// }
//
// public boolean isUserApp() {
// return userApp;
// }
//
// public void setUserApp(boolean userApp) {
// this.userApp = userApp;
// }
//
// public String getApkPackageName() {
// return apkPackageName;
// }
//
// public void setApkPackageName(String apkPackageName) {
// this.apkPackageName = apkPackageName;
// }
//
// @Override
// public String toString() {
// return "AppInfo{" +
// "icon=" + icon +
// ", apkName='" + apkName + '\'' +
// ", apkSize=" + apkSize +
// ", userApp=" + userApp +
// ", apkPackageName='" + apkPackageName + '\'' +
// '}';
// }
// }
//
// Path: app/src/main/java/com/yan/mobilesafe/adapter/listentr/MyItemClickListener.java
// public interface MyItemClickListener {
// public void onItemClick(View view,int position);
// }
//
// Path: app/src/main/java/com/yan/mobilesafe/utils/ToastUtils.java
// public class ToastUtils {
// public static void showToast(final Activity context, final String string){
// if ("main".equals(Thread.currentThread().getName())){ //判断是否为主线程
// Toast.makeText(context,string,Toast.LENGTH_SHORT).show();
// }else {
// context.runOnUiThread(new Runnable() { //如果不是,就用该方法使其在ui线程中运行
// @Override
// public void run() {
// Toast.makeText(context, string, Toast.LENGTH_SHORT).show();
// }
// });
// }
//
// }
// }
// Path: app/src/main/java/com/yan/mobilesafe/adapter/AppManagerHeadersAdapter.java
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.text.format.Formatter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersAdapter;
import com.yan.mobilesafe.Bean.AppInfo;
import com.yan.mobilesafe.R;
import com.yan.mobilesafe.adapter.listentr.MyItemClickListener;
import com.yan.mobilesafe.utils.ToastUtils;
import java.util.List;
package com.yan.mobilesafe.adapter;
/**
* AppManagerAdapter
* Created by a7501 on 2015/12/12.
*/
public class AppManagerHeadersAdapter extends RecyclerView.Adapter<AppManagerHeadersAdapter.SimpleViewHolder>
implements StickyRecyclerHeadersAdapter<AppManagerHeadersAdapter.ViewHeadersHolder> {
private Context context;
private List<AppInfo> appInfoList = null;
private List<AppInfo> userAppInfos;
private List<AppInfo> systemAppInfos;
private String appName;
private Drawable appIcon;
private long apkSize;
private String apkPackageName; | private MyItemClickListener listener; |
a750183047/MobileSafe | app/src/main/java/com/yan/mobilesafe/activity/Setup/SetupActivity3.java | // Path: app/src/main/java/com/yan/mobilesafe/activity/ChooseContacts.java
// public class ChooseContacts extends AppCompatActivity {
// ListView contactsView;
// ArrayAdapter<String> adapter;
// List<String> contactsList = new ArrayList<String>();
// private String name;
// private String number;
//
// @TargetApi(Build.VERSION_CODES.KITKAT)
// @Override
// protected void onCreate(@Nullable Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.choose_contacts_layout);
//
// //透明状态栏
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// //透明导航栏
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
// contactsView = (ListView) findViewById(R.id.contacts_view);
// adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, contactsList);
// contactsView.setAdapter(adapter);
// readContacts();
//
// contactsView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
// @Override
// public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// String chickNumber = adapter.getItem(position);
// chickNumber = chickNumber.substring(chickNumber.indexOf("\n") + 1, chickNumber.length());
//
// Intent intent = new Intent();
// intent.putExtra("phoneNumber", chickNumber);
// setResult(Activity.RESULT_OK, intent); //回调返回手机号码
// finish();
// }
// });
// }
//
// private void readContacts() {
// Cursor cursor = null;
// cursor = getContentResolver().query(
// ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
// assert cursor != null;
// while (cursor.moveToNext()) {
// //获取联系人名字
// name = cursor.getString(cursor.getColumnIndex(
// ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
// ));
// //获取联系人手机号
// number = cursor.getString(cursor.getColumnIndex(
// ContactsContract.CommonDataKinds.Phone.NUMBER
// ));
// contactsList.add(name + "\n" + number);
// }
// cursor.close();
// }
// }
//
// Path: app/src/main/java/com/yan/mobilesafe/utils/ToastUtils.java
// public class ToastUtils {
// public static void showToast(final Activity context, final String string){
// if ("main".equals(Thread.currentThread().getName())){ //判断是否为主线程
// Toast.makeText(context,string,Toast.LENGTH_SHORT).show();
// }else {
// context.runOnUiThread(new Runnable() { //如果不是,就用该方法使其在ui线程中运行
// @Override
// public void run() {
// Toast.makeText(context, string, Toast.LENGTH_SHORT).show();
// }
// });
// }
//
// }
// }
| import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.yan.mobilesafe.R;
import com.yan.mobilesafe.activity.ChooseContacts;
import com.yan.mobilesafe.utils.ToastUtils; | package com.yan.mobilesafe.activity.Setup;
/**
* 第三个设置向导页
* Created by yan on 2015/11/22.
*/
public class SetupActivity3 extends AppCompatActivity {
private EditText inputNumber;
private SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setup3);
Button next = (Button) findViewById(R.id.next);
Button back = (Button) findViewById(R.id.back);
Button chooseContacts = (Button) findViewById(R.id.choose_contacts);
inputNumber = (EditText) findViewById(R.id.et_number_input);
sharedPreferences = getSharedPreferences("config", MODE_PRIVATE);
String safePhone = sharedPreferences.getString("safe_number","");
inputNumber.setText(safePhone);
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String number = inputNumber.getText().toString();
if (TextUtils.isEmpty(number)) { | // Path: app/src/main/java/com/yan/mobilesafe/activity/ChooseContacts.java
// public class ChooseContacts extends AppCompatActivity {
// ListView contactsView;
// ArrayAdapter<String> adapter;
// List<String> contactsList = new ArrayList<String>();
// private String name;
// private String number;
//
// @TargetApi(Build.VERSION_CODES.KITKAT)
// @Override
// protected void onCreate(@Nullable Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.choose_contacts_layout);
//
// //透明状态栏
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// //透明导航栏
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
// contactsView = (ListView) findViewById(R.id.contacts_view);
// adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, contactsList);
// contactsView.setAdapter(adapter);
// readContacts();
//
// contactsView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
// @Override
// public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// String chickNumber = adapter.getItem(position);
// chickNumber = chickNumber.substring(chickNumber.indexOf("\n") + 1, chickNumber.length());
//
// Intent intent = new Intent();
// intent.putExtra("phoneNumber", chickNumber);
// setResult(Activity.RESULT_OK, intent); //回调返回手机号码
// finish();
// }
// });
// }
//
// private void readContacts() {
// Cursor cursor = null;
// cursor = getContentResolver().query(
// ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
// assert cursor != null;
// while (cursor.moveToNext()) {
// //获取联系人名字
// name = cursor.getString(cursor.getColumnIndex(
// ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
// ));
// //获取联系人手机号
// number = cursor.getString(cursor.getColumnIndex(
// ContactsContract.CommonDataKinds.Phone.NUMBER
// ));
// contactsList.add(name + "\n" + number);
// }
// cursor.close();
// }
// }
//
// Path: app/src/main/java/com/yan/mobilesafe/utils/ToastUtils.java
// public class ToastUtils {
// public static void showToast(final Activity context, final String string){
// if ("main".equals(Thread.currentThread().getName())){ //判断是否为主线程
// Toast.makeText(context,string,Toast.LENGTH_SHORT).show();
// }else {
// context.runOnUiThread(new Runnable() { //如果不是,就用该方法使其在ui线程中运行
// @Override
// public void run() {
// Toast.makeText(context, string, Toast.LENGTH_SHORT).show();
// }
// });
// }
//
// }
// }
// Path: app/src/main/java/com/yan/mobilesafe/activity/Setup/SetupActivity3.java
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.yan.mobilesafe.R;
import com.yan.mobilesafe.activity.ChooseContacts;
import com.yan.mobilesafe.utils.ToastUtils;
package com.yan.mobilesafe.activity.Setup;
/**
* 第三个设置向导页
* Created by yan on 2015/11/22.
*/
public class SetupActivity3 extends AppCompatActivity {
private EditText inputNumber;
private SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setup3);
Button next = (Button) findViewById(R.id.next);
Button back = (Button) findViewById(R.id.back);
Button chooseContacts = (Button) findViewById(R.id.choose_contacts);
inputNumber = (EditText) findViewById(R.id.et_number_input);
sharedPreferences = getSharedPreferences("config", MODE_PRIVATE);
String safePhone = sharedPreferences.getString("safe_number","");
inputNumber.setText(safePhone);
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String number = inputNumber.getText().toString();
if (TextUtils.isEmpty(number)) { | ToastUtils.showToast(SetupActivity3.this, "安全号码不能为空"); |
a750183047/MobileSafe | app/src/main/java/com/yan/mobilesafe/activity/Setup/SetupActivity3.java | // Path: app/src/main/java/com/yan/mobilesafe/activity/ChooseContacts.java
// public class ChooseContacts extends AppCompatActivity {
// ListView contactsView;
// ArrayAdapter<String> adapter;
// List<String> contactsList = new ArrayList<String>();
// private String name;
// private String number;
//
// @TargetApi(Build.VERSION_CODES.KITKAT)
// @Override
// protected void onCreate(@Nullable Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.choose_contacts_layout);
//
// //透明状态栏
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// //透明导航栏
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
// contactsView = (ListView) findViewById(R.id.contacts_view);
// adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, contactsList);
// contactsView.setAdapter(adapter);
// readContacts();
//
// contactsView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
// @Override
// public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// String chickNumber = adapter.getItem(position);
// chickNumber = chickNumber.substring(chickNumber.indexOf("\n") + 1, chickNumber.length());
//
// Intent intent = new Intent();
// intent.putExtra("phoneNumber", chickNumber);
// setResult(Activity.RESULT_OK, intent); //回调返回手机号码
// finish();
// }
// });
// }
//
// private void readContacts() {
// Cursor cursor = null;
// cursor = getContentResolver().query(
// ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
// assert cursor != null;
// while (cursor.moveToNext()) {
// //获取联系人名字
// name = cursor.getString(cursor.getColumnIndex(
// ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
// ));
// //获取联系人手机号
// number = cursor.getString(cursor.getColumnIndex(
// ContactsContract.CommonDataKinds.Phone.NUMBER
// ));
// contactsList.add(name + "\n" + number);
// }
// cursor.close();
// }
// }
//
// Path: app/src/main/java/com/yan/mobilesafe/utils/ToastUtils.java
// public class ToastUtils {
// public static void showToast(final Activity context, final String string){
// if ("main".equals(Thread.currentThread().getName())){ //判断是否为主线程
// Toast.makeText(context,string,Toast.LENGTH_SHORT).show();
// }else {
// context.runOnUiThread(new Runnable() { //如果不是,就用该方法使其在ui线程中运行
// @Override
// public void run() {
// Toast.makeText(context, string, Toast.LENGTH_SHORT).show();
// }
// });
// }
//
// }
// }
| import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.yan.mobilesafe.R;
import com.yan.mobilesafe.activity.ChooseContacts;
import com.yan.mobilesafe.utils.ToastUtils; |
String number = inputNumber.getText().toString();
if (TextUtils.isEmpty(number)) {
ToastUtils.showToast(SetupActivity3.this, "安全号码不能为空");
return;
}
sharedPreferences.edit().putString("safe_number", number).apply();//保存安全号码
startActivity(new Intent(getApplicationContext(), SetupActivity4.class));
finish();
overridePendingTransition(R.anim.tran_in, R.anim.tran_out);//进入动画和退出动画
}
});
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), SetupActivity2.class));
finish();
// 两个界面切换的动画
overridePendingTransition(R.anim.tran_previous_in,
R.anim.tran_previous_out);// 进入动画和退出动画
}
});
chooseContacts.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { | // Path: app/src/main/java/com/yan/mobilesafe/activity/ChooseContacts.java
// public class ChooseContacts extends AppCompatActivity {
// ListView contactsView;
// ArrayAdapter<String> adapter;
// List<String> contactsList = new ArrayList<String>();
// private String name;
// private String number;
//
// @TargetApi(Build.VERSION_CODES.KITKAT)
// @Override
// protected void onCreate(@Nullable Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.choose_contacts_layout);
//
// //透明状态栏
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// //透明导航栏
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
// contactsView = (ListView) findViewById(R.id.contacts_view);
// adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, contactsList);
// contactsView.setAdapter(adapter);
// readContacts();
//
// contactsView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
// @Override
// public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// String chickNumber = adapter.getItem(position);
// chickNumber = chickNumber.substring(chickNumber.indexOf("\n") + 1, chickNumber.length());
//
// Intent intent = new Intent();
// intent.putExtra("phoneNumber", chickNumber);
// setResult(Activity.RESULT_OK, intent); //回调返回手机号码
// finish();
// }
// });
// }
//
// private void readContacts() {
// Cursor cursor = null;
// cursor = getContentResolver().query(
// ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
// assert cursor != null;
// while (cursor.moveToNext()) {
// //获取联系人名字
// name = cursor.getString(cursor.getColumnIndex(
// ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
// ));
// //获取联系人手机号
// number = cursor.getString(cursor.getColumnIndex(
// ContactsContract.CommonDataKinds.Phone.NUMBER
// ));
// contactsList.add(name + "\n" + number);
// }
// cursor.close();
// }
// }
//
// Path: app/src/main/java/com/yan/mobilesafe/utils/ToastUtils.java
// public class ToastUtils {
// public static void showToast(final Activity context, final String string){
// if ("main".equals(Thread.currentThread().getName())){ //判断是否为主线程
// Toast.makeText(context,string,Toast.LENGTH_SHORT).show();
// }else {
// context.runOnUiThread(new Runnable() { //如果不是,就用该方法使其在ui线程中运行
// @Override
// public void run() {
// Toast.makeText(context, string, Toast.LENGTH_SHORT).show();
// }
// });
// }
//
// }
// }
// Path: app/src/main/java/com/yan/mobilesafe/activity/Setup/SetupActivity3.java
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.yan.mobilesafe.R;
import com.yan.mobilesafe.activity.ChooseContacts;
import com.yan.mobilesafe.utils.ToastUtils;
String number = inputNumber.getText().toString();
if (TextUtils.isEmpty(number)) {
ToastUtils.showToast(SetupActivity3.this, "安全号码不能为空");
return;
}
sharedPreferences.edit().putString("safe_number", number).apply();//保存安全号码
startActivity(new Intent(getApplicationContext(), SetupActivity4.class));
finish();
overridePendingTransition(R.anim.tran_in, R.anim.tran_out);//进入动画和退出动画
}
});
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), SetupActivity2.class));
finish();
// 两个界面切换的动画
overridePendingTransition(R.anim.tran_previous_in,
R.anim.tran_previous_out);// 进入动画和退出动画
}
});
chooseContacts.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { | Intent intent = new Intent(SetupActivity3.this, ChooseContacts.class); |
a750183047/MobileSafe | app/src/main/java/com/yan/mobilesafe/activity/Atool/AddressActivity.java | // Path: app/src/main/java/com/yan/mobilesafe/DataBase/AddressDB.java
// public class AddressDB {
// private static final String PATH = "data/data/com.yan.mobilesafe/files/address.db";
//
// public static String getAddress(String number){
// String address = "未知号码";
//
// //获取数据库对象
// SQLiteDatabase database = SQLiteDatabase.openDatabase(PATH,null,SQLiteDatabase.OPEN_READONLY);
//
// //手机号正则表达式匹配
// //1 + (3.4.5.6.7.8)+(9位数字)
// //^1[3-8]\d{9}$
//
// if (number.matches("^1[3-8]\\d{9}$")){
// Cursor cursor = database.rawQuery("select location from data2 where id = (select outkey from data1 where id = ?)"
// ,new String[]{number.substring(0,7)});
// if (cursor.moveToNext()){
// address = cursor.getString(0);
// }
// cursor.close();
// }else if (number.matches("^\\d+$")){ //匹配数字
// switch (number.length()){
// case 3:
// address = "报警电话";
// break;
// case 4:
// address = "模拟器电话";
// break;
// case 5:
// address = "客服电话";
// break;
// case 7:
// case 8:
// address = "本地电话";
// break;
// default:
// //03154011111
// //01055225525
// if (number.startsWith("0") && number.length()>10){ //可能是长途电话
// //先查询3位区号
// Cursor cursor = database.rawQuery("select location from data2 where area = ?",
// new String[]{number.substring(1,3)});
// if (cursor.moveToNext()){
// address = cursor.getString(0);
// address = address.substring(0,address.length()-2);
// }else {
// cursor.close();
// //查询4位区号
// cursor = database.rawQuery("select location from data2 where area = ?",
// new String[]{number.substring(1,4)});
// if (cursor.moveToNext()){
// address = cursor.getString(0);
// address = address.substring(0,address.length()-2);
// }
// cursor.close();
// }
// }
// break;
// }
// }
//
// database.close();
// return address;
// }
// }
| import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.yan.mobilesafe.DataBase.AddressDB;
import com.yan.mobilesafe.R; | package com.yan.mobilesafe.activity.Atool;
/**
* 号码归属地查询
* Created by a7501 on 2015/11/30.
*/
public class AddressActivity extends AppCompatActivity {
private EditText inputNumber;
private Button select;
private TextView result;
@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_address_layout);
//透明状态栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//透明导航栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
inputNumber = (EditText) findViewById(R.id.et_number_address);
select = (Button) findViewById(R.id.btn_ok);
result = (TextView) findViewById(R.id.tv_result);
inputNumber.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) { | // Path: app/src/main/java/com/yan/mobilesafe/DataBase/AddressDB.java
// public class AddressDB {
// private static final String PATH = "data/data/com.yan.mobilesafe/files/address.db";
//
// public static String getAddress(String number){
// String address = "未知号码";
//
// //获取数据库对象
// SQLiteDatabase database = SQLiteDatabase.openDatabase(PATH,null,SQLiteDatabase.OPEN_READONLY);
//
// //手机号正则表达式匹配
// //1 + (3.4.5.6.7.8)+(9位数字)
// //^1[3-8]\d{9}$
//
// if (number.matches("^1[3-8]\\d{9}$")){
// Cursor cursor = database.rawQuery("select location from data2 where id = (select outkey from data1 where id = ?)"
// ,new String[]{number.substring(0,7)});
// if (cursor.moveToNext()){
// address = cursor.getString(0);
// }
// cursor.close();
// }else if (number.matches("^\\d+$")){ //匹配数字
// switch (number.length()){
// case 3:
// address = "报警电话";
// break;
// case 4:
// address = "模拟器电话";
// break;
// case 5:
// address = "客服电话";
// break;
// case 7:
// case 8:
// address = "本地电话";
// break;
// default:
// //03154011111
// //01055225525
// if (number.startsWith("0") && number.length()>10){ //可能是长途电话
// //先查询3位区号
// Cursor cursor = database.rawQuery("select location from data2 where area = ?",
// new String[]{number.substring(1,3)});
// if (cursor.moveToNext()){
// address = cursor.getString(0);
// address = address.substring(0,address.length()-2);
// }else {
// cursor.close();
// //查询4位区号
// cursor = database.rawQuery("select location from data2 where area = ?",
// new String[]{number.substring(1,4)});
// if (cursor.moveToNext()){
// address = cursor.getString(0);
// address = address.substring(0,address.length()-2);
// }
// cursor.close();
// }
// }
// break;
// }
// }
//
// database.close();
// return address;
// }
// }
// Path: app/src/main/java/com/yan/mobilesafe/activity/Atool/AddressActivity.java
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.yan.mobilesafe.DataBase.AddressDB;
import com.yan.mobilesafe.R;
package com.yan.mobilesafe.activity.Atool;
/**
* 号码归属地查询
* Created by a7501 on 2015/11/30.
*/
public class AddressActivity extends AppCompatActivity {
private EditText inputNumber;
private Button select;
private TextView result;
@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_address_layout);
//透明状态栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//透明导航栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
inputNumber = (EditText) findViewById(R.id.et_number_address);
select = (Button) findViewById(R.id.btn_ok);
result = (TextView) findViewById(R.id.tv_result);
inputNumber.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) { | result.setText(AddressDB.getAddress(s.toString())); |
a750183047/MobileSafe | app/src/main/java/com/yan/mobilesafe/receiver/SmsReceiver.java | // Path: app/src/main/java/com/yan/mobilesafe/Service/LocationService.java
// public class LocationService extends Service {
//
// private SharedPreferences sharedPreferences;
// private LocationManager locationManager;
// private MylocationListenter listener;
//
// @Nullable
// @Override
// public IBinder onBind(Intent intent) {
// return null;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// sharedPreferences = getSharedPreferences("config", MODE_PRIVATE);
// //获取位置
// locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
//
// Criteria criteria = new Criteria();
// criteria.setCostAllowed(true); //是否获取付费
// criteria.setAccuracy(Criteria.ACCURACY_FINE);
// String bestProvider = locationManager.getBestProvider(criteria, true); //获取最佳位置提供者
//
// listener = new MylocationListenter();
// locationManager.requestLocationUpdates(bestProvider,0,0,listener); //启动获取位置
// }
//
// class MylocationListenter implements LocationListener {
//
// //位置发生变化
// @Override
// public void onLocationChanged(Location location) {
// //保存经纬度
// sharedPreferences.edit().putString("location", "jing" +
// location.getLongitude() + ";" + "wei" + location.getLatitude()).apply();
//
// stopSelf(); //停掉service
//
// }
//
// @Override
// public void onStatusChanged(String provider, int status, Bundle extras) {
//
// }
//
// @Override
// public void onProviderEnabled(String provider) {
//
// }
//
// @Override
// public void onProviderDisabled(String provider) {
//
// }
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// locationManager.removeUpdates(listener);
// }
// }
| import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
import com.yan.mobilesafe.R;
import com.yan.mobilesafe.Service.LocationService; | package com.yan.mobilesafe.receiver;
/**
* 短信拦截
* Created by a7501 on 2015/11/25.
*/
public class SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences sharedPreferences = context.getSharedPreferences("config", Context.MODE_PRIVATE);
Object[] objects = (Object[]) intent.getExtras().get("pdus");
assert objects != null;
for (Object object :objects){
SmsMessage message = SmsMessage.createFromPdu((byte[]) object);
String originatingAddress = message.getOriginatingAddress(); //获取短信来源号码
String messageBody = message.getMessageBody(); //获取短信内容
abortBroadcast();// 中断短信的传递, 从而系统短信app就收不到内容了
Log.e("SmsReceiver",originatingAddress + ":" +messageBody);
if ("#*alarm*#".equals(messageBody)){
//播放报警音乐
MediaPlayer player = MediaPlayer.create(context, R.raw.ylzs);
player.setVolume(1f,1f);
player.setLooping(true);
player.start();
}else if ("#*location*#".equals(messageBody)) {
| // Path: app/src/main/java/com/yan/mobilesafe/Service/LocationService.java
// public class LocationService extends Service {
//
// private SharedPreferences sharedPreferences;
// private LocationManager locationManager;
// private MylocationListenter listener;
//
// @Nullable
// @Override
// public IBinder onBind(Intent intent) {
// return null;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// sharedPreferences = getSharedPreferences("config", MODE_PRIVATE);
// //获取位置
// locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
//
// Criteria criteria = new Criteria();
// criteria.setCostAllowed(true); //是否获取付费
// criteria.setAccuracy(Criteria.ACCURACY_FINE);
// String bestProvider = locationManager.getBestProvider(criteria, true); //获取最佳位置提供者
//
// listener = new MylocationListenter();
// locationManager.requestLocationUpdates(bestProvider,0,0,listener); //启动获取位置
// }
//
// class MylocationListenter implements LocationListener {
//
// //位置发生变化
// @Override
// public void onLocationChanged(Location location) {
// //保存经纬度
// sharedPreferences.edit().putString("location", "jing" +
// location.getLongitude() + ";" + "wei" + location.getLatitude()).apply();
//
// stopSelf(); //停掉service
//
// }
//
// @Override
// public void onStatusChanged(String provider, int status, Bundle extras) {
//
// }
//
// @Override
// public void onProviderEnabled(String provider) {
//
// }
//
// @Override
// public void onProviderDisabled(String provider) {
//
// }
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// locationManager.removeUpdates(listener);
// }
// }
// Path: app/src/main/java/com/yan/mobilesafe/receiver/SmsReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
import com.yan.mobilesafe.R;
import com.yan.mobilesafe.Service.LocationService;
package com.yan.mobilesafe.receiver;
/**
* 短信拦截
* Created by a7501 on 2015/11/25.
*/
public class SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences sharedPreferences = context.getSharedPreferences("config", Context.MODE_PRIVATE);
Object[] objects = (Object[]) intent.getExtras().get("pdus");
assert objects != null;
for (Object object :objects){
SmsMessage message = SmsMessage.createFromPdu((byte[]) object);
String originatingAddress = message.getOriginatingAddress(); //获取短信来源号码
String messageBody = message.getMessageBody(); //获取短信内容
abortBroadcast();// 中断短信的传递, 从而系统短信app就收不到内容了
Log.e("SmsReceiver",originatingAddress + ":" +messageBody);
if ("#*alarm*#".equals(messageBody)){
//播放报警音乐
MediaPlayer player = MediaPlayer.create(context, R.raw.ylzs);
player.setVolume(1f,1f);
player.setLooping(true);
player.start();
}else if ("#*location*#".equals(messageBody)) {
| context.startService(new Intent(context, LocationService.class)); |
Darkona/AdventureBackpack2 | src/main/java/com/darkona/adventurebackpack/util/Utils.java | // Path: src/main/java/com/darkona/adventurebackpack/AdventureBackpack.java
// @Mod(modid = ModInfo.MOD_ID,
// name = ModInfo.MOD_NAME,
// version = ModInfo.MOD_VERSION,
// guiFactory = ModInfo.GUI_FACTORY_CLASS
// )
// public class AdventureBackpack
// {
//
// @SidedProxy(clientSide = ModInfo.MOD_CLIENT_PROXY, serverSide = ModInfo.MOD_SERVER_PROXY)
// public static IProxy proxy;
// @Mod.Instance(ModInfo.MOD_ID)
// public static AdventureBackpack instance;
//
// //Static things
// public static CreativeTabAB creativeTab = new CreativeTabAB();
//
//
// public boolean chineseNewYear;
// public boolean hannukah;
// public String Holiday;
// PlayerEventHandler playerEventHandler;
// ClientEventHandler clientEventHandler;
// GeneralEventHandler generalEventHandler;
//
// GuiHandler guiHandler;
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event)
// {
//
// int year = Calendar.getInstance().get(Calendar.YEAR), month = Calendar.getInstance().get(Calendar.MONTH) + 1, day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
//
// //Configuration
// FMLCommonHandler.instance().bus().register(new ConfigHandler());
// ConfigHandler.init(event.getSuggestedConfigurationFile());
// chineseNewYear = ChineseCalendar.isChineseNewYear(year, month, day);
// hannukah = JewishCalendar.isHannukah(year, month, day);
// Holiday = Utils.getHoliday();
//
// //ModStuff
// ModItems.init();
// ModBlocks.init();
// ModFluids.init();
// FluidEffectRegistry.init();
// ModEntities.init();
// ModNetwork.init();
// proxy.initNetwork();
// // EVENTS
// playerEventHandler = new PlayerEventHandler();
// generalEventHandler = new GeneralEventHandler();
// clientEventHandler = new ClientEventHandler();
//
//
// MinecraftForge.EVENT_BUS.register(generalEventHandler);
// MinecraftForge.EVENT_BUS.register(clientEventHandler);
// MinecraftForge.EVENT_BUS.register(playerEventHandler);
//
// FMLCommonHandler.instance().bus().register(playerEventHandler);
//
// }
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event)
// {
//
// proxy.init();
// ModRecipes.init();
//
// ModWorldGen.init();
// //GUIs
// guiHandler = new GuiHandler();
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, guiHandler);
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event)
// {
//
// ConfigHandler.IS_TINKERS = Loader.isModLoaded("TConstruct");
// ConfigHandler.IS_THAUM = Loader.isModLoaded("Thaumcraft");
// ConfigHandler.IS_TWILIGHT = Loader.isModLoaded("TwilightForest");
// ConfigHandler.IS_ENVIROMINE = Loader.isModLoaded("EnviroMine");
// ConfigHandler.IS_BUILDCRAFT = Loader.isModLoaded("BuildCraft|Core");
// ConfigHandler.IS_RAILCRAFT = Loader.isModLoaded("Railcraft");
//
//
// if (ConfigHandler.IS_BUILDCRAFT)
// {
// LogHelper.info("Buildcraft is present. Acting accordingly");
// }
//
// if (ConfigHandler.IS_TWILIGHT)
// {
// LogHelper.info("Twilight Forest is present. Acting accordingly");
// }
//
// ConditionalFluidEffect.init();
// ModItems.conditionalInit();
// ModRecipes.conditionalInit();
//
//
// /*
// LogHelper.info("DUMPING FLUID INFORMATION");
// LogHelper.info("-------------------------------------------------------------------------");
// for(Fluid fluid : FluidRegistry.getRegisteredFluids().values())
// {
//
// LogHelper.info("Unlocalized name: " + fluid.getUnlocalizedName());
// LogHelper.info("Name: " + fluid.getName());
// LogHelper.info("");
// }
// LogHelper.info("-------------------------------------------------------------------------");
// */
// /*
// LogHelper.info("DUMPING TILE INFORMATION");
// LogHelper.info("-------------------------------------------------------------------------");
// for (Block block : GameData.getBlockRegistry().typeSafeIterable())
// {
// LogHelper.info("Block= " + block.getUnlocalizedName());
// }
// LogHelper.info("-------------------------------------------------------------------------");
// */
// }
//
// }
| import com.darkona.adventurebackpack.AdventureBackpack;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.relauncher.Side;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ChunkCoordinates;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidRegistry;
import java.util.Calendar; |
public static int[] calculateEaster(int year)
{
int a = year % 19,
b = year / 100,
c = year % 100,
d = b / 4,
e = b % 4,
g = (8 * b + 13) / 25,
h = (19 * a + b - d - g + 15) % 30,
j = c / 4,
k = c % 4,
m = (a + 11 * h) / 319,
r = (2 * e + 2 * j - k - h + m + 32) % 7,
n = (h - m + r + 90) / 25,
p = (h - m + r + n + 19) % 32;
return new int[]{n, p};
}
public static String getHoliday()
{
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR),
month = calendar.get(Calendar.MONTH) + 1,
day = calendar.get(Calendar.DAY_OF_MONTH);
| // Path: src/main/java/com/darkona/adventurebackpack/AdventureBackpack.java
// @Mod(modid = ModInfo.MOD_ID,
// name = ModInfo.MOD_NAME,
// version = ModInfo.MOD_VERSION,
// guiFactory = ModInfo.GUI_FACTORY_CLASS
// )
// public class AdventureBackpack
// {
//
// @SidedProxy(clientSide = ModInfo.MOD_CLIENT_PROXY, serverSide = ModInfo.MOD_SERVER_PROXY)
// public static IProxy proxy;
// @Mod.Instance(ModInfo.MOD_ID)
// public static AdventureBackpack instance;
//
// //Static things
// public static CreativeTabAB creativeTab = new CreativeTabAB();
//
//
// public boolean chineseNewYear;
// public boolean hannukah;
// public String Holiday;
// PlayerEventHandler playerEventHandler;
// ClientEventHandler clientEventHandler;
// GeneralEventHandler generalEventHandler;
//
// GuiHandler guiHandler;
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event)
// {
//
// int year = Calendar.getInstance().get(Calendar.YEAR), month = Calendar.getInstance().get(Calendar.MONTH) + 1, day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
//
// //Configuration
// FMLCommonHandler.instance().bus().register(new ConfigHandler());
// ConfigHandler.init(event.getSuggestedConfigurationFile());
// chineseNewYear = ChineseCalendar.isChineseNewYear(year, month, day);
// hannukah = JewishCalendar.isHannukah(year, month, day);
// Holiday = Utils.getHoliday();
//
// //ModStuff
// ModItems.init();
// ModBlocks.init();
// ModFluids.init();
// FluidEffectRegistry.init();
// ModEntities.init();
// ModNetwork.init();
// proxy.initNetwork();
// // EVENTS
// playerEventHandler = new PlayerEventHandler();
// generalEventHandler = new GeneralEventHandler();
// clientEventHandler = new ClientEventHandler();
//
//
// MinecraftForge.EVENT_BUS.register(generalEventHandler);
// MinecraftForge.EVENT_BUS.register(clientEventHandler);
// MinecraftForge.EVENT_BUS.register(playerEventHandler);
//
// FMLCommonHandler.instance().bus().register(playerEventHandler);
//
// }
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event)
// {
//
// proxy.init();
// ModRecipes.init();
//
// ModWorldGen.init();
// //GUIs
// guiHandler = new GuiHandler();
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, guiHandler);
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event)
// {
//
// ConfigHandler.IS_TINKERS = Loader.isModLoaded("TConstruct");
// ConfigHandler.IS_THAUM = Loader.isModLoaded("Thaumcraft");
// ConfigHandler.IS_TWILIGHT = Loader.isModLoaded("TwilightForest");
// ConfigHandler.IS_ENVIROMINE = Loader.isModLoaded("EnviroMine");
// ConfigHandler.IS_BUILDCRAFT = Loader.isModLoaded("BuildCraft|Core");
// ConfigHandler.IS_RAILCRAFT = Loader.isModLoaded("Railcraft");
//
//
// if (ConfigHandler.IS_BUILDCRAFT)
// {
// LogHelper.info("Buildcraft is present. Acting accordingly");
// }
//
// if (ConfigHandler.IS_TWILIGHT)
// {
// LogHelper.info("Twilight Forest is present. Acting accordingly");
// }
//
// ConditionalFluidEffect.init();
// ModItems.conditionalInit();
// ModRecipes.conditionalInit();
//
//
// /*
// LogHelper.info("DUMPING FLUID INFORMATION");
// LogHelper.info("-------------------------------------------------------------------------");
// for(Fluid fluid : FluidRegistry.getRegisteredFluids().values())
// {
//
// LogHelper.info("Unlocalized name: " + fluid.getUnlocalizedName());
// LogHelper.info("Name: " + fluid.getName());
// LogHelper.info("");
// }
// LogHelper.info("-------------------------------------------------------------------------");
// */
// /*
// LogHelper.info("DUMPING TILE INFORMATION");
// LogHelper.info("-------------------------------------------------------------------------");
// for (Block block : GameData.getBlockRegistry().typeSafeIterable())
// {
// LogHelper.info("Block= " + block.getUnlocalizedName());
// }
// LogHelper.info("-------------------------------------------------------------------------");
// */
// }
//
// }
// Path: src/main/java/com/darkona/adventurebackpack/util/Utils.java
import com.darkona.adventurebackpack.AdventureBackpack;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.relauncher.Side;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ChunkCoordinates;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidRegistry;
import java.util.Calendar;
public static int[] calculateEaster(int year)
{
int a = year % 19,
b = year / 100,
c = year % 100,
d = b / 4,
e = b % 4,
g = (8 * b + 13) / 25,
h = (19 * a + b - d - g + 15) % 30,
j = c / 4,
k = c % 4,
m = (a + 11 * h) / 319,
r = (2 * e + 2 * j - k - h + m + 32) % 7,
n = (h - m + r + 90) / 25,
p = (h - m + r + n + 19) % 32;
return new int[]{n, p};
}
public static String getHoliday()
{
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR),
month = calendar.get(Calendar.MONTH) + 1,
day = calendar.get(Calendar.DAY_OF_MONTH);
| if (AdventureBackpack.instance.chineseNewYear) return "ChinaNewYear"; |
Darkona/AdventureBackpack2 | src/main/java/com/darkona/adventurebackpack/init/ModFluids.java | // Path: src/main/java/com/darkona/adventurebackpack/fluids/FluidMilk.java
// public class FluidMilk extends Fluid
// {
//
// public FluidMilk()
// {
// super("milk");
// setDensity(1200);
// setViscosity(1200);
// setLuminosity(0);
// }
//
//
// @Override
// public IIcon getStillIcon()
// {
// return Icons.milkStill;
// }
//
// @Override
// public IIcon getIcon()
// {
// return Icons.milkStill;
// }
//
// @Override
// public IIcon getFlowingIcon()
// {
// return Icons.milkStill;
// }
//
// @Override
// public int getColor(FluidStack stack)
// {
// return 0xffffff;
// }
//
// @Override
// public boolean isGaseous(World world, int x, int y, int z)
// {
// return false;
// }
//
//
// }
//
// Path: src/main/java/com/darkona/adventurebackpack/fluids/FluidMushroomStew.java
// public class FluidMushroomStew extends Fluid
// {
// public FluidMushroomStew()
// {
// super("mushroomStew");
// setDensity(1200);
// setViscosity(1200);
// setLuminosity(0);
// }
//
// @Override
// public IIcon getStillIcon()
// {
// return Icons.mushRoomStewStill;
// }
//
// @Override
// public IIcon getIcon()
// {
// return Icons.mushRoomStewStill;
// }
//
// @Override
// public IIcon getFlowingIcon()
// {
// return Icons.mushRoomStewFlowing;
// }
//
// @Override
// public int getColor(FluidStack stack)
// {
// //Color color1 = new Color(205,140,111);
// return 0xcd8c6f;
// }
//
// @Override
// public boolean isGaseous(World world, int x, int y, int z)
// {
// return false;
// }
// }
| import com.darkona.adventurebackpack.fluids.FluidMelonJuice;
import com.darkona.adventurebackpack.fluids.FluidMilk;
import com.darkona.adventurebackpack.fluids.FluidMushroomStew;
import com.darkona.adventurebackpack.reference.GeneralReference;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.FluidRegistry; | package com.darkona.adventurebackpack.init;
/**
* Created on 12/10/2014.
*
* @author Javier Darkona
*/
public class ModFluids
{ | // Path: src/main/java/com/darkona/adventurebackpack/fluids/FluidMilk.java
// public class FluidMilk extends Fluid
// {
//
// public FluidMilk()
// {
// super("milk");
// setDensity(1200);
// setViscosity(1200);
// setLuminosity(0);
// }
//
//
// @Override
// public IIcon getStillIcon()
// {
// return Icons.milkStill;
// }
//
// @Override
// public IIcon getIcon()
// {
// return Icons.milkStill;
// }
//
// @Override
// public IIcon getFlowingIcon()
// {
// return Icons.milkStill;
// }
//
// @Override
// public int getColor(FluidStack stack)
// {
// return 0xffffff;
// }
//
// @Override
// public boolean isGaseous(World world, int x, int y, int z)
// {
// return false;
// }
//
//
// }
//
// Path: src/main/java/com/darkona/adventurebackpack/fluids/FluidMushroomStew.java
// public class FluidMushroomStew extends Fluid
// {
// public FluidMushroomStew()
// {
// super("mushroomStew");
// setDensity(1200);
// setViscosity(1200);
// setLuminosity(0);
// }
//
// @Override
// public IIcon getStillIcon()
// {
// return Icons.mushRoomStewStill;
// }
//
// @Override
// public IIcon getIcon()
// {
// return Icons.mushRoomStewStill;
// }
//
// @Override
// public IIcon getFlowingIcon()
// {
// return Icons.mushRoomStewFlowing;
// }
//
// @Override
// public int getColor(FluidStack stack)
// {
// //Color color1 = new Color(205,140,111);
// return 0xcd8c6f;
// }
//
// @Override
// public boolean isGaseous(World world, int x, int y, int z)
// {
// return false;
// }
// }
// Path: src/main/java/com/darkona/adventurebackpack/init/ModFluids.java
import com.darkona.adventurebackpack.fluids.FluidMelonJuice;
import com.darkona.adventurebackpack.fluids.FluidMilk;
import com.darkona.adventurebackpack.fluids.FluidMushroomStew;
import com.darkona.adventurebackpack.reference.GeneralReference;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.FluidRegistry;
package com.darkona.adventurebackpack.init;
/**
* Created on 12/10/2014.
*
* @author Javier Darkona
*/
public class ModFluids
{ | public static FluidMilk milk; |
Darkona/AdventureBackpack2 | src/main/java/com/darkona/adventurebackpack/init/ModFluids.java | // Path: src/main/java/com/darkona/adventurebackpack/fluids/FluidMilk.java
// public class FluidMilk extends Fluid
// {
//
// public FluidMilk()
// {
// super("milk");
// setDensity(1200);
// setViscosity(1200);
// setLuminosity(0);
// }
//
//
// @Override
// public IIcon getStillIcon()
// {
// return Icons.milkStill;
// }
//
// @Override
// public IIcon getIcon()
// {
// return Icons.milkStill;
// }
//
// @Override
// public IIcon getFlowingIcon()
// {
// return Icons.milkStill;
// }
//
// @Override
// public int getColor(FluidStack stack)
// {
// return 0xffffff;
// }
//
// @Override
// public boolean isGaseous(World world, int x, int y, int z)
// {
// return false;
// }
//
//
// }
//
// Path: src/main/java/com/darkona/adventurebackpack/fluids/FluidMushroomStew.java
// public class FluidMushroomStew extends Fluid
// {
// public FluidMushroomStew()
// {
// super("mushroomStew");
// setDensity(1200);
// setViscosity(1200);
// setLuminosity(0);
// }
//
// @Override
// public IIcon getStillIcon()
// {
// return Icons.mushRoomStewStill;
// }
//
// @Override
// public IIcon getIcon()
// {
// return Icons.mushRoomStewStill;
// }
//
// @Override
// public IIcon getFlowingIcon()
// {
// return Icons.mushRoomStewFlowing;
// }
//
// @Override
// public int getColor(FluidStack stack)
// {
// //Color color1 = new Color(205,140,111);
// return 0xcd8c6f;
// }
//
// @Override
// public boolean isGaseous(World world, int x, int y, int z)
// {
// return false;
// }
// }
| import com.darkona.adventurebackpack.fluids.FluidMelonJuice;
import com.darkona.adventurebackpack.fluids.FluidMilk;
import com.darkona.adventurebackpack.fluids.FluidMushroomStew;
import com.darkona.adventurebackpack.reference.GeneralReference;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.FluidRegistry; | package com.darkona.adventurebackpack.init;
/**
* Created on 12/10/2014.
*
* @author Javier Darkona
*/
public class ModFluids
{
public static FluidMilk milk;
public static FluidMelonJuice melonJuice; | // Path: src/main/java/com/darkona/adventurebackpack/fluids/FluidMilk.java
// public class FluidMilk extends Fluid
// {
//
// public FluidMilk()
// {
// super("milk");
// setDensity(1200);
// setViscosity(1200);
// setLuminosity(0);
// }
//
//
// @Override
// public IIcon getStillIcon()
// {
// return Icons.milkStill;
// }
//
// @Override
// public IIcon getIcon()
// {
// return Icons.milkStill;
// }
//
// @Override
// public IIcon getFlowingIcon()
// {
// return Icons.milkStill;
// }
//
// @Override
// public int getColor(FluidStack stack)
// {
// return 0xffffff;
// }
//
// @Override
// public boolean isGaseous(World world, int x, int y, int z)
// {
// return false;
// }
//
//
// }
//
// Path: src/main/java/com/darkona/adventurebackpack/fluids/FluidMushroomStew.java
// public class FluidMushroomStew extends Fluid
// {
// public FluidMushroomStew()
// {
// super("mushroomStew");
// setDensity(1200);
// setViscosity(1200);
// setLuminosity(0);
// }
//
// @Override
// public IIcon getStillIcon()
// {
// return Icons.mushRoomStewStill;
// }
//
// @Override
// public IIcon getIcon()
// {
// return Icons.mushRoomStewStill;
// }
//
// @Override
// public IIcon getFlowingIcon()
// {
// return Icons.mushRoomStewFlowing;
// }
//
// @Override
// public int getColor(FluidStack stack)
// {
// //Color color1 = new Color(205,140,111);
// return 0xcd8c6f;
// }
//
// @Override
// public boolean isGaseous(World world, int x, int y, int z)
// {
// return false;
// }
// }
// Path: src/main/java/com/darkona/adventurebackpack/init/ModFluids.java
import com.darkona.adventurebackpack.fluids.FluidMelonJuice;
import com.darkona.adventurebackpack.fluids.FluidMilk;
import com.darkona.adventurebackpack.fluids.FluidMushroomStew;
import com.darkona.adventurebackpack.reference.GeneralReference;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.FluidRegistry;
package com.darkona.adventurebackpack.init;
/**
* Created on 12/10/2014.
*
* @author Javier Darkona
*/
public class ModFluids
{
public static FluidMilk milk;
public static FluidMelonJuice melonJuice; | public static FluidMushroomStew mushroomStew; |
Darkona/AdventureBackpack2 | src/main/java/com/darkona/adventurebackpack/config/ConfigHandler.java | // Path: src/main/java/com/darkona/adventurebackpack/reference/ModInfo.java
// public class ModInfo
// {
// public static final String MOD_NAME = "Adventure Backpack";
// public static final String MOD_VERSION = "1.7.10-0.8d";
// public static final String MOD_ID = "adventurebackpack";
// public static final String MOD_CHANNEL = "advBackpackChan";
// public static final String MOD_CLIENT_PROXY = "com.darkona.adventurebackpack.proxy.ClientProxy";
// public static final String MOD_SERVER_PROXY = "com.darkona.adventurebackpack.proxy.ServerProxy";
// public static final String GUI_FACTORY_CLASS = "com.darkona.adventurebackpack.client.gui.GuiFactory";
// }
| import com.darkona.adventurebackpack.reference.ModInfo;
import cpw.mods.fml.client.event.ConfigChangedEvent;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.common.config.Configuration;
import java.io.File; | config = new Configuration(configFile);
loadConfiguration();
}
}
private static void loadConfiguration()
{
GUI_TANK_RENDER = config.getInt("TankRenderType", config.CATEGORY_GENERAL, 3, 1, 3, "1,2 or 3 for different rendering of fluids in the Backpack GUI");
BONUS_CHEST_ALLOWED = config.getBoolean("BonusBackpack", config.CATEGORY_GENERAL, false, "Include a Standard Adventure Backpack in bonus chest?");
PIGMAN_ALLOWED = config.getBoolean("PigmanBackpacks", config.CATEGORY_GENERAL, false, "Allow generation of Pigman Backpacks in dungeon loot and villager trades");
ALLOW_COPTER_SOUND = config.getBoolean("CopterPackSound", config.CATEGORY_GENERAL, true, "Allow playing the CopterPack sound (Client Only, other players may hear it)");
BACKPACK_ABILITIES = config.getBoolean("BackpackAbilities", config.CATEGORY_GENERAL, true, "Allow the backpacks to execute their special abilities, or be only cosmetic (Doesn't affect lightning transformation) Must be " +
"disabled in both Client and Server to work properly");
STATUS_OVERLAY = config.getBoolean("StatusOverlay", config.CATEGORY_GENERAL,true, "Show player status effects on screen?");
TANKS_OVERLAY = config.getBoolean("BackpackOverlay", config.CATEGORY_GENERAL,true, "Show the different wearable overlays on screen?");
HOVERING_TEXT_TANKS = config.getBoolean("HoveringText", config.CATEGORY_GENERAL,false, "Show hovering text on fluid tanks?");
FIX_LEAD = config.getBoolean("FixVanillaLead", config.CATEGORY_GENERAL,true, "Fix the vanilla Lead? (Checks mobs falling on a leash to not die of fall damage if they're not falling so fast)");
BACKPACK_DEATH_PLACE = config.getBoolean("BackpackDeathPlace", config.CATEGORY_GENERAL,true,"Place backpacks as a block when you die?");
//RECIPES
SADDLE_RECIPE = config.getBoolean("SaddleRecipe", config.CATEGORY_GENERAL,true, "Add recipe for saddle?");
if (config.hasChanged())
{
config.save();
}
}
@SubscribeEvent
public void onConfigChangeEvent(ConfigChangedEvent.OnConfigChangedEvent event)
{ | // Path: src/main/java/com/darkona/adventurebackpack/reference/ModInfo.java
// public class ModInfo
// {
// public static final String MOD_NAME = "Adventure Backpack";
// public static final String MOD_VERSION = "1.7.10-0.8d";
// public static final String MOD_ID = "adventurebackpack";
// public static final String MOD_CHANNEL = "advBackpackChan";
// public static final String MOD_CLIENT_PROXY = "com.darkona.adventurebackpack.proxy.ClientProxy";
// public static final String MOD_SERVER_PROXY = "com.darkona.adventurebackpack.proxy.ServerProxy";
// public static final String GUI_FACTORY_CLASS = "com.darkona.adventurebackpack.client.gui.GuiFactory";
// }
// Path: src/main/java/com/darkona/adventurebackpack/config/ConfigHandler.java
import com.darkona.adventurebackpack.reference.ModInfo;
import cpw.mods.fml.client.event.ConfigChangedEvent;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.common.config.Configuration;
import java.io.File;
config = new Configuration(configFile);
loadConfiguration();
}
}
private static void loadConfiguration()
{
GUI_TANK_RENDER = config.getInt("TankRenderType", config.CATEGORY_GENERAL, 3, 1, 3, "1,2 or 3 for different rendering of fluids in the Backpack GUI");
BONUS_CHEST_ALLOWED = config.getBoolean("BonusBackpack", config.CATEGORY_GENERAL, false, "Include a Standard Adventure Backpack in bonus chest?");
PIGMAN_ALLOWED = config.getBoolean("PigmanBackpacks", config.CATEGORY_GENERAL, false, "Allow generation of Pigman Backpacks in dungeon loot and villager trades");
ALLOW_COPTER_SOUND = config.getBoolean("CopterPackSound", config.CATEGORY_GENERAL, true, "Allow playing the CopterPack sound (Client Only, other players may hear it)");
BACKPACK_ABILITIES = config.getBoolean("BackpackAbilities", config.CATEGORY_GENERAL, true, "Allow the backpacks to execute their special abilities, or be only cosmetic (Doesn't affect lightning transformation) Must be " +
"disabled in both Client and Server to work properly");
STATUS_OVERLAY = config.getBoolean("StatusOverlay", config.CATEGORY_GENERAL,true, "Show player status effects on screen?");
TANKS_OVERLAY = config.getBoolean("BackpackOverlay", config.CATEGORY_GENERAL,true, "Show the different wearable overlays on screen?");
HOVERING_TEXT_TANKS = config.getBoolean("HoveringText", config.CATEGORY_GENERAL,false, "Show hovering text on fluid tanks?");
FIX_LEAD = config.getBoolean("FixVanillaLead", config.CATEGORY_GENERAL,true, "Fix the vanilla Lead? (Checks mobs falling on a leash to not die of fall damage if they're not falling so fast)");
BACKPACK_DEATH_PLACE = config.getBoolean("BackpackDeathPlace", config.CATEGORY_GENERAL,true,"Place backpacks as a block when you die?");
//RECIPES
SADDLE_RECIPE = config.getBoolean("SaddleRecipe", config.CATEGORY_GENERAL,true, "Add recipe for saddle?");
if (config.hasChanged())
{
config.save();
}
}
@SubscribeEvent
public void onConfigChangeEvent(ConfigChangedEvent.OnConfigChangedEvent event)
{ | if (event.modID.equalsIgnoreCase(ModInfo.MOD_ID)) |
Darkona/AdventureBackpack2 | src/main/java/com/darkona/adventurebackpack/CreativeTabAB.java | // Path: src/main/java/com/darkona/adventurebackpack/reference/ModInfo.java
// public class ModInfo
// {
// public static final String MOD_NAME = "Adventure Backpack";
// public static final String MOD_VERSION = "1.7.10-0.8d";
// public static final String MOD_ID = "adventurebackpack";
// public static final String MOD_CHANNEL = "advBackpackChan";
// public static final String MOD_CLIENT_PROXY = "com.darkona.adventurebackpack.proxy.ClientProxy";
// public static final String MOD_SERVER_PROXY = "com.darkona.adventurebackpack.proxy.ServerProxy";
// public static final String GUI_FACTORY_CLASS = "com.darkona.adventurebackpack.client.gui.GuiFactory";
// }
| import com.darkona.adventurebackpack.init.ModItems;
import com.darkona.adventurebackpack.reference.ModInfo;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item; | package com.darkona.adventurebackpack;
/**
* Created on 11/10/2014.
* @author Javier Darkona
*/
public class CreativeTabAB
{
| // Path: src/main/java/com/darkona/adventurebackpack/reference/ModInfo.java
// public class ModInfo
// {
// public static final String MOD_NAME = "Adventure Backpack";
// public static final String MOD_VERSION = "1.7.10-0.8d";
// public static final String MOD_ID = "adventurebackpack";
// public static final String MOD_CHANNEL = "advBackpackChan";
// public static final String MOD_CLIENT_PROXY = "com.darkona.adventurebackpack.proxy.ClientProxy";
// public static final String MOD_SERVER_PROXY = "com.darkona.adventurebackpack.proxy.ServerProxy";
// public static final String GUI_FACTORY_CLASS = "com.darkona.adventurebackpack.client.gui.GuiFactory";
// }
// Path: src/main/java/com/darkona/adventurebackpack/CreativeTabAB.java
import com.darkona.adventurebackpack.init.ModItems;
import com.darkona.adventurebackpack.reference.ModInfo;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
package com.darkona.adventurebackpack;
/**
* Created on 11/10/2014.
* @author Javier Darkona
*/
public class CreativeTabAB
{
| public static final CreativeTabs ADVENTURE_BACKPACK_CREATIVE_TAB = new CreativeTabs(ModInfo.MOD_ID.toLowerCase()) |
Darkona/AdventureBackpack2 | src/main/java/com/darkona/adventurebackpack/client/audio/LeakingBoilerSound.java | // Path: src/main/java/com/darkona/adventurebackpack/reference/ModInfo.java
// public class ModInfo
// {
// public static final String MOD_NAME = "Adventure Backpack";
// public static final String MOD_VERSION = "1.7.10-0.8d";
// public static final String MOD_ID = "adventurebackpack";
// public static final String MOD_CHANNEL = "advBackpackChan";
// public static final String MOD_CLIENT_PROXY = "com.darkona.adventurebackpack.proxy.ClientProxy";
// public static final String MOD_SERVER_PROXY = "com.darkona.adventurebackpack.proxy.ServerProxy";
// public static final String GUI_FACTORY_CLASS = "com.darkona.adventurebackpack.client.gui.GuiFactory";
// }
| import com.darkona.adventurebackpack.inventory.InventorySteamJetpack;
import com.darkona.adventurebackpack.reference.ModInfo;
import com.darkona.adventurebackpack.util.Wearing;
import net.minecraft.client.audio.MovingSound;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ResourceLocation; | package com.darkona.adventurebackpack.client.audio;
/**
* Created on 16/01/2015
*
* @author Darkona
*/
public class LeakingBoilerSound extends MovingSound
{
public EntityPlayer thePlayer;
protected boolean repeat = true;
protected int repeatDelay = 0;
protected float pitch;
public LeakingBoilerSound(EntityPlayer player)
{ | // Path: src/main/java/com/darkona/adventurebackpack/reference/ModInfo.java
// public class ModInfo
// {
// public static final String MOD_NAME = "Adventure Backpack";
// public static final String MOD_VERSION = "1.7.10-0.8d";
// public static final String MOD_ID = "adventurebackpack";
// public static final String MOD_CHANNEL = "advBackpackChan";
// public static final String MOD_CLIENT_PROXY = "com.darkona.adventurebackpack.proxy.ClientProxy";
// public static final String MOD_SERVER_PROXY = "com.darkona.adventurebackpack.proxy.ServerProxy";
// public static final String GUI_FACTORY_CLASS = "com.darkona.adventurebackpack.client.gui.GuiFactory";
// }
// Path: src/main/java/com/darkona/adventurebackpack/client/audio/LeakingBoilerSound.java
import com.darkona.adventurebackpack.inventory.InventorySteamJetpack;
import com.darkona.adventurebackpack.reference.ModInfo;
import com.darkona.adventurebackpack.util.Wearing;
import net.minecraft.client.audio.MovingSound;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ResourceLocation;
package com.darkona.adventurebackpack.client.audio;
/**
* Created on 16/01/2015
*
* @author Darkona
*/
public class LeakingBoilerSound extends MovingSound
{
public EntityPlayer thePlayer;
protected boolean repeat = true;
protected int repeatDelay = 0;
protected float pitch;
public LeakingBoilerSound(EntityPlayer player)
{ | super(new ResourceLocation(ModInfo.MOD_ID, "s_background2")); |
Darkona/AdventureBackpack2 | src/main/java/com/darkona/adventurebackpack/handlers/RenderHandler.java | // Path: src/main/java/com/darkona/adventurebackpack/proxy/ClientProxy.java
// public class ClientProxy implements IProxy
// {
//
// public static RendererItemAdventureBackpack rendererItemAdventureBackpack;
// public static RendererItemAdventureHat rendererItemAdventureHat;
// public static RendererHose rendererHose;
// public static RendererWearableEquipped rendererWearableEquipped;
// public static RenderHandler renderHandler;
// public static RendererInflatableBoat renderInflatableBoat;
// public static RenderRideableSpider renderRideableSpider;
// public static RendererItemClockworkCrossbow renderCrossbow;
// public static ModelSteamJetpack modelSteamJetpack = new ModelSteamJetpack();
// public static ModelBackpackArmor modelAdventureBackpack = new ModelBackpackArmor();
// public static ModelCopterPack modelCopterPack = new ModelCopterPack();
//
//
// public void init()
// {
// initRenderers();
// registerKeybindings();
// MinecraftForge.EVENT_BUS.register(new GuiOverlay(Minecraft.getMinecraft()));
// }
//
// public void initNetwork()
// {
//
// }
//
// @Override
// public void joinPlayer(EntityPlayer player)
// {
// LogHelper.info("Joined Player in client");
// }
//
// @Override
// public void synchronizePlayer(int id, NBTTagCompound properties)
// {
// Entity entity = Minecraft.getMinecraft().theWorld.getEntityByID(id);
// if(Utils.notNullAndInstanceOf(entity, EntityPlayer.class)&& properties != null)
// {
// EntityPlayer player = (EntityPlayer)entity;
// if(BackpackProperty.get(player) == null) BackpackProperty.register(player);
// BackpackProperty.get(player).loadNBTData(properties);
// }
// }
//
// public void initRenderers()
// {
// renderHandler = new RenderHandler();
// MinecraftForge.EVENT_BUS.register(renderHandler);
// rendererWearableEquipped = new RendererWearableEquipped();
//
// rendererItemAdventureBackpack = new RendererItemAdventureBackpack();
// MinecraftForgeClient.registerItemRenderer(ModItems.adventureBackpack, rendererItemAdventureBackpack);
// MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(ModBlocks.blockBackpack), rendererItemAdventureBackpack);
// ClientRegistry.bindTileEntitySpecialRenderer(TileAdventureBackpack.class, new RendererAdventureBackpackBlock());
//
// rendererItemAdventureHat = new RendererItemAdventureHat();
// MinecraftForgeClient.registerItemRenderer(ModItems.adventureHat, rendererItemAdventureHat);
//
// if(!ConfigHandler.TANKS_OVERLAY)
// {
// rendererHose = new RendererHose();
// MinecraftForgeClient.registerItemRenderer(ModItems.hose, rendererHose);
// }
//
// ClientRegistry.bindTileEntitySpecialRenderer(TileCampfire.class, new RendererCampFire());
//
// renderInflatableBoat = new RendererInflatableBoat();
// RenderingRegistry.registerEntityRenderingHandler(EntityInflatableBoat.class, renderInflatableBoat);
// renderRideableSpider = new RenderRideableSpider();
// RenderingRegistry.registerEntityRenderingHandler(EntityFriendlySpider.class, renderRideableSpider);
//
// renderCrossbow = new RendererItemClockworkCrossbow();
// MinecraftForgeClient.registerItemRenderer(ModItems.cwxbow, renderCrossbow);
// }
//
// public void registerKeybindings()
// {
// ClientRegistry.registerKeyBinding(Keybindings.openBackpack);
// ClientRegistry.registerKeyBinding(Keybindings.toggleHose);
// FMLCommonHandler.instance().bus().register(new KeybindHandler());
// }
//
// }
| import com.darkona.adventurebackpack.proxy.ClientProxy;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraftforge.client.event.RenderPlayerEvent; | package com.darkona.adventurebackpack.handlers;
/**
* Created on 25/12/2014
*
* @author Darkona
*/
public class RenderHandler
{
@SubscribeEvent
@SideOnly(Side.CLIENT)
public void playerSpecialsRendering(RenderPlayerEvent.Specials.Pre event)
{
float rotationY = event.renderer.modelBipedMain.bipedBody.rotateAngleY;
float rotationX = event.renderer.modelBipedMain.bipedBody.rotateAngleX;
float rotationZ = event.renderer.modelBipedMain.bipedBody.rotateAngleZ;
double x = event.entity.posX;
double y = event.entity.posY;
double z = event.entity.posZ;
float pitch = event.entity.rotationPitch;
float yaw = event.entity.rotationYaw; | // Path: src/main/java/com/darkona/adventurebackpack/proxy/ClientProxy.java
// public class ClientProxy implements IProxy
// {
//
// public static RendererItemAdventureBackpack rendererItemAdventureBackpack;
// public static RendererItemAdventureHat rendererItemAdventureHat;
// public static RendererHose rendererHose;
// public static RendererWearableEquipped rendererWearableEquipped;
// public static RenderHandler renderHandler;
// public static RendererInflatableBoat renderInflatableBoat;
// public static RenderRideableSpider renderRideableSpider;
// public static RendererItemClockworkCrossbow renderCrossbow;
// public static ModelSteamJetpack modelSteamJetpack = new ModelSteamJetpack();
// public static ModelBackpackArmor modelAdventureBackpack = new ModelBackpackArmor();
// public static ModelCopterPack modelCopterPack = new ModelCopterPack();
//
//
// public void init()
// {
// initRenderers();
// registerKeybindings();
// MinecraftForge.EVENT_BUS.register(new GuiOverlay(Minecraft.getMinecraft()));
// }
//
// public void initNetwork()
// {
//
// }
//
// @Override
// public void joinPlayer(EntityPlayer player)
// {
// LogHelper.info("Joined Player in client");
// }
//
// @Override
// public void synchronizePlayer(int id, NBTTagCompound properties)
// {
// Entity entity = Minecraft.getMinecraft().theWorld.getEntityByID(id);
// if(Utils.notNullAndInstanceOf(entity, EntityPlayer.class)&& properties != null)
// {
// EntityPlayer player = (EntityPlayer)entity;
// if(BackpackProperty.get(player) == null) BackpackProperty.register(player);
// BackpackProperty.get(player).loadNBTData(properties);
// }
// }
//
// public void initRenderers()
// {
// renderHandler = new RenderHandler();
// MinecraftForge.EVENT_BUS.register(renderHandler);
// rendererWearableEquipped = new RendererWearableEquipped();
//
// rendererItemAdventureBackpack = new RendererItemAdventureBackpack();
// MinecraftForgeClient.registerItemRenderer(ModItems.adventureBackpack, rendererItemAdventureBackpack);
// MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(ModBlocks.blockBackpack), rendererItemAdventureBackpack);
// ClientRegistry.bindTileEntitySpecialRenderer(TileAdventureBackpack.class, new RendererAdventureBackpackBlock());
//
// rendererItemAdventureHat = new RendererItemAdventureHat();
// MinecraftForgeClient.registerItemRenderer(ModItems.adventureHat, rendererItemAdventureHat);
//
// if(!ConfigHandler.TANKS_OVERLAY)
// {
// rendererHose = new RendererHose();
// MinecraftForgeClient.registerItemRenderer(ModItems.hose, rendererHose);
// }
//
// ClientRegistry.bindTileEntitySpecialRenderer(TileCampfire.class, new RendererCampFire());
//
// renderInflatableBoat = new RendererInflatableBoat();
// RenderingRegistry.registerEntityRenderingHandler(EntityInflatableBoat.class, renderInflatableBoat);
// renderRideableSpider = new RenderRideableSpider();
// RenderingRegistry.registerEntityRenderingHandler(EntityFriendlySpider.class, renderRideableSpider);
//
// renderCrossbow = new RendererItemClockworkCrossbow();
// MinecraftForgeClient.registerItemRenderer(ModItems.cwxbow, renderCrossbow);
// }
//
// public void registerKeybindings()
// {
// ClientRegistry.registerKeyBinding(Keybindings.openBackpack);
// ClientRegistry.registerKeyBinding(Keybindings.toggleHose);
// FMLCommonHandler.instance().bus().register(new KeybindHandler());
// }
//
// }
// Path: src/main/java/com/darkona/adventurebackpack/handlers/RenderHandler.java
import com.darkona.adventurebackpack.proxy.ClientProxy;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraftforge.client.event.RenderPlayerEvent;
package com.darkona.adventurebackpack.handlers;
/**
* Created on 25/12/2014
*
* @author Darkona
*/
public class RenderHandler
{
@SubscribeEvent
@SideOnly(Side.CLIENT)
public void playerSpecialsRendering(RenderPlayerEvent.Specials.Pre event)
{
float rotationY = event.renderer.modelBipedMain.bipedBody.rotateAngleY;
float rotationX = event.renderer.modelBipedMain.bipedBody.rotateAngleX;
float rotationZ = event.renderer.modelBipedMain.bipedBody.rotateAngleZ;
double x = event.entity.posX;
double y = event.entity.posY;
double z = event.entity.posZ;
float pitch = event.entity.rotationPitch;
float yaw = event.entity.rotationYaw; | ClientProxy.rendererWearableEquipped.render(event.entity, x, y, z, rotationX, rotationY, rotationZ, pitch, yaw); |
Darkona/AdventureBackpack2 | src/main/java/com/darkona/adventurebackpack/item/ArmorAB.java | // Path: src/main/java/com/darkona/adventurebackpack/CreativeTabAB.java
// public class CreativeTabAB
// {
//
// public static final CreativeTabs ADVENTURE_BACKPACK_CREATIVE_TAB = new CreativeTabs(ModInfo.MOD_ID.toLowerCase())
// {
// @Override
// public Item getTabIconItem()
// {
// return ModItems.machete;
// }
//
// @Override
// public String getTranslatedTabLabel()
// {
// return super.getTranslatedTabLabel();
// }
//
// @Override
// public String getTabLabel()
// {
// return ModInfo.MOD_ID.toLowerCase();
// }
//
// };
//
// }
//
// Path: src/main/java/com/darkona/adventurebackpack/reference/ModInfo.java
// public class ModInfo
// {
// public static final String MOD_NAME = "Adventure Backpack";
// public static final String MOD_VERSION = "1.7.10-0.8d";
// public static final String MOD_ID = "adventurebackpack";
// public static final String MOD_CHANNEL = "advBackpackChan";
// public static final String MOD_CLIENT_PROXY = "com.darkona.adventurebackpack.proxy.ClientProxy";
// public static final String MOD_SERVER_PROXY = "com.darkona.adventurebackpack.proxy.ServerProxy";
// public static final String GUI_FACTORY_CLASS = "com.darkona.adventurebackpack.client.gui.GuiFactory";
// }
| import com.darkona.adventurebackpack.CreativeTabAB;
import com.darkona.adventurebackpack.init.ModMaterials;
import com.darkona.adventurebackpack.reference.ModInfo;
import com.darkona.adventurebackpack.util.Resources;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.Entity;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack; | package com.darkona.adventurebackpack.item;
/**
* Created on 11/10/2014.
* @author Javier Darkona
*/
public class ArmorAB extends ItemArmor
{
/**
* @param type 2 Chain
* @param renderIndex 0 Helmet, 1 Plate, 2 Pants, 3 Boots
*/
public ArmorAB(int renderIndex, int type)
{
super(ModMaterials.ruggedLeather, renderIndex, type); | // Path: src/main/java/com/darkona/adventurebackpack/CreativeTabAB.java
// public class CreativeTabAB
// {
//
// public static final CreativeTabs ADVENTURE_BACKPACK_CREATIVE_TAB = new CreativeTabs(ModInfo.MOD_ID.toLowerCase())
// {
// @Override
// public Item getTabIconItem()
// {
// return ModItems.machete;
// }
//
// @Override
// public String getTranslatedTabLabel()
// {
// return super.getTranslatedTabLabel();
// }
//
// @Override
// public String getTabLabel()
// {
// return ModInfo.MOD_ID.toLowerCase();
// }
//
// };
//
// }
//
// Path: src/main/java/com/darkona/adventurebackpack/reference/ModInfo.java
// public class ModInfo
// {
// public static final String MOD_NAME = "Adventure Backpack";
// public static final String MOD_VERSION = "1.7.10-0.8d";
// public static final String MOD_ID = "adventurebackpack";
// public static final String MOD_CHANNEL = "advBackpackChan";
// public static final String MOD_CLIENT_PROXY = "com.darkona.adventurebackpack.proxy.ClientProxy";
// public static final String MOD_SERVER_PROXY = "com.darkona.adventurebackpack.proxy.ServerProxy";
// public static final String GUI_FACTORY_CLASS = "com.darkona.adventurebackpack.client.gui.GuiFactory";
// }
// Path: src/main/java/com/darkona/adventurebackpack/item/ArmorAB.java
import com.darkona.adventurebackpack.CreativeTabAB;
import com.darkona.adventurebackpack.init.ModMaterials;
import com.darkona.adventurebackpack.reference.ModInfo;
import com.darkona.adventurebackpack.util.Resources;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.Entity;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
package com.darkona.adventurebackpack.item;
/**
* Created on 11/10/2014.
* @author Javier Darkona
*/
public class ArmorAB extends ItemArmor
{
/**
* @param type 2 Chain
* @param renderIndex 0 Helmet, 1 Plate, 2 Pants, 3 Boots
*/
public ArmorAB(int renderIndex, int type)
{
super(ModMaterials.ruggedLeather, renderIndex, type); | setCreativeTab(CreativeTabAB.ADVENTURE_BACKPACK_CREATIVE_TAB); |
Darkona/AdventureBackpack2 | src/main/java/com/darkona/adventurebackpack/item/ArmorAB.java | // Path: src/main/java/com/darkona/adventurebackpack/CreativeTabAB.java
// public class CreativeTabAB
// {
//
// public static final CreativeTabs ADVENTURE_BACKPACK_CREATIVE_TAB = new CreativeTabs(ModInfo.MOD_ID.toLowerCase())
// {
// @Override
// public Item getTabIconItem()
// {
// return ModItems.machete;
// }
//
// @Override
// public String getTranslatedTabLabel()
// {
// return super.getTranslatedTabLabel();
// }
//
// @Override
// public String getTabLabel()
// {
// return ModInfo.MOD_ID.toLowerCase();
// }
//
// };
//
// }
//
// Path: src/main/java/com/darkona/adventurebackpack/reference/ModInfo.java
// public class ModInfo
// {
// public static final String MOD_NAME = "Adventure Backpack";
// public static final String MOD_VERSION = "1.7.10-0.8d";
// public static final String MOD_ID = "adventurebackpack";
// public static final String MOD_CHANNEL = "advBackpackChan";
// public static final String MOD_CLIENT_PROXY = "com.darkona.adventurebackpack.proxy.ClientProxy";
// public static final String MOD_SERVER_PROXY = "com.darkona.adventurebackpack.proxy.ServerProxy";
// public static final String GUI_FACTORY_CLASS = "com.darkona.adventurebackpack.client.gui.GuiFactory";
// }
| import com.darkona.adventurebackpack.CreativeTabAB;
import com.darkona.adventurebackpack.init.ModMaterials;
import com.darkona.adventurebackpack.reference.ModInfo;
import com.darkona.adventurebackpack.util.Resources;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.Entity;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack; | package com.darkona.adventurebackpack.item;
/**
* Created on 11/10/2014.
* @author Javier Darkona
*/
public class ArmorAB extends ItemArmor
{
/**
* @param type 2 Chain
* @param renderIndex 0 Helmet, 1 Plate, 2 Pants, 3 Boots
*/
public ArmorAB(int renderIndex, int type)
{
super(ModMaterials.ruggedLeather, renderIndex, type);
setCreativeTab(CreativeTabAB.ADVENTURE_BACKPACK_CREATIVE_TAB);
}
protected String getUnwrappedUnlocalizedName(String unlocalizedName)
{
return unlocalizedName.substring(unlocalizedName.indexOf(".") + 1);
}
@Override
public String getUnlocalizedName(ItemStack stack)
{
return getUnlocalizedName();
}
@Override
public String getUnlocalizedName()
{ | // Path: src/main/java/com/darkona/adventurebackpack/CreativeTabAB.java
// public class CreativeTabAB
// {
//
// public static final CreativeTabs ADVENTURE_BACKPACK_CREATIVE_TAB = new CreativeTabs(ModInfo.MOD_ID.toLowerCase())
// {
// @Override
// public Item getTabIconItem()
// {
// return ModItems.machete;
// }
//
// @Override
// public String getTranslatedTabLabel()
// {
// return super.getTranslatedTabLabel();
// }
//
// @Override
// public String getTabLabel()
// {
// return ModInfo.MOD_ID.toLowerCase();
// }
//
// };
//
// }
//
// Path: src/main/java/com/darkona/adventurebackpack/reference/ModInfo.java
// public class ModInfo
// {
// public static final String MOD_NAME = "Adventure Backpack";
// public static final String MOD_VERSION = "1.7.10-0.8d";
// public static final String MOD_ID = "adventurebackpack";
// public static final String MOD_CHANNEL = "advBackpackChan";
// public static final String MOD_CLIENT_PROXY = "com.darkona.adventurebackpack.proxy.ClientProxy";
// public static final String MOD_SERVER_PROXY = "com.darkona.adventurebackpack.proxy.ServerProxy";
// public static final String GUI_FACTORY_CLASS = "com.darkona.adventurebackpack.client.gui.GuiFactory";
// }
// Path: src/main/java/com/darkona/adventurebackpack/item/ArmorAB.java
import com.darkona.adventurebackpack.CreativeTabAB;
import com.darkona.adventurebackpack.init.ModMaterials;
import com.darkona.adventurebackpack.reference.ModInfo;
import com.darkona.adventurebackpack.util.Resources;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.Entity;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
package com.darkona.adventurebackpack.item;
/**
* Created on 11/10/2014.
* @author Javier Darkona
*/
public class ArmorAB extends ItemArmor
{
/**
* @param type 2 Chain
* @param renderIndex 0 Helmet, 1 Plate, 2 Pants, 3 Boots
*/
public ArmorAB(int renderIndex, int type)
{
super(ModMaterials.ruggedLeather, renderIndex, type);
setCreativeTab(CreativeTabAB.ADVENTURE_BACKPACK_CREATIVE_TAB);
}
protected String getUnwrappedUnlocalizedName(String unlocalizedName)
{
return unlocalizedName.substring(unlocalizedName.indexOf(".") + 1);
}
@Override
public String getUnlocalizedName(ItemStack stack)
{
return getUnlocalizedName();
}
@Override
public String getUnlocalizedName()
{ | return String.format("item.%s%s", ModInfo.MOD_ID.toLowerCase() + ":", getUnwrappedUnlocalizedName(super.getUnlocalizedName())); |
Darkona/AdventureBackpack2 | src/main/java/com/darkona/adventurebackpack/client/audio/BoilingBoilerSound.java | // Path: src/main/java/com/darkona/adventurebackpack/reference/ModInfo.java
// public class ModInfo
// {
// public static final String MOD_NAME = "Adventure Backpack";
// public static final String MOD_VERSION = "1.7.10-0.8d";
// public static final String MOD_ID = "adventurebackpack";
// public static final String MOD_CHANNEL = "advBackpackChan";
// public static final String MOD_CLIENT_PROXY = "com.darkona.adventurebackpack.proxy.ClientProxy";
// public static final String MOD_SERVER_PROXY = "com.darkona.adventurebackpack.proxy.ServerProxy";
// public static final String GUI_FACTORY_CLASS = "com.darkona.adventurebackpack.client.gui.GuiFactory";
// }
| import com.darkona.adventurebackpack.inventory.InventorySteamJetpack;
import com.darkona.adventurebackpack.reference.ModInfo;
import com.darkona.adventurebackpack.util.Wearing;
import net.minecraft.client.audio.MovingSound;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ResourceLocation; | package com.darkona.adventurebackpack.client.audio;
/**
* Created on 16/01/2015
*
* @author Darkona
*/
public class BoilingBoilerSound extends MovingSound
{
public EntityPlayer thePlayer;
protected boolean repeat = true;
protected int repeatDelay = 0;
protected float pitch;
public BoilingBoilerSound(EntityPlayer player)
{ | // Path: src/main/java/com/darkona/adventurebackpack/reference/ModInfo.java
// public class ModInfo
// {
// public static final String MOD_NAME = "Adventure Backpack";
// public static final String MOD_VERSION = "1.7.10-0.8d";
// public static final String MOD_ID = "adventurebackpack";
// public static final String MOD_CHANNEL = "advBackpackChan";
// public static final String MOD_CLIENT_PROXY = "com.darkona.adventurebackpack.proxy.ClientProxy";
// public static final String MOD_SERVER_PROXY = "com.darkona.adventurebackpack.proxy.ServerProxy";
// public static final String GUI_FACTORY_CLASS = "com.darkona.adventurebackpack.client.gui.GuiFactory";
// }
// Path: src/main/java/com/darkona/adventurebackpack/client/audio/BoilingBoilerSound.java
import com.darkona.adventurebackpack.inventory.InventorySteamJetpack;
import com.darkona.adventurebackpack.reference.ModInfo;
import com.darkona.adventurebackpack.util.Wearing;
import net.minecraft.client.audio.MovingSound;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ResourceLocation;
package com.darkona.adventurebackpack.client.audio;
/**
* Created on 16/01/2015
*
* @author Darkona
*/
public class BoilingBoilerSound extends MovingSound
{
public EntityPlayer thePlayer;
protected boolean repeat = true;
protected int repeatDelay = 0;
protected float pitch;
public BoilingBoilerSound(EntityPlayer player)
{ | super(new ResourceLocation(ModInfo.MOD_ID, "s_boiling")); |
Darkona/AdventureBackpack2 | src/main/java/com/darkona/adventurebackpack/client/audio/JetpackSoundOn.java | // Path: src/main/java/com/darkona/adventurebackpack/reference/ModInfo.java
// public class ModInfo
// {
// public static final String MOD_NAME = "Adventure Backpack";
// public static final String MOD_VERSION = "1.7.10-0.8d";
// public static final String MOD_ID = "adventurebackpack";
// public static final String MOD_CHANNEL = "advBackpackChan";
// public static final String MOD_CLIENT_PROXY = "com.darkona.adventurebackpack.proxy.ClientProxy";
// public static final String MOD_SERVER_PROXY = "com.darkona.adventurebackpack.proxy.ServerProxy";
// public static final String GUI_FACTORY_CLASS = "com.darkona.adventurebackpack.client.gui.GuiFactory";
// }
| import com.darkona.adventurebackpack.inventory.InventorySteamJetpack;
import com.darkona.adventurebackpack.reference.ModInfo;
import com.darkona.adventurebackpack.util.Wearing;
import net.minecraft.client.audio.MovingSound;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ResourceLocation; | package com.darkona.adventurebackpack.client.audio;
/**
* Created on 16/01/2015
*
* @author Darkona
*/
public class JetpackSoundOn extends MovingSound
{
public EntityPlayer thePlayer;
protected boolean repeat = true;
protected int repeatDelay = 0;
protected float pitch;
public JetpackSoundOn(EntityPlayer player)
{ | // Path: src/main/java/com/darkona/adventurebackpack/reference/ModInfo.java
// public class ModInfo
// {
// public static final String MOD_NAME = "Adventure Backpack";
// public static final String MOD_VERSION = "1.7.10-0.8d";
// public static final String MOD_ID = "adventurebackpack";
// public static final String MOD_CHANNEL = "advBackpackChan";
// public static final String MOD_CLIENT_PROXY = "com.darkona.adventurebackpack.proxy.ClientProxy";
// public static final String MOD_SERVER_PROXY = "com.darkona.adventurebackpack.proxy.ServerProxy";
// public static final String GUI_FACTORY_CLASS = "com.darkona.adventurebackpack.client.gui.GuiFactory";
// }
// Path: src/main/java/com/darkona/adventurebackpack/client/audio/JetpackSoundOn.java
import com.darkona.adventurebackpack.inventory.InventorySteamJetpack;
import com.darkona.adventurebackpack.reference.ModInfo;
import com.darkona.adventurebackpack.util.Wearing;
import net.minecraft.client.audio.MovingSound;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ResourceLocation;
package com.darkona.adventurebackpack.client.audio;
/**
* Created on 16/01/2015
*
* @author Darkona
*/
public class JetpackSoundOn extends MovingSound
{
public EntityPlayer thePlayer;
protected boolean repeat = true;
protected int repeatDelay = 0;
protected float pitch;
public JetpackSoundOn(EntityPlayer player)
{ | super(new ResourceLocation(ModInfo.MOD_ID, "s_jetpackon")); |
miguelbcr/RxGpsService | lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/GrantPermissions.java | // Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/PermissionDeniedException.java
// public class PermissionDeniedException extends RuntimeException {
//
// public PermissionDeniedException() {
// this("No permission granted");
// }
//
// public PermissionDeniedException(String detailMessage) {
// super(detailMessage);
// }
// }
| import android.app.Activity;
import com.miguelbcr.io.rx_gps_service.lib.entities.PermissionDeniedException;
import com.tbruyelle.rxpermissions.RxPermissions;
import rx.Observable;
import rx.functions.Func1; | /*
* Copyright 2016 miguelbcr
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.miguelbcr.io.rx_gps_service.lib;
final class GrantPermissions {
private Activity activity;
private String[] permissions;
GrantPermissions(Activity activity) {
this.activity = activity;
}
GrantPermissions with(String... permissions) {
this.permissions = permissions;
return this;
}
Observable<Void> builtObservable() {
if (permissions.length == 0) {
return Observable.just(null);
}
return RxPermissions.getInstance(activity)
.request(permissions)
.flatMap(new Func1<Boolean, Observable<Void>>() {
@Override public Observable<Void> call(Boolean granted) {
if (granted) {
return Observable.just(null);
}
return Observable.error( | // Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/PermissionDeniedException.java
// public class PermissionDeniedException extends RuntimeException {
//
// public PermissionDeniedException() {
// this("No permission granted");
// }
//
// public PermissionDeniedException(String detailMessage) {
// super(detailMessage);
// }
// }
// Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/GrantPermissions.java
import android.app.Activity;
import com.miguelbcr.io.rx_gps_service.lib.entities.PermissionDeniedException;
import com.tbruyelle.rxpermissions.RxPermissions;
import rx.Observable;
import rx.functions.Func1;
/*
* Copyright 2016 miguelbcr
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.miguelbcr.io.rx_gps_service.lib;
final class GrantPermissions {
private Activity activity;
private String[] permissions;
GrantPermissions(Activity activity) {
this.activity = activity;
}
GrantPermissions with(String... permissions) {
this.permissions = permissions;
return this;
}
Observable<Void> builtObservable() {
if (permissions.length == 0) {
return Observable.just(null);
}
return RxPermissions.getInstance(activity)
.request(permissions)
.flatMap(new Func1<Boolean, Observable<Void>>() {
@Override public Observable<Void> call(Boolean granted) {
if (granted) {
return Observable.just(null);
}
return Observable.error( | new PermissionDeniedException("No permissions granted: " + permissionsToString())); |
miguelbcr/RxGpsService | lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/RxGpsService.java | // Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/RouteStats.java
// @AutoValue public abstract class RouteStats {
//
// public abstract long time();
//
// public abstract long distance();
//
// public abstract float speedMax();
//
// public abstract float speedMin();
//
// public abstract float speedAverage();
//
// public abstract float speed();
//
// public abstract LatLongDetailed currentLocation();
//
// public abstract List<LatLong> latLongs();
//
// public abstract List<LatLongDetailed> latLongsDetailed();
//
// public static RouteStats create(long time, long distance, float speedMax, float speedMin,
// float speedAverage, float speed, LatLongDetailed currentLocation, List<LatLong> latLongs,
// List<LatLongDetailed> latLongsDetailed) {
// return new AutoValue_RouteStats(time, distance, speedMax, speedMin, speedAverage, speed,
// currentLocation, latLongs, latLongsDetailed);
// }
//
// public LatLong getLastLatLong() {
// return latLongs() != null && !latLongs().isEmpty() ? latLongs().get(latLongs().size() - 1)
// : LatLong.create(0, 0);
// }
//
// public LatLongDetailed getLastLatLongDetailed() {
// int size = latLongsDetailed().size();
// return latLongsDetailed() != null && !latLongsDetailed().isEmpty() ? latLongsDetailed().get(
// size - 1) : LatLongDetailed.create(new Location("Location-" + size));
// }
//
// @Override public String toString() {
// return " time="
// + time()
// + " distance="
// + distance()
// + " speed="
// + speed()
// + " latLong="
// + "("
// + currentLocation().location().getLatitude()
// + ", "
// + currentLocation().location().getLongitude()
// + ") checkpoint="
// + currentLocation().isCheckPoint()
// + " waypoints="
// + (latLongs() != null && !latLongs().isEmpty() ? latLongs().size()
// : latLongsDetailed() != null && !latLongsDetailed().isEmpty() ? latLongsDetailed().size()
// : 0);
// }
// }
| import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import com.miguelbcr.io.rx_gps_service.lib.entities.RouteStats;
import rx.Observable; | /*
* Copyright 2016 miguelbcr
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.miguelbcr.io.rx_gps_service.lib;
public class RxGpsService extends Service implements RxGpsServiceView {
private static RxGpsService instance;
private static Listener listener;
private static GpsConfig gpsConfig;
private NotificationFactory notificationFactory;
private RxGpsPresenter rxGpsPresenter; | // Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/RouteStats.java
// @AutoValue public abstract class RouteStats {
//
// public abstract long time();
//
// public abstract long distance();
//
// public abstract float speedMax();
//
// public abstract float speedMin();
//
// public abstract float speedAverage();
//
// public abstract float speed();
//
// public abstract LatLongDetailed currentLocation();
//
// public abstract List<LatLong> latLongs();
//
// public abstract List<LatLongDetailed> latLongsDetailed();
//
// public static RouteStats create(long time, long distance, float speedMax, float speedMin,
// float speedAverage, float speed, LatLongDetailed currentLocation, List<LatLong> latLongs,
// List<LatLongDetailed> latLongsDetailed) {
// return new AutoValue_RouteStats(time, distance, speedMax, speedMin, speedAverage, speed,
// currentLocation, latLongs, latLongsDetailed);
// }
//
// public LatLong getLastLatLong() {
// return latLongs() != null && !latLongs().isEmpty() ? latLongs().get(latLongs().size() - 1)
// : LatLong.create(0, 0);
// }
//
// public LatLongDetailed getLastLatLongDetailed() {
// int size = latLongsDetailed().size();
// return latLongsDetailed() != null && !latLongsDetailed().isEmpty() ? latLongsDetailed().get(
// size - 1) : LatLongDetailed.create(new Location("Location-" + size));
// }
//
// @Override public String toString() {
// return " time="
// + time()
// + " distance="
// + distance()
// + " speed="
// + speed()
// + " latLong="
// + "("
// + currentLocation().location().getLatitude()
// + ", "
// + currentLocation().location().getLongitude()
// + ") checkpoint="
// + currentLocation().isCheckPoint()
// + " waypoints="
// + (latLongs() != null && !latLongs().isEmpty() ? latLongs().size()
// : latLongsDetailed() != null && !latLongsDetailed().isEmpty() ? latLongsDetailed().size()
// : 0);
// }
// }
// Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/RxGpsService.java
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import com.miguelbcr.io.rx_gps_service.lib.entities.RouteStats;
import rx.Observable;
/*
* Copyright 2016 miguelbcr
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.miguelbcr.io.rx_gps_service.lib;
public class RxGpsService extends Service implements RxGpsServiceView {
private static RxGpsService instance;
private static Listener listener;
private static GpsConfig gpsConfig;
private NotificationFactory notificationFactory;
private RxGpsPresenter rxGpsPresenter; | private Observable<RouteStats> oRouteStats; |
miguelbcr/RxGpsService | lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/RxGpsPresenter.java | // Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/LatLong.java
// @AutoValue public abstract class LatLong {
// public abstract double latitude();
//
// public abstract double longitude();
//
// public abstract float altitude();
//
// public abstract boolean isCheckPoint();
//
// public static LatLong create(double latitude, double longitude) {
// return create(latitude, longitude, 0, false);
// }
//
// public static LatLong create(double latitude, double longitude, float altitude,
// boolean isCheckPoint) {
// return new AutoValue_LatLong(latitude, longitude, altitude, isCheckPoint);
// }
// }
//
// Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/LatLongDetailed.java
// @AutoValue public abstract class LatLongDetailed {
// public abstract Location location();
//
// public abstract boolean isCheckPoint();
//
// public static LatLongDetailed create(Location location) {
// return create(location, false);
// }
//
// public static LatLongDetailed create(Location location, boolean isCheckPoint) {
// return new AutoValue_LatLongDetailed(location, isCheckPoint);
// }
// }
//
// Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/RouteStats.java
// @AutoValue public abstract class RouteStats {
//
// public abstract long time();
//
// public abstract long distance();
//
// public abstract float speedMax();
//
// public abstract float speedMin();
//
// public abstract float speedAverage();
//
// public abstract float speed();
//
// public abstract LatLongDetailed currentLocation();
//
// public abstract List<LatLong> latLongs();
//
// public abstract List<LatLongDetailed> latLongsDetailed();
//
// public static RouteStats create(long time, long distance, float speedMax, float speedMin,
// float speedAverage, float speed, LatLongDetailed currentLocation, List<LatLong> latLongs,
// List<LatLongDetailed> latLongsDetailed) {
// return new AutoValue_RouteStats(time, distance, speedMax, speedMin, speedAverage, speed,
// currentLocation, latLongs, latLongsDetailed);
// }
//
// public LatLong getLastLatLong() {
// return latLongs() != null && !latLongs().isEmpty() ? latLongs().get(latLongs().size() - 1)
// : LatLong.create(0, 0);
// }
//
// public LatLongDetailed getLastLatLongDetailed() {
// int size = latLongsDetailed().size();
// return latLongsDetailed() != null && !latLongsDetailed().isEmpty() ? latLongsDetailed().get(
// size - 1) : LatLongDetailed.create(new Location("Location-" + size));
// }
//
// @Override public String toString() {
// return " time="
// + time()
// + " distance="
// + distance()
// + " speed="
// + speed()
// + " latLong="
// + "("
// + currentLocation().location().getLatitude()
// + ", "
// + currentLocation().location().getLongitude()
// + ") checkpoint="
// + currentLocation().isCheckPoint()
// + " waypoints="
// + (latLongs() != null && !latLongs().isEmpty() ? latLongs().size()
// : latLongsDetailed() != null && !latLongsDetailed().isEmpty() ? latLongsDetailed().size()
// : 0);
// }
// }
| import rx.observables.ConnectableObservable;
import rx.subscriptions.CompositeSubscription;
import android.location.Location;
import android.util.Log;
import com.miguelbcr.io.rx_gps_service.lib.entities.LatLong;
import com.miguelbcr.io.rx_gps_service.lib.entities.LatLongDetailed;
import com.miguelbcr.io.rx_gps_service.lib.entities.RouteStats;
import java.util.ArrayList;
import java.util.List;
import rx.Observable;
import rx.Subscription;
import rx.functions.Action1;
import rx.functions.Func1; | /*
* Copyright 2016 miguelbcr
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.miguelbcr.io.rx_gps_service.lib;
class RxGpsPresenter {
private static final String TAG = "RxGpsService";
private final MeaningfulUpdatesLocation meaningfulUpdatesLocation;
private final RecordTime recordTime;
private final GetTripDistance getTripDistance;
private final GetTripSpeed getTripSpeed;
private final GetTripSpeedAverage getTripSpeedAverage;
private final GetTripSpeedMax getTripSpeedMax;
private final GetTripSpeedMin getTripSpeedMin;
private final Utilities utilities;
private final CompositeSubscription subscriptions; | // Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/LatLong.java
// @AutoValue public abstract class LatLong {
// public abstract double latitude();
//
// public abstract double longitude();
//
// public abstract float altitude();
//
// public abstract boolean isCheckPoint();
//
// public static LatLong create(double latitude, double longitude) {
// return create(latitude, longitude, 0, false);
// }
//
// public static LatLong create(double latitude, double longitude, float altitude,
// boolean isCheckPoint) {
// return new AutoValue_LatLong(latitude, longitude, altitude, isCheckPoint);
// }
// }
//
// Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/LatLongDetailed.java
// @AutoValue public abstract class LatLongDetailed {
// public abstract Location location();
//
// public abstract boolean isCheckPoint();
//
// public static LatLongDetailed create(Location location) {
// return create(location, false);
// }
//
// public static LatLongDetailed create(Location location, boolean isCheckPoint) {
// return new AutoValue_LatLongDetailed(location, isCheckPoint);
// }
// }
//
// Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/RouteStats.java
// @AutoValue public abstract class RouteStats {
//
// public abstract long time();
//
// public abstract long distance();
//
// public abstract float speedMax();
//
// public abstract float speedMin();
//
// public abstract float speedAverage();
//
// public abstract float speed();
//
// public abstract LatLongDetailed currentLocation();
//
// public abstract List<LatLong> latLongs();
//
// public abstract List<LatLongDetailed> latLongsDetailed();
//
// public static RouteStats create(long time, long distance, float speedMax, float speedMin,
// float speedAverage, float speed, LatLongDetailed currentLocation, List<LatLong> latLongs,
// List<LatLongDetailed> latLongsDetailed) {
// return new AutoValue_RouteStats(time, distance, speedMax, speedMin, speedAverage, speed,
// currentLocation, latLongs, latLongsDetailed);
// }
//
// public LatLong getLastLatLong() {
// return latLongs() != null && !latLongs().isEmpty() ? latLongs().get(latLongs().size() - 1)
// : LatLong.create(0, 0);
// }
//
// public LatLongDetailed getLastLatLongDetailed() {
// int size = latLongsDetailed().size();
// return latLongsDetailed() != null && !latLongsDetailed().isEmpty() ? latLongsDetailed().get(
// size - 1) : LatLongDetailed.create(new Location("Location-" + size));
// }
//
// @Override public String toString() {
// return " time="
// + time()
// + " distance="
// + distance()
// + " speed="
// + speed()
// + " latLong="
// + "("
// + currentLocation().location().getLatitude()
// + ", "
// + currentLocation().location().getLongitude()
// + ") checkpoint="
// + currentLocation().isCheckPoint()
// + " waypoints="
// + (latLongs() != null && !latLongs().isEmpty() ? latLongs().size()
// : latLongsDetailed() != null && !latLongsDetailed().isEmpty() ? latLongsDetailed().size()
// : 0);
// }
// }
// Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/RxGpsPresenter.java
import rx.observables.ConnectableObservable;
import rx.subscriptions.CompositeSubscription;
import android.location.Location;
import android.util.Log;
import com.miguelbcr.io.rx_gps_service.lib.entities.LatLong;
import com.miguelbcr.io.rx_gps_service.lib.entities.LatLongDetailed;
import com.miguelbcr.io.rx_gps_service.lib.entities.RouteStats;
import java.util.ArrayList;
import java.util.List;
import rx.Observable;
import rx.Subscription;
import rx.functions.Action1;
import rx.functions.Func1;
/*
* Copyright 2016 miguelbcr
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.miguelbcr.io.rx_gps_service.lib;
class RxGpsPresenter {
private static final String TAG = "RxGpsService";
private final MeaningfulUpdatesLocation meaningfulUpdatesLocation;
private final RecordTime recordTime;
private final GetTripDistance getTripDistance;
private final GetTripSpeed getTripSpeed;
private final GetTripSpeedAverage getTripSpeedAverage;
private final GetTripSpeedMax getTripSpeedMax;
private final GetTripSpeedMin getTripSpeedMin;
private final Utilities utilities;
private final CompositeSubscription subscriptions; | private ConnectableObservable<RouteStats> connectableObservable; |
miguelbcr/RxGpsService | lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/RxGpsPresenter.java | // Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/LatLong.java
// @AutoValue public abstract class LatLong {
// public abstract double latitude();
//
// public abstract double longitude();
//
// public abstract float altitude();
//
// public abstract boolean isCheckPoint();
//
// public static LatLong create(double latitude, double longitude) {
// return create(latitude, longitude, 0, false);
// }
//
// public static LatLong create(double latitude, double longitude, float altitude,
// boolean isCheckPoint) {
// return new AutoValue_LatLong(latitude, longitude, altitude, isCheckPoint);
// }
// }
//
// Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/LatLongDetailed.java
// @AutoValue public abstract class LatLongDetailed {
// public abstract Location location();
//
// public abstract boolean isCheckPoint();
//
// public static LatLongDetailed create(Location location) {
// return create(location, false);
// }
//
// public static LatLongDetailed create(Location location, boolean isCheckPoint) {
// return new AutoValue_LatLongDetailed(location, isCheckPoint);
// }
// }
//
// Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/RouteStats.java
// @AutoValue public abstract class RouteStats {
//
// public abstract long time();
//
// public abstract long distance();
//
// public abstract float speedMax();
//
// public abstract float speedMin();
//
// public abstract float speedAverage();
//
// public abstract float speed();
//
// public abstract LatLongDetailed currentLocation();
//
// public abstract List<LatLong> latLongs();
//
// public abstract List<LatLongDetailed> latLongsDetailed();
//
// public static RouteStats create(long time, long distance, float speedMax, float speedMin,
// float speedAverage, float speed, LatLongDetailed currentLocation, List<LatLong> latLongs,
// List<LatLongDetailed> latLongsDetailed) {
// return new AutoValue_RouteStats(time, distance, speedMax, speedMin, speedAverage, speed,
// currentLocation, latLongs, latLongsDetailed);
// }
//
// public LatLong getLastLatLong() {
// return latLongs() != null && !latLongs().isEmpty() ? latLongs().get(latLongs().size() - 1)
// : LatLong.create(0, 0);
// }
//
// public LatLongDetailed getLastLatLongDetailed() {
// int size = latLongsDetailed().size();
// return latLongsDetailed() != null && !latLongsDetailed().isEmpty() ? latLongsDetailed().get(
// size - 1) : LatLongDetailed.create(new Location("Location-" + size));
// }
//
// @Override public String toString() {
// return " time="
// + time()
// + " distance="
// + distance()
// + " speed="
// + speed()
// + " latLong="
// + "("
// + currentLocation().location().getLatitude()
// + ", "
// + currentLocation().location().getLongitude()
// + ") checkpoint="
// + currentLocation().isCheckPoint()
// + " waypoints="
// + (latLongs() != null && !latLongs().isEmpty() ? latLongs().size()
// : latLongsDetailed() != null && !latLongsDetailed().isEmpty() ? latLongsDetailed().size()
// : 0);
// }
// }
| import rx.observables.ConnectableObservable;
import rx.subscriptions.CompositeSubscription;
import android.location.Location;
import android.util.Log;
import com.miguelbcr.io.rx_gps_service.lib.entities.LatLong;
import com.miguelbcr.io.rx_gps_service.lib.entities.LatLongDetailed;
import com.miguelbcr.io.rx_gps_service.lib.entities.RouteStats;
import java.util.ArrayList;
import java.util.List;
import rx.Observable;
import rx.Subscription;
import rx.functions.Action1;
import rx.functions.Func1; | /*
* Copyright 2016 miguelbcr
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.miguelbcr.io.rx_gps_service.lib;
class RxGpsPresenter {
private static final String TAG = "RxGpsService";
private final MeaningfulUpdatesLocation meaningfulUpdatesLocation;
private final RecordTime recordTime;
private final GetTripDistance getTripDistance;
private final GetTripSpeed getTripSpeed;
private final GetTripSpeedAverage getTripSpeedAverage;
private final GetTripSpeedMax getTripSpeedMax;
private final GetTripSpeedMin getTripSpeedMin;
private final Utilities utilities;
private final CompositeSubscription subscriptions;
private ConnectableObservable<RouteStats> connectableObservable; | // Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/LatLong.java
// @AutoValue public abstract class LatLong {
// public abstract double latitude();
//
// public abstract double longitude();
//
// public abstract float altitude();
//
// public abstract boolean isCheckPoint();
//
// public static LatLong create(double latitude, double longitude) {
// return create(latitude, longitude, 0, false);
// }
//
// public static LatLong create(double latitude, double longitude, float altitude,
// boolean isCheckPoint) {
// return new AutoValue_LatLong(latitude, longitude, altitude, isCheckPoint);
// }
// }
//
// Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/LatLongDetailed.java
// @AutoValue public abstract class LatLongDetailed {
// public abstract Location location();
//
// public abstract boolean isCheckPoint();
//
// public static LatLongDetailed create(Location location) {
// return create(location, false);
// }
//
// public static LatLongDetailed create(Location location, boolean isCheckPoint) {
// return new AutoValue_LatLongDetailed(location, isCheckPoint);
// }
// }
//
// Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/RouteStats.java
// @AutoValue public abstract class RouteStats {
//
// public abstract long time();
//
// public abstract long distance();
//
// public abstract float speedMax();
//
// public abstract float speedMin();
//
// public abstract float speedAverage();
//
// public abstract float speed();
//
// public abstract LatLongDetailed currentLocation();
//
// public abstract List<LatLong> latLongs();
//
// public abstract List<LatLongDetailed> latLongsDetailed();
//
// public static RouteStats create(long time, long distance, float speedMax, float speedMin,
// float speedAverage, float speed, LatLongDetailed currentLocation, List<LatLong> latLongs,
// List<LatLongDetailed> latLongsDetailed) {
// return new AutoValue_RouteStats(time, distance, speedMax, speedMin, speedAverage, speed,
// currentLocation, latLongs, latLongsDetailed);
// }
//
// public LatLong getLastLatLong() {
// return latLongs() != null && !latLongs().isEmpty() ? latLongs().get(latLongs().size() - 1)
// : LatLong.create(0, 0);
// }
//
// public LatLongDetailed getLastLatLongDetailed() {
// int size = latLongsDetailed().size();
// return latLongsDetailed() != null && !latLongsDetailed().isEmpty() ? latLongsDetailed().get(
// size - 1) : LatLongDetailed.create(new Location("Location-" + size));
// }
//
// @Override public String toString() {
// return " time="
// + time()
// + " distance="
// + distance()
// + " speed="
// + speed()
// + " latLong="
// + "("
// + currentLocation().location().getLatitude()
// + ", "
// + currentLocation().location().getLongitude()
// + ") checkpoint="
// + currentLocation().isCheckPoint()
// + " waypoints="
// + (latLongs() != null && !latLongs().isEmpty() ? latLongs().size()
// : latLongsDetailed() != null && !latLongsDetailed().isEmpty() ? latLongsDetailed().size()
// : 0);
// }
// }
// Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/RxGpsPresenter.java
import rx.observables.ConnectableObservable;
import rx.subscriptions.CompositeSubscription;
import android.location.Location;
import android.util.Log;
import com.miguelbcr.io.rx_gps_service.lib.entities.LatLong;
import com.miguelbcr.io.rx_gps_service.lib.entities.LatLongDetailed;
import com.miguelbcr.io.rx_gps_service.lib.entities.RouteStats;
import java.util.ArrayList;
import java.util.List;
import rx.Observable;
import rx.Subscription;
import rx.functions.Action1;
import rx.functions.Func1;
/*
* Copyright 2016 miguelbcr
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.miguelbcr.io.rx_gps_service.lib;
class RxGpsPresenter {
private static final String TAG = "RxGpsService";
private final MeaningfulUpdatesLocation meaningfulUpdatesLocation;
private final RecordTime recordTime;
private final GetTripDistance getTripDistance;
private final GetTripSpeed getTripSpeed;
private final GetTripSpeedAverage getTripSpeedAverage;
private final GetTripSpeedMax getTripSpeedMax;
private final GetTripSpeedMin getTripSpeedMin;
private final Utilities utilities;
private final CompositeSubscription subscriptions;
private ConnectableObservable<RouteStats> connectableObservable; | private List<LatLong> latLongs; |
miguelbcr/RxGpsService | lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/RxGpsPresenter.java | // Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/LatLong.java
// @AutoValue public abstract class LatLong {
// public abstract double latitude();
//
// public abstract double longitude();
//
// public abstract float altitude();
//
// public abstract boolean isCheckPoint();
//
// public static LatLong create(double latitude, double longitude) {
// return create(latitude, longitude, 0, false);
// }
//
// public static LatLong create(double latitude, double longitude, float altitude,
// boolean isCheckPoint) {
// return new AutoValue_LatLong(latitude, longitude, altitude, isCheckPoint);
// }
// }
//
// Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/LatLongDetailed.java
// @AutoValue public abstract class LatLongDetailed {
// public abstract Location location();
//
// public abstract boolean isCheckPoint();
//
// public static LatLongDetailed create(Location location) {
// return create(location, false);
// }
//
// public static LatLongDetailed create(Location location, boolean isCheckPoint) {
// return new AutoValue_LatLongDetailed(location, isCheckPoint);
// }
// }
//
// Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/RouteStats.java
// @AutoValue public abstract class RouteStats {
//
// public abstract long time();
//
// public abstract long distance();
//
// public abstract float speedMax();
//
// public abstract float speedMin();
//
// public abstract float speedAverage();
//
// public abstract float speed();
//
// public abstract LatLongDetailed currentLocation();
//
// public abstract List<LatLong> latLongs();
//
// public abstract List<LatLongDetailed> latLongsDetailed();
//
// public static RouteStats create(long time, long distance, float speedMax, float speedMin,
// float speedAverage, float speed, LatLongDetailed currentLocation, List<LatLong> latLongs,
// List<LatLongDetailed> latLongsDetailed) {
// return new AutoValue_RouteStats(time, distance, speedMax, speedMin, speedAverage, speed,
// currentLocation, latLongs, latLongsDetailed);
// }
//
// public LatLong getLastLatLong() {
// return latLongs() != null && !latLongs().isEmpty() ? latLongs().get(latLongs().size() - 1)
// : LatLong.create(0, 0);
// }
//
// public LatLongDetailed getLastLatLongDetailed() {
// int size = latLongsDetailed().size();
// return latLongsDetailed() != null && !latLongsDetailed().isEmpty() ? latLongsDetailed().get(
// size - 1) : LatLongDetailed.create(new Location("Location-" + size));
// }
//
// @Override public String toString() {
// return " time="
// + time()
// + " distance="
// + distance()
// + " speed="
// + speed()
// + " latLong="
// + "("
// + currentLocation().location().getLatitude()
// + ", "
// + currentLocation().location().getLongitude()
// + ") checkpoint="
// + currentLocation().isCheckPoint()
// + " waypoints="
// + (latLongs() != null && !latLongs().isEmpty() ? latLongs().size()
// : latLongsDetailed() != null && !latLongsDetailed().isEmpty() ? latLongsDetailed().size()
// : 0);
// }
// }
| import rx.observables.ConnectableObservable;
import rx.subscriptions.CompositeSubscription;
import android.location.Location;
import android.util.Log;
import com.miguelbcr.io.rx_gps_service.lib.entities.LatLong;
import com.miguelbcr.io.rx_gps_service.lib.entities.LatLongDetailed;
import com.miguelbcr.io.rx_gps_service.lib.entities.RouteStats;
import java.util.ArrayList;
import java.util.List;
import rx.Observable;
import rx.Subscription;
import rx.functions.Action1;
import rx.functions.Func1; | /*
* Copyright 2016 miguelbcr
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.miguelbcr.io.rx_gps_service.lib;
class RxGpsPresenter {
private static final String TAG = "RxGpsService";
private final MeaningfulUpdatesLocation meaningfulUpdatesLocation;
private final RecordTime recordTime;
private final GetTripDistance getTripDistance;
private final GetTripSpeed getTripSpeed;
private final GetTripSpeedAverage getTripSpeedAverage;
private final GetTripSpeedMax getTripSpeedMax;
private final GetTripSpeedMin getTripSpeedMin;
private final Utilities utilities;
private final CompositeSubscription subscriptions;
private ConnectableObservable<RouteStats> connectableObservable;
private List<LatLong> latLongs; | // Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/LatLong.java
// @AutoValue public abstract class LatLong {
// public abstract double latitude();
//
// public abstract double longitude();
//
// public abstract float altitude();
//
// public abstract boolean isCheckPoint();
//
// public static LatLong create(double latitude, double longitude) {
// return create(latitude, longitude, 0, false);
// }
//
// public static LatLong create(double latitude, double longitude, float altitude,
// boolean isCheckPoint) {
// return new AutoValue_LatLong(latitude, longitude, altitude, isCheckPoint);
// }
// }
//
// Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/LatLongDetailed.java
// @AutoValue public abstract class LatLongDetailed {
// public abstract Location location();
//
// public abstract boolean isCheckPoint();
//
// public static LatLongDetailed create(Location location) {
// return create(location, false);
// }
//
// public static LatLongDetailed create(Location location, boolean isCheckPoint) {
// return new AutoValue_LatLongDetailed(location, isCheckPoint);
// }
// }
//
// Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/RouteStats.java
// @AutoValue public abstract class RouteStats {
//
// public abstract long time();
//
// public abstract long distance();
//
// public abstract float speedMax();
//
// public abstract float speedMin();
//
// public abstract float speedAverage();
//
// public abstract float speed();
//
// public abstract LatLongDetailed currentLocation();
//
// public abstract List<LatLong> latLongs();
//
// public abstract List<LatLongDetailed> latLongsDetailed();
//
// public static RouteStats create(long time, long distance, float speedMax, float speedMin,
// float speedAverage, float speed, LatLongDetailed currentLocation, List<LatLong> latLongs,
// List<LatLongDetailed> latLongsDetailed) {
// return new AutoValue_RouteStats(time, distance, speedMax, speedMin, speedAverage, speed,
// currentLocation, latLongs, latLongsDetailed);
// }
//
// public LatLong getLastLatLong() {
// return latLongs() != null && !latLongs().isEmpty() ? latLongs().get(latLongs().size() - 1)
// : LatLong.create(0, 0);
// }
//
// public LatLongDetailed getLastLatLongDetailed() {
// int size = latLongsDetailed().size();
// return latLongsDetailed() != null && !latLongsDetailed().isEmpty() ? latLongsDetailed().get(
// size - 1) : LatLongDetailed.create(new Location("Location-" + size));
// }
//
// @Override public String toString() {
// return " time="
// + time()
// + " distance="
// + distance()
// + " speed="
// + speed()
// + " latLong="
// + "("
// + currentLocation().location().getLatitude()
// + ", "
// + currentLocation().location().getLongitude()
// + ") checkpoint="
// + currentLocation().isCheckPoint()
// + " waypoints="
// + (latLongs() != null && !latLongs().isEmpty() ? latLongs().size()
// : latLongsDetailed() != null && !latLongsDetailed().isEmpty() ? latLongsDetailed().size()
// : 0);
// }
// }
// Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/RxGpsPresenter.java
import rx.observables.ConnectableObservable;
import rx.subscriptions.CompositeSubscription;
import android.location.Location;
import android.util.Log;
import com.miguelbcr.io.rx_gps_service.lib.entities.LatLong;
import com.miguelbcr.io.rx_gps_service.lib.entities.LatLongDetailed;
import com.miguelbcr.io.rx_gps_service.lib.entities.RouteStats;
import java.util.ArrayList;
import java.util.List;
import rx.Observable;
import rx.Subscription;
import rx.functions.Action1;
import rx.functions.Func1;
/*
* Copyright 2016 miguelbcr
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.miguelbcr.io.rx_gps_service.lib;
class RxGpsPresenter {
private static final String TAG = "RxGpsService";
private final MeaningfulUpdatesLocation meaningfulUpdatesLocation;
private final RecordTime recordTime;
private final GetTripDistance getTripDistance;
private final GetTripSpeed getTripSpeed;
private final GetTripSpeedAverage getTripSpeedAverage;
private final GetTripSpeedMax getTripSpeedMax;
private final GetTripSpeedMin getTripSpeedMin;
private final Utilities utilities;
private final CompositeSubscription subscriptions;
private ConnectableObservable<RouteStats> connectableObservable;
private List<LatLong> latLongs; | private List<LatLongDetailed> latLongsDetailed; |
miguelbcr/RxGpsService | lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/Utilities.java | // Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/LatLong.java
// @AutoValue public abstract class LatLong {
// public abstract double latitude();
//
// public abstract double longitude();
//
// public abstract float altitude();
//
// public abstract boolean isCheckPoint();
//
// public static LatLong create(double latitude, double longitude) {
// return create(latitude, longitude, 0, false);
// }
//
// public static LatLong create(double latitude, double longitude, float altitude,
// boolean isCheckPoint) {
// return new AutoValue_LatLong(latitude, longitude, altitude, isCheckPoint);
// }
// }
| import android.location.Location;
import com.miguelbcr.io.rx_gps_service.lib.entities.LatLong;
import java.util.Locale;
import rx.Observable; | /*
* Copyright 2016 miguelbcr
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.miguelbcr.io.rx_gps_service.lib;
class Utilities {
Utilities() {
}
| // Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/LatLong.java
// @AutoValue public abstract class LatLong {
// public abstract double latitude();
//
// public abstract double longitude();
//
// public abstract float altitude();
//
// public abstract boolean isCheckPoint();
//
// public static LatLong create(double latitude, double longitude) {
// return create(latitude, longitude, 0, false);
// }
//
// public static LatLong create(double latitude, double longitude, float altitude,
// boolean isCheckPoint) {
// return new AutoValue_LatLong(latitude, longitude, altitude, isCheckPoint);
// }
// }
// Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/Utilities.java
import android.location.Location;
import com.miguelbcr.io.rx_gps_service.lib.entities.LatLong;
import java.util.Locale;
import rx.Observable;
/*
* Copyright 2016 miguelbcr
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.miguelbcr.io.rx_gps_service.lib;
class Utilities {
Utilities() {
}
| Observable<Float> getDistanceFromTo(LatLong fromLatLong, LatLong toLatLong) { |
miguelbcr/RxGpsService | lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/MeaningfulUpdatesLocation.java | // Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/LatLong.java
// @AutoValue public abstract class LatLong {
// public abstract double latitude();
//
// public abstract double longitude();
//
// public abstract float altitude();
//
// public abstract boolean isCheckPoint();
//
// public static LatLong create(double latitude, double longitude) {
// return create(latitude, longitude, 0, false);
// }
//
// public static LatLong create(double latitude, double longitude, float altitude,
// boolean isCheckPoint) {
// return new AutoValue_LatLong(latitude, longitude, altitude, isCheckPoint);
// }
// }
| import android.location.Location;
import com.miguelbcr.io.rx_gps_service.lib.entities.LatLong;
import rx.Observable;
import rx.functions.Func1; | /*
* Copyright 2016 miguelbcr
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.miguelbcr.io.rx_gps_service.lib;
class MeaningfulUpdatesLocation {
private Location previousLocation;
private Location currentLocation;
private final Utilities utilities;
private long lastMeaningfulDistance;
MeaningfulUpdatesLocation() {
utilities = new Utilities();
}
void setPreviousLocation(Location previousLocation) {
this.previousLocation = previousLocation;
}
void setCurrentLocation(Location currentLocation) {
this.currentLocation = currentLocation;
}
Location getCurrentLocation() {
return currentLocation;
}
long getLastMeaningfulDistance() {
return lastMeaningfulDistance;
}
Observable<Boolean> builtObservable(final int minDistanceTraveled) {
if (previousLocation == null) previousLocation = new Location("previousLocation");
| // Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/LatLong.java
// @AutoValue public abstract class LatLong {
// public abstract double latitude();
//
// public abstract double longitude();
//
// public abstract float altitude();
//
// public abstract boolean isCheckPoint();
//
// public static LatLong create(double latitude, double longitude) {
// return create(latitude, longitude, 0, false);
// }
//
// public static LatLong create(double latitude, double longitude, float altitude,
// boolean isCheckPoint) {
// return new AutoValue_LatLong(latitude, longitude, altitude, isCheckPoint);
// }
// }
// Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/MeaningfulUpdatesLocation.java
import android.location.Location;
import com.miguelbcr.io.rx_gps_service.lib.entities.LatLong;
import rx.Observable;
import rx.functions.Func1;
/*
* Copyright 2016 miguelbcr
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.miguelbcr.io.rx_gps_service.lib;
class MeaningfulUpdatesLocation {
private Location previousLocation;
private Location currentLocation;
private final Utilities utilities;
private long lastMeaningfulDistance;
MeaningfulUpdatesLocation() {
utilities = new Utilities();
}
void setPreviousLocation(Location previousLocation) {
this.previousLocation = previousLocation;
}
void setCurrentLocation(Location currentLocation) {
this.currentLocation = currentLocation;
}
Location getCurrentLocation() {
return currentLocation;
}
long getLastMeaningfulDistance() {
return lastMeaningfulDistance;
}
Observable<Boolean> builtObservable(final int minDistanceTraveled) {
if (previousLocation == null) previousLocation = new Location("previousLocation");
| LatLong previousLatLng = |
miguelbcr/RxGpsService | app/src/main/java/com/miguelbcr/rx_gpsservice/app/Place.java | // Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/LatLong.java
// @AutoValue public abstract class LatLong {
// public abstract double latitude();
//
// public abstract double longitude();
//
// public abstract float altitude();
//
// public abstract boolean isCheckPoint();
//
// public static LatLong create(double latitude, double longitude) {
// return create(latitude, longitude, 0, false);
// }
//
// public static LatLong create(double latitude, double longitude, float altitude,
// boolean isCheckPoint) {
// return new AutoValue_LatLong(latitude, longitude, altitude, isCheckPoint);
// }
// }
| import com.miguelbcr.io.rx_gps_service.lib.entities.LatLong; | package com.miguelbcr.rx_gpsservice.app;
public class Place {
private int id;
private String name; | // Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/LatLong.java
// @AutoValue public abstract class LatLong {
// public abstract double latitude();
//
// public abstract double longitude();
//
// public abstract float altitude();
//
// public abstract boolean isCheckPoint();
//
// public static LatLong create(double latitude, double longitude) {
// return create(latitude, longitude, 0, false);
// }
//
// public static LatLong create(double latitude, double longitude, float altitude,
// boolean isCheckPoint) {
// return new AutoValue_LatLong(latitude, longitude, altitude, isCheckPoint);
// }
// }
// Path: app/src/main/java/com/miguelbcr/rx_gpsservice/app/Place.java
import com.miguelbcr.io.rx_gps_service.lib.entities.LatLong;
package com.miguelbcr.rx_gpsservice.app;
public class Place {
private int id;
private String name; | private LatLong latLong; |
miguelbcr/RxGpsService | app/src/main/java/com/miguelbcr/rx_gpsservice/app/MainActivity.java | // Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/RxLocation.java
// public class RxLocation {
// private static final String TAG = "RxLocation";
// public static final int REQUEST_CHECK_LOCATION_SETTINGS = 65456;
// private final GrantPermissions grantPermissions;
// private GpsConfig gpsConfig;
//
// RxLocation(GpsConfig gpsConfig) {
// this.gpsConfig = gpsConfig;
// this.grantPermissions = new GrantPermissions(gpsConfig.getActivity());
// }
//
// Observable<Location> getCurrentLocationForService() {
// final ReactiveLocationProvider locationProvider =
// new ReactiveLocationProvider(gpsConfig.getActivity());
//
// final LocationRequest locationRequest = LocationRequest.create()
// .setPriority(gpsConfig.getPriority())
// .setInterval(gpsConfig.getInterval())
// .setFastestInterval(gpsConfig.getFastestInterval());
//
// final LocationSettingsRequest locationSettingsRequest =
// new LocationSettingsRequest.Builder().addLocationRequest(locationRequest)
// .setAlwaysShow(
// true) //Reference: http://stackoverflow.com/questions/29824408/google-play-services-locationservices-api-new-option-never
// .build();
//
// return Observable.zip(
// grantPermissions.with(permissions()).builtObservable().subscribeOn(Schedulers.io()),
// locationProvider.checkLocationSettings(locationSettingsRequest)
// .subscribeOn(Schedulers.io()),
// new Func2<Void, LocationSettingsResult, LocationSettingsResult>() {
// @Override public LocationSettingsResult call(Void aVoid,
// LocationSettingsResult locationSettingsResult) {
// return locationSettingsResult;
// }
// }).doOnNext(new Action1<LocationSettingsResult>() {
// @Override public void call(LocationSettingsResult locationSettingsResult) {
// Status status = locationSettingsResult.getStatus();
// if (status.getStatusCode() == LocationSettingsStatusCodes.RESOLUTION_REQUIRED) {
// try {
// status.startResolutionForResult(gpsConfig.getActivity(),
// REQUEST_CHECK_LOCATION_SETTINGS);
// } catch (IntentSender.SendIntentException exception) {
// Log.e(TAG, "Error opening settings activity.", exception);
// }
// }
// }
// }).flatMap(new Func1<LocationSettingsResult, Observable<Location>>() {
// @Override public Observable<Location> call(LocationSettingsResult locationSettingsResult) {
// return locationProvider.getUpdatedLocation(locationRequest);
// }
// });
// }
//
// private String[] permissions() {
// return new String[] {
// Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION
// };
// }
// }
| import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import com.miguelbcr.io.rx_gps_service.lib.RxLocation;
import com.miguelbcr.rx_gpsservice.R; | package com.miguelbcr.rx_gpsservice.app;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
| // Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/RxLocation.java
// public class RxLocation {
// private static final String TAG = "RxLocation";
// public static final int REQUEST_CHECK_LOCATION_SETTINGS = 65456;
// private final GrantPermissions grantPermissions;
// private GpsConfig gpsConfig;
//
// RxLocation(GpsConfig gpsConfig) {
// this.gpsConfig = gpsConfig;
// this.grantPermissions = new GrantPermissions(gpsConfig.getActivity());
// }
//
// Observable<Location> getCurrentLocationForService() {
// final ReactiveLocationProvider locationProvider =
// new ReactiveLocationProvider(gpsConfig.getActivity());
//
// final LocationRequest locationRequest = LocationRequest.create()
// .setPriority(gpsConfig.getPriority())
// .setInterval(gpsConfig.getInterval())
// .setFastestInterval(gpsConfig.getFastestInterval());
//
// final LocationSettingsRequest locationSettingsRequest =
// new LocationSettingsRequest.Builder().addLocationRequest(locationRequest)
// .setAlwaysShow(
// true) //Reference: http://stackoverflow.com/questions/29824408/google-play-services-locationservices-api-new-option-never
// .build();
//
// return Observable.zip(
// grantPermissions.with(permissions()).builtObservable().subscribeOn(Schedulers.io()),
// locationProvider.checkLocationSettings(locationSettingsRequest)
// .subscribeOn(Schedulers.io()),
// new Func2<Void, LocationSettingsResult, LocationSettingsResult>() {
// @Override public LocationSettingsResult call(Void aVoid,
// LocationSettingsResult locationSettingsResult) {
// return locationSettingsResult;
// }
// }).doOnNext(new Action1<LocationSettingsResult>() {
// @Override public void call(LocationSettingsResult locationSettingsResult) {
// Status status = locationSettingsResult.getStatus();
// if (status.getStatusCode() == LocationSettingsStatusCodes.RESOLUTION_REQUIRED) {
// try {
// status.startResolutionForResult(gpsConfig.getActivity(),
// REQUEST_CHECK_LOCATION_SETTINGS);
// } catch (IntentSender.SendIntentException exception) {
// Log.e(TAG, "Error opening settings activity.", exception);
// }
// }
// }
// }).flatMap(new Func1<LocationSettingsResult, Observable<Location>>() {
// @Override public Observable<Location> call(LocationSettingsResult locationSettingsResult) {
// return locationProvider.getUpdatedLocation(locationRequest);
// }
// });
// }
//
// private String[] permissions() {
// return new String[] {
// Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION
// };
// }
// }
// Path: app/src/main/java/com/miguelbcr/rx_gpsservice/app/MainActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import com.miguelbcr.io.rx_gps_service.lib.RxLocation;
import com.miguelbcr.rx_gpsservice.R;
package com.miguelbcr.rx_gpsservice.app;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
| if (requestCode == RxLocation.REQUEST_CHECK_LOCATION_SETTINGS) { |
miguelbcr/RxGpsService | lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/GetTripDistance.java | // Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/LatLong.java
// @AutoValue public abstract class LatLong {
// public abstract double latitude();
//
// public abstract double longitude();
//
// public abstract float altitude();
//
// public abstract boolean isCheckPoint();
//
// public static LatLong create(double latitude, double longitude) {
// return create(latitude, longitude, 0, false);
// }
//
// public static LatLong create(double latitude, double longitude, float altitude,
// boolean isCheckPoint) {
// return new AutoValue_LatLong(latitude, longitude, altitude, isCheckPoint);
// }
// }
| import com.miguelbcr.io.rx_gps_service.lib.entities.LatLong;
import rx.Observable;
import rx.functions.Func1; | /*
* Copyright 2016 miguelbcr
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.miguelbcr.io.rx_gps_service.lib;
class GetTripDistance {
private long distanceAccumulated; | // Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/LatLong.java
// @AutoValue public abstract class LatLong {
// public abstract double latitude();
//
// public abstract double longitude();
//
// public abstract float altitude();
//
// public abstract boolean isCheckPoint();
//
// public static LatLong create(double latitude, double longitude) {
// return create(latitude, longitude, 0, false);
// }
//
// public static LatLong create(double latitude, double longitude, float altitude,
// boolean isCheckPoint) {
// return new AutoValue_LatLong(latitude, longitude, altitude, isCheckPoint);
// }
// }
// Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/GetTripDistance.java
import com.miguelbcr.io.rx_gps_service.lib.entities.LatLong;
import rx.Observable;
import rx.functions.Func1;
/*
* Copyright 2016 miguelbcr
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.miguelbcr.io.rx_gps_service.lib;
class GetTripDistance {
private long distanceAccumulated; | private LatLong previousLatLong; |
miguelbcr/RxGpsService | app/src/main/java/com/miguelbcr/rx_gpsservice/app/PlaceMapFragment.java | // Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/LatLong.java
// @AutoValue public abstract class LatLong {
// public abstract double latitude();
//
// public abstract double longitude();
//
// public abstract float altitude();
//
// public abstract boolean isCheckPoint();
//
// public static LatLong create(double latitude, double longitude) {
// return create(latitude, longitude, 0, false);
// }
//
// public static LatLong create(double latitude, double longitude, float altitude,
// boolean isCheckPoint) {
// return new AutoValue_LatLong(latitude, longitude, altitude, isCheckPoint);
// }
// }
//
// Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/LatLongDetailed.java
// @AutoValue public abstract class LatLongDetailed {
// public abstract Location location();
//
// public abstract boolean isCheckPoint();
//
// public static LatLongDetailed create(Location location) {
// return create(location, false);
// }
//
// public static LatLongDetailed create(Location location, boolean isCheckPoint) {
// return new AutoValue_LatLongDetailed(location, isCheckPoint);
// }
// }
//
// Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/RouteStats.java
// @AutoValue public abstract class RouteStats {
//
// public abstract long time();
//
// public abstract long distance();
//
// public abstract float speedMax();
//
// public abstract float speedMin();
//
// public abstract float speedAverage();
//
// public abstract float speed();
//
// public abstract LatLongDetailed currentLocation();
//
// public abstract List<LatLong> latLongs();
//
// public abstract List<LatLongDetailed> latLongsDetailed();
//
// public static RouteStats create(long time, long distance, float speedMax, float speedMin,
// float speedAverage, float speed, LatLongDetailed currentLocation, List<LatLong> latLongs,
// List<LatLongDetailed> latLongsDetailed) {
// return new AutoValue_RouteStats(time, distance, speedMax, speedMin, speedAverage, speed,
// currentLocation, latLongs, latLongsDetailed);
// }
//
// public LatLong getLastLatLong() {
// return latLongs() != null && !latLongs().isEmpty() ? latLongs().get(latLongs().size() - 1)
// : LatLong.create(0, 0);
// }
//
// public LatLongDetailed getLastLatLongDetailed() {
// int size = latLongsDetailed().size();
// return latLongsDetailed() != null && !latLongsDetailed().isEmpty() ? latLongsDetailed().get(
// size - 1) : LatLongDetailed.create(new Location("Location-" + size));
// }
//
// @Override public String toString() {
// return " time="
// + time()
// + " distance="
// + distance()
// + " speed="
// + speed()
// + " latLong="
// + "("
// + currentLocation().location().getLatitude()
// + ", "
// + currentLocation().location().getLongitude()
// + ") checkpoint="
// + currentLocation().isCheckPoint()
// + " waypoints="
// + (latLongs() != null && !latLongs().isEmpty() ? latLongs().size()
// : latLongsDetailed() != null && !latLongsDetailed().isEmpty() ? latLongsDetailed().size()
// : 0);
// }
// }
| import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.miguelbcr.io.rx_gps_service.lib.entities.LatLong;
import com.miguelbcr.io.rx_gps_service.lib.entities.LatLongDetailed;
import com.miguelbcr.io.rx_gps_service.lib.entities.RouteStats;
import com.miguelbcr.rx_gpsservice.R;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map; | return;
}
if (clearMap) {
googleMap.clear();
}
this.places = places;
this.listener = listener;
for (Place place : places) {
showPlace(place, false, idPlaceToGo, listener);
if (place.getId() == idPlaceToGo) {
showMarkInfoWindow(idPlaceToGo);
}
}
}
public void disableNavigationControls() {
if (googleMap == null) return;
googleMap.getUiSettings().setMapToolbarEnabled(false);
}
public void navigateTo(double latitude, double longitude) {
Uri gmmIntentUri = Uri.parse("google.navigation:q=" + latitude + ", " + longitude);
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent);
}
| // Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/LatLong.java
// @AutoValue public abstract class LatLong {
// public abstract double latitude();
//
// public abstract double longitude();
//
// public abstract float altitude();
//
// public abstract boolean isCheckPoint();
//
// public static LatLong create(double latitude, double longitude) {
// return create(latitude, longitude, 0, false);
// }
//
// public static LatLong create(double latitude, double longitude, float altitude,
// boolean isCheckPoint) {
// return new AutoValue_LatLong(latitude, longitude, altitude, isCheckPoint);
// }
// }
//
// Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/LatLongDetailed.java
// @AutoValue public abstract class LatLongDetailed {
// public abstract Location location();
//
// public abstract boolean isCheckPoint();
//
// public static LatLongDetailed create(Location location) {
// return create(location, false);
// }
//
// public static LatLongDetailed create(Location location, boolean isCheckPoint) {
// return new AutoValue_LatLongDetailed(location, isCheckPoint);
// }
// }
//
// Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/RouteStats.java
// @AutoValue public abstract class RouteStats {
//
// public abstract long time();
//
// public abstract long distance();
//
// public abstract float speedMax();
//
// public abstract float speedMin();
//
// public abstract float speedAverage();
//
// public abstract float speed();
//
// public abstract LatLongDetailed currentLocation();
//
// public abstract List<LatLong> latLongs();
//
// public abstract List<LatLongDetailed> latLongsDetailed();
//
// public static RouteStats create(long time, long distance, float speedMax, float speedMin,
// float speedAverage, float speed, LatLongDetailed currentLocation, List<LatLong> latLongs,
// List<LatLongDetailed> latLongsDetailed) {
// return new AutoValue_RouteStats(time, distance, speedMax, speedMin, speedAverage, speed,
// currentLocation, latLongs, latLongsDetailed);
// }
//
// public LatLong getLastLatLong() {
// return latLongs() != null && !latLongs().isEmpty() ? latLongs().get(latLongs().size() - 1)
// : LatLong.create(0, 0);
// }
//
// public LatLongDetailed getLastLatLongDetailed() {
// int size = latLongsDetailed().size();
// return latLongsDetailed() != null && !latLongsDetailed().isEmpty() ? latLongsDetailed().get(
// size - 1) : LatLongDetailed.create(new Location("Location-" + size));
// }
//
// @Override public String toString() {
// return " time="
// + time()
// + " distance="
// + distance()
// + " speed="
// + speed()
// + " latLong="
// + "("
// + currentLocation().location().getLatitude()
// + ", "
// + currentLocation().location().getLongitude()
// + ") checkpoint="
// + currentLocation().isCheckPoint()
// + " waypoints="
// + (latLongs() != null && !latLongs().isEmpty() ? latLongs().size()
// : latLongsDetailed() != null && !latLongsDetailed().isEmpty() ? latLongsDetailed().size()
// : 0);
// }
// }
// Path: app/src/main/java/com/miguelbcr/rx_gpsservice/app/PlaceMapFragment.java
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.miguelbcr.io.rx_gps_service.lib.entities.LatLong;
import com.miguelbcr.io.rx_gps_service.lib.entities.LatLongDetailed;
import com.miguelbcr.io.rx_gps_service.lib.entities.RouteStats;
import com.miguelbcr.rx_gpsservice.R;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
return;
}
if (clearMap) {
googleMap.clear();
}
this.places = places;
this.listener = listener;
for (Place place : places) {
showPlace(place, false, idPlaceToGo, listener);
if (place.getId() == idPlaceToGo) {
showMarkInfoWindow(idPlaceToGo);
}
}
}
public void disableNavigationControls() {
if (googleMap == null) return;
googleMap.getUiSettings().setMapToolbarEnabled(false);
}
public void navigateTo(double latitude, double longitude) {
Uri gmmIntentUri = Uri.parse("google.navigation:q=" + latitude + ", " + longitude);
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent);
}
| public void drawPathUser(List<LatLong> waypoints) { |
miguelbcr/RxGpsService | app/src/main/java/com/miguelbcr/rx_gpsservice/app/PlaceMapFragment.java | // Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/LatLong.java
// @AutoValue public abstract class LatLong {
// public abstract double latitude();
//
// public abstract double longitude();
//
// public abstract float altitude();
//
// public abstract boolean isCheckPoint();
//
// public static LatLong create(double latitude, double longitude) {
// return create(latitude, longitude, 0, false);
// }
//
// public static LatLong create(double latitude, double longitude, float altitude,
// boolean isCheckPoint) {
// return new AutoValue_LatLong(latitude, longitude, altitude, isCheckPoint);
// }
// }
//
// Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/LatLongDetailed.java
// @AutoValue public abstract class LatLongDetailed {
// public abstract Location location();
//
// public abstract boolean isCheckPoint();
//
// public static LatLongDetailed create(Location location) {
// return create(location, false);
// }
//
// public static LatLongDetailed create(Location location, boolean isCheckPoint) {
// return new AutoValue_LatLongDetailed(location, isCheckPoint);
// }
// }
//
// Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/RouteStats.java
// @AutoValue public abstract class RouteStats {
//
// public abstract long time();
//
// public abstract long distance();
//
// public abstract float speedMax();
//
// public abstract float speedMin();
//
// public abstract float speedAverage();
//
// public abstract float speed();
//
// public abstract LatLongDetailed currentLocation();
//
// public abstract List<LatLong> latLongs();
//
// public abstract List<LatLongDetailed> latLongsDetailed();
//
// public static RouteStats create(long time, long distance, float speedMax, float speedMin,
// float speedAverage, float speed, LatLongDetailed currentLocation, List<LatLong> latLongs,
// List<LatLongDetailed> latLongsDetailed) {
// return new AutoValue_RouteStats(time, distance, speedMax, speedMin, speedAverage, speed,
// currentLocation, latLongs, latLongsDetailed);
// }
//
// public LatLong getLastLatLong() {
// return latLongs() != null && !latLongs().isEmpty() ? latLongs().get(latLongs().size() - 1)
// : LatLong.create(0, 0);
// }
//
// public LatLongDetailed getLastLatLongDetailed() {
// int size = latLongsDetailed().size();
// return latLongsDetailed() != null && !latLongsDetailed().isEmpty() ? latLongsDetailed().get(
// size - 1) : LatLongDetailed.create(new Location("Location-" + size));
// }
//
// @Override public String toString() {
// return " time="
// + time()
// + " distance="
// + distance()
// + " speed="
// + speed()
// + " latLong="
// + "("
// + currentLocation().location().getLatitude()
// + ", "
// + currentLocation().location().getLongitude()
// + ") checkpoint="
// + currentLocation().isCheckPoint()
// + " waypoints="
// + (latLongs() != null && !latLongs().isEmpty() ? latLongs().size()
// : latLongsDetailed() != null && !latLongsDetailed().isEmpty() ? latLongsDetailed().size()
// : 0);
// }
// }
| import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.miguelbcr.io.rx_gps_service.lib.entities.LatLong;
import com.miguelbcr.io.rx_gps_service.lib.entities.LatLongDetailed;
import com.miguelbcr.io.rx_gps_service.lib.entities.RouteStats;
import com.miguelbcr.rx_gpsservice.R;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map; | }
public void disableNavigationControls() {
if (googleMap == null) return;
googleMap.getUiSettings().setMapToolbarEnabled(false);
}
public void navigateTo(double latitude, double longitude) {
Uri gmmIntentUri = Uri.parse("google.navigation:q=" + latitude + ", " + longitude);
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent);
}
public void drawPathUser(List<LatLong> waypoints) {
if (googleMap == null) return;
if (polylineUser != null && polylineUser.getPoints().size() == waypoints.size()) return;
polylineUser = removePath(polylineUser);
polylineUserLastPath = removePath(polylineUserLastPath);
polylineUser = drawPath(waypoints, ContextCompat.getColor(getContext(), R.color.blue), 2f, polylineUser);
if (waypoints != null && !waypoints.isEmpty()) {
showCheckpoints(waypoints);
LatLong lastLatLong = waypoints.get(waypoints.size() - 1);
LatLng latLng = new LatLng(lastLatLong.latitude(), lastLatLong.longitude());
drawSegmentPathUser(latLng);
}
}
| // Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/LatLong.java
// @AutoValue public abstract class LatLong {
// public abstract double latitude();
//
// public abstract double longitude();
//
// public abstract float altitude();
//
// public abstract boolean isCheckPoint();
//
// public static LatLong create(double latitude, double longitude) {
// return create(latitude, longitude, 0, false);
// }
//
// public static LatLong create(double latitude, double longitude, float altitude,
// boolean isCheckPoint) {
// return new AutoValue_LatLong(latitude, longitude, altitude, isCheckPoint);
// }
// }
//
// Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/LatLongDetailed.java
// @AutoValue public abstract class LatLongDetailed {
// public abstract Location location();
//
// public abstract boolean isCheckPoint();
//
// public static LatLongDetailed create(Location location) {
// return create(location, false);
// }
//
// public static LatLongDetailed create(Location location, boolean isCheckPoint) {
// return new AutoValue_LatLongDetailed(location, isCheckPoint);
// }
// }
//
// Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/RouteStats.java
// @AutoValue public abstract class RouteStats {
//
// public abstract long time();
//
// public abstract long distance();
//
// public abstract float speedMax();
//
// public abstract float speedMin();
//
// public abstract float speedAverage();
//
// public abstract float speed();
//
// public abstract LatLongDetailed currentLocation();
//
// public abstract List<LatLong> latLongs();
//
// public abstract List<LatLongDetailed> latLongsDetailed();
//
// public static RouteStats create(long time, long distance, float speedMax, float speedMin,
// float speedAverage, float speed, LatLongDetailed currentLocation, List<LatLong> latLongs,
// List<LatLongDetailed> latLongsDetailed) {
// return new AutoValue_RouteStats(time, distance, speedMax, speedMin, speedAverage, speed,
// currentLocation, latLongs, latLongsDetailed);
// }
//
// public LatLong getLastLatLong() {
// return latLongs() != null && !latLongs().isEmpty() ? latLongs().get(latLongs().size() - 1)
// : LatLong.create(0, 0);
// }
//
// public LatLongDetailed getLastLatLongDetailed() {
// int size = latLongsDetailed().size();
// return latLongsDetailed() != null && !latLongsDetailed().isEmpty() ? latLongsDetailed().get(
// size - 1) : LatLongDetailed.create(new Location("Location-" + size));
// }
//
// @Override public String toString() {
// return " time="
// + time()
// + " distance="
// + distance()
// + " speed="
// + speed()
// + " latLong="
// + "("
// + currentLocation().location().getLatitude()
// + ", "
// + currentLocation().location().getLongitude()
// + ") checkpoint="
// + currentLocation().isCheckPoint()
// + " waypoints="
// + (latLongs() != null && !latLongs().isEmpty() ? latLongs().size()
// : latLongsDetailed() != null && !latLongsDetailed().isEmpty() ? latLongsDetailed().size()
// : 0);
// }
// }
// Path: app/src/main/java/com/miguelbcr/rx_gpsservice/app/PlaceMapFragment.java
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.miguelbcr.io.rx_gps_service.lib.entities.LatLong;
import com.miguelbcr.io.rx_gps_service.lib.entities.LatLongDetailed;
import com.miguelbcr.io.rx_gps_service.lib.entities.RouteStats;
import com.miguelbcr.rx_gpsservice.R;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
}
public void disableNavigationControls() {
if (googleMap == null) return;
googleMap.getUiSettings().setMapToolbarEnabled(false);
}
public void navigateTo(double latitude, double longitude) {
Uri gmmIntentUri = Uri.parse("google.navigation:q=" + latitude + ", " + longitude);
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent);
}
public void drawPathUser(List<LatLong> waypoints) {
if (googleMap == null) return;
if (polylineUser != null && polylineUser.getPoints().size() == waypoints.size()) return;
polylineUser = removePath(polylineUser);
polylineUserLastPath = removePath(polylineUserLastPath);
polylineUser = drawPath(waypoints, ContextCompat.getColor(getContext(), R.color.blue), 2f, polylineUser);
if (waypoints != null && !waypoints.isEmpty()) {
showCheckpoints(waypoints);
LatLong lastLatLong = waypoints.get(waypoints.size() - 1);
LatLng latLng = new LatLng(lastLatLong.latitude(), lastLatLong.longitude());
drawSegmentPathUser(latLng);
}
}
| public void updateUserLocation(RouteStats routeStats, boolean goToUserLocation) { |
miguelbcr/RxGpsService | app/src/main/java/com/miguelbcr/rx_gpsservice/app/PlaceMapFragment.java | // Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/LatLong.java
// @AutoValue public abstract class LatLong {
// public abstract double latitude();
//
// public abstract double longitude();
//
// public abstract float altitude();
//
// public abstract boolean isCheckPoint();
//
// public static LatLong create(double latitude, double longitude) {
// return create(latitude, longitude, 0, false);
// }
//
// public static LatLong create(double latitude, double longitude, float altitude,
// boolean isCheckPoint) {
// return new AutoValue_LatLong(latitude, longitude, altitude, isCheckPoint);
// }
// }
//
// Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/LatLongDetailed.java
// @AutoValue public abstract class LatLongDetailed {
// public abstract Location location();
//
// public abstract boolean isCheckPoint();
//
// public static LatLongDetailed create(Location location) {
// return create(location, false);
// }
//
// public static LatLongDetailed create(Location location, boolean isCheckPoint) {
// return new AutoValue_LatLongDetailed(location, isCheckPoint);
// }
// }
//
// Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/RouteStats.java
// @AutoValue public abstract class RouteStats {
//
// public abstract long time();
//
// public abstract long distance();
//
// public abstract float speedMax();
//
// public abstract float speedMin();
//
// public abstract float speedAverage();
//
// public abstract float speed();
//
// public abstract LatLongDetailed currentLocation();
//
// public abstract List<LatLong> latLongs();
//
// public abstract List<LatLongDetailed> latLongsDetailed();
//
// public static RouteStats create(long time, long distance, float speedMax, float speedMin,
// float speedAverage, float speed, LatLongDetailed currentLocation, List<LatLong> latLongs,
// List<LatLongDetailed> latLongsDetailed) {
// return new AutoValue_RouteStats(time, distance, speedMax, speedMin, speedAverage, speed,
// currentLocation, latLongs, latLongsDetailed);
// }
//
// public LatLong getLastLatLong() {
// return latLongs() != null && !latLongs().isEmpty() ? latLongs().get(latLongs().size() - 1)
// : LatLong.create(0, 0);
// }
//
// public LatLongDetailed getLastLatLongDetailed() {
// int size = latLongsDetailed().size();
// return latLongsDetailed() != null && !latLongsDetailed().isEmpty() ? latLongsDetailed().get(
// size - 1) : LatLongDetailed.create(new Location("Location-" + size));
// }
//
// @Override public String toString() {
// return " time="
// + time()
// + " distance="
// + distance()
// + " speed="
// + speed()
// + " latLong="
// + "("
// + currentLocation().location().getLatitude()
// + ", "
// + currentLocation().location().getLongitude()
// + ") checkpoint="
// + currentLocation().isCheckPoint()
// + " waypoints="
// + (latLongs() != null && !latLongs().isEmpty() ? latLongs().size()
// : latLongsDetailed() != null && !latLongsDetailed().isEmpty() ? latLongsDetailed().size()
// : 0);
// }
// }
| import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.miguelbcr.io.rx_gps_service.lib.entities.LatLong;
import com.miguelbcr.io.rx_gps_service.lib.entities.LatLongDetailed;
import com.miguelbcr.io.rx_gps_service.lib.entities.RouteStats;
import com.miguelbcr.rx_gpsservice.R;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map; | showCheckpoints(waypoints);
LatLong lastLatLong = waypoints.get(waypoints.size() - 1);
LatLng latLng = new LatLng(lastLatLong.latitude(), lastLatLong.longitude());
drawSegmentPathUser(latLng);
}
}
public void updateUserLocation(RouteStats routeStats, boolean goToUserLocation) {
LatLong currentLocation = routeStats.getLastLatLong();
if (googleMap == null || isEmptyLatLong(currentLocation)) return;
LatLng latLng = new LatLng(currentLocation.latitude(), currentLocation.longitude());
drawSegmentPathUser(latLng);
if (markerUser != null) markerUser.remove();
markerUser = addMark(latLng, "", getIconUser(), false);
markersMap.put(markerUser, routeStats);
markerUser.showInfoWindow();
if (goToUserLocation) googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
public void resetUserPosition(LatLong latLong) {
if (googleMap == null || isEmptyLatLong(latLong)) return;
LatLng latLng = new LatLng(latLong.latitude(), latLong.longitude());
if (markerUser != null) markerUser.remove();
markerUser = addMark(latLng, "", getIconUser(), false);
markerUser.hideInfoWindow();
markersMap.put(markerUser, RouteStats.create(0, 0, 0f, 0f, 0f, 0f, | // Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/LatLong.java
// @AutoValue public abstract class LatLong {
// public abstract double latitude();
//
// public abstract double longitude();
//
// public abstract float altitude();
//
// public abstract boolean isCheckPoint();
//
// public static LatLong create(double latitude, double longitude) {
// return create(latitude, longitude, 0, false);
// }
//
// public static LatLong create(double latitude, double longitude, float altitude,
// boolean isCheckPoint) {
// return new AutoValue_LatLong(latitude, longitude, altitude, isCheckPoint);
// }
// }
//
// Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/LatLongDetailed.java
// @AutoValue public abstract class LatLongDetailed {
// public abstract Location location();
//
// public abstract boolean isCheckPoint();
//
// public static LatLongDetailed create(Location location) {
// return create(location, false);
// }
//
// public static LatLongDetailed create(Location location, boolean isCheckPoint) {
// return new AutoValue_LatLongDetailed(location, isCheckPoint);
// }
// }
//
// Path: lib/src/main/java/com/miguelbcr/io/rx_gps_service/lib/entities/RouteStats.java
// @AutoValue public abstract class RouteStats {
//
// public abstract long time();
//
// public abstract long distance();
//
// public abstract float speedMax();
//
// public abstract float speedMin();
//
// public abstract float speedAverage();
//
// public abstract float speed();
//
// public abstract LatLongDetailed currentLocation();
//
// public abstract List<LatLong> latLongs();
//
// public abstract List<LatLongDetailed> latLongsDetailed();
//
// public static RouteStats create(long time, long distance, float speedMax, float speedMin,
// float speedAverage, float speed, LatLongDetailed currentLocation, List<LatLong> latLongs,
// List<LatLongDetailed> latLongsDetailed) {
// return new AutoValue_RouteStats(time, distance, speedMax, speedMin, speedAverage, speed,
// currentLocation, latLongs, latLongsDetailed);
// }
//
// public LatLong getLastLatLong() {
// return latLongs() != null && !latLongs().isEmpty() ? latLongs().get(latLongs().size() - 1)
// : LatLong.create(0, 0);
// }
//
// public LatLongDetailed getLastLatLongDetailed() {
// int size = latLongsDetailed().size();
// return latLongsDetailed() != null && !latLongsDetailed().isEmpty() ? latLongsDetailed().get(
// size - 1) : LatLongDetailed.create(new Location("Location-" + size));
// }
//
// @Override public String toString() {
// return " time="
// + time()
// + " distance="
// + distance()
// + " speed="
// + speed()
// + " latLong="
// + "("
// + currentLocation().location().getLatitude()
// + ", "
// + currentLocation().location().getLongitude()
// + ") checkpoint="
// + currentLocation().isCheckPoint()
// + " waypoints="
// + (latLongs() != null && !latLongs().isEmpty() ? latLongs().size()
// : latLongsDetailed() != null && !latLongsDetailed().isEmpty() ? latLongsDetailed().size()
// : 0);
// }
// }
// Path: app/src/main/java/com/miguelbcr/rx_gpsservice/app/PlaceMapFragment.java
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.miguelbcr.io.rx_gps_service.lib.entities.LatLong;
import com.miguelbcr.io.rx_gps_service.lib.entities.LatLongDetailed;
import com.miguelbcr.io.rx_gps_service.lib.entities.RouteStats;
import com.miguelbcr.rx_gpsservice.R;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
showCheckpoints(waypoints);
LatLong lastLatLong = waypoints.get(waypoints.size() - 1);
LatLng latLng = new LatLng(lastLatLong.latitude(), lastLatLong.longitude());
drawSegmentPathUser(latLng);
}
}
public void updateUserLocation(RouteStats routeStats, boolean goToUserLocation) {
LatLong currentLocation = routeStats.getLastLatLong();
if (googleMap == null || isEmptyLatLong(currentLocation)) return;
LatLng latLng = new LatLng(currentLocation.latitude(), currentLocation.longitude());
drawSegmentPathUser(latLng);
if (markerUser != null) markerUser.remove();
markerUser = addMark(latLng, "", getIconUser(), false);
markersMap.put(markerUser, routeStats);
markerUser.showInfoWindow();
if (goToUserLocation) googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
public void resetUserPosition(LatLong latLong) {
if (googleMap == null || isEmptyLatLong(latLong)) return;
LatLng latLng = new LatLng(latLong.latitude(), latLong.longitude());
if (markerUser != null) markerUser.remove();
markerUser = addMark(latLng, "", getIconUser(), false);
markerUser.hideInfoWindow();
markersMap.put(markerUser, RouteStats.create(0, 0, 0f, 0f, 0f, 0f, | LatLongDetailed.create(new Location("empty")), |
gill3s/opentipbot | opentipbot-webapp/src/main/java/opentipbot/web/security/UserInterceptor.java | // Path: opentipbot-persistence/src/main/java/opentipbot/persistence/model/OpenTipBotUser.java
// @Entity
// @Table(name = "opentipbot_user")
// /**
// * @author Gilles Cadignan
// */
// public class OpenTipBotUser extends BaseEntity<Long>{
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String email;
// private String displayName;
// private String userName;
// private String twitterIdentifier;
// private String coinAddress;
// private String profileImageUrl;
// private String profileUrl;
//
// @Basic(fetch = FetchType.LAZY)
// private byte[] coinAddressQRCode;
//
// @Transient
// private double balance;
//
// @Transient
// private double pendingBalance;
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getCoinAddress() {
// return coinAddress;
// }
//
// public void setCoinAddress(String coinAddress) {
// this.coinAddress = coinAddress;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public String getTwitterIdentifier() {
// return twitterIdentifier;
// }
//
// public void setTwitterIdentifier(String twitterIdentifier) {
// this.twitterIdentifier = twitterIdentifier;
// }
//
// public double getBalance() {
// return balance;
// }
//
// public void setBalance(double balance) {
// this.balance = balance;
// }
//
// public String getProfileImageUrl() {
// return profileImageUrl;
// }
//
// public void setProfileImageUrl(String profileImageUrl) {
// this.profileImageUrl = profileImageUrl;
// }
//
// public byte[] getCoinAddressQRCode() {
// return coinAddressQRCode;
// }
//
// public void setCoinAddressQRCode(byte[] coinAddressQRCode) {
// this.coinAddressQRCode = coinAddressQRCode;
// }
//
// public String getProfileUrl() {
// return profileUrl;
// }
//
// public void setProfileUrl(String profileUrl) {
// this.profileUrl = profileUrl;
// }
//
// public double getPendingBalance() {
// return pendingBalance;
// }
//
// public void setPendingBalance(double pendingBalance) {
// this.pendingBalance = pendingBalance;
// }
// }
//
// Path: opentipbot-persistence/src/main/java/opentipbot/persistence/repository/OpenTipBotUserRepository.java
// public interface OpenTipBotUserRepository extends JpaRepository<OpenTipBotUser, Long> {
// OpenTipBotUser findByTwitterIdentifier(String twitterIdentifier);
// OpenTipBotUser findByUserName(String UserName);
// }
| import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.twitter.api.Twitter;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.view.RedirectView;
import opentipbot.persistence.model.OpenTipBotUser;
import opentipbot.persistence.repository.OpenTipBotUserRepository;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; | /*
* Copyright 2014 the original author or authors.
*
* 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 opentipbot.web.security;
/**
* Before a request is handled:
* 1. sets the current User in the {@link SecurityContext} from a cookie, if present and the user is still connected to Facebook.
* 2. requires that the user sign-in if he or she hasn't already.
* @author Gilles Cadignan
*/
public final class UserInterceptor extends HandlerInterceptorAdapter {
private final UsersConnectionRepository connectionRepository;
| // Path: opentipbot-persistence/src/main/java/opentipbot/persistence/model/OpenTipBotUser.java
// @Entity
// @Table(name = "opentipbot_user")
// /**
// * @author Gilles Cadignan
// */
// public class OpenTipBotUser extends BaseEntity<Long>{
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String email;
// private String displayName;
// private String userName;
// private String twitterIdentifier;
// private String coinAddress;
// private String profileImageUrl;
// private String profileUrl;
//
// @Basic(fetch = FetchType.LAZY)
// private byte[] coinAddressQRCode;
//
// @Transient
// private double balance;
//
// @Transient
// private double pendingBalance;
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getCoinAddress() {
// return coinAddress;
// }
//
// public void setCoinAddress(String coinAddress) {
// this.coinAddress = coinAddress;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public String getTwitterIdentifier() {
// return twitterIdentifier;
// }
//
// public void setTwitterIdentifier(String twitterIdentifier) {
// this.twitterIdentifier = twitterIdentifier;
// }
//
// public double getBalance() {
// return balance;
// }
//
// public void setBalance(double balance) {
// this.balance = balance;
// }
//
// public String getProfileImageUrl() {
// return profileImageUrl;
// }
//
// public void setProfileImageUrl(String profileImageUrl) {
// this.profileImageUrl = profileImageUrl;
// }
//
// public byte[] getCoinAddressQRCode() {
// return coinAddressQRCode;
// }
//
// public void setCoinAddressQRCode(byte[] coinAddressQRCode) {
// this.coinAddressQRCode = coinAddressQRCode;
// }
//
// public String getProfileUrl() {
// return profileUrl;
// }
//
// public void setProfileUrl(String profileUrl) {
// this.profileUrl = profileUrl;
// }
//
// public double getPendingBalance() {
// return pendingBalance;
// }
//
// public void setPendingBalance(double pendingBalance) {
// this.pendingBalance = pendingBalance;
// }
// }
//
// Path: opentipbot-persistence/src/main/java/opentipbot/persistence/repository/OpenTipBotUserRepository.java
// public interface OpenTipBotUserRepository extends JpaRepository<OpenTipBotUser, Long> {
// OpenTipBotUser findByTwitterIdentifier(String twitterIdentifier);
// OpenTipBotUser findByUserName(String UserName);
// }
// Path: opentipbot-webapp/src/main/java/opentipbot/web/security/UserInterceptor.java
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.twitter.api.Twitter;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.view.RedirectView;
import opentipbot.persistence.model.OpenTipBotUser;
import opentipbot.persistence.repository.OpenTipBotUserRepository;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*
* Copyright 2014 the original author or authors.
*
* 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 opentipbot.web.security;
/**
* Before a request is handled:
* 1. sets the current User in the {@link SecurityContext} from a cookie, if present and the user is still connected to Facebook.
* 2. requires that the user sign-in if he or she hasn't already.
* @author Gilles Cadignan
*/
public final class UserInterceptor extends HandlerInterceptorAdapter {
private final UsersConnectionRepository connectionRepository;
| private final OpenTipBotUserRepository opentipbotUserRepository; |
gill3s/opentipbot | opentipbot-webapp/src/main/java/opentipbot/web/security/UserInterceptor.java | // Path: opentipbot-persistence/src/main/java/opentipbot/persistence/model/OpenTipBotUser.java
// @Entity
// @Table(name = "opentipbot_user")
// /**
// * @author Gilles Cadignan
// */
// public class OpenTipBotUser extends BaseEntity<Long>{
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String email;
// private String displayName;
// private String userName;
// private String twitterIdentifier;
// private String coinAddress;
// private String profileImageUrl;
// private String profileUrl;
//
// @Basic(fetch = FetchType.LAZY)
// private byte[] coinAddressQRCode;
//
// @Transient
// private double balance;
//
// @Transient
// private double pendingBalance;
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getCoinAddress() {
// return coinAddress;
// }
//
// public void setCoinAddress(String coinAddress) {
// this.coinAddress = coinAddress;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public String getTwitterIdentifier() {
// return twitterIdentifier;
// }
//
// public void setTwitterIdentifier(String twitterIdentifier) {
// this.twitterIdentifier = twitterIdentifier;
// }
//
// public double getBalance() {
// return balance;
// }
//
// public void setBalance(double balance) {
// this.balance = balance;
// }
//
// public String getProfileImageUrl() {
// return profileImageUrl;
// }
//
// public void setProfileImageUrl(String profileImageUrl) {
// this.profileImageUrl = profileImageUrl;
// }
//
// public byte[] getCoinAddressQRCode() {
// return coinAddressQRCode;
// }
//
// public void setCoinAddressQRCode(byte[] coinAddressQRCode) {
// this.coinAddressQRCode = coinAddressQRCode;
// }
//
// public String getProfileUrl() {
// return profileUrl;
// }
//
// public void setProfileUrl(String profileUrl) {
// this.profileUrl = profileUrl;
// }
//
// public double getPendingBalance() {
// return pendingBalance;
// }
//
// public void setPendingBalance(double pendingBalance) {
// this.pendingBalance = pendingBalance;
// }
// }
//
// Path: opentipbot-persistence/src/main/java/opentipbot/persistence/repository/OpenTipBotUserRepository.java
// public interface OpenTipBotUserRepository extends JpaRepository<OpenTipBotUser, Long> {
// OpenTipBotUser findByTwitterIdentifier(String twitterIdentifier);
// OpenTipBotUser findByUserName(String UserName);
// }
| import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.twitter.api.Twitter;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.view.RedirectView;
import opentipbot.persistence.model.OpenTipBotUser;
import opentipbot.persistence.repository.OpenTipBotUserRepository;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; | /*
* Copyright 2014 the original author or authors.
*
* 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 opentipbot.web.security;
/**
* Before a request is handled:
* 1. sets the current User in the {@link SecurityContext} from a cookie, if present and the user is still connected to Facebook.
* 2. requires that the user sign-in if he or she hasn't already.
* @author Gilles Cadignan
*/
public final class UserInterceptor extends HandlerInterceptorAdapter {
private final UsersConnectionRepository connectionRepository;
private final OpenTipBotUserRepository opentipbotUserRepository;
private final UserCookieGenerator userCookieGenerator = new UserCookieGenerator();
public UserInterceptor(UsersConnectionRepository connectionRepository, OpenTipBotUserRepository opentipbotUserRepository) {
this.connectionRepository = connectionRepository;
this.opentipbotUserRepository = opentipbotUserRepository;
}
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
rememberUser(request, response);
handleSignOut(request, response);
if (SecurityContext.userSignedIn() || requestForNotProtected(request)) {
return true;
} else {
return requireSignIn(request, response);
}
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
SecurityContext.remove();
}
// internal helpers
private void rememberUser(HttpServletRequest request, HttpServletResponse response) {
String userId = userCookieGenerator.readCookieValue(request);
if (userId == null) {
return;
}
if (!userNotFound(userId)) {
userCookieGenerator.removeCookie(response);
return;
} | // Path: opentipbot-persistence/src/main/java/opentipbot/persistence/model/OpenTipBotUser.java
// @Entity
// @Table(name = "opentipbot_user")
// /**
// * @author Gilles Cadignan
// */
// public class OpenTipBotUser extends BaseEntity<Long>{
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String email;
// private String displayName;
// private String userName;
// private String twitterIdentifier;
// private String coinAddress;
// private String profileImageUrl;
// private String profileUrl;
//
// @Basic(fetch = FetchType.LAZY)
// private byte[] coinAddressQRCode;
//
// @Transient
// private double balance;
//
// @Transient
// private double pendingBalance;
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getCoinAddress() {
// return coinAddress;
// }
//
// public void setCoinAddress(String coinAddress) {
// this.coinAddress = coinAddress;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public String getTwitterIdentifier() {
// return twitterIdentifier;
// }
//
// public void setTwitterIdentifier(String twitterIdentifier) {
// this.twitterIdentifier = twitterIdentifier;
// }
//
// public double getBalance() {
// return balance;
// }
//
// public void setBalance(double balance) {
// this.balance = balance;
// }
//
// public String getProfileImageUrl() {
// return profileImageUrl;
// }
//
// public void setProfileImageUrl(String profileImageUrl) {
// this.profileImageUrl = profileImageUrl;
// }
//
// public byte[] getCoinAddressQRCode() {
// return coinAddressQRCode;
// }
//
// public void setCoinAddressQRCode(byte[] coinAddressQRCode) {
// this.coinAddressQRCode = coinAddressQRCode;
// }
//
// public String getProfileUrl() {
// return profileUrl;
// }
//
// public void setProfileUrl(String profileUrl) {
// this.profileUrl = profileUrl;
// }
//
// public double getPendingBalance() {
// return pendingBalance;
// }
//
// public void setPendingBalance(double pendingBalance) {
// this.pendingBalance = pendingBalance;
// }
// }
//
// Path: opentipbot-persistence/src/main/java/opentipbot/persistence/repository/OpenTipBotUserRepository.java
// public interface OpenTipBotUserRepository extends JpaRepository<OpenTipBotUser, Long> {
// OpenTipBotUser findByTwitterIdentifier(String twitterIdentifier);
// OpenTipBotUser findByUserName(String UserName);
// }
// Path: opentipbot-webapp/src/main/java/opentipbot/web/security/UserInterceptor.java
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.twitter.api.Twitter;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.view.RedirectView;
import opentipbot.persistence.model.OpenTipBotUser;
import opentipbot.persistence.repository.OpenTipBotUserRepository;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*
* Copyright 2014 the original author or authors.
*
* 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 opentipbot.web.security;
/**
* Before a request is handled:
* 1. sets the current User in the {@link SecurityContext} from a cookie, if present and the user is still connected to Facebook.
* 2. requires that the user sign-in if he or she hasn't already.
* @author Gilles Cadignan
*/
public final class UserInterceptor extends HandlerInterceptorAdapter {
private final UsersConnectionRepository connectionRepository;
private final OpenTipBotUserRepository opentipbotUserRepository;
private final UserCookieGenerator userCookieGenerator = new UserCookieGenerator();
public UserInterceptor(UsersConnectionRepository connectionRepository, OpenTipBotUserRepository opentipbotUserRepository) {
this.connectionRepository = connectionRepository;
this.opentipbotUserRepository = opentipbotUserRepository;
}
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
rememberUser(request, response);
handleSignOut(request, response);
if (SecurityContext.userSignedIn() || requestForNotProtected(request)) {
return true;
} else {
return requireSignIn(request, response);
}
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
SecurityContext.remove();
}
// internal helpers
private void rememberUser(HttpServletRequest request, HttpServletResponse response) {
String userId = userCookieGenerator.readCookieValue(request);
if (userId == null) {
return;
}
if (!userNotFound(userId)) {
userCookieGenerator.removeCookie(response);
return;
} | OpenTipBotUser opentipbotUser= opentipbotUserRepository.findOne(Long.parseLong(userId)); |
gill3s/opentipbot | opentipbot-service/src/test/java/opentipbot/service/config/ServiceTestConfig.java | // Path: opentipbot-persistence/src/main/java/opentipbot/persistence/config/PersistenceContext.java
// @Configuration
// @EnableJpaRepositories(basePackages = {
// "opentipbot.persistence.repository"
// })
// @PropertySource("classpath:application.properties")
// public class PersistenceContext {
// //Entity package
// private static final String[] PROPERTY_PACKAGES_TO_SCAN = {
// "opentipbot.persistence.model"
// };
//
// //Database properties
// protected static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
// protected static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
// protected static final String PROPERTY_NAME_DATABASE_URL = "db.url";
// protected static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
//
// //Hibernate Properties
// private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
// private static final String PROPERTY_NAME_HIBERNATE_FORMAT_SQL = "hibernate.format_sql";
// private static final String PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO = "hibernate.hbm2ddl.auto";
// private static final String PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY = "hibernate.ejb.naming_strategy";
// private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
// private static final String PROPERTY_NAME_HIBERNATE_CONNECTION_AUTOCOMMIT = "hibernate.connection.autocommit";
//
// @Autowired
// private Environment env;
//
// @Bean
// public DataSource dataSource() {
// BoneCPDataSource dataSource = new BoneCPDataSource();
//
// dataSource.setDriverClass(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
// dataSource.setJdbcUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
// dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
// dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
//
// return dataSource;
// }
//
// @Bean
// public JpaTransactionManager transactionManager() {
// JpaTransactionManager transactionManager = new JpaTransactionManager();
//
// transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
//
// return transactionManager;
// }
//
// @Bean
// public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
// LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
//
// entityManagerFactoryBean.setDataSource(dataSource());
// entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
// entityManagerFactoryBean.setPackagesToScan(PROPERTY_PACKAGES_TO_SCAN);
//
// Properties jpaProperties = new Properties();
// jpaProperties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
// jpaProperties.put(PROPERTY_NAME_HIBERNATE_FORMAT_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_FORMAT_SQL));
// jpaProperties.put(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO));
// jpaProperties.put(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY));
// jpaProperties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
// jpaProperties.put("hibernate.jdbc.use_streams_for_binary", "false");
//
// entityManagerFactoryBean.setJpaProperties(jpaProperties);
//
// return entityManagerFactoryBean;
// }
//
// @Bean
// public BitcoinJSONRPCClient bitcoinJSONRPCClient() throws MalformedURLException {
// return new BitcoinJSONRPCClient(env.getRequiredProperty("coind.url"));
// }
//
// }
| import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import opentipbot.persistence.config.PersistenceContext; | package opentipbot.service.config;
/**
* @author Gilles Cadignan
*/
@Configuration
@ComponentScan(basePackages = {
"opentipbot.service"
}) | // Path: opentipbot-persistence/src/main/java/opentipbot/persistence/config/PersistenceContext.java
// @Configuration
// @EnableJpaRepositories(basePackages = {
// "opentipbot.persistence.repository"
// })
// @PropertySource("classpath:application.properties")
// public class PersistenceContext {
// //Entity package
// private static final String[] PROPERTY_PACKAGES_TO_SCAN = {
// "opentipbot.persistence.model"
// };
//
// //Database properties
// protected static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
// protected static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
// protected static final String PROPERTY_NAME_DATABASE_URL = "db.url";
// protected static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
//
// //Hibernate Properties
// private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
// private static final String PROPERTY_NAME_HIBERNATE_FORMAT_SQL = "hibernate.format_sql";
// private static final String PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO = "hibernate.hbm2ddl.auto";
// private static final String PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY = "hibernate.ejb.naming_strategy";
// private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
// private static final String PROPERTY_NAME_HIBERNATE_CONNECTION_AUTOCOMMIT = "hibernate.connection.autocommit";
//
// @Autowired
// private Environment env;
//
// @Bean
// public DataSource dataSource() {
// BoneCPDataSource dataSource = new BoneCPDataSource();
//
// dataSource.setDriverClass(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
// dataSource.setJdbcUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
// dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
// dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
//
// return dataSource;
// }
//
// @Bean
// public JpaTransactionManager transactionManager() {
// JpaTransactionManager transactionManager = new JpaTransactionManager();
//
// transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
//
// return transactionManager;
// }
//
// @Bean
// public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
// LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
//
// entityManagerFactoryBean.setDataSource(dataSource());
// entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
// entityManagerFactoryBean.setPackagesToScan(PROPERTY_PACKAGES_TO_SCAN);
//
// Properties jpaProperties = new Properties();
// jpaProperties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
// jpaProperties.put(PROPERTY_NAME_HIBERNATE_FORMAT_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_FORMAT_SQL));
// jpaProperties.put(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO));
// jpaProperties.put(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY));
// jpaProperties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
// jpaProperties.put("hibernate.jdbc.use_streams_for_binary", "false");
//
// entityManagerFactoryBean.setJpaProperties(jpaProperties);
//
// return entityManagerFactoryBean;
// }
//
// @Bean
// public BitcoinJSONRPCClient bitcoinJSONRPCClient() throws MalformedURLException {
// return new BitcoinJSONRPCClient(env.getRequiredProperty("coind.url"));
// }
//
// }
// Path: opentipbot-service/src/test/java/opentipbot/service/config/ServiceTestConfig.java
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import opentipbot.persistence.config.PersistenceContext;
package opentipbot.service.config;
/**
* @author Gilles Cadignan
*/
@Configuration
@ComponentScan(basePackages = {
"opentipbot.service"
}) | @Import({PersistenceContext.class, ServiceSocialConfig.class}) |
gill3s/opentipbot | opentipbot-service/src/test/java/opentipbot/service/OpenTipBotServiceTest.java | // Path: opentipbot-service/src/test/java/opentipbot/service/config/ServiceTestConfig.java
// @Configuration
// @ComponentScan(basePackages = {
// "opentipbot.service"
// })
// @Import({PersistenceContext.class, ServiceSocialConfig.class})
// @PropertySource("classpath:application.properties")
// public class ServiceTestConfig {
// }
//
// Path: opentipbot-service/src/main/java/opentipbot/service/exception/OpenTipBotServiceException.java
// public class OpenTipBotServiceException extends Exception {
//
// //the opentipbotCommand object which has generated this exception
// private OpenTipBotCommand command;
//
// /**
// * Build BitcoinServiceException with a message only
// * @param message
// */
// public OpenTipBotServiceException(String message) {
// super(message);
// }
//
// /**
// * Build BitcoinServiceException with message and cause
// * @param message
// * @param cause
// */
// public OpenTipBotServiceException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * Build BitcoinServiceException with message and specific BitcoinServiceException fields
// * @param message
// * @param command
// */
// public OpenTipBotServiceException(String message, OpenTipBotCommand command) {
// super(message);
// this.command = command;
// }
//
// /**
// * Build BitcoinServiceException with message, cause and specific BitcoinServiceException fields
// * @param message
// * @param cause
// * @param command
// */
// public OpenTipBotServiceException(String message, Throwable cause, OpenTipBotCommand command) {
// super(message, cause);
// this.command = command;
// }
//
// // Getters and setters
// //********************
//
//
// public OpenTipBotCommand getCommand() {
// return command;
// }
//
// public void setCommand(OpenTipBotCommand command) {
// this.command = command;
// }
// }
| import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
import opentipbot.service.config.ServiceTestConfig;
import opentipbot.service.exception.OpenTipBotServiceException; | package opentipbot.service;
/**
* @author Gilles Cadignan
*/
@ContextConfiguration(classes = ServiceTestConfig.class)
@Transactional
@TransactionConfiguration(transactionManager="transactionManager", defaultRollback=true)
@RunWith(SpringJUnit4ClassRunner.class)
public class OpenTipBotServiceTest extends AbstractTransactionalJUnit4SpringContextTests
{
@Autowired
protected OpenTipBotService opentipbotService;
@Test
public void handleNewTweetsTest()
{
try {
opentipbotService.handleNewTweets(); | // Path: opentipbot-service/src/test/java/opentipbot/service/config/ServiceTestConfig.java
// @Configuration
// @ComponentScan(basePackages = {
// "opentipbot.service"
// })
// @Import({PersistenceContext.class, ServiceSocialConfig.class})
// @PropertySource("classpath:application.properties")
// public class ServiceTestConfig {
// }
//
// Path: opentipbot-service/src/main/java/opentipbot/service/exception/OpenTipBotServiceException.java
// public class OpenTipBotServiceException extends Exception {
//
// //the opentipbotCommand object which has generated this exception
// private OpenTipBotCommand command;
//
// /**
// * Build BitcoinServiceException with a message only
// * @param message
// */
// public OpenTipBotServiceException(String message) {
// super(message);
// }
//
// /**
// * Build BitcoinServiceException with message and cause
// * @param message
// * @param cause
// */
// public OpenTipBotServiceException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * Build BitcoinServiceException with message and specific BitcoinServiceException fields
// * @param message
// * @param command
// */
// public OpenTipBotServiceException(String message, OpenTipBotCommand command) {
// super(message);
// this.command = command;
// }
//
// /**
// * Build BitcoinServiceException with message, cause and specific BitcoinServiceException fields
// * @param message
// * @param cause
// * @param command
// */
// public OpenTipBotServiceException(String message, Throwable cause, OpenTipBotCommand command) {
// super(message, cause);
// this.command = command;
// }
//
// // Getters and setters
// //********************
//
//
// public OpenTipBotCommand getCommand() {
// return command;
// }
//
// public void setCommand(OpenTipBotCommand command) {
// this.command = command;
// }
// }
// Path: opentipbot-service/src/test/java/opentipbot/service/OpenTipBotServiceTest.java
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
import opentipbot.service.config.ServiceTestConfig;
import opentipbot.service.exception.OpenTipBotServiceException;
package opentipbot.service;
/**
* @author Gilles Cadignan
*/
@ContextConfiguration(classes = ServiceTestConfig.class)
@Transactional
@TransactionConfiguration(transactionManager="transactionManager", defaultRollback=true)
@RunWith(SpringJUnit4ClassRunner.class)
public class OpenTipBotServiceTest extends AbstractTransactionalJUnit4SpringContextTests
{
@Autowired
protected OpenTipBotService opentipbotService;
@Test
public void handleNewTweetsTest()
{
try {
opentipbotService.handleNewTweets(); | } catch (OpenTipBotServiceException e) { |
gill3s/opentipbot | opentipbot-jobs/src/main/java/opentipbot/jobs/JobsRunner.java | // Path: opentipbot-jobs/src/main/java/opentipbot/jobs/configuration/JobsConfig.java
// @Configuration
// @EnableScheduling
// @ComponentScan(basePackages = {
// "opentipbot.service"
// })
// @Import({PersistenceContext.class, ServiceSocialConfig.class})
// @PropertySource("classpath:application.properties")
// public class JobsConfig {
//
// @Autowired
// OpenTipBotService opentipbotService;
//
// @Autowired
// private Environment env;
//
// @Bean
// public OpenTipBotHandleNewTweetsTask opentipbotTask(){
// return new OpenTipBotHandleNewTweetsTask(opentipbotService);
// }
//
// @Bean
// public OpenTipBotProcessCommandsTask opentipbotProcessCommandsTask(){
// return new OpenTipBotProcessCommandsTask(opentipbotService);
// }
//
// }
| import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import opentipbot.jobs.configuration.JobsConfig; | package opentipbot.jobs;
/**
* @author Gilles Cadignan
* Job runner class. Main method to be executed in the packaged jar.
*/
public class JobsRunner {
private static final Logger log = LoggerFactory.getLogger(JobsRunner.class.getSimpleName());
public static void main(String[] args) {
log.info("Starting jobs application context"); | // Path: opentipbot-jobs/src/main/java/opentipbot/jobs/configuration/JobsConfig.java
// @Configuration
// @EnableScheduling
// @ComponentScan(basePackages = {
// "opentipbot.service"
// })
// @Import({PersistenceContext.class, ServiceSocialConfig.class})
// @PropertySource("classpath:application.properties")
// public class JobsConfig {
//
// @Autowired
// OpenTipBotService opentipbotService;
//
// @Autowired
// private Environment env;
//
// @Bean
// public OpenTipBotHandleNewTweetsTask opentipbotTask(){
// return new OpenTipBotHandleNewTweetsTask(opentipbotService);
// }
//
// @Bean
// public OpenTipBotProcessCommandsTask opentipbotProcessCommandsTask(){
// return new OpenTipBotProcessCommandsTask(opentipbotService);
// }
//
// }
// Path: opentipbot-jobs/src/main/java/opentipbot/jobs/JobsRunner.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import opentipbot.jobs.configuration.JobsConfig;
package opentipbot.jobs;
/**
* @author Gilles Cadignan
* Job runner class. Main method to be executed in the packaged jar.
*/
public class JobsRunner {
private static final Logger log = LoggerFactory.getLogger(JobsRunner.class.getSimpleName());
public static void main(String[] args) {
log.info("Starting jobs application context"); | AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(JobsConfig.class); |
gill3s/opentipbot | opentipbot-persistence/src/main/java/opentipbot/persistence/repository/OpenTipBotCommandRepository.java | // Path: opentipbot-persistence/src/main/java/opentipbot/persistence/model/OpenTipBotCommand.java
// @Entity
// @Table(name = "opentipbot_command")
// public class OpenTipBotCommand extends BaseEntity<Long> {
//
// @Id
// @GeneratedValue
// private Long id;
//
// @NotNull
// private OpenTipBotCommandEnum opentipbotCommandEnum;
//
// private String fromUserName;
//
// private String toUserName;
//
// private String toUsernames;
//
// private String txId;
//
// private Double amout;
//
// private String errorMessage;
//
// private String notificationText;
//
// private Long tweetIdentifier;
//
// private String coinAddress;
//
// private String originaleTweet;
//
// @NotNull
// private OpenTipBotCommandStatus opentipbotCommandStatus;
//
// public OpenTipBotCommandEnum getOpenTipBotCommandEnum() {
// return opentipbotCommandEnum;
// }
//
// public OpenTipBotCommandStatus getOpenTipBotCommandStatus() {
// return opentipbotCommandStatus;
// }
//
// public void setOpenTipBotCommandStatus(OpenTipBotCommandStatus opentipbotCommandStatus) {
// this.opentipbotCommandStatus = opentipbotCommandStatus;
// }
//
// public Long getTweetIdentifier() {
// return tweetIdentifier;
// }
//
// public void setTweetIdentifier(Long tweetId) {
// this.tweetIdentifier = tweetId;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// @Override
// public Long getId() {
// return this.id;
// }
//
// public OpenTipBotCommandEnum getCommand() {
// return this.opentipbotCommandEnum;
// }
//
// public void setOpenTipBotCommandEnum(OpenTipBotCommandEnum opentipbotCommandEnum) {
// this.opentipbotCommandEnum = opentipbotCommandEnum;
// }
//
// public String getFromUserName() {
// return fromUserName;
// }
//
// public void setFromUserName(String fromUserName) {
// this.fromUserName = fromUserName;
// }
//
// public String getToUserName() {
// return toUserName;
// }
//
// public void setToUserName(String toUserName) {
// this.toUserName = toUserName;
// }
//
// public Double getAmout() {
// return amout;
// }
//
// public void setAmout(Double amout) {
// this.amout = amout;
// }
//
// public String getCoinAddress() {
// return coinAddress;
// }
//
// public void setCoinAddress(String coinAddress) {
// this.coinAddress = coinAddress;
// }
//
// public String getToUsernames() {
// return toUsernames;
// }
//
// public void setToUsernames(String toUsernames) {
// this.toUsernames = toUsernames;
// }
//
// @Transient
// public String[] getToUsernamesList(){
// return this.toUsernames.split(",");
// }
//
// public String getTxId() {
// return txId;
// }
//
// public void setTxId(String txId) {
// this.txId = txId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public String getNotificationText() {
// return notificationText;
// }
//
// public void setNotificationText(String notificationText) {
// this.notificationText = notificationText;
// }
//
// public String getOriginaleTweet() {
// return originaleTweet;
// }
//
// public void setOriginaleTweet(String originaleTweet) {
// this.originaleTweet = originaleTweet;
// }
// }
//
// Path: opentipbot-persistence/src/main/java/opentipbot/persistence/model/OpenTipBotCommandEnum.java
// public enum OpenTipBotCommandEnum {
// TIP, WITHDRAW, TIP_RAIN, TIP_RANDOM, FAV, NOTIFY_RECEIVER, NOTIFY_ERROR;
// }
//
// Path: opentipbot-persistence/src/main/java/opentipbot/persistence/model/OpenTipBotCommandStatus.java
// public enum OpenTipBotCommandStatus {
// NEW,PENDING,PROCESSED,ERROR;
// }
| import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import opentipbot.persistence.model.OpenTipBotCommand;
import opentipbot.persistence.model.OpenTipBotCommandEnum;
import opentipbot.persistence.model.OpenTipBotCommandStatus;
import java.util.List; | package opentipbot.persistence.repository;
/**
* @author Gilles Cadignan
*/
public interface OpenTipBotCommandRepository extends JpaRepository<OpenTipBotCommand, Long> {
List<OpenTipBotCommand> findByTweetIdentifier(Long tweetIdentifier);
| // Path: opentipbot-persistence/src/main/java/opentipbot/persistence/model/OpenTipBotCommand.java
// @Entity
// @Table(name = "opentipbot_command")
// public class OpenTipBotCommand extends BaseEntity<Long> {
//
// @Id
// @GeneratedValue
// private Long id;
//
// @NotNull
// private OpenTipBotCommandEnum opentipbotCommandEnum;
//
// private String fromUserName;
//
// private String toUserName;
//
// private String toUsernames;
//
// private String txId;
//
// private Double amout;
//
// private String errorMessage;
//
// private String notificationText;
//
// private Long tweetIdentifier;
//
// private String coinAddress;
//
// private String originaleTweet;
//
// @NotNull
// private OpenTipBotCommandStatus opentipbotCommandStatus;
//
// public OpenTipBotCommandEnum getOpenTipBotCommandEnum() {
// return opentipbotCommandEnum;
// }
//
// public OpenTipBotCommandStatus getOpenTipBotCommandStatus() {
// return opentipbotCommandStatus;
// }
//
// public void setOpenTipBotCommandStatus(OpenTipBotCommandStatus opentipbotCommandStatus) {
// this.opentipbotCommandStatus = opentipbotCommandStatus;
// }
//
// public Long getTweetIdentifier() {
// return tweetIdentifier;
// }
//
// public void setTweetIdentifier(Long tweetId) {
// this.tweetIdentifier = tweetId;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// @Override
// public Long getId() {
// return this.id;
// }
//
// public OpenTipBotCommandEnum getCommand() {
// return this.opentipbotCommandEnum;
// }
//
// public void setOpenTipBotCommandEnum(OpenTipBotCommandEnum opentipbotCommandEnum) {
// this.opentipbotCommandEnum = opentipbotCommandEnum;
// }
//
// public String getFromUserName() {
// return fromUserName;
// }
//
// public void setFromUserName(String fromUserName) {
// this.fromUserName = fromUserName;
// }
//
// public String getToUserName() {
// return toUserName;
// }
//
// public void setToUserName(String toUserName) {
// this.toUserName = toUserName;
// }
//
// public Double getAmout() {
// return amout;
// }
//
// public void setAmout(Double amout) {
// this.amout = amout;
// }
//
// public String getCoinAddress() {
// return coinAddress;
// }
//
// public void setCoinAddress(String coinAddress) {
// this.coinAddress = coinAddress;
// }
//
// public String getToUsernames() {
// return toUsernames;
// }
//
// public void setToUsernames(String toUsernames) {
// this.toUsernames = toUsernames;
// }
//
// @Transient
// public String[] getToUsernamesList(){
// return this.toUsernames.split(",");
// }
//
// public String getTxId() {
// return txId;
// }
//
// public void setTxId(String txId) {
// this.txId = txId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public String getNotificationText() {
// return notificationText;
// }
//
// public void setNotificationText(String notificationText) {
// this.notificationText = notificationText;
// }
//
// public String getOriginaleTweet() {
// return originaleTweet;
// }
//
// public void setOriginaleTweet(String originaleTweet) {
// this.originaleTweet = originaleTweet;
// }
// }
//
// Path: opentipbot-persistence/src/main/java/opentipbot/persistence/model/OpenTipBotCommandEnum.java
// public enum OpenTipBotCommandEnum {
// TIP, WITHDRAW, TIP_RAIN, TIP_RANDOM, FAV, NOTIFY_RECEIVER, NOTIFY_ERROR;
// }
//
// Path: opentipbot-persistence/src/main/java/opentipbot/persistence/model/OpenTipBotCommandStatus.java
// public enum OpenTipBotCommandStatus {
// NEW,PENDING,PROCESSED,ERROR;
// }
// Path: opentipbot-persistence/src/main/java/opentipbot/persistence/repository/OpenTipBotCommandRepository.java
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import opentipbot.persistence.model.OpenTipBotCommand;
import opentipbot.persistence.model.OpenTipBotCommandEnum;
import opentipbot.persistence.model.OpenTipBotCommandStatus;
import java.util.List;
package opentipbot.persistence.repository;
/**
* @author Gilles Cadignan
*/
public interface OpenTipBotCommandRepository extends JpaRepository<OpenTipBotCommand, Long> {
List<OpenTipBotCommand> findByTweetIdentifier(Long tweetIdentifier);
| List<OpenTipBotCommand> findByOpenTipBotCommandStatusAndOpenTipBotCommandEnumOrderByCreationTimeAsc(OpenTipBotCommandStatus status, OpenTipBotCommandEnum commandEnum); |
gill3s/opentipbot | opentipbot-persistence/src/main/java/opentipbot/persistence/repository/OpenTipBotCommandRepository.java | // Path: opentipbot-persistence/src/main/java/opentipbot/persistence/model/OpenTipBotCommand.java
// @Entity
// @Table(name = "opentipbot_command")
// public class OpenTipBotCommand extends BaseEntity<Long> {
//
// @Id
// @GeneratedValue
// private Long id;
//
// @NotNull
// private OpenTipBotCommandEnum opentipbotCommandEnum;
//
// private String fromUserName;
//
// private String toUserName;
//
// private String toUsernames;
//
// private String txId;
//
// private Double amout;
//
// private String errorMessage;
//
// private String notificationText;
//
// private Long tweetIdentifier;
//
// private String coinAddress;
//
// private String originaleTweet;
//
// @NotNull
// private OpenTipBotCommandStatus opentipbotCommandStatus;
//
// public OpenTipBotCommandEnum getOpenTipBotCommandEnum() {
// return opentipbotCommandEnum;
// }
//
// public OpenTipBotCommandStatus getOpenTipBotCommandStatus() {
// return opentipbotCommandStatus;
// }
//
// public void setOpenTipBotCommandStatus(OpenTipBotCommandStatus opentipbotCommandStatus) {
// this.opentipbotCommandStatus = opentipbotCommandStatus;
// }
//
// public Long getTweetIdentifier() {
// return tweetIdentifier;
// }
//
// public void setTweetIdentifier(Long tweetId) {
// this.tweetIdentifier = tweetId;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// @Override
// public Long getId() {
// return this.id;
// }
//
// public OpenTipBotCommandEnum getCommand() {
// return this.opentipbotCommandEnum;
// }
//
// public void setOpenTipBotCommandEnum(OpenTipBotCommandEnum opentipbotCommandEnum) {
// this.opentipbotCommandEnum = opentipbotCommandEnum;
// }
//
// public String getFromUserName() {
// return fromUserName;
// }
//
// public void setFromUserName(String fromUserName) {
// this.fromUserName = fromUserName;
// }
//
// public String getToUserName() {
// return toUserName;
// }
//
// public void setToUserName(String toUserName) {
// this.toUserName = toUserName;
// }
//
// public Double getAmout() {
// return amout;
// }
//
// public void setAmout(Double amout) {
// this.amout = amout;
// }
//
// public String getCoinAddress() {
// return coinAddress;
// }
//
// public void setCoinAddress(String coinAddress) {
// this.coinAddress = coinAddress;
// }
//
// public String getToUsernames() {
// return toUsernames;
// }
//
// public void setToUsernames(String toUsernames) {
// this.toUsernames = toUsernames;
// }
//
// @Transient
// public String[] getToUsernamesList(){
// return this.toUsernames.split(",");
// }
//
// public String getTxId() {
// return txId;
// }
//
// public void setTxId(String txId) {
// this.txId = txId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public String getNotificationText() {
// return notificationText;
// }
//
// public void setNotificationText(String notificationText) {
// this.notificationText = notificationText;
// }
//
// public String getOriginaleTweet() {
// return originaleTweet;
// }
//
// public void setOriginaleTweet(String originaleTweet) {
// this.originaleTweet = originaleTweet;
// }
// }
//
// Path: opentipbot-persistence/src/main/java/opentipbot/persistence/model/OpenTipBotCommandEnum.java
// public enum OpenTipBotCommandEnum {
// TIP, WITHDRAW, TIP_RAIN, TIP_RANDOM, FAV, NOTIFY_RECEIVER, NOTIFY_ERROR;
// }
//
// Path: opentipbot-persistence/src/main/java/opentipbot/persistence/model/OpenTipBotCommandStatus.java
// public enum OpenTipBotCommandStatus {
// NEW,PENDING,PROCESSED,ERROR;
// }
| import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import opentipbot.persistence.model.OpenTipBotCommand;
import opentipbot.persistence.model.OpenTipBotCommandEnum;
import opentipbot.persistence.model.OpenTipBotCommandStatus;
import java.util.List; | package opentipbot.persistence.repository;
/**
* @author Gilles Cadignan
*/
public interface OpenTipBotCommandRepository extends JpaRepository<OpenTipBotCommand, Long> {
List<OpenTipBotCommand> findByTweetIdentifier(Long tweetIdentifier);
| // Path: opentipbot-persistence/src/main/java/opentipbot/persistence/model/OpenTipBotCommand.java
// @Entity
// @Table(name = "opentipbot_command")
// public class OpenTipBotCommand extends BaseEntity<Long> {
//
// @Id
// @GeneratedValue
// private Long id;
//
// @NotNull
// private OpenTipBotCommandEnum opentipbotCommandEnum;
//
// private String fromUserName;
//
// private String toUserName;
//
// private String toUsernames;
//
// private String txId;
//
// private Double amout;
//
// private String errorMessage;
//
// private String notificationText;
//
// private Long tweetIdentifier;
//
// private String coinAddress;
//
// private String originaleTweet;
//
// @NotNull
// private OpenTipBotCommandStatus opentipbotCommandStatus;
//
// public OpenTipBotCommandEnum getOpenTipBotCommandEnum() {
// return opentipbotCommandEnum;
// }
//
// public OpenTipBotCommandStatus getOpenTipBotCommandStatus() {
// return opentipbotCommandStatus;
// }
//
// public void setOpenTipBotCommandStatus(OpenTipBotCommandStatus opentipbotCommandStatus) {
// this.opentipbotCommandStatus = opentipbotCommandStatus;
// }
//
// public Long getTweetIdentifier() {
// return tweetIdentifier;
// }
//
// public void setTweetIdentifier(Long tweetId) {
// this.tweetIdentifier = tweetId;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// @Override
// public Long getId() {
// return this.id;
// }
//
// public OpenTipBotCommandEnum getCommand() {
// return this.opentipbotCommandEnum;
// }
//
// public void setOpenTipBotCommandEnum(OpenTipBotCommandEnum opentipbotCommandEnum) {
// this.opentipbotCommandEnum = opentipbotCommandEnum;
// }
//
// public String getFromUserName() {
// return fromUserName;
// }
//
// public void setFromUserName(String fromUserName) {
// this.fromUserName = fromUserName;
// }
//
// public String getToUserName() {
// return toUserName;
// }
//
// public void setToUserName(String toUserName) {
// this.toUserName = toUserName;
// }
//
// public Double getAmout() {
// return amout;
// }
//
// public void setAmout(Double amout) {
// this.amout = amout;
// }
//
// public String getCoinAddress() {
// return coinAddress;
// }
//
// public void setCoinAddress(String coinAddress) {
// this.coinAddress = coinAddress;
// }
//
// public String getToUsernames() {
// return toUsernames;
// }
//
// public void setToUsernames(String toUsernames) {
// this.toUsernames = toUsernames;
// }
//
// @Transient
// public String[] getToUsernamesList(){
// return this.toUsernames.split(",");
// }
//
// public String getTxId() {
// return txId;
// }
//
// public void setTxId(String txId) {
// this.txId = txId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public String getNotificationText() {
// return notificationText;
// }
//
// public void setNotificationText(String notificationText) {
// this.notificationText = notificationText;
// }
//
// public String getOriginaleTweet() {
// return originaleTweet;
// }
//
// public void setOriginaleTweet(String originaleTweet) {
// this.originaleTweet = originaleTweet;
// }
// }
//
// Path: opentipbot-persistence/src/main/java/opentipbot/persistence/model/OpenTipBotCommandEnum.java
// public enum OpenTipBotCommandEnum {
// TIP, WITHDRAW, TIP_RAIN, TIP_RANDOM, FAV, NOTIFY_RECEIVER, NOTIFY_ERROR;
// }
//
// Path: opentipbot-persistence/src/main/java/opentipbot/persistence/model/OpenTipBotCommandStatus.java
// public enum OpenTipBotCommandStatus {
// NEW,PENDING,PROCESSED,ERROR;
// }
// Path: opentipbot-persistence/src/main/java/opentipbot/persistence/repository/OpenTipBotCommandRepository.java
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import opentipbot.persistence.model.OpenTipBotCommand;
import opentipbot.persistence.model.OpenTipBotCommandEnum;
import opentipbot.persistence.model.OpenTipBotCommandStatus;
import java.util.List;
package opentipbot.persistence.repository;
/**
* @author Gilles Cadignan
*/
public interface OpenTipBotCommandRepository extends JpaRepository<OpenTipBotCommand, Long> {
List<OpenTipBotCommand> findByTweetIdentifier(Long tweetIdentifier);
| List<OpenTipBotCommand> findByOpenTipBotCommandStatusAndOpenTipBotCommandEnumOrderByCreationTimeAsc(OpenTipBotCommandStatus status, OpenTipBotCommandEnum commandEnum); |
gill3s/opentipbot | opentipbot-service/src/main/java/opentipbot/service/exception/BitcoinServiceException.java | // Path: opentipbot-persistence/src/main/java/opentipbot/persistence/model/OpenTipBotCommand.java
// @Entity
// @Table(name = "opentipbot_command")
// public class OpenTipBotCommand extends BaseEntity<Long> {
//
// @Id
// @GeneratedValue
// private Long id;
//
// @NotNull
// private OpenTipBotCommandEnum opentipbotCommandEnum;
//
// private String fromUserName;
//
// private String toUserName;
//
// private String toUsernames;
//
// private String txId;
//
// private Double amout;
//
// private String errorMessage;
//
// private String notificationText;
//
// private Long tweetIdentifier;
//
// private String coinAddress;
//
// private String originaleTweet;
//
// @NotNull
// private OpenTipBotCommandStatus opentipbotCommandStatus;
//
// public OpenTipBotCommandEnum getOpenTipBotCommandEnum() {
// return opentipbotCommandEnum;
// }
//
// public OpenTipBotCommandStatus getOpenTipBotCommandStatus() {
// return opentipbotCommandStatus;
// }
//
// public void setOpenTipBotCommandStatus(OpenTipBotCommandStatus opentipbotCommandStatus) {
// this.opentipbotCommandStatus = opentipbotCommandStatus;
// }
//
// public Long getTweetIdentifier() {
// return tweetIdentifier;
// }
//
// public void setTweetIdentifier(Long tweetId) {
// this.tweetIdentifier = tweetId;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// @Override
// public Long getId() {
// return this.id;
// }
//
// public OpenTipBotCommandEnum getCommand() {
// return this.opentipbotCommandEnum;
// }
//
// public void setOpenTipBotCommandEnum(OpenTipBotCommandEnum opentipbotCommandEnum) {
// this.opentipbotCommandEnum = opentipbotCommandEnum;
// }
//
// public String getFromUserName() {
// return fromUserName;
// }
//
// public void setFromUserName(String fromUserName) {
// this.fromUserName = fromUserName;
// }
//
// public String getToUserName() {
// return toUserName;
// }
//
// public void setToUserName(String toUserName) {
// this.toUserName = toUserName;
// }
//
// public Double getAmout() {
// return amout;
// }
//
// public void setAmout(Double amout) {
// this.amout = amout;
// }
//
// public String getCoinAddress() {
// return coinAddress;
// }
//
// public void setCoinAddress(String coinAddress) {
// this.coinAddress = coinAddress;
// }
//
// public String getToUsernames() {
// return toUsernames;
// }
//
// public void setToUsernames(String toUsernames) {
// this.toUsernames = toUsernames;
// }
//
// @Transient
// public String[] getToUsernamesList(){
// return this.toUsernames.split(",");
// }
//
// public String getTxId() {
// return txId;
// }
//
// public void setTxId(String txId) {
// this.txId = txId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public String getNotificationText() {
// return notificationText;
// }
//
// public void setNotificationText(String notificationText) {
// this.notificationText = notificationText;
// }
//
// public String getOriginaleTweet() {
// return originaleTweet;
// }
//
// public void setOriginaleTweet(String originaleTweet) {
// this.originaleTweet = originaleTweet;
// }
// }
| import opentipbot.persistence.model.OpenTipBotCommand; | package opentipbot.service.exception;
/**
* Created by gilles on 05/09/2014.
*/
public class BitcoinServiceException extends OpenTipBotServiceException {
public BitcoinServiceException(String message) {
super(message);
}
public BitcoinServiceException(String message, Throwable cause) {
super(message, cause);
}
| // Path: opentipbot-persistence/src/main/java/opentipbot/persistence/model/OpenTipBotCommand.java
// @Entity
// @Table(name = "opentipbot_command")
// public class OpenTipBotCommand extends BaseEntity<Long> {
//
// @Id
// @GeneratedValue
// private Long id;
//
// @NotNull
// private OpenTipBotCommandEnum opentipbotCommandEnum;
//
// private String fromUserName;
//
// private String toUserName;
//
// private String toUsernames;
//
// private String txId;
//
// private Double amout;
//
// private String errorMessage;
//
// private String notificationText;
//
// private Long tweetIdentifier;
//
// private String coinAddress;
//
// private String originaleTweet;
//
// @NotNull
// private OpenTipBotCommandStatus opentipbotCommandStatus;
//
// public OpenTipBotCommandEnum getOpenTipBotCommandEnum() {
// return opentipbotCommandEnum;
// }
//
// public OpenTipBotCommandStatus getOpenTipBotCommandStatus() {
// return opentipbotCommandStatus;
// }
//
// public void setOpenTipBotCommandStatus(OpenTipBotCommandStatus opentipbotCommandStatus) {
// this.opentipbotCommandStatus = opentipbotCommandStatus;
// }
//
// public Long getTweetIdentifier() {
// return tweetIdentifier;
// }
//
// public void setTweetIdentifier(Long tweetId) {
// this.tweetIdentifier = tweetId;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// @Override
// public Long getId() {
// return this.id;
// }
//
// public OpenTipBotCommandEnum getCommand() {
// return this.opentipbotCommandEnum;
// }
//
// public void setOpenTipBotCommandEnum(OpenTipBotCommandEnum opentipbotCommandEnum) {
// this.opentipbotCommandEnum = opentipbotCommandEnum;
// }
//
// public String getFromUserName() {
// return fromUserName;
// }
//
// public void setFromUserName(String fromUserName) {
// this.fromUserName = fromUserName;
// }
//
// public String getToUserName() {
// return toUserName;
// }
//
// public void setToUserName(String toUserName) {
// this.toUserName = toUserName;
// }
//
// public Double getAmout() {
// return amout;
// }
//
// public void setAmout(Double amout) {
// this.amout = amout;
// }
//
// public String getCoinAddress() {
// return coinAddress;
// }
//
// public void setCoinAddress(String coinAddress) {
// this.coinAddress = coinAddress;
// }
//
// public String getToUsernames() {
// return toUsernames;
// }
//
// public void setToUsernames(String toUsernames) {
// this.toUsernames = toUsernames;
// }
//
// @Transient
// public String[] getToUsernamesList(){
// return this.toUsernames.split(",");
// }
//
// public String getTxId() {
// return txId;
// }
//
// public void setTxId(String txId) {
// this.txId = txId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public String getNotificationText() {
// return notificationText;
// }
//
// public void setNotificationText(String notificationText) {
// this.notificationText = notificationText;
// }
//
// public String getOriginaleTweet() {
// return originaleTweet;
// }
//
// public void setOriginaleTweet(String originaleTweet) {
// this.originaleTweet = originaleTweet;
// }
// }
// Path: opentipbot-service/src/main/java/opentipbot/service/exception/BitcoinServiceException.java
import opentipbot.persistence.model.OpenTipBotCommand;
package opentipbot.service.exception;
/**
* Created by gilles on 05/09/2014.
*/
public class BitcoinServiceException extends OpenTipBotServiceException {
public BitcoinServiceException(String message) {
super(message);
}
public BitcoinServiceException(String message, Throwable cause) {
super(message, cause);
}
| public BitcoinServiceException(String message, OpenTipBotCommand command) { |
gill3s/opentipbot | opentipbot-webapp/src/main/java/opentipbot/web/security/OpenTipBotSignInAdapter.java | // Path: opentipbot-persistence/src/main/java/opentipbot/persistence/repository/OpenTipBotUserRepository.java
// public interface OpenTipBotUserRepository extends JpaRepository<OpenTipBotUser, Long> {
// OpenTipBotUser findByTwitterIdentifier(String twitterIdentifier);
// OpenTipBotUser findByUserName(String UserName);
// }
| import org.springframework.social.connect.Connection;
import org.springframework.social.connect.web.SignInAdapter;
import org.springframework.web.context.request.NativeWebRequest;
import opentipbot.persistence.repository.OpenTipBotUserRepository;
import javax.servlet.http.HttpServletResponse; | /*
* Copyright 2014 the original author or authors.
*
* 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 opentipbot.web.security;
/**
* Signs the user in by setting the currentUser property on the {@link SecurityContext}.
* Remembers the sign-in after the current request completes by storing the user's id in a cookie.
* This is cookie is read in {@link UserInterceptor#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, Object)} on subsequent requests.
* @author Gilles Cadignan
* @see UserInterceptor
*/
public class OpenTipBotSignInAdapter implements SignInAdapter {
private final UserCookieGenerator userCookieGenerator = new UserCookieGenerator();
| // Path: opentipbot-persistence/src/main/java/opentipbot/persistence/repository/OpenTipBotUserRepository.java
// public interface OpenTipBotUserRepository extends JpaRepository<OpenTipBotUser, Long> {
// OpenTipBotUser findByTwitterIdentifier(String twitterIdentifier);
// OpenTipBotUser findByUserName(String UserName);
// }
// Path: opentipbot-webapp/src/main/java/opentipbot/web/security/OpenTipBotSignInAdapter.java
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.web.SignInAdapter;
import org.springframework.web.context.request.NativeWebRequest;
import opentipbot.persistence.repository.OpenTipBotUserRepository;
import javax.servlet.http.HttpServletResponse;
/*
* Copyright 2014 the original author or authors.
*
* 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 opentipbot.web.security;
/**
* Signs the user in by setting the currentUser property on the {@link SecurityContext}.
* Remembers the sign-in after the current request completes by storing the user's id in a cookie.
* This is cookie is read in {@link UserInterceptor#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, Object)} on subsequent requests.
* @author Gilles Cadignan
* @see UserInterceptor
*/
public class OpenTipBotSignInAdapter implements SignInAdapter {
private final UserCookieGenerator userCookieGenerator = new UserCookieGenerator();
| private final OpenTipBotUserRepository opentipbotUserRepository; |
gill3s/opentipbot | opentipbot-webapp/src/main/java/opentipbot/web/config/WebAppContext.java | // Path: opentipbot-persistence/src/main/java/opentipbot/persistence/repository/OpenTipBotUserRepository.java
// public interface OpenTipBotUserRepository extends JpaRepository<OpenTipBotUser, Long> {
// OpenTipBotUser findByTwitterIdentifier(String twitterIdentifier);
// OpenTipBotUser findByUserName(String UserName);
// }
//
// Path: opentipbot-webapp/src/main/java/opentipbot/web/security/UserInterceptor.java
// public final class UserInterceptor extends HandlerInterceptorAdapter {
//
// private final UsersConnectionRepository connectionRepository;
//
// private final OpenTipBotUserRepository opentipbotUserRepository;
//
// private final UserCookieGenerator userCookieGenerator = new UserCookieGenerator();
//
// public UserInterceptor(UsersConnectionRepository connectionRepository, OpenTipBotUserRepository opentipbotUserRepository) {
// this.connectionRepository = connectionRepository;
// this.opentipbotUserRepository = opentipbotUserRepository;
// }
//
// public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// rememberUser(request, response);
// handleSignOut(request, response);
// if (SecurityContext.userSignedIn() || requestForNotProtected(request)) {
// return true;
// } else {
// return requireSignIn(request, response);
// }
// }
//
// public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// SecurityContext.remove();
// }
//
// // internal helpers
//
// private void rememberUser(HttpServletRequest request, HttpServletResponse response) {
// String userId = userCookieGenerator.readCookieValue(request);
// if (userId == null) {
// return;
// }
// if (!userNotFound(userId)) {
// userCookieGenerator.removeCookie(response);
// return;
// }
// OpenTipBotUser opentipbotUser= opentipbotUserRepository.findOne(Long.parseLong(userId));
// if (opentipbotUser == null)
// return;
// SecurityContext.setCurrentUser(opentipbotUser);
// }
//
// private void handleSignOut(HttpServletRequest request, HttpServletResponse response) {
// if (SecurityContext.userSignedIn() && request.getServletPath().startsWith("/signout")) {
// connectionRepository.createConnectionRepository(SecurityContext.getCurrentUser().getId().toString()).removeConnections("twitter");
// userCookieGenerator.removeCookie(response);
// SecurityContext.remove();
// }
// }
//
// private boolean requestForNotProtected(HttpServletRequest request) {
// return request.getServletPath().startsWith("/signin") || request.getServletPath().startsWith("/documentation")
// || request.getServletPath().startsWith("/about");
// }
//
// private boolean requireSignIn(HttpServletRequest request, HttpServletResponse response) throws Exception {
// new RedirectView("/signin", true).render(null, request, response);
// return false;
// }
//
// private boolean userNotFound(String userId) {
// // doesn't bother checking a local user database: simply checks if the userId is connected to Twitter
// return connectionRepository.createConnectionRepository(userId).findPrimaryConnection(Twitter.class) != null;
// }
//
// }
| import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
import org.springframework.web.servlet.view.tiles2.TilesConfigurer;
import org.springframework.web.servlet.view.tiles2.TilesView;
import opentipbot.persistence.repository.OpenTipBotUserRepository;
import opentipbot.web.security.UserInterceptor;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties; | package opentipbot.web.config;
/**
* @author Petri Kainulainen
*/
@Configuration
@ComponentScan(basePackages = {
"opentipbot.web.controller"
})
@EnableWebMvc
public class WebAppContext extends WebMvcConfigurerAdapter {
@Autowired | // Path: opentipbot-persistence/src/main/java/opentipbot/persistence/repository/OpenTipBotUserRepository.java
// public interface OpenTipBotUserRepository extends JpaRepository<OpenTipBotUser, Long> {
// OpenTipBotUser findByTwitterIdentifier(String twitterIdentifier);
// OpenTipBotUser findByUserName(String UserName);
// }
//
// Path: opentipbot-webapp/src/main/java/opentipbot/web/security/UserInterceptor.java
// public final class UserInterceptor extends HandlerInterceptorAdapter {
//
// private final UsersConnectionRepository connectionRepository;
//
// private final OpenTipBotUserRepository opentipbotUserRepository;
//
// private final UserCookieGenerator userCookieGenerator = new UserCookieGenerator();
//
// public UserInterceptor(UsersConnectionRepository connectionRepository, OpenTipBotUserRepository opentipbotUserRepository) {
// this.connectionRepository = connectionRepository;
// this.opentipbotUserRepository = opentipbotUserRepository;
// }
//
// public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// rememberUser(request, response);
// handleSignOut(request, response);
// if (SecurityContext.userSignedIn() || requestForNotProtected(request)) {
// return true;
// } else {
// return requireSignIn(request, response);
// }
// }
//
// public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// SecurityContext.remove();
// }
//
// // internal helpers
//
// private void rememberUser(HttpServletRequest request, HttpServletResponse response) {
// String userId = userCookieGenerator.readCookieValue(request);
// if (userId == null) {
// return;
// }
// if (!userNotFound(userId)) {
// userCookieGenerator.removeCookie(response);
// return;
// }
// OpenTipBotUser opentipbotUser= opentipbotUserRepository.findOne(Long.parseLong(userId));
// if (opentipbotUser == null)
// return;
// SecurityContext.setCurrentUser(opentipbotUser);
// }
//
// private void handleSignOut(HttpServletRequest request, HttpServletResponse response) {
// if (SecurityContext.userSignedIn() && request.getServletPath().startsWith("/signout")) {
// connectionRepository.createConnectionRepository(SecurityContext.getCurrentUser().getId().toString()).removeConnections("twitter");
// userCookieGenerator.removeCookie(response);
// SecurityContext.remove();
// }
// }
//
// private boolean requestForNotProtected(HttpServletRequest request) {
// return request.getServletPath().startsWith("/signin") || request.getServletPath().startsWith("/documentation")
// || request.getServletPath().startsWith("/about");
// }
//
// private boolean requireSignIn(HttpServletRequest request, HttpServletResponse response) throws Exception {
// new RedirectView("/signin", true).render(null, request, response);
// return false;
// }
//
// private boolean userNotFound(String userId) {
// // doesn't bother checking a local user database: simply checks if the userId is connected to Twitter
// return connectionRepository.createConnectionRepository(userId).findPrimaryConnection(Twitter.class) != null;
// }
//
// }
// Path: opentipbot-webapp/src/main/java/opentipbot/web/config/WebAppContext.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
import org.springframework.web.servlet.view.tiles2.TilesConfigurer;
import org.springframework.web.servlet.view.tiles2.TilesView;
import opentipbot.persistence.repository.OpenTipBotUserRepository;
import opentipbot.web.security.UserInterceptor;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
package opentipbot.web.config;
/**
* @author Petri Kainulainen
*/
@Configuration
@ComponentScan(basePackages = {
"opentipbot.web.controller"
})
@EnableWebMvc
public class WebAppContext extends WebMvcConfigurerAdapter {
@Autowired | OpenTipBotUserRepository opentipbotUserRepository; |
gill3s/opentipbot | opentipbot-webapp/src/main/java/opentipbot/web/config/WebAppContext.java | // Path: opentipbot-persistence/src/main/java/opentipbot/persistence/repository/OpenTipBotUserRepository.java
// public interface OpenTipBotUserRepository extends JpaRepository<OpenTipBotUser, Long> {
// OpenTipBotUser findByTwitterIdentifier(String twitterIdentifier);
// OpenTipBotUser findByUserName(String UserName);
// }
//
// Path: opentipbot-webapp/src/main/java/opentipbot/web/security/UserInterceptor.java
// public final class UserInterceptor extends HandlerInterceptorAdapter {
//
// private final UsersConnectionRepository connectionRepository;
//
// private final OpenTipBotUserRepository opentipbotUserRepository;
//
// private final UserCookieGenerator userCookieGenerator = new UserCookieGenerator();
//
// public UserInterceptor(UsersConnectionRepository connectionRepository, OpenTipBotUserRepository opentipbotUserRepository) {
// this.connectionRepository = connectionRepository;
// this.opentipbotUserRepository = opentipbotUserRepository;
// }
//
// public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// rememberUser(request, response);
// handleSignOut(request, response);
// if (SecurityContext.userSignedIn() || requestForNotProtected(request)) {
// return true;
// } else {
// return requireSignIn(request, response);
// }
// }
//
// public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// SecurityContext.remove();
// }
//
// // internal helpers
//
// private void rememberUser(HttpServletRequest request, HttpServletResponse response) {
// String userId = userCookieGenerator.readCookieValue(request);
// if (userId == null) {
// return;
// }
// if (!userNotFound(userId)) {
// userCookieGenerator.removeCookie(response);
// return;
// }
// OpenTipBotUser opentipbotUser= opentipbotUserRepository.findOne(Long.parseLong(userId));
// if (opentipbotUser == null)
// return;
// SecurityContext.setCurrentUser(opentipbotUser);
// }
//
// private void handleSignOut(HttpServletRequest request, HttpServletResponse response) {
// if (SecurityContext.userSignedIn() && request.getServletPath().startsWith("/signout")) {
// connectionRepository.createConnectionRepository(SecurityContext.getCurrentUser().getId().toString()).removeConnections("twitter");
// userCookieGenerator.removeCookie(response);
// SecurityContext.remove();
// }
// }
//
// private boolean requestForNotProtected(HttpServletRequest request) {
// return request.getServletPath().startsWith("/signin") || request.getServletPath().startsWith("/documentation")
// || request.getServletPath().startsWith("/about");
// }
//
// private boolean requireSignIn(HttpServletRequest request, HttpServletResponse response) throws Exception {
// new RedirectView("/signin", true).render(null, request, response);
// return false;
// }
//
// private boolean userNotFound(String userId) {
// // doesn't bother checking a local user database: simply checks if the userId is connected to Twitter
// return connectionRepository.createConnectionRepository(userId).findPrimaryConnection(Twitter.class) != null;
// }
//
// }
| import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
import org.springframework.web.servlet.view.tiles2.TilesConfigurer;
import org.springframework.web.servlet.view.tiles2.TilesView;
import opentipbot.persistence.repository.OpenTipBotUserRepository;
import opentipbot.web.security.UserInterceptor;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties; | }
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
@Bean
public SimpleMappingExceptionResolver exceptionResolver() {
SimpleMappingExceptionResolver exceptionResolver = new SimpleMappingExceptionResolver();
Properties exceptionMappings = new Properties();
exceptionMappings.put("java.lang.Exception", "home");
exceptionMappings.put("java.lang.RuntimeException", "home");
exceptionResolver.setExceptionMappings(exceptionMappings);
Properties statusCodes = new Properties();
statusCodes.put("error/404", "404");
statusCodes.put("error/error", "500");
exceptionResolver.setStatusCodes(statusCodes);
return exceptionResolver;
}
public void addInterceptors(InterceptorRegistry registry) { | // Path: opentipbot-persistence/src/main/java/opentipbot/persistence/repository/OpenTipBotUserRepository.java
// public interface OpenTipBotUserRepository extends JpaRepository<OpenTipBotUser, Long> {
// OpenTipBotUser findByTwitterIdentifier(String twitterIdentifier);
// OpenTipBotUser findByUserName(String UserName);
// }
//
// Path: opentipbot-webapp/src/main/java/opentipbot/web/security/UserInterceptor.java
// public final class UserInterceptor extends HandlerInterceptorAdapter {
//
// private final UsersConnectionRepository connectionRepository;
//
// private final OpenTipBotUserRepository opentipbotUserRepository;
//
// private final UserCookieGenerator userCookieGenerator = new UserCookieGenerator();
//
// public UserInterceptor(UsersConnectionRepository connectionRepository, OpenTipBotUserRepository opentipbotUserRepository) {
// this.connectionRepository = connectionRepository;
// this.opentipbotUserRepository = opentipbotUserRepository;
// }
//
// public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// rememberUser(request, response);
// handleSignOut(request, response);
// if (SecurityContext.userSignedIn() || requestForNotProtected(request)) {
// return true;
// } else {
// return requireSignIn(request, response);
// }
// }
//
// public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// SecurityContext.remove();
// }
//
// // internal helpers
//
// private void rememberUser(HttpServletRequest request, HttpServletResponse response) {
// String userId = userCookieGenerator.readCookieValue(request);
// if (userId == null) {
// return;
// }
// if (!userNotFound(userId)) {
// userCookieGenerator.removeCookie(response);
// return;
// }
// OpenTipBotUser opentipbotUser= opentipbotUserRepository.findOne(Long.parseLong(userId));
// if (opentipbotUser == null)
// return;
// SecurityContext.setCurrentUser(opentipbotUser);
// }
//
// private void handleSignOut(HttpServletRequest request, HttpServletResponse response) {
// if (SecurityContext.userSignedIn() && request.getServletPath().startsWith("/signout")) {
// connectionRepository.createConnectionRepository(SecurityContext.getCurrentUser().getId().toString()).removeConnections("twitter");
// userCookieGenerator.removeCookie(response);
// SecurityContext.remove();
// }
// }
//
// private boolean requestForNotProtected(HttpServletRequest request) {
// return request.getServletPath().startsWith("/signin") || request.getServletPath().startsWith("/documentation")
// || request.getServletPath().startsWith("/about");
// }
//
// private boolean requireSignIn(HttpServletRequest request, HttpServletResponse response) throws Exception {
// new RedirectView("/signin", true).render(null, request, response);
// return false;
// }
//
// private boolean userNotFound(String userId) {
// // doesn't bother checking a local user database: simply checks if the userId is connected to Twitter
// return connectionRepository.createConnectionRepository(userId).findPrimaryConnection(Twitter.class) != null;
// }
//
// }
// Path: opentipbot-webapp/src/main/java/opentipbot/web/config/WebAppContext.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
import org.springframework.web.servlet.view.tiles2.TilesConfigurer;
import org.springframework.web.servlet.view.tiles2.TilesView;
import opentipbot.persistence.repository.OpenTipBotUserRepository;
import opentipbot.web.security.UserInterceptor;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
@Bean
public SimpleMappingExceptionResolver exceptionResolver() {
SimpleMappingExceptionResolver exceptionResolver = new SimpleMappingExceptionResolver();
Properties exceptionMappings = new Properties();
exceptionMappings.put("java.lang.Exception", "home");
exceptionMappings.put("java.lang.RuntimeException", "home");
exceptionResolver.setExceptionMappings(exceptionMappings);
Properties statusCodes = new Properties();
statusCodes.put("error/404", "404");
statusCodes.put("error/error", "500");
exceptionResolver.setStatusCodes(statusCodes);
return exceptionResolver;
}
public void addInterceptors(InterceptorRegistry registry) { | registry.addInterceptor(new UserInterceptor(usersConnectionRepository, opentipbotUserRepository)); |
gill3s/opentipbot | opentipbot-webapp/src/main/java/opentipbot/web/config/OpenTipBotApplicationContext.java | // Path: opentipbot-persistence/src/main/java/opentipbot/persistence/config/PersistenceContext.java
// @Configuration
// @EnableJpaRepositories(basePackages = {
// "opentipbot.persistence.repository"
// })
// @PropertySource("classpath:application.properties")
// public class PersistenceContext {
// //Entity package
// private static final String[] PROPERTY_PACKAGES_TO_SCAN = {
// "opentipbot.persistence.model"
// };
//
// //Database properties
// protected static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
// protected static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
// protected static final String PROPERTY_NAME_DATABASE_URL = "db.url";
// protected static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
//
// //Hibernate Properties
// private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
// private static final String PROPERTY_NAME_HIBERNATE_FORMAT_SQL = "hibernate.format_sql";
// private static final String PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO = "hibernate.hbm2ddl.auto";
// private static final String PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY = "hibernate.ejb.naming_strategy";
// private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
// private static final String PROPERTY_NAME_HIBERNATE_CONNECTION_AUTOCOMMIT = "hibernate.connection.autocommit";
//
// @Autowired
// private Environment env;
//
// @Bean
// public DataSource dataSource() {
// BoneCPDataSource dataSource = new BoneCPDataSource();
//
// dataSource.setDriverClass(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
// dataSource.setJdbcUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
// dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
// dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
//
// return dataSource;
// }
//
// @Bean
// public JpaTransactionManager transactionManager() {
// JpaTransactionManager transactionManager = new JpaTransactionManager();
//
// transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
//
// return transactionManager;
// }
//
// @Bean
// public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
// LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
//
// entityManagerFactoryBean.setDataSource(dataSource());
// entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
// entityManagerFactoryBean.setPackagesToScan(PROPERTY_PACKAGES_TO_SCAN);
//
// Properties jpaProperties = new Properties();
// jpaProperties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
// jpaProperties.put(PROPERTY_NAME_HIBERNATE_FORMAT_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_FORMAT_SQL));
// jpaProperties.put(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO));
// jpaProperties.put(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY));
// jpaProperties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
// jpaProperties.put("hibernate.jdbc.use_streams_for_binary", "false");
//
// entityManagerFactoryBean.setJpaProperties(jpaProperties);
//
// return entityManagerFactoryBean;
// }
//
// @Bean
// public BitcoinJSONRPCClient bitcoinJSONRPCClient() throws MalformedURLException {
// return new BitcoinJSONRPCClient(env.getRequiredProperty("coind.url"));
// }
//
// }
//
// Path: opentipbot-service/src/main/java/opentipbot/service/config/ServiceSocialConfig.java
// @Configuration
// public class ServiceSocialConfig {
// @Bean
// public TwitterTemplate getTwitterTemplate(Environment env){
// String consumerKey = env.getProperty("opentipbot.notifier.twitter.appKey");
// String consumerSecret = env.getProperty("opentipbot.notifier.twitter.appSecret");
// String accessToken = env.getProperty("opentipbot.notifier.twitter.accessToken");
// String accessTokenSecret = env.getProperty("opentipbot.notifier.twitter.accessTokenSecret");
// Preconditions.checkNotNull(consumerKey);
// Preconditions.checkNotNull(consumerSecret);
// Preconditions.checkNotNull(accessToken);
// Preconditions.checkNotNull(accessTokenSecret);
// return new TwitterTemplate(consumerKey, consumerSecret, accessToken, accessTokenSecret);
// }
// }
| import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.*;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.env.Environment;
import opentipbot.persistence.config.PersistenceContext;
import opentipbot.service.config.ServiceSocialConfig; | package opentipbot.web.config;
/**
* @author Gilles Cadignan
*
* Opentipbot application conctext declaring message source ressource bundle
* and Property Placeholder
*/
@Configuration
@ComponentScan(basePackages = {
"opentipbot.service"
}) | // Path: opentipbot-persistence/src/main/java/opentipbot/persistence/config/PersistenceContext.java
// @Configuration
// @EnableJpaRepositories(basePackages = {
// "opentipbot.persistence.repository"
// })
// @PropertySource("classpath:application.properties")
// public class PersistenceContext {
// //Entity package
// private static final String[] PROPERTY_PACKAGES_TO_SCAN = {
// "opentipbot.persistence.model"
// };
//
// //Database properties
// protected static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
// protected static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
// protected static final String PROPERTY_NAME_DATABASE_URL = "db.url";
// protected static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
//
// //Hibernate Properties
// private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
// private static final String PROPERTY_NAME_HIBERNATE_FORMAT_SQL = "hibernate.format_sql";
// private static final String PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO = "hibernate.hbm2ddl.auto";
// private static final String PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY = "hibernate.ejb.naming_strategy";
// private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
// private static final String PROPERTY_NAME_HIBERNATE_CONNECTION_AUTOCOMMIT = "hibernate.connection.autocommit";
//
// @Autowired
// private Environment env;
//
// @Bean
// public DataSource dataSource() {
// BoneCPDataSource dataSource = new BoneCPDataSource();
//
// dataSource.setDriverClass(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
// dataSource.setJdbcUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
// dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
// dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
//
// return dataSource;
// }
//
// @Bean
// public JpaTransactionManager transactionManager() {
// JpaTransactionManager transactionManager = new JpaTransactionManager();
//
// transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
//
// return transactionManager;
// }
//
// @Bean
// public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
// LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
//
// entityManagerFactoryBean.setDataSource(dataSource());
// entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
// entityManagerFactoryBean.setPackagesToScan(PROPERTY_PACKAGES_TO_SCAN);
//
// Properties jpaProperties = new Properties();
// jpaProperties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
// jpaProperties.put(PROPERTY_NAME_HIBERNATE_FORMAT_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_FORMAT_SQL));
// jpaProperties.put(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO));
// jpaProperties.put(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY));
// jpaProperties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
// jpaProperties.put("hibernate.jdbc.use_streams_for_binary", "false");
//
// entityManagerFactoryBean.setJpaProperties(jpaProperties);
//
// return entityManagerFactoryBean;
// }
//
// @Bean
// public BitcoinJSONRPCClient bitcoinJSONRPCClient() throws MalformedURLException {
// return new BitcoinJSONRPCClient(env.getRequiredProperty("coind.url"));
// }
//
// }
//
// Path: opentipbot-service/src/main/java/opentipbot/service/config/ServiceSocialConfig.java
// @Configuration
// public class ServiceSocialConfig {
// @Bean
// public TwitterTemplate getTwitterTemplate(Environment env){
// String consumerKey = env.getProperty("opentipbot.notifier.twitter.appKey");
// String consumerSecret = env.getProperty("opentipbot.notifier.twitter.appSecret");
// String accessToken = env.getProperty("opentipbot.notifier.twitter.accessToken");
// String accessTokenSecret = env.getProperty("opentipbot.notifier.twitter.accessTokenSecret");
// Preconditions.checkNotNull(consumerKey);
// Preconditions.checkNotNull(consumerSecret);
// Preconditions.checkNotNull(accessToken);
// Preconditions.checkNotNull(accessTokenSecret);
// return new TwitterTemplate(consumerKey, consumerSecret, accessToken, accessTokenSecret);
// }
// }
// Path: opentipbot-webapp/src/main/java/opentipbot/web/config/OpenTipBotApplicationContext.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.*;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.env.Environment;
import opentipbot.persistence.config.PersistenceContext;
import opentipbot.service.config.ServiceSocialConfig;
package opentipbot.web.config;
/**
* @author Gilles Cadignan
*
* Opentipbot application conctext declaring message source ressource bundle
* and Property Placeholder
*/
@Configuration
@ComponentScan(basePackages = {
"opentipbot.service"
}) | @Import({WebAppContext.class, PersistenceContext.class, SocialContext.class, ServiceSocialConfig.class}) |
gill3s/opentipbot | opentipbot-webapp/src/main/java/opentipbot/web/config/OpenTipBotApplicationContext.java | // Path: opentipbot-persistence/src/main/java/opentipbot/persistence/config/PersistenceContext.java
// @Configuration
// @EnableJpaRepositories(basePackages = {
// "opentipbot.persistence.repository"
// })
// @PropertySource("classpath:application.properties")
// public class PersistenceContext {
// //Entity package
// private static final String[] PROPERTY_PACKAGES_TO_SCAN = {
// "opentipbot.persistence.model"
// };
//
// //Database properties
// protected static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
// protected static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
// protected static final String PROPERTY_NAME_DATABASE_URL = "db.url";
// protected static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
//
// //Hibernate Properties
// private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
// private static final String PROPERTY_NAME_HIBERNATE_FORMAT_SQL = "hibernate.format_sql";
// private static final String PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO = "hibernate.hbm2ddl.auto";
// private static final String PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY = "hibernate.ejb.naming_strategy";
// private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
// private static final String PROPERTY_NAME_HIBERNATE_CONNECTION_AUTOCOMMIT = "hibernate.connection.autocommit";
//
// @Autowired
// private Environment env;
//
// @Bean
// public DataSource dataSource() {
// BoneCPDataSource dataSource = new BoneCPDataSource();
//
// dataSource.setDriverClass(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
// dataSource.setJdbcUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
// dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
// dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
//
// return dataSource;
// }
//
// @Bean
// public JpaTransactionManager transactionManager() {
// JpaTransactionManager transactionManager = new JpaTransactionManager();
//
// transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
//
// return transactionManager;
// }
//
// @Bean
// public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
// LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
//
// entityManagerFactoryBean.setDataSource(dataSource());
// entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
// entityManagerFactoryBean.setPackagesToScan(PROPERTY_PACKAGES_TO_SCAN);
//
// Properties jpaProperties = new Properties();
// jpaProperties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
// jpaProperties.put(PROPERTY_NAME_HIBERNATE_FORMAT_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_FORMAT_SQL));
// jpaProperties.put(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO));
// jpaProperties.put(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY));
// jpaProperties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
// jpaProperties.put("hibernate.jdbc.use_streams_for_binary", "false");
//
// entityManagerFactoryBean.setJpaProperties(jpaProperties);
//
// return entityManagerFactoryBean;
// }
//
// @Bean
// public BitcoinJSONRPCClient bitcoinJSONRPCClient() throws MalformedURLException {
// return new BitcoinJSONRPCClient(env.getRequiredProperty("coind.url"));
// }
//
// }
//
// Path: opentipbot-service/src/main/java/opentipbot/service/config/ServiceSocialConfig.java
// @Configuration
// public class ServiceSocialConfig {
// @Bean
// public TwitterTemplate getTwitterTemplate(Environment env){
// String consumerKey = env.getProperty("opentipbot.notifier.twitter.appKey");
// String consumerSecret = env.getProperty("opentipbot.notifier.twitter.appSecret");
// String accessToken = env.getProperty("opentipbot.notifier.twitter.accessToken");
// String accessTokenSecret = env.getProperty("opentipbot.notifier.twitter.accessTokenSecret");
// Preconditions.checkNotNull(consumerKey);
// Preconditions.checkNotNull(consumerSecret);
// Preconditions.checkNotNull(accessToken);
// Preconditions.checkNotNull(accessTokenSecret);
// return new TwitterTemplate(consumerKey, consumerSecret, accessToken, accessTokenSecret);
// }
// }
| import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.*;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.env.Environment;
import opentipbot.persistence.config.PersistenceContext;
import opentipbot.service.config.ServiceSocialConfig; | package opentipbot.web.config;
/**
* @author Gilles Cadignan
*
* Opentipbot application conctext declaring message source ressource bundle
* and Property Placeholder
*/
@Configuration
@ComponentScan(basePackages = {
"opentipbot.service"
}) | // Path: opentipbot-persistence/src/main/java/opentipbot/persistence/config/PersistenceContext.java
// @Configuration
// @EnableJpaRepositories(basePackages = {
// "opentipbot.persistence.repository"
// })
// @PropertySource("classpath:application.properties")
// public class PersistenceContext {
// //Entity package
// private static final String[] PROPERTY_PACKAGES_TO_SCAN = {
// "opentipbot.persistence.model"
// };
//
// //Database properties
// protected static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
// protected static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
// protected static final String PROPERTY_NAME_DATABASE_URL = "db.url";
// protected static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
//
// //Hibernate Properties
// private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
// private static final String PROPERTY_NAME_HIBERNATE_FORMAT_SQL = "hibernate.format_sql";
// private static final String PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO = "hibernate.hbm2ddl.auto";
// private static final String PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY = "hibernate.ejb.naming_strategy";
// private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
// private static final String PROPERTY_NAME_HIBERNATE_CONNECTION_AUTOCOMMIT = "hibernate.connection.autocommit";
//
// @Autowired
// private Environment env;
//
// @Bean
// public DataSource dataSource() {
// BoneCPDataSource dataSource = new BoneCPDataSource();
//
// dataSource.setDriverClass(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
// dataSource.setJdbcUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
// dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
// dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
//
// return dataSource;
// }
//
// @Bean
// public JpaTransactionManager transactionManager() {
// JpaTransactionManager transactionManager = new JpaTransactionManager();
//
// transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
//
// return transactionManager;
// }
//
// @Bean
// public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
// LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
//
// entityManagerFactoryBean.setDataSource(dataSource());
// entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
// entityManagerFactoryBean.setPackagesToScan(PROPERTY_PACKAGES_TO_SCAN);
//
// Properties jpaProperties = new Properties();
// jpaProperties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
// jpaProperties.put(PROPERTY_NAME_HIBERNATE_FORMAT_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_FORMAT_SQL));
// jpaProperties.put(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO));
// jpaProperties.put(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY));
// jpaProperties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
// jpaProperties.put("hibernate.jdbc.use_streams_for_binary", "false");
//
// entityManagerFactoryBean.setJpaProperties(jpaProperties);
//
// return entityManagerFactoryBean;
// }
//
// @Bean
// public BitcoinJSONRPCClient bitcoinJSONRPCClient() throws MalformedURLException {
// return new BitcoinJSONRPCClient(env.getRequiredProperty("coind.url"));
// }
//
// }
//
// Path: opentipbot-service/src/main/java/opentipbot/service/config/ServiceSocialConfig.java
// @Configuration
// public class ServiceSocialConfig {
// @Bean
// public TwitterTemplate getTwitterTemplate(Environment env){
// String consumerKey = env.getProperty("opentipbot.notifier.twitter.appKey");
// String consumerSecret = env.getProperty("opentipbot.notifier.twitter.appSecret");
// String accessToken = env.getProperty("opentipbot.notifier.twitter.accessToken");
// String accessTokenSecret = env.getProperty("opentipbot.notifier.twitter.accessTokenSecret");
// Preconditions.checkNotNull(consumerKey);
// Preconditions.checkNotNull(consumerSecret);
// Preconditions.checkNotNull(accessToken);
// Preconditions.checkNotNull(accessTokenSecret);
// return new TwitterTemplate(consumerKey, consumerSecret, accessToken, accessTokenSecret);
// }
// }
// Path: opentipbot-webapp/src/main/java/opentipbot/web/config/OpenTipBotApplicationContext.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.*;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.env.Environment;
import opentipbot.persistence.config.PersistenceContext;
import opentipbot.service.config.ServiceSocialConfig;
package opentipbot.web.config;
/**
* @author Gilles Cadignan
*
* Opentipbot application conctext declaring message source ressource bundle
* and Property Placeholder
*/
@Configuration
@ComponentScan(basePackages = {
"opentipbot.service"
}) | @Import({WebAppContext.class, PersistenceContext.class, SocialContext.class, ServiceSocialConfig.class}) |
gill3s/opentipbot | opentipbot-service/src/test/java/opentipbot/service/OpenTipBotUserServiceTest.java | // Path: opentipbot-persistence/src/main/java/opentipbot/persistence/model/OpenTipBotUser.java
// @Entity
// @Table(name = "opentipbot_user")
// /**
// * @author Gilles Cadignan
// */
// public class OpenTipBotUser extends BaseEntity<Long>{
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String email;
// private String displayName;
// private String userName;
// private String twitterIdentifier;
// private String coinAddress;
// private String profileImageUrl;
// private String profileUrl;
//
// @Basic(fetch = FetchType.LAZY)
// private byte[] coinAddressQRCode;
//
// @Transient
// private double balance;
//
// @Transient
// private double pendingBalance;
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getCoinAddress() {
// return coinAddress;
// }
//
// public void setCoinAddress(String coinAddress) {
// this.coinAddress = coinAddress;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public String getTwitterIdentifier() {
// return twitterIdentifier;
// }
//
// public void setTwitterIdentifier(String twitterIdentifier) {
// this.twitterIdentifier = twitterIdentifier;
// }
//
// public double getBalance() {
// return balance;
// }
//
// public void setBalance(double balance) {
// this.balance = balance;
// }
//
// public String getProfileImageUrl() {
// return profileImageUrl;
// }
//
// public void setProfileImageUrl(String profileImageUrl) {
// this.profileImageUrl = profileImageUrl;
// }
//
// public byte[] getCoinAddressQRCode() {
// return coinAddressQRCode;
// }
//
// public void setCoinAddressQRCode(byte[] coinAddressQRCode) {
// this.coinAddressQRCode = coinAddressQRCode;
// }
//
// public String getProfileUrl() {
// return profileUrl;
// }
//
// public void setProfileUrl(String profileUrl) {
// this.profileUrl = profileUrl;
// }
//
// public double getPendingBalance() {
// return pendingBalance;
// }
//
// public void setPendingBalance(double pendingBalance) {
// this.pendingBalance = pendingBalance;
// }
// }
//
// Path: opentipbot-service/src/test/java/opentipbot/service/config/ServiceTestConfig.java
// @Configuration
// @ComponentScan(basePackages = {
// "opentipbot.service"
// })
// @Import({PersistenceContext.class, ServiceSocialConfig.class})
// @PropertySource("classpath:application.properties")
// public class ServiceTestConfig {
// }
//
// Path: opentipbot-service/src/main/java/opentipbot/service/exception/OpenTipBotServiceException.java
// public class OpenTipBotServiceException extends Exception {
//
// //the opentipbotCommand object which has generated this exception
// private OpenTipBotCommand command;
//
// /**
// * Build BitcoinServiceException with a message only
// * @param message
// */
// public OpenTipBotServiceException(String message) {
// super(message);
// }
//
// /**
// * Build BitcoinServiceException with message and cause
// * @param message
// * @param cause
// */
// public OpenTipBotServiceException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * Build BitcoinServiceException with message and specific BitcoinServiceException fields
// * @param message
// * @param command
// */
// public OpenTipBotServiceException(String message, OpenTipBotCommand command) {
// super(message);
// this.command = command;
// }
//
// /**
// * Build BitcoinServiceException with message, cause and specific BitcoinServiceException fields
// * @param message
// * @param cause
// * @param command
// */
// public OpenTipBotServiceException(String message, Throwable cause, OpenTipBotCommand command) {
// super(message, cause);
// this.command = command;
// }
//
// // Getters and setters
// //********************
//
//
// public OpenTipBotCommand getCommand() {
// return command;
// }
//
// public void setCommand(OpenTipBotCommand command) {
// this.command = command;
// }
// }
| import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
import opentipbot.persistence.model.OpenTipBotUser;
import opentipbot.service.config.ServiceTestConfig;
import opentipbot.service.exception.OpenTipBotServiceException; | package opentipbot.service;
/**
* @author Gilles Cadignan
*/
@ContextConfiguration(classes = ServiceTestConfig.class)
@Transactional
@TransactionConfiguration(transactionManager="transactionManager", defaultRollback=true)
@RunWith(SpringJUnit4ClassRunner.class)
public class OpenTipBotUserServiceTest extends AbstractTransactionalJUnit4SpringContextTests
{
@Autowired
protected OpenTipBotUserService opentipbotUserService;
@Test
public void createNewOpenTipBotUser()
{ | // Path: opentipbot-persistence/src/main/java/opentipbot/persistence/model/OpenTipBotUser.java
// @Entity
// @Table(name = "opentipbot_user")
// /**
// * @author Gilles Cadignan
// */
// public class OpenTipBotUser extends BaseEntity<Long>{
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String email;
// private String displayName;
// private String userName;
// private String twitterIdentifier;
// private String coinAddress;
// private String profileImageUrl;
// private String profileUrl;
//
// @Basic(fetch = FetchType.LAZY)
// private byte[] coinAddressQRCode;
//
// @Transient
// private double balance;
//
// @Transient
// private double pendingBalance;
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getCoinAddress() {
// return coinAddress;
// }
//
// public void setCoinAddress(String coinAddress) {
// this.coinAddress = coinAddress;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public String getTwitterIdentifier() {
// return twitterIdentifier;
// }
//
// public void setTwitterIdentifier(String twitterIdentifier) {
// this.twitterIdentifier = twitterIdentifier;
// }
//
// public double getBalance() {
// return balance;
// }
//
// public void setBalance(double balance) {
// this.balance = balance;
// }
//
// public String getProfileImageUrl() {
// return profileImageUrl;
// }
//
// public void setProfileImageUrl(String profileImageUrl) {
// this.profileImageUrl = profileImageUrl;
// }
//
// public byte[] getCoinAddressQRCode() {
// return coinAddressQRCode;
// }
//
// public void setCoinAddressQRCode(byte[] coinAddressQRCode) {
// this.coinAddressQRCode = coinAddressQRCode;
// }
//
// public String getProfileUrl() {
// return profileUrl;
// }
//
// public void setProfileUrl(String profileUrl) {
// this.profileUrl = profileUrl;
// }
//
// public double getPendingBalance() {
// return pendingBalance;
// }
//
// public void setPendingBalance(double pendingBalance) {
// this.pendingBalance = pendingBalance;
// }
// }
//
// Path: opentipbot-service/src/test/java/opentipbot/service/config/ServiceTestConfig.java
// @Configuration
// @ComponentScan(basePackages = {
// "opentipbot.service"
// })
// @Import({PersistenceContext.class, ServiceSocialConfig.class})
// @PropertySource("classpath:application.properties")
// public class ServiceTestConfig {
// }
//
// Path: opentipbot-service/src/main/java/opentipbot/service/exception/OpenTipBotServiceException.java
// public class OpenTipBotServiceException extends Exception {
//
// //the opentipbotCommand object which has generated this exception
// private OpenTipBotCommand command;
//
// /**
// * Build BitcoinServiceException with a message only
// * @param message
// */
// public OpenTipBotServiceException(String message) {
// super(message);
// }
//
// /**
// * Build BitcoinServiceException with message and cause
// * @param message
// * @param cause
// */
// public OpenTipBotServiceException(String message, Throwable cause) {
// super(message, cause);
// }
//
// /**
// * Build BitcoinServiceException with message and specific BitcoinServiceException fields
// * @param message
// * @param command
// */
// public OpenTipBotServiceException(String message, OpenTipBotCommand command) {
// super(message);
// this.command = command;
// }
//
// /**
// * Build BitcoinServiceException with message, cause and specific BitcoinServiceException fields
// * @param message
// * @param cause
// * @param command
// */
// public OpenTipBotServiceException(String message, Throwable cause, OpenTipBotCommand command) {
// super(message, cause);
// this.command = command;
// }
//
// // Getters and setters
// //********************
//
//
// public OpenTipBotCommand getCommand() {
// return command;
// }
//
// public void setCommand(OpenTipBotCommand command) {
// this.command = command;
// }
// }
// Path: opentipbot-service/src/test/java/opentipbot/service/OpenTipBotUserServiceTest.java
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
import opentipbot.persistence.model.OpenTipBotUser;
import opentipbot.service.config.ServiceTestConfig;
import opentipbot.service.exception.OpenTipBotServiceException;
package opentipbot.service;
/**
* @author Gilles Cadignan
*/
@ContextConfiguration(classes = ServiceTestConfig.class)
@Transactional
@TransactionConfiguration(transactionManager="transactionManager", defaultRollback=true)
@RunWith(SpringJUnit4ClassRunner.class)
public class OpenTipBotUserServiceTest extends AbstractTransactionalJUnit4SpringContextTests
{
@Autowired
protected OpenTipBotUserService opentipbotUserService;
@Test
public void createNewOpenTipBotUser()
{ | OpenTipBotUser opentipbotUser = new OpenTipBotUser(); |
gill3s/opentipbot | opentipbot-json-rpc-client/src/main/java/opentipbot/jsonrpcclient/ConfirmedPaymentListener.java | // Path: opentipbot-json-rpc-client/src/main/java/opentipbot/jsonrpcclient/Bitcoin.java
// public static interface Transaction {
// public String account();
// public String address();
// public String category();
// public double amount();
// public double fee();
// public int confirmations();
// public String blockHash();
// public int blockIndex();
// public Date blockTime();
// public String txId();
// public Date time();
// public Date timeReceived();
// public String comment();
// public String commentTo();
//
// public RawTransaction raw();
// }
| import java.util.Set;
import opentipbot.jsonrpcclient.Bitcoin.Transaction;
import java.util.Collections;
import java.util.HashSet; | /*
* Copyright (c) 2013, Mikhail Yevchenko. All rights reserved. PROPRIETARY/CONFIDENTIAL.
*/
package opentipbot.jsonrpcclient;
/**
*
* @author Gilles Cadignan
*/
public abstract class ConfirmedPaymentListener extends SimpleBitcoinPaymentListener {
public int minConf;
public ConfirmedPaymentListener(int minConf) {
this.minConf = minConf;
}
public ConfirmedPaymentListener() {
this(6);
}
protected Set<String> processed = Collections.synchronizedSet(new HashSet<String>());
protected boolean markProcess(String txId) {
return processed.add(txId);
}
@Override | // Path: opentipbot-json-rpc-client/src/main/java/opentipbot/jsonrpcclient/Bitcoin.java
// public static interface Transaction {
// public String account();
// public String address();
// public String category();
// public double amount();
// public double fee();
// public int confirmations();
// public String blockHash();
// public int blockIndex();
// public Date blockTime();
// public String txId();
// public Date time();
// public Date timeReceived();
// public String comment();
// public String commentTo();
//
// public RawTransaction raw();
// }
// Path: opentipbot-json-rpc-client/src/main/java/opentipbot/jsonrpcclient/ConfirmedPaymentListener.java
import java.util.Set;
import opentipbot.jsonrpcclient.Bitcoin.Transaction;
import java.util.Collections;
import java.util.HashSet;
/*
* Copyright (c) 2013, Mikhail Yevchenko. All rights reserved. PROPRIETARY/CONFIDENTIAL.
*/
package opentipbot.jsonrpcclient;
/**
*
* @author Gilles Cadignan
*/
public abstract class ConfirmedPaymentListener extends SimpleBitcoinPaymentListener {
public int minConf;
public ConfirmedPaymentListener(int minConf) {
this.minConf = minConf;
}
public ConfirmedPaymentListener() {
this(6);
}
protected Set<String> processed = Collections.synchronizedSet(new HashSet<String>());
protected boolean markProcess(String txId) {
return processed.add(txId);
}
@Override | public void transaction(Transaction transaction) { |
gill3s/opentipbot | opentipbot-json-rpc-client/src/main/java/opentipbot/jsonrpcclient/SimpleBitcoinPaymentListener.java | // Path: opentipbot-json-rpc-client/src/main/java/opentipbot/jsonrpcclient/Bitcoin.java
// public static interface Transaction {
// public String account();
// public String address();
// public String category();
// public double amount();
// public double fee();
// public int confirmations();
// public String blockHash();
// public int blockIndex();
// public Date blockTime();
// public String txId();
// public Date time();
// public Date timeReceived();
// public String comment();
// public String commentTo();
//
// public RawTransaction raw();
// }
| import opentipbot.jsonrpcclient.Bitcoin.Transaction; | /*
* Copyright (c) 2013, Mikhail Yevchenko. All rights reserved. PROPRIETARY/CONFIDENTIAL.
*/
package opentipbot.jsonrpcclient;
/**
*
* @author Gilles Cadignan
*/
public class SimpleBitcoinPaymentListener implements BitcoinPaymentListener {
@Override
public void block(String blockHash) {
}
@Override | // Path: opentipbot-json-rpc-client/src/main/java/opentipbot/jsonrpcclient/Bitcoin.java
// public static interface Transaction {
// public String account();
// public String address();
// public String category();
// public double amount();
// public double fee();
// public int confirmations();
// public String blockHash();
// public int blockIndex();
// public Date blockTime();
// public String txId();
// public Date time();
// public Date timeReceived();
// public String comment();
// public String commentTo();
//
// public RawTransaction raw();
// }
// Path: opentipbot-json-rpc-client/src/main/java/opentipbot/jsonrpcclient/SimpleBitcoinPaymentListener.java
import opentipbot.jsonrpcclient.Bitcoin.Transaction;
/*
* Copyright (c) 2013, Mikhail Yevchenko. All rights reserved. PROPRIETARY/CONFIDENTIAL.
*/
package opentipbot.jsonrpcclient;
/**
*
* @author Gilles Cadignan
*/
public class SimpleBitcoinPaymentListener implements BitcoinPaymentListener {
@Override
public void block(String blockHash) {
}
@Override | public void transaction(Transaction transaction) { |
christophersmith/summer-mqtt | summer-mqtt-core/src/test/java/com/github/christophersmith/summer/mqtt/core/util/MqttHeaderHelperTest.java | // Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/MqttQualityOfService.java
// public enum MqttQualityOfService
// {
// /**
// * Represents a Quality of Service (Qos) of 0, for At Most Once.
// */
// QOS_0(0),
// /**
// * Represents a Quality of Service (Qos) of 1, for At Least Once.
// */
// QOS_1(1),
// /**
// * Represents a Quality of Service (Qos) of 2, for Exactly Once.
// */
// QOS_2(2);
//
// private transient final int levelIdentifier;
//
// MqttQualityOfService(final int levelIdentifier)
// {
// this.levelIdentifier = levelIdentifier;
// }
//
// /**
// * Returns an {@code int} value representation of the Quality of Service Level for this
// * instance.
// *
// * @return the Level Identifier
// */
// public int getLevelIdentifier()
// {
// return levelIdentifier;
// }
//
// /**
// * Finds the {@link MqttQualityOfService} instance that matches the {@code levelIdentifier}
// * value.
// * <p>
// * If the {@code levelIdentifier} does not match a {@code MqttQualityOfService} instance, a
// * default value of {@link MqttQualityOfService#QOS_0} will be returned.
// *
// * @param levelIdentifier the Level Identifier to search by
// * @return a {@code MqttQualityOfService} value
// */
// public static final MqttQualityOfService findByLevelIdentifier(final int levelIdentifier)
// {
// MqttQualityOfService record = QOS_0;
// for (MqttQualityOfService value : values())
// {
// if (value.getLevelIdentifier() == levelIdentifier)
// {
// record = value;
// break;
// }
// }
// return record;
// }
// }
| import org.junit.Test;
import org.springframework.messaging.support.MessageBuilder;
import com.github.christophersmith.summer.mqtt.core.MqttQualityOfService;
import org.junit.Assert; | /*******************************************************************************
* Copyright (c) 2019 Christopher Smith - https://github.com/christophersmith
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.github.christophersmith.summer.mqtt.core.util;
public class MqttHeaderHelperTest
{
private static final String TOPIC = "status/client";
@Test
public void createDefaultInstance()
{
new MqttHeaderHelper();
}
@Test
public void testTopicHeader()
{
Assert.assertNull(MqttHeaderHelper.getTopicHeaderValue(null));
MessageBuilder<String> builder = MessageBuilder.withPayload("See topic header");
Assert.assertNull(MqttHeaderHelper.getTopicHeaderValue(builder.build()));
builder.setHeader(MqttHeaderHelper.TOPIC, TOPIC);
Assert.assertEquals(TOPIC, MqttHeaderHelper.getTopicHeaderValue(builder.build()));
}
@Test
public void testMqttQualityOfServiceHeader()
{ | // Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/MqttQualityOfService.java
// public enum MqttQualityOfService
// {
// /**
// * Represents a Quality of Service (Qos) of 0, for At Most Once.
// */
// QOS_0(0),
// /**
// * Represents a Quality of Service (Qos) of 1, for At Least Once.
// */
// QOS_1(1),
// /**
// * Represents a Quality of Service (Qos) of 2, for Exactly Once.
// */
// QOS_2(2);
//
// private transient final int levelIdentifier;
//
// MqttQualityOfService(final int levelIdentifier)
// {
// this.levelIdentifier = levelIdentifier;
// }
//
// /**
// * Returns an {@code int} value representation of the Quality of Service Level for this
// * instance.
// *
// * @return the Level Identifier
// */
// public int getLevelIdentifier()
// {
// return levelIdentifier;
// }
//
// /**
// * Finds the {@link MqttQualityOfService} instance that matches the {@code levelIdentifier}
// * value.
// * <p>
// * If the {@code levelIdentifier} does not match a {@code MqttQualityOfService} instance, a
// * default value of {@link MqttQualityOfService#QOS_0} will be returned.
// *
// * @param levelIdentifier the Level Identifier to search by
// * @return a {@code MqttQualityOfService} value
// */
// public static final MqttQualityOfService findByLevelIdentifier(final int levelIdentifier)
// {
// MqttQualityOfService record = QOS_0;
// for (MqttQualityOfService value : values())
// {
// if (value.getLevelIdentifier() == levelIdentifier)
// {
// record = value;
// break;
// }
// }
// return record;
// }
// }
// Path: summer-mqtt-core/src/test/java/com/github/christophersmith/summer/mqtt/core/util/MqttHeaderHelperTest.java
import org.junit.Test;
import org.springframework.messaging.support.MessageBuilder;
import com.github.christophersmith.summer.mqtt.core.MqttQualityOfService;
import org.junit.Assert;
/*******************************************************************************
* Copyright (c) 2019 Christopher Smith - https://github.com/christophersmith
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.github.christophersmith.summer.mqtt.core.util;
public class MqttHeaderHelperTest
{
private static final String TOPIC = "status/client";
@Test
public void createDefaultInstance()
{
new MqttHeaderHelper();
}
@Test
public void testTopicHeader()
{
Assert.assertNull(MqttHeaderHelper.getTopicHeaderValue(null));
MessageBuilder<String> builder = MessageBuilder.withPayload("See topic header");
Assert.assertNull(MqttHeaderHelper.getTopicHeaderValue(builder.build()));
builder.setHeader(MqttHeaderHelper.TOPIC, TOPIC);
Assert.assertEquals(TOPIC, MqttHeaderHelper.getTopicHeaderValue(builder.build()));
}
@Test
public void testMqttQualityOfServiceHeader()
{ | Assert.assertEquals(MqttQualityOfService.QOS_2, |
christophersmith/summer-mqtt | summer-mqtt-core/src/test/java/com/github/christophersmith/summer/mqtt/core/util/TopicSubscriptionHelperTest.java | // Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/MqttQualityOfService.java
// public enum MqttQualityOfService
// {
// /**
// * Represents a Quality of Service (Qos) of 0, for At Most Once.
// */
// QOS_0(0),
// /**
// * Represents a Quality of Service (Qos) of 1, for At Least Once.
// */
// QOS_1(1),
// /**
// * Represents a Quality of Service (Qos) of 2, for Exactly Once.
// */
// QOS_2(2);
//
// private transient final int levelIdentifier;
//
// MqttQualityOfService(final int levelIdentifier)
// {
// this.levelIdentifier = levelIdentifier;
// }
//
// /**
// * Returns an {@code int} value representation of the Quality of Service Level for this
// * instance.
// *
// * @return the Level Identifier
// */
// public int getLevelIdentifier()
// {
// return levelIdentifier;
// }
//
// /**
// * Finds the {@link MqttQualityOfService} instance that matches the {@code levelIdentifier}
// * value.
// * <p>
// * If the {@code levelIdentifier} does not match a {@code MqttQualityOfService} instance, a
// * default value of {@link MqttQualityOfService#QOS_0} will be returned.
// *
// * @param levelIdentifier the Level Identifier to search by
// * @return a {@code MqttQualityOfService} value
// */
// public static final MqttQualityOfService findByLevelIdentifier(final int levelIdentifier)
// {
// MqttQualityOfService record = QOS_0;
// for (MqttQualityOfService value : values())
// {
// if (value.getLevelIdentifier() == levelIdentifier)
// {
// record = value;
// break;
// }
// }
// return record;
// }
// }
//
// Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/TopicSubscription.java
// public final class TopicSubscription
// {
// private transient final String topicFilter;
// private transient final MqttQualityOfService qualityOfService;
// private boolean subscribed;
//
// /**
// * Creates a new {@code TopicSubscription} object that represents the Topic Filter and
// * subscription information.
// *
// * @param topicFilter the Topic Filter to subscribe to, which can include wildcards
// * @param qualityOfService the maximum QoS to use for this Topic Filter
// *
// * @throws IllegalArgumentException if the {@code topicFilter} is null or empty, or if the
// * {@code qualityOfService} is null
// */
// public TopicSubscription(final String topicFilter, final MqttQualityOfService qualityOfService)
// {
// Assert.hasText(topicFilter, "'topicFilter' must be set!");
// Assert.notNull(qualityOfService, "'qualityOfService' must be set!");
// this.topicFilter = topicFilter;
// this.qualityOfService = qualityOfService;
// }
//
// /**
// * Returns the Topic Filter for this instance.
// *
// * @return the Topic Filter for this instance
// */
// public String getTopicFilter()
// {
// return topicFilter;
// }
//
// /**
// * Returns the {@link MqttQualityOfService} for this instance.
// *
// * @return a {@link MqttQualityOfService} value
// */
// public MqttQualityOfService getQualityOfService()
// {
// return qualityOfService;
// }
//
// /**
// * Returns whether the Topic Filter is subscribed to.
// *
// * @return true if the Topic Filter is subscribed to, otherwise false
// */
// public boolean isSubscribed()
// {
// return subscribed;
// }
//
// /**
// * Sets whether the Topic Filter is currently subscribed to.
// *
// * @param subscribed true if the Topic Filter is subscribed to, otherwise false
// */
// public void setSubscribed(boolean subscribed)
// {
// this.subscribed = subscribed;
// }
//
// /**
// * Returns a deep copy of this instance.
// */
// @Override
// public TopicSubscription clone()
// {
// TopicSubscription record = new TopicSubscription(this.topicFilter, this.qualityOfService);
// record.setSubscribed(this.subscribed);
// return record;
// }
// }
| import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.github.christophersmith.summer.mqtt.core.MqttQualityOfService;
import com.github.christophersmith.summer.mqtt.core.TopicSubscription; | /*******************************************************************************
* Copyright (c) 2019 Christopher Smith - https://github.com/christophersmith
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.github.christophersmith.summer.mqtt.core.util;
public class TopicSubscriptionHelperTest
{
private static final String TOPIC_FILTER_1 = "status/client";
private static final String TOPIC_FILTER_2 = "client/delivered"; | // Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/MqttQualityOfService.java
// public enum MqttQualityOfService
// {
// /**
// * Represents a Quality of Service (Qos) of 0, for At Most Once.
// */
// QOS_0(0),
// /**
// * Represents a Quality of Service (Qos) of 1, for At Least Once.
// */
// QOS_1(1),
// /**
// * Represents a Quality of Service (Qos) of 2, for Exactly Once.
// */
// QOS_2(2);
//
// private transient final int levelIdentifier;
//
// MqttQualityOfService(final int levelIdentifier)
// {
// this.levelIdentifier = levelIdentifier;
// }
//
// /**
// * Returns an {@code int} value representation of the Quality of Service Level for this
// * instance.
// *
// * @return the Level Identifier
// */
// public int getLevelIdentifier()
// {
// return levelIdentifier;
// }
//
// /**
// * Finds the {@link MqttQualityOfService} instance that matches the {@code levelIdentifier}
// * value.
// * <p>
// * If the {@code levelIdentifier} does not match a {@code MqttQualityOfService} instance, a
// * default value of {@link MqttQualityOfService#QOS_0} will be returned.
// *
// * @param levelIdentifier the Level Identifier to search by
// * @return a {@code MqttQualityOfService} value
// */
// public static final MqttQualityOfService findByLevelIdentifier(final int levelIdentifier)
// {
// MqttQualityOfService record = QOS_0;
// for (MqttQualityOfService value : values())
// {
// if (value.getLevelIdentifier() == levelIdentifier)
// {
// record = value;
// break;
// }
// }
// return record;
// }
// }
//
// Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/TopicSubscription.java
// public final class TopicSubscription
// {
// private transient final String topicFilter;
// private transient final MqttQualityOfService qualityOfService;
// private boolean subscribed;
//
// /**
// * Creates a new {@code TopicSubscription} object that represents the Topic Filter and
// * subscription information.
// *
// * @param topicFilter the Topic Filter to subscribe to, which can include wildcards
// * @param qualityOfService the maximum QoS to use for this Topic Filter
// *
// * @throws IllegalArgumentException if the {@code topicFilter} is null or empty, or if the
// * {@code qualityOfService} is null
// */
// public TopicSubscription(final String topicFilter, final MqttQualityOfService qualityOfService)
// {
// Assert.hasText(topicFilter, "'topicFilter' must be set!");
// Assert.notNull(qualityOfService, "'qualityOfService' must be set!");
// this.topicFilter = topicFilter;
// this.qualityOfService = qualityOfService;
// }
//
// /**
// * Returns the Topic Filter for this instance.
// *
// * @return the Topic Filter for this instance
// */
// public String getTopicFilter()
// {
// return topicFilter;
// }
//
// /**
// * Returns the {@link MqttQualityOfService} for this instance.
// *
// * @return a {@link MqttQualityOfService} value
// */
// public MqttQualityOfService getQualityOfService()
// {
// return qualityOfService;
// }
//
// /**
// * Returns whether the Topic Filter is subscribed to.
// *
// * @return true if the Topic Filter is subscribed to, otherwise false
// */
// public boolean isSubscribed()
// {
// return subscribed;
// }
//
// /**
// * Sets whether the Topic Filter is currently subscribed to.
// *
// * @param subscribed true if the Topic Filter is subscribed to, otherwise false
// */
// public void setSubscribed(boolean subscribed)
// {
// this.subscribed = subscribed;
// }
//
// /**
// * Returns a deep copy of this instance.
// */
// @Override
// public TopicSubscription clone()
// {
// TopicSubscription record = new TopicSubscription(this.topicFilter, this.qualityOfService);
// record.setSubscribed(this.subscribed);
// return record;
// }
// }
// Path: summer-mqtt-core/src/test/java/com/github/christophersmith/summer/mqtt/core/util/TopicSubscriptionHelperTest.java
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.github.christophersmith.summer.mqtt.core.MqttQualityOfService;
import com.github.christophersmith.summer.mqtt.core.TopicSubscription;
/*******************************************************************************
* Copyright (c) 2019 Christopher Smith - https://github.com/christophersmith
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.github.christophersmith.summer.mqtt.core.util;
public class TopicSubscriptionHelperTest
{
private static final String TOPIC_FILTER_1 = "status/client";
private static final String TOPIC_FILTER_2 = "client/delivered"; | private List<TopicSubscription> topicSubscriptions = new ArrayList<TopicSubscription>(); |
christophersmith/summer-mqtt | summer-mqtt-core/src/test/java/com/github/christophersmith/summer/mqtt/core/util/TopicSubscriptionHelperTest.java | // Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/MqttQualityOfService.java
// public enum MqttQualityOfService
// {
// /**
// * Represents a Quality of Service (Qos) of 0, for At Most Once.
// */
// QOS_0(0),
// /**
// * Represents a Quality of Service (Qos) of 1, for At Least Once.
// */
// QOS_1(1),
// /**
// * Represents a Quality of Service (Qos) of 2, for Exactly Once.
// */
// QOS_2(2);
//
// private transient final int levelIdentifier;
//
// MqttQualityOfService(final int levelIdentifier)
// {
// this.levelIdentifier = levelIdentifier;
// }
//
// /**
// * Returns an {@code int} value representation of the Quality of Service Level for this
// * instance.
// *
// * @return the Level Identifier
// */
// public int getLevelIdentifier()
// {
// return levelIdentifier;
// }
//
// /**
// * Finds the {@link MqttQualityOfService} instance that matches the {@code levelIdentifier}
// * value.
// * <p>
// * If the {@code levelIdentifier} does not match a {@code MqttQualityOfService} instance, a
// * default value of {@link MqttQualityOfService#QOS_0} will be returned.
// *
// * @param levelIdentifier the Level Identifier to search by
// * @return a {@code MqttQualityOfService} value
// */
// public static final MqttQualityOfService findByLevelIdentifier(final int levelIdentifier)
// {
// MqttQualityOfService record = QOS_0;
// for (MqttQualityOfService value : values())
// {
// if (value.getLevelIdentifier() == levelIdentifier)
// {
// record = value;
// break;
// }
// }
// return record;
// }
// }
//
// Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/TopicSubscription.java
// public final class TopicSubscription
// {
// private transient final String topicFilter;
// private transient final MqttQualityOfService qualityOfService;
// private boolean subscribed;
//
// /**
// * Creates a new {@code TopicSubscription} object that represents the Topic Filter and
// * subscription information.
// *
// * @param topicFilter the Topic Filter to subscribe to, which can include wildcards
// * @param qualityOfService the maximum QoS to use for this Topic Filter
// *
// * @throws IllegalArgumentException if the {@code topicFilter} is null or empty, or if the
// * {@code qualityOfService} is null
// */
// public TopicSubscription(final String topicFilter, final MqttQualityOfService qualityOfService)
// {
// Assert.hasText(topicFilter, "'topicFilter' must be set!");
// Assert.notNull(qualityOfService, "'qualityOfService' must be set!");
// this.topicFilter = topicFilter;
// this.qualityOfService = qualityOfService;
// }
//
// /**
// * Returns the Topic Filter for this instance.
// *
// * @return the Topic Filter for this instance
// */
// public String getTopicFilter()
// {
// return topicFilter;
// }
//
// /**
// * Returns the {@link MqttQualityOfService} for this instance.
// *
// * @return a {@link MqttQualityOfService} value
// */
// public MqttQualityOfService getQualityOfService()
// {
// return qualityOfService;
// }
//
// /**
// * Returns whether the Topic Filter is subscribed to.
// *
// * @return true if the Topic Filter is subscribed to, otherwise false
// */
// public boolean isSubscribed()
// {
// return subscribed;
// }
//
// /**
// * Sets whether the Topic Filter is currently subscribed to.
// *
// * @param subscribed true if the Topic Filter is subscribed to, otherwise false
// */
// public void setSubscribed(boolean subscribed)
// {
// this.subscribed = subscribed;
// }
//
// /**
// * Returns a deep copy of this instance.
// */
// @Override
// public TopicSubscription clone()
// {
// TopicSubscription record = new TopicSubscription(this.topicFilter, this.qualityOfService);
// record.setSubscribed(this.subscribed);
// return record;
// }
// }
| import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.github.christophersmith.summer.mqtt.core.MqttQualityOfService;
import com.github.christophersmith.summer.mqtt.core.TopicSubscription; | /*******************************************************************************
* Copyright (c) 2019 Christopher Smith - https://github.com/christophersmith
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.github.christophersmith.summer.mqtt.core.util;
public class TopicSubscriptionHelperTest
{
private static final String TOPIC_FILTER_1 = "status/client";
private static final String TOPIC_FILTER_2 = "client/delivered";
private List<TopicSubscription> topicSubscriptions = new ArrayList<TopicSubscription>();
@Before
public void initialize()
{
new TopicSubscriptionHelper();
topicSubscriptions.clear(); | // Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/MqttQualityOfService.java
// public enum MqttQualityOfService
// {
// /**
// * Represents a Quality of Service (Qos) of 0, for At Most Once.
// */
// QOS_0(0),
// /**
// * Represents a Quality of Service (Qos) of 1, for At Least Once.
// */
// QOS_1(1),
// /**
// * Represents a Quality of Service (Qos) of 2, for Exactly Once.
// */
// QOS_2(2);
//
// private transient final int levelIdentifier;
//
// MqttQualityOfService(final int levelIdentifier)
// {
// this.levelIdentifier = levelIdentifier;
// }
//
// /**
// * Returns an {@code int} value representation of the Quality of Service Level for this
// * instance.
// *
// * @return the Level Identifier
// */
// public int getLevelIdentifier()
// {
// return levelIdentifier;
// }
//
// /**
// * Finds the {@link MqttQualityOfService} instance that matches the {@code levelIdentifier}
// * value.
// * <p>
// * If the {@code levelIdentifier} does not match a {@code MqttQualityOfService} instance, a
// * default value of {@link MqttQualityOfService#QOS_0} will be returned.
// *
// * @param levelIdentifier the Level Identifier to search by
// * @return a {@code MqttQualityOfService} value
// */
// public static final MqttQualityOfService findByLevelIdentifier(final int levelIdentifier)
// {
// MqttQualityOfService record = QOS_0;
// for (MqttQualityOfService value : values())
// {
// if (value.getLevelIdentifier() == levelIdentifier)
// {
// record = value;
// break;
// }
// }
// return record;
// }
// }
//
// Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/TopicSubscription.java
// public final class TopicSubscription
// {
// private transient final String topicFilter;
// private transient final MqttQualityOfService qualityOfService;
// private boolean subscribed;
//
// /**
// * Creates a new {@code TopicSubscription} object that represents the Topic Filter and
// * subscription information.
// *
// * @param topicFilter the Topic Filter to subscribe to, which can include wildcards
// * @param qualityOfService the maximum QoS to use for this Topic Filter
// *
// * @throws IllegalArgumentException if the {@code topicFilter} is null or empty, or if the
// * {@code qualityOfService} is null
// */
// public TopicSubscription(final String topicFilter, final MqttQualityOfService qualityOfService)
// {
// Assert.hasText(topicFilter, "'topicFilter' must be set!");
// Assert.notNull(qualityOfService, "'qualityOfService' must be set!");
// this.topicFilter = topicFilter;
// this.qualityOfService = qualityOfService;
// }
//
// /**
// * Returns the Topic Filter for this instance.
// *
// * @return the Topic Filter for this instance
// */
// public String getTopicFilter()
// {
// return topicFilter;
// }
//
// /**
// * Returns the {@link MqttQualityOfService} for this instance.
// *
// * @return a {@link MqttQualityOfService} value
// */
// public MqttQualityOfService getQualityOfService()
// {
// return qualityOfService;
// }
//
// /**
// * Returns whether the Topic Filter is subscribed to.
// *
// * @return true if the Topic Filter is subscribed to, otherwise false
// */
// public boolean isSubscribed()
// {
// return subscribed;
// }
//
// /**
// * Sets whether the Topic Filter is currently subscribed to.
// *
// * @param subscribed true if the Topic Filter is subscribed to, otherwise false
// */
// public void setSubscribed(boolean subscribed)
// {
// this.subscribed = subscribed;
// }
//
// /**
// * Returns a deep copy of this instance.
// */
// @Override
// public TopicSubscription clone()
// {
// TopicSubscription record = new TopicSubscription(this.topicFilter, this.qualityOfService);
// record.setSubscribed(this.subscribed);
// return record;
// }
// }
// Path: summer-mqtt-core/src/test/java/com/github/christophersmith/summer/mqtt/core/util/TopicSubscriptionHelperTest.java
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.github.christophersmith.summer.mqtt.core.MqttQualityOfService;
import com.github.christophersmith.summer.mqtt.core.TopicSubscription;
/*******************************************************************************
* Copyright (c) 2019 Christopher Smith - https://github.com/christophersmith
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.github.christophersmith.summer.mqtt.core.util;
public class TopicSubscriptionHelperTest
{
private static final String TOPIC_FILTER_1 = "status/client";
private static final String TOPIC_FILTER_2 = "client/delivered";
private List<TopicSubscription> topicSubscriptions = new ArrayList<TopicSubscription>();
@Before
public void initialize()
{
new TopicSubscriptionHelper();
topicSubscriptions.clear(); | topicSubscriptions.add(new TopicSubscription(TOPIC_FILTER_1, MqttQualityOfService.QOS_0)); |
christophersmith/summer-mqtt | summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/util/TopicSubscriptionHelper.java | // Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/TopicSubscription.java
// public final class TopicSubscription
// {
// private transient final String topicFilter;
// private transient final MqttQualityOfService qualityOfService;
// private boolean subscribed;
//
// /**
// * Creates a new {@code TopicSubscription} object that represents the Topic Filter and
// * subscription information.
// *
// * @param topicFilter the Topic Filter to subscribe to, which can include wildcards
// * @param qualityOfService the maximum QoS to use for this Topic Filter
// *
// * @throws IllegalArgumentException if the {@code topicFilter} is null or empty, or if the
// * {@code qualityOfService} is null
// */
// public TopicSubscription(final String topicFilter, final MqttQualityOfService qualityOfService)
// {
// Assert.hasText(topicFilter, "'topicFilter' must be set!");
// Assert.notNull(qualityOfService, "'qualityOfService' must be set!");
// this.topicFilter = topicFilter;
// this.qualityOfService = qualityOfService;
// }
//
// /**
// * Returns the Topic Filter for this instance.
// *
// * @return the Topic Filter for this instance
// */
// public String getTopicFilter()
// {
// return topicFilter;
// }
//
// /**
// * Returns the {@link MqttQualityOfService} for this instance.
// *
// * @return a {@link MqttQualityOfService} value
// */
// public MqttQualityOfService getQualityOfService()
// {
// return qualityOfService;
// }
//
// /**
// * Returns whether the Topic Filter is subscribed to.
// *
// * @return true if the Topic Filter is subscribed to, otherwise false
// */
// public boolean isSubscribed()
// {
// return subscribed;
// }
//
// /**
// * Sets whether the Topic Filter is currently subscribed to.
// *
// * @param subscribed true if the Topic Filter is subscribed to, otherwise false
// */
// public void setSubscribed(boolean subscribed)
// {
// this.subscribed = subscribed;
// }
//
// /**
// * Returns a deep copy of this instance.
// */
// @Override
// public TopicSubscription clone()
// {
// TopicSubscription record = new TopicSubscription(this.topicFilter, this.qualityOfService);
// record.setSubscribed(this.subscribed);
// return record;
// }
// }
| import java.util.ArrayList;
import java.util.List;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import com.github.christophersmith.summer.mqtt.core.TopicSubscription; | /*******************************************************************************
* Copyright (c) 2019 Christopher Smith - https://github.com/christophersmith
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.github.christophersmith.summer.mqtt.core.util;
/**
* A {@link TopicSubscription} utility class that provides common functionality for dealing with
* Topics.
*/
public final class TopicSubscriptionHelper
{
/**
* Finds the {@link TopicSubscription} object from the {@code topicSubscriptions} list that
* matches the {@code topicFilter}.
* <p>
* The search on the {@code topicFilter} is case-sensitive. If a matching
* {@link TopicSubscription} value could not be found, a null value will be returned.
*
* @param topicFilter the Topic Filter to search for
* @param topicSubscriptions a {@link List} of {@link TopicSubscription} objects for search
*
* @return a {@link TopicSubscription} object, or null if not found
*/ | // Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/TopicSubscription.java
// public final class TopicSubscription
// {
// private transient final String topicFilter;
// private transient final MqttQualityOfService qualityOfService;
// private boolean subscribed;
//
// /**
// * Creates a new {@code TopicSubscription} object that represents the Topic Filter and
// * subscription information.
// *
// * @param topicFilter the Topic Filter to subscribe to, which can include wildcards
// * @param qualityOfService the maximum QoS to use for this Topic Filter
// *
// * @throws IllegalArgumentException if the {@code topicFilter} is null or empty, or if the
// * {@code qualityOfService} is null
// */
// public TopicSubscription(final String topicFilter, final MqttQualityOfService qualityOfService)
// {
// Assert.hasText(topicFilter, "'topicFilter' must be set!");
// Assert.notNull(qualityOfService, "'qualityOfService' must be set!");
// this.topicFilter = topicFilter;
// this.qualityOfService = qualityOfService;
// }
//
// /**
// * Returns the Topic Filter for this instance.
// *
// * @return the Topic Filter for this instance
// */
// public String getTopicFilter()
// {
// return topicFilter;
// }
//
// /**
// * Returns the {@link MqttQualityOfService} for this instance.
// *
// * @return a {@link MqttQualityOfService} value
// */
// public MqttQualityOfService getQualityOfService()
// {
// return qualityOfService;
// }
//
// /**
// * Returns whether the Topic Filter is subscribed to.
// *
// * @return true if the Topic Filter is subscribed to, otherwise false
// */
// public boolean isSubscribed()
// {
// return subscribed;
// }
//
// /**
// * Sets whether the Topic Filter is currently subscribed to.
// *
// * @param subscribed true if the Topic Filter is subscribed to, otherwise false
// */
// public void setSubscribed(boolean subscribed)
// {
// this.subscribed = subscribed;
// }
//
// /**
// * Returns a deep copy of this instance.
// */
// @Override
// public TopicSubscription clone()
// {
// TopicSubscription record = new TopicSubscription(this.topicFilter, this.qualityOfService);
// record.setSubscribed(this.subscribed);
// return record;
// }
// }
// Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/util/TopicSubscriptionHelper.java
import java.util.ArrayList;
import java.util.List;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import com.github.christophersmith.summer.mqtt.core.TopicSubscription;
/*******************************************************************************
* Copyright (c) 2019 Christopher Smith - https://github.com/christophersmith
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.github.christophersmith.summer.mqtt.core.util;
/**
* A {@link TopicSubscription} utility class that provides common functionality for dealing with
* Topics.
*/
public final class TopicSubscriptionHelper
{
/**
* Finds the {@link TopicSubscription} object from the {@code topicSubscriptions} list that
* matches the {@code topicFilter}.
* <p>
* The search on the {@code topicFilter} is case-sensitive. If a matching
* {@link TopicSubscription} value could not be found, a null value will be returned.
*
* @param topicFilter the Topic Filter to search for
* @param topicSubscriptions a {@link List} of {@link TopicSubscription} objects for search
*
* @return a {@link TopicSubscription} object, or null if not found
*/ | public static TopicSubscription findByTopicFilter(final String topicFilter, |
christophersmith/summer-mqtt | summer-mqtt-paho/src/test/java/com/github/christophersmith/summer/mqtt/paho/service/SubscribeUnsubscribeTest.java | // Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/MqttClientConnectionType.java
// public enum MqttClientConnectionType
// {
// /**
// * Represents a connection type that can only publish messages.
// */
// PUBLISHER,
// /**
// * Represents a connection type that can both publish and receive messages.
// */
// PUBSUB,
// /**
// * Represents a connection type can only receive messages.
// */
// SUBSCRIBER;
// }
//
// Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/MqttQualityOfService.java
// public enum MqttQualityOfService
// {
// /**
// * Represents a Quality of Service (Qos) of 0, for At Most Once.
// */
// QOS_0(0),
// /**
// * Represents a Quality of Service (Qos) of 1, for At Least Once.
// */
// QOS_1(1),
// /**
// * Represents a Quality of Service (Qos) of 2, for Exactly Once.
// */
// QOS_2(2);
//
// private transient final int levelIdentifier;
//
// MqttQualityOfService(final int levelIdentifier)
// {
// this.levelIdentifier = levelIdentifier;
// }
//
// /**
// * Returns an {@code int} value representation of the Quality of Service Level for this
// * instance.
// *
// * @return the Level Identifier
// */
// public int getLevelIdentifier()
// {
// return levelIdentifier;
// }
//
// /**
// * Finds the {@link MqttQualityOfService} instance that matches the {@code levelIdentifier}
// * value.
// * <p>
// * If the {@code levelIdentifier} does not match a {@code MqttQualityOfService} instance, a
// * default value of {@link MqttQualityOfService#QOS_0} will be returned.
// *
// * @param levelIdentifier the Level Identifier to search by
// * @return a {@code MqttQualityOfService} value
// */
// public static final MqttQualityOfService findByLevelIdentifier(final int levelIdentifier)
// {
// MqttQualityOfService record = QOS_0;
// for (MqttQualityOfService value : values())
// {
// if (value.getLevelIdentifier() == levelIdentifier)
// {
// record = value;
// break;
// }
// }
// return record;
// }
// }
//
// Path: summer-mqtt-paho/src/test/java/com/github/christophersmith/summer/mqtt/paho/service/util/BrokerHelper.java
// public class BrokerHelper
// {
// private static final String CLIENT_ID = MqttAsyncClient.generateClientId();
// private static final String BROKER_URI_FORMAT = "tcp://%s:%s";
// private static final String BROKER_HOST_NAME = "mqtt.eclipse.org";
// private static final int BROKER_PORT = 1883;
// private static final String PROXY_HOST_NAME = "localhost";
// private static final int PROXY_PORT = 10080;
//
// public static String getClientId()
// {
// return CLIENT_ID;
// }
//
// public static String getBrokerHostName()
// {
// return BROKER_HOST_NAME;
// }
//
// public static int getBrokerPort()
// {
// return BROKER_PORT;
// }
//
// public static String getBrokerUri()
// {
// return String.format(BROKER_URI_FORMAT, BROKER_HOST_NAME, String.valueOf(BROKER_PORT));
// }
//
// public static String getProxyHostName()
// {
// return PROXY_HOST_NAME;
// }
//
// public static int getProxyPort()
// {
// return PROXY_PORT;
// }
//
// public static String getProxyUri()
// {
// return String.format(BROKER_URI_FORMAT, PROXY_HOST_NAME, String.valueOf(PROXY_PORT));
// }
// }
| import java.io.IOException;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.netcrusher.core.reactor.NioReactor;
import org.netcrusher.tcp.TcpCrusher;
import org.netcrusher.tcp.TcpCrusherBuilder;
import com.github.christophersmith.summer.mqtt.core.MqttClientConnectionType;
import com.github.christophersmith.summer.mqtt.core.MqttQualityOfService;
import com.github.christophersmith.summer.mqtt.paho.service.util.BrokerHelper; | /*******************************************************************************
* Copyright (c) 2019 Christopher Smith - https://github.com/christophersmith
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.github.christophersmith.summer.mqtt.paho.service;
public class SubscribeUnsubscribeTest
{
private static final String EXCEPTION_MESSAGE_CANNOT_SUBSCRIBE_FORMAT = "Client ID %s is a %s and cannot subscribe or unsubscribe from Topic Filters.";
@Rule
public ExpectedException thrown = ExpectedException
.none();
@Test
public void testSubscribeBeforeStartClientSubscriber() throws MqttException
{
PahoAsyncMqttClientService service = new PahoAsyncMqttClientService( | // Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/MqttClientConnectionType.java
// public enum MqttClientConnectionType
// {
// /**
// * Represents a connection type that can only publish messages.
// */
// PUBLISHER,
// /**
// * Represents a connection type that can both publish and receive messages.
// */
// PUBSUB,
// /**
// * Represents a connection type can only receive messages.
// */
// SUBSCRIBER;
// }
//
// Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/MqttQualityOfService.java
// public enum MqttQualityOfService
// {
// /**
// * Represents a Quality of Service (Qos) of 0, for At Most Once.
// */
// QOS_0(0),
// /**
// * Represents a Quality of Service (Qos) of 1, for At Least Once.
// */
// QOS_1(1),
// /**
// * Represents a Quality of Service (Qos) of 2, for Exactly Once.
// */
// QOS_2(2);
//
// private transient final int levelIdentifier;
//
// MqttQualityOfService(final int levelIdentifier)
// {
// this.levelIdentifier = levelIdentifier;
// }
//
// /**
// * Returns an {@code int} value representation of the Quality of Service Level for this
// * instance.
// *
// * @return the Level Identifier
// */
// public int getLevelIdentifier()
// {
// return levelIdentifier;
// }
//
// /**
// * Finds the {@link MqttQualityOfService} instance that matches the {@code levelIdentifier}
// * value.
// * <p>
// * If the {@code levelIdentifier} does not match a {@code MqttQualityOfService} instance, a
// * default value of {@link MqttQualityOfService#QOS_0} will be returned.
// *
// * @param levelIdentifier the Level Identifier to search by
// * @return a {@code MqttQualityOfService} value
// */
// public static final MqttQualityOfService findByLevelIdentifier(final int levelIdentifier)
// {
// MqttQualityOfService record = QOS_0;
// for (MqttQualityOfService value : values())
// {
// if (value.getLevelIdentifier() == levelIdentifier)
// {
// record = value;
// break;
// }
// }
// return record;
// }
// }
//
// Path: summer-mqtt-paho/src/test/java/com/github/christophersmith/summer/mqtt/paho/service/util/BrokerHelper.java
// public class BrokerHelper
// {
// private static final String CLIENT_ID = MqttAsyncClient.generateClientId();
// private static final String BROKER_URI_FORMAT = "tcp://%s:%s";
// private static final String BROKER_HOST_NAME = "mqtt.eclipse.org";
// private static final int BROKER_PORT = 1883;
// private static final String PROXY_HOST_NAME = "localhost";
// private static final int PROXY_PORT = 10080;
//
// public static String getClientId()
// {
// return CLIENT_ID;
// }
//
// public static String getBrokerHostName()
// {
// return BROKER_HOST_NAME;
// }
//
// public static int getBrokerPort()
// {
// return BROKER_PORT;
// }
//
// public static String getBrokerUri()
// {
// return String.format(BROKER_URI_FORMAT, BROKER_HOST_NAME, String.valueOf(BROKER_PORT));
// }
//
// public static String getProxyHostName()
// {
// return PROXY_HOST_NAME;
// }
//
// public static int getProxyPort()
// {
// return PROXY_PORT;
// }
//
// public static String getProxyUri()
// {
// return String.format(BROKER_URI_FORMAT, PROXY_HOST_NAME, String.valueOf(PROXY_PORT));
// }
// }
// Path: summer-mqtt-paho/src/test/java/com/github/christophersmith/summer/mqtt/paho/service/SubscribeUnsubscribeTest.java
import java.io.IOException;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.netcrusher.core.reactor.NioReactor;
import org.netcrusher.tcp.TcpCrusher;
import org.netcrusher.tcp.TcpCrusherBuilder;
import com.github.christophersmith.summer.mqtt.core.MqttClientConnectionType;
import com.github.christophersmith.summer.mqtt.core.MqttQualityOfService;
import com.github.christophersmith.summer.mqtt.paho.service.util.BrokerHelper;
/*******************************************************************************
* Copyright (c) 2019 Christopher Smith - https://github.com/christophersmith
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.github.christophersmith.summer.mqtt.paho.service;
public class SubscribeUnsubscribeTest
{
private static final String EXCEPTION_MESSAGE_CANNOT_SUBSCRIBE_FORMAT = "Client ID %s is a %s and cannot subscribe or unsubscribe from Topic Filters.";
@Rule
public ExpectedException thrown = ExpectedException
.none();
@Test
public void testSubscribeBeforeStartClientSubscriber() throws MqttException
{
PahoAsyncMqttClientService service = new PahoAsyncMqttClientService( | BrokerHelper.getBrokerUri(), BrokerHelper.getClientId(), |
christophersmith/summer-mqtt | summer-mqtt-paho/src/test/java/com/github/christophersmith/summer/mqtt/paho/service/SubscribeUnsubscribeTest.java | // Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/MqttClientConnectionType.java
// public enum MqttClientConnectionType
// {
// /**
// * Represents a connection type that can only publish messages.
// */
// PUBLISHER,
// /**
// * Represents a connection type that can both publish and receive messages.
// */
// PUBSUB,
// /**
// * Represents a connection type can only receive messages.
// */
// SUBSCRIBER;
// }
//
// Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/MqttQualityOfService.java
// public enum MqttQualityOfService
// {
// /**
// * Represents a Quality of Service (Qos) of 0, for At Most Once.
// */
// QOS_0(0),
// /**
// * Represents a Quality of Service (Qos) of 1, for At Least Once.
// */
// QOS_1(1),
// /**
// * Represents a Quality of Service (Qos) of 2, for Exactly Once.
// */
// QOS_2(2);
//
// private transient final int levelIdentifier;
//
// MqttQualityOfService(final int levelIdentifier)
// {
// this.levelIdentifier = levelIdentifier;
// }
//
// /**
// * Returns an {@code int} value representation of the Quality of Service Level for this
// * instance.
// *
// * @return the Level Identifier
// */
// public int getLevelIdentifier()
// {
// return levelIdentifier;
// }
//
// /**
// * Finds the {@link MqttQualityOfService} instance that matches the {@code levelIdentifier}
// * value.
// * <p>
// * If the {@code levelIdentifier} does not match a {@code MqttQualityOfService} instance, a
// * default value of {@link MqttQualityOfService#QOS_0} will be returned.
// *
// * @param levelIdentifier the Level Identifier to search by
// * @return a {@code MqttQualityOfService} value
// */
// public static final MqttQualityOfService findByLevelIdentifier(final int levelIdentifier)
// {
// MqttQualityOfService record = QOS_0;
// for (MqttQualityOfService value : values())
// {
// if (value.getLevelIdentifier() == levelIdentifier)
// {
// record = value;
// break;
// }
// }
// return record;
// }
// }
//
// Path: summer-mqtt-paho/src/test/java/com/github/christophersmith/summer/mqtt/paho/service/util/BrokerHelper.java
// public class BrokerHelper
// {
// private static final String CLIENT_ID = MqttAsyncClient.generateClientId();
// private static final String BROKER_URI_FORMAT = "tcp://%s:%s";
// private static final String BROKER_HOST_NAME = "mqtt.eclipse.org";
// private static final int BROKER_PORT = 1883;
// private static final String PROXY_HOST_NAME = "localhost";
// private static final int PROXY_PORT = 10080;
//
// public static String getClientId()
// {
// return CLIENT_ID;
// }
//
// public static String getBrokerHostName()
// {
// return BROKER_HOST_NAME;
// }
//
// public static int getBrokerPort()
// {
// return BROKER_PORT;
// }
//
// public static String getBrokerUri()
// {
// return String.format(BROKER_URI_FORMAT, BROKER_HOST_NAME, String.valueOf(BROKER_PORT));
// }
//
// public static String getProxyHostName()
// {
// return PROXY_HOST_NAME;
// }
//
// public static int getProxyPort()
// {
// return PROXY_PORT;
// }
//
// public static String getProxyUri()
// {
// return String.format(BROKER_URI_FORMAT, PROXY_HOST_NAME, String.valueOf(PROXY_PORT));
// }
// }
| import java.io.IOException;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.netcrusher.core.reactor.NioReactor;
import org.netcrusher.tcp.TcpCrusher;
import org.netcrusher.tcp.TcpCrusherBuilder;
import com.github.christophersmith.summer.mqtt.core.MqttClientConnectionType;
import com.github.christophersmith.summer.mqtt.core.MqttQualityOfService;
import com.github.christophersmith.summer.mqtt.paho.service.util.BrokerHelper; | /*******************************************************************************
* Copyright (c) 2019 Christopher Smith - https://github.com/christophersmith
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.github.christophersmith.summer.mqtt.paho.service;
public class SubscribeUnsubscribeTest
{
private static final String EXCEPTION_MESSAGE_CANNOT_SUBSCRIBE_FORMAT = "Client ID %s is a %s and cannot subscribe or unsubscribe from Topic Filters.";
@Rule
public ExpectedException thrown = ExpectedException
.none();
@Test
public void testSubscribeBeforeStartClientSubscriber() throws MqttException
{
PahoAsyncMqttClientService service = new PahoAsyncMqttClientService(
BrokerHelper.getBrokerUri(), BrokerHelper.getClientId(), | // Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/MqttClientConnectionType.java
// public enum MqttClientConnectionType
// {
// /**
// * Represents a connection type that can only publish messages.
// */
// PUBLISHER,
// /**
// * Represents a connection type that can both publish and receive messages.
// */
// PUBSUB,
// /**
// * Represents a connection type can only receive messages.
// */
// SUBSCRIBER;
// }
//
// Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/MqttQualityOfService.java
// public enum MqttQualityOfService
// {
// /**
// * Represents a Quality of Service (Qos) of 0, for At Most Once.
// */
// QOS_0(0),
// /**
// * Represents a Quality of Service (Qos) of 1, for At Least Once.
// */
// QOS_1(1),
// /**
// * Represents a Quality of Service (Qos) of 2, for Exactly Once.
// */
// QOS_2(2);
//
// private transient final int levelIdentifier;
//
// MqttQualityOfService(final int levelIdentifier)
// {
// this.levelIdentifier = levelIdentifier;
// }
//
// /**
// * Returns an {@code int} value representation of the Quality of Service Level for this
// * instance.
// *
// * @return the Level Identifier
// */
// public int getLevelIdentifier()
// {
// return levelIdentifier;
// }
//
// /**
// * Finds the {@link MqttQualityOfService} instance that matches the {@code levelIdentifier}
// * value.
// * <p>
// * If the {@code levelIdentifier} does not match a {@code MqttQualityOfService} instance, a
// * default value of {@link MqttQualityOfService#QOS_0} will be returned.
// *
// * @param levelIdentifier the Level Identifier to search by
// * @return a {@code MqttQualityOfService} value
// */
// public static final MqttQualityOfService findByLevelIdentifier(final int levelIdentifier)
// {
// MqttQualityOfService record = QOS_0;
// for (MqttQualityOfService value : values())
// {
// if (value.getLevelIdentifier() == levelIdentifier)
// {
// record = value;
// break;
// }
// }
// return record;
// }
// }
//
// Path: summer-mqtt-paho/src/test/java/com/github/christophersmith/summer/mqtt/paho/service/util/BrokerHelper.java
// public class BrokerHelper
// {
// private static final String CLIENT_ID = MqttAsyncClient.generateClientId();
// private static final String BROKER_URI_FORMAT = "tcp://%s:%s";
// private static final String BROKER_HOST_NAME = "mqtt.eclipse.org";
// private static final int BROKER_PORT = 1883;
// private static final String PROXY_HOST_NAME = "localhost";
// private static final int PROXY_PORT = 10080;
//
// public static String getClientId()
// {
// return CLIENT_ID;
// }
//
// public static String getBrokerHostName()
// {
// return BROKER_HOST_NAME;
// }
//
// public static int getBrokerPort()
// {
// return BROKER_PORT;
// }
//
// public static String getBrokerUri()
// {
// return String.format(BROKER_URI_FORMAT, BROKER_HOST_NAME, String.valueOf(BROKER_PORT));
// }
//
// public static String getProxyHostName()
// {
// return PROXY_HOST_NAME;
// }
//
// public static int getProxyPort()
// {
// return PROXY_PORT;
// }
//
// public static String getProxyUri()
// {
// return String.format(BROKER_URI_FORMAT, PROXY_HOST_NAME, String.valueOf(PROXY_PORT));
// }
// }
// Path: summer-mqtt-paho/src/test/java/com/github/christophersmith/summer/mqtt/paho/service/SubscribeUnsubscribeTest.java
import java.io.IOException;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.netcrusher.core.reactor.NioReactor;
import org.netcrusher.tcp.TcpCrusher;
import org.netcrusher.tcp.TcpCrusherBuilder;
import com.github.christophersmith.summer.mqtt.core.MqttClientConnectionType;
import com.github.christophersmith.summer.mqtt.core.MqttQualityOfService;
import com.github.christophersmith.summer.mqtt.paho.service.util.BrokerHelper;
/*******************************************************************************
* Copyright (c) 2019 Christopher Smith - https://github.com/christophersmith
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.github.christophersmith.summer.mqtt.paho.service;
public class SubscribeUnsubscribeTest
{
private static final String EXCEPTION_MESSAGE_CANNOT_SUBSCRIBE_FORMAT = "Client ID %s is a %s and cannot subscribe or unsubscribe from Topic Filters.";
@Rule
public ExpectedException thrown = ExpectedException
.none();
@Test
public void testSubscribeBeforeStartClientSubscriber() throws MqttException
{
PahoAsyncMqttClientService service = new PahoAsyncMqttClientService(
BrokerHelper.getBrokerUri(), BrokerHelper.getClientId(), | MqttClientConnectionType.SUBSCRIBER, null); |
christophersmith/summer-mqtt | summer-mqtt-paho/src/test/java/com/github/christophersmith/summer/mqtt/paho/service/SubscribeUnsubscribeTest.java | // Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/MqttClientConnectionType.java
// public enum MqttClientConnectionType
// {
// /**
// * Represents a connection type that can only publish messages.
// */
// PUBLISHER,
// /**
// * Represents a connection type that can both publish and receive messages.
// */
// PUBSUB,
// /**
// * Represents a connection type can only receive messages.
// */
// SUBSCRIBER;
// }
//
// Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/MqttQualityOfService.java
// public enum MqttQualityOfService
// {
// /**
// * Represents a Quality of Service (Qos) of 0, for At Most Once.
// */
// QOS_0(0),
// /**
// * Represents a Quality of Service (Qos) of 1, for At Least Once.
// */
// QOS_1(1),
// /**
// * Represents a Quality of Service (Qos) of 2, for Exactly Once.
// */
// QOS_2(2);
//
// private transient final int levelIdentifier;
//
// MqttQualityOfService(final int levelIdentifier)
// {
// this.levelIdentifier = levelIdentifier;
// }
//
// /**
// * Returns an {@code int} value representation of the Quality of Service Level for this
// * instance.
// *
// * @return the Level Identifier
// */
// public int getLevelIdentifier()
// {
// return levelIdentifier;
// }
//
// /**
// * Finds the {@link MqttQualityOfService} instance that matches the {@code levelIdentifier}
// * value.
// * <p>
// * If the {@code levelIdentifier} does not match a {@code MqttQualityOfService} instance, a
// * default value of {@link MqttQualityOfService#QOS_0} will be returned.
// *
// * @param levelIdentifier the Level Identifier to search by
// * @return a {@code MqttQualityOfService} value
// */
// public static final MqttQualityOfService findByLevelIdentifier(final int levelIdentifier)
// {
// MqttQualityOfService record = QOS_0;
// for (MqttQualityOfService value : values())
// {
// if (value.getLevelIdentifier() == levelIdentifier)
// {
// record = value;
// break;
// }
// }
// return record;
// }
// }
//
// Path: summer-mqtt-paho/src/test/java/com/github/christophersmith/summer/mqtt/paho/service/util/BrokerHelper.java
// public class BrokerHelper
// {
// private static final String CLIENT_ID = MqttAsyncClient.generateClientId();
// private static final String BROKER_URI_FORMAT = "tcp://%s:%s";
// private static final String BROKER_HOST_NAME = "mqtt.eclipse.org";
// private static final int BROKER_PORT = 1883;
// private static final String PROXY_HOST_NAME = "localhost";
// private static final int PROXY_PORT = 10080;
//
// public static String getClientId()
// {
// return CLIENT_ID;
// }
//
// public static String getBrokerHostName()
// {
// return BROKER_HOST_NAME;
// }
//
// public static int getBrokerPort()
// {
// return BROKER_PORT;
// }
//
// public static String getBrokerUri()
// {
// return String.format(BROKER_URI_FORMAT, BROKER_HOST_NAME, String.valueOf(BROKER_PORT));
// }
//
// public static String getProxyHostName()
// {
// return PROXY_HOST_NAME;
// }
//
// public static int getProxyPort()
// {
// return PROXY_PORT;
// }
//
// public static String getProxyUri()
// {
// return String.format(BROKER_URI_FORMAT, PROXY_HOST_NAME, String.valueOf(PROXY_PORT));
// }
// }
| import java.io.IOException;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.netcrusher.core.reactor.NioReactor;
import org.netcrusher.tcp.TcpCrusher;
import org.netcrusher.tcp.TcpCrusherBuilder;
import com.github.christophersmith.summer.mqtt.core.MqttClientConnectionType;
import com.github.christophersmith.summer.mqtt.core.MqttQualityOfService;
import com.github.christophersmith.summer.mqtt.paho.service.util.BrokerHelper; | /*******************************************************************************
* Copyright (c) 2019 Christopher Smith - https://github.com/christophersmith
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.github.christophersmith.summer.mqtt.paho.service;
public class SubscribeUnsubscribeTest
{
private static final String EXCEPTION_MESSAGE_CANNOT_SUBSCRIBE_FORMAT = "Client ID %s is a %s and cannot subscribe or unsubscribe from Topic Filters.";
@Rule
public ExpectedException thrown = ExpectedException
.none();
@Test
public void testSubscribeBeforeStartClientSubscriber() throws MqttException
{
PahoAsyncMqttClientService service = new PahoAsyncMqttClientService(
BrokerHelper.getBrokerUri(), BrokerHelper.getClientId(),
MqttClientConnectionType.SUBSCRIBER, null);
Assert.assertEquals(0, service.getTopicSubscriptions().size());
service.subscribe(String.format("client/%s", BrokerHelper.getClientId()), | // Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/MqttClientConnectionType.java
// public enum MqttClientConnectionType
// {
// /**
// * Represents a connection type that can only publish messages.
// */
// PUBLISHER,
// /**
// * Represents a connection type that can both publish and receive messages.
// */
// PUBSUB,
// /**
// * Represents a connection type can only receive messages.
// */
// SUBSCRIBER;
// }
//
// Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/MqttQualityOfService.java
// public enum MqttQualityOfService
// {
// /**
// * Represents a Quality of Service (Qos) of 0, for At Most Once.
// */
// QOS_0(0),
// /**
// * Represents a Quality of Service (Qos) of 1, for At Least Once.
// */
// QOS_1(1),
// /**
// * Represents a Quality of Service (Qos) of 2, for Exactly Once.
// */
// QOS_2(2);
//
// private transient final int levelIdentifier;
//
// MqttQualityOfService(final int levelIdentifier)
// {
// this.levelIdentifier = levelIdentifier;
// }
//
// /**
// * Returns an {@code int} value representation of the Quality of Service Level for this
// * instance.
// *
// * @return the Level Identifier
// */
// public int getLevelIdentifier()
// {
// return levelIdentifier;
// }
//
// /**
// * Finds the {@link MqttQualityOfService} instance that matches the {@code levelIdentifier}
// * value.
// * <p>
// * If the {@code levelIdentifier} does not match a {@code MqttQualityOfService} instance, a
// * default value of {@link MqttQualityOfService#QOS_0} will be returned.
// *
// * @param levelIdentifier the Level Identifier to search by
// * @return a {@code MqttQualityOfService} value
// */
// public static final MqttQualityOfService findByLevelIdentifier(final int levelIdentifier)
// {
// MqttQualityOfService record = QOS_0;
// for (MqttQualityOfService value : values())
// {
// if (value.getLevelIdentifier() == levelIdentifier)
// {
// record = value;
// break;
// }
// }
// return record;
// }
// }
//
// Path: summer-mqtt-paho/src/test/java/com/github/christophersmith/summer/mqtt/paho/service/util/BrokerHelper.java
// public class BrokerHelper
// {
// private static final String CLIENT_ID = MqttAsyncClient.generateClientId();
// private static final String BROKER_URI_FORMAT = "tcp://%s:%s";
// private static final String BROKER_HOST_NAME = "mqtt.eclipse.org";
// private static final int BROKER_PORT = 1883;
// private static final String PROXY_HOST_NAME = "localhost";
// private static final int PROXY_PORT = 10080;
//
// public static String getClientId()
// {
// return CLIENT_ID;
// }
//
// public static String getBrokerHostName()
// {
// return BROKER_HOST_NAME;
// }
//
// public static int getBrokerPort()
// {
// return BROKER_PORT;
// }
//
// public static String getBrokerUri()
// {
// return String.format(BROKER_URI_FORMAT, BROKER_HOST_NAME, String.valueOf(BROKER_PORT));
// }
//
// public static String getProxyHostName()
// {
// return PROXY_HOST_NAME;
// }
//
// public static int getProxyPort()
// {
// return PROXY_PORT;
// }
//
// public static String getProxyUri()
// {
// return String.format(BROKER_URI_FORMAT, PROXY_HOST_NAME, String.valueOf(PROXY_PORT));
// }
// }
// Path: summer-mqtt-paho/src/test/java/com/github/christophersmith/summer/mqtt/paho/service/SubscribeUnsubscribeTest.java
import java.io.IOException;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.netcrusher.core.reactor.NioReactor;
import org.netcrusher.tcp.TcpCrusher;
import org.netcrusher.tcp.TcpCrusherBuilder;
import com.github.christophersmith.summer.mqtt.core.MqttClientConnectionType;
import com.github.christophersmith.summer.mqtt.core.MqttQualityOfService;
import com.github.christophersmith.summer.mqtt.paho.service.util.BrokerHelper;
/*******************************************************************************
* Copyright (c) 2019 Christopher Smith - https://github.com/christophersmith
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.github.christophersmith.summer.mqtt.paho.service;
public class SubscribeUnsubscribeTest
{
private static final String EXCEPTION_MESSAGE_CANNOT_SUBSCRIBE_FORMAT = "Client ID %s is a %s and cannot subscribe or unsubscribe from Topic Filters.";
@Rule
public ExpectedException thrown = ExpectedException
.none();
@Test
public void testSubscribeBeforeStartClientSubscriber() throws MqttException
{
PahoAsyncMqttClientService service = new PahoAsyncMqttClientService(
BrokerHelper.getBrokerUri(), BrokerHelper.getClientId(),
MqttClientConnectionType.SUBSCRIBER, null);
Assert.assertEquals(0, service.getTopicSubscriptions().size());
service.subscribe(String.format("client/%s", BrokerHelper.getClientId()), | MqttQualityOfService.QOS_0); |
christophersmith/summer-mqtt | summer-mqtt-paho/src/test/java/com/github/christophersmith/summer/mqtt/paho/service/PahoAsyncMqttClientServiceTest.java | // Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/MqttClientConnectionType.java
// public enum MqttClientConnectionType
// {
// /**
// * Represents a connection type that can only publish messages.
// */
// PUBLISHER,
// /**
// * Represents a connection type that can both publish and receive messages.
// */
// PUBSUB,
// /**
// * Represents a connection type can only receive messages.
// */
// SUBSCRIBER;
// }
//
// Path: summer-mqtt-paho/src/test/java/com/github/christophersmith/summer/mqtt/paho/service/util/BrokerHelper.java
// public class BrokerHelper
// {
// private static final String CLIENT_ID = MqttAsyncClient.generateClientId();
// private static final String BROKER_URI_FORMAT = "tcp://%s:%s";
// private static final String BROKER_HOST_NAME = "mqtt.eclipse.org";
// private static final int BROKER_PORT = 1883;
// private static final String PROXY_HOST_NAME = "localhost";
// private static final int PROXY_PORT = 10080;
//
// public static String getClientId()
// {
// return CLIENT_ID;
// }
//
// public static String getBrokerHostName()
// {
// return BROKER_HOST_NAME;
// }
//
// public static int getBrokerPort()
// {
// return BROKER_PORT;
// }
//
// public static String getBrokerUri()
// {
// return String.format(BROKER_URI_FORMAT, BROKER_HOST_NAME, String.valueOf(BROKER_PORT));
// }
//
// public static String getProxyHostName()
// {
// return PROXY_HOST_NAME;
// }
//
// public static int getProxyPort()
// {
// return PROXY_PORT;
// }
//
// public static String getProxyUri()
// {
// return String.format(BROKER_URI_FORMAT, PROXY_HOST_NAME, String.valueOf(PROXY_PORT));
// }
// }
| import org.eclipse.paho.client.mqttv3.MqttException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import com.github.christophersmith.summer.mqtt.core.MqttClientConnectionType;
import com.github.christophersmith.summer.mqtt.paho.service.util.BrokerHelper; | /*******************************************************************************
* Copyright (c) 2019 Christopher Smith - https://github.com/christophersmith
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.github.christophersmith.summer.mqtt.paho.service;
public class PahoAsyncMqttClientServiceTest
{
private static final String VALUE_BLANK = "";
private static final String EXCEPTION_MESSAGE_SERVER_URI = "'serverUri' must be set!";
private static final String EXCEPTION_MESSAGE_CLIENT_ID = "'clientId' must be set!";
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void testConstructionBlankServerUri() throws MqttException
{
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage(EXCEPTION_MESSAGE_SERVER_URI); | // Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/MqttClientConnectionType.java
// public enum MqttClientConnectionType
// {
// /**
// * Represents a connection type that can only publish messages.
// */
// PUBLISHER,
// /**
// * Represents a connection type that can both publish and receive messages.
// */
// PUBSUB,
// /**
// * Represents a connection type can only receive messages.
// */
// SUBSCRIBER;
// }
//
// Path: summer-mqtt-paho/src/test/java/com/github/christophersmith/summer/mqtt/paho/service/util/BrokerHelper.java
// public class BrokerHelper
// {
// private static final String CLIENT_ID = MqttAsyncClient.generateClientId();
// private static final String BROKER_URI_FORMAT = "tcp://%s:%s";
// private static final String BROKER_HOST_NAME = "mqtt.eclipse.org";
// private static final int BROKER_PORT = 1883;
// private static final String PROXY_HOST_NAME = "localhost";
// private static final int PROXY_PORT = 10080;
//
// public static String getClientId()
// {
// return CLIENT_ID;
// }
//
// public static String getBrokerHostName()
// {
// return BROKER_HOST_NAME;
// }
//
// public static int getBrokerPort()
// {
// return BROKER_PORT;
// }
//
// public static String getBrokerUri()
// {
// return String.format(BROKER_URI_FORMAT, BROKER_HOST_NAME, String.valueOf(BROKER_PORT));
// }
//
// public static String getProxyHostName()
// {
// return PROXY_HOST_NAME;
// }
//
// public static int getProxyPort()
// {
// return PROXY_PORT;
// }
//
// public static String getProxyUri()
// {
// return String.format(BROKER_URI_FORMAT, PROXY_HOST_NAME, String.valueOf(PROXY_PORT));
// }
// }
// Path: summer-mqtt-paho/src/test/java/com/github/christophersmith/summer/mqtt/paho/service/PahoAsyncMqttClientServiceTest.java
import org.eclipse.paho.client.mqttv3.MqttException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import com.github.christophersmith.summer.mqtt.core.MqttClientConnectionType;
import com.github.christophersmith.summer.mqtt.paho.service.util.BrokerHelper;
/*******************************************************************************
* Copyright (c) 2019 Christopher Smith - https://github.com/christophersmith
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.github.christophersmith.summer.mqtt.paho.service;
public class PahoAsyncMqttClientServiceTest
{
private static final String VALUE_BLANK = "";
private static final String EXCEPTION_MESSAGE_SERVER_URI = "'serverUri' must be set!";
private static final String EXCEPTION_MESSAGE_CLIENT_ID = "'clientId' must be set!";
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void testConstructionBlankServerUri() throws MqttException
{
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage(EXCEPTION_MESSAGE_SERVER_URI); | new PahoAsyncMqttClientService(VALUE_BLANK, BrokerHelper.getClientId(), |
christophersmith/summer-mqtt | summer-mqtt-paho/src/test/java/com/github/christophersmith/summer/mqtt/paho/service/PahoAsyncMqttClientServiceTest.java | // Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/MqttClientConnectionType.java
// public enum MqttClientConnectionType
// {
// /**
// * Represents a connection type that can only publish messages.
// */
// PUBLISHER,
// /**
// * Represents a connection type that can both publish and receive messages.
// */
// PUBSUB,
// /**
// * Represents a connection type can only receive messages.
// */
// SUBSCRIBER;
// }
//
// Path: summer-mqtt-paho/src/test/java/com/github/christophersmith/summer/mqtt/paho/service/util/BrokerHelper.java
// public class BrokerHelper
// {
// private static final String CLIENT_ID = MqttAsyncClient.generateClientId();
// private static final String BROKER_URI_FORMAT = "tcp://%s:%s";
// private static final String BROKER_HOST_NAME = "mqtt.eclipse.org";
// private static final int BROKER_PORT = 1883;
// private static final String PROXY_HOST_NAME = "localhost";
// private static final int PROXY_PORT = 10080;
//
// public static String getClientId()
// {
// return CLIENT_ID;
// }
//
// public static String getBrokerHostName()
// {
// return BROKER_HOST_NAME;
// }
//
// public static int getBrokerPort()
// {
// return BROKER_PORT;
// }
//
// public static String getBrokerUri()
// {
// return String.format(BROKER_URI_FORMAT, BROKER_HOST_NAME, String.valueOf(BROKER_PORT));
// }
//
// public static String getProxyHostName()
// {
// return PROXY_HOST_NAME;
// }
//
// public static int getProxyPort()
// {
// return PROXY_PORT;
// }
//
// public static String getProxyUri()
// {
// return String.format(BROKER_URI_FORMAT, PROXY_HOST_NAME, String.valueOf(PROXY_PORT));
// }
// }
| import org.eclipse.paho.client.mqttv3.MqttException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import com.github.christophersmith.summer.mqtt.core.MqttClientConnectionType;
import com.github.christophersmith.summer.mqtt.paho.service.util.BrokerHelper; | /*******************************************************************************
* Copyright (c) 2019 Christopher Smith - https://github.com/christophersmith
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.github.christophersmith.summer.mqtt.paho.service;
public class PahoAsyncMqttClientServiceTest
{
private static final String VALUE_BLANK = "";
private static final String EXCEPTION_MESSAGE_SERVER_URI = "'serverUri' must be set!";
private static final String EXCEPTION_MESSAGE_CLIENT_ID = "'clientId' must be set!";
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void testConstructionBlankServerUri() throws MqttException
{
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage(EXCEPTION_MESSAGE_SERVER_URI);
new PahoAsyncMqttClientService(VALUE_BLANK, BrokerHelper.getClientId(), | // Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/MqttClientConnectionType.java
// public enum MqttClientConnectionType
// {
// /**
// * Represents a connection type that can only publish messages.
// */
// PUBLISHER,
// /**
// * Represents a connection type that can both publish and receive messages.
// */
// PUBSUB,
// /**
// * Represents a connection type can only receive messages.
// */
// SUBSCRIBER;
// }
//
// Path: summer-mqtt-paho/src/test/java/com/github/christophersmith/summer/mqtt/paho/service/util/BrokerHelper.java
// public class BrokerHelper
// {
// private static final String CLIENT_ID = MqttAsyncClient.generateClientId();
// private static final String BROKER_URI_FORMAT = "tcp://%s:%s";
// private static final String BROKER_HOST_NAME = "mqtt.eclipse.org";
// private static final int BROKER_PORT = 1883;
// private static final String PROXY_HOST_NAME = "localhost";
// private static final int PROXY_PORT = 10080;
//
// public static String getClientId()
// {
// return CLIENT_ID;
// }
//
// public static String getBrokerHostName()
// {
// return BROKER_HOST_NAME;
// }
//
// public static int getBrokerPort()
// {
// return BROKER_PORT;
// }
//
// public static String getBrokerUri()
// {
// return String.format(BROKER_URI_FORMAT, BROKER_HOST_NAME, String.valueOf(BROKER_PORT));
// }
//
// public static String getProxyHostName()
// {
// return PROXY_HOST_NAME;
// }
//
// public static int getProxyPort()
// {
// return PROXY_PORT;
// }
//
// public static String getProxyUri()
// {
// return String.format(BROKER_URI_FORMAT, PROXY_HOST_NAME, String.valueOf(PROXY_PORT));
// }
// }
// Path: summer-mqtt-paho/src/test/java/com/github/christophersmith/summer/mqtt/paho/service/PahoAsyncMqttClientServiceTest.java
import org.eclipse.paho.client.mqttv3.MqttException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import com.github.christophersmith.summer.mqtt.core.MqttClientConnectionType;
import com.github.christophersmith.summer.mqtt.paho.service.util.BrokerHelper;
/*******************************************************************************
* Copyright (c) 2019 Christopher Smith - https://github.com/christophersmith
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.github.christophersmith.summer.mqtt.paho.service;
public class PahoAsyncMqttClientServiceTest
{
private static final String VALUE_BLANK = "";
private static final String EXCEPTION_MESSAGE_SERVER_URI = "'serverUri' must be set!";
private static final String EXCEPTION_MESSAGE_CLIENT_ID = "'clientId' must be set!";
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void testConstructionBlankServerUri() throws MqttException
{
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage(EXCEPTION_MESSAGE_SERVER_URI);
new PahoAsyncMqttClientService(VALUE_BLANK, BrokerHelper.getClientId(), | MqttClientConnectionType.PUBSUB, null); |
christophersmith/summer-mqtt | summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/util/MqttHeaderHelper.java | // Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/MqttQualityOfService.java
// public enum MqttQualityOfService
// {
// /**
// * Represents a Quality of Service (Qos) of 0, for At Most Once.
// */
// QOS_0(0),
// /**
// * Represents a Quality of Service (Qos) of 1, for At Least Once.
// */
// QOS_1(1),
// /**
// * Represents a Quality of Service (Qos) of 2, for Exactly Once.
// */
// QOS_2(2);
//
// private transient final int levelIdentifier;
//
// MqttQualityOfService(final int levelIdentifier)
// {
// this.levelIdentifier = levelIdentifier;
// }
//
// /**
// * Returns an {@code int} value representation of the Quality of Service Level for this
// * instance.
// *
// * @return the Level Identifier
// */
// public int getLevelIdentifier()
// {
// return levelIdentifier;
// }
//
// /**
// * Finds the {@link MqttQualityOfService} instance that matches the {@code levelIdentifier}
// * value.
// * <p>
// * If the {@code levelIdentifier} does not match a {@code MqttQualityOfService} instance, a
// * default value of {@link MqttQualityOfService#QOS_0} will be returned.
// *
// * @param levelIdentifier the Level Identifier to search by
// * @return a {@code MqttQualityOfService} value
// */
// public static final MqttQualityOfService findByLevelIdentifier(final int levelIdentifier)
// {
// MqttQualityOfService record = QOS_0;
// for (MqttQualityOfService value : values())
// {
// if (value.getLevelIdentifier() == levelIdentifier)
// {
// record = value;
// break;
// }
// }
// return record;
// }
// }
| import org.slf4j.LoggerFactory;
import org.springframework.messaging.Message;
import com.github.christophersmith.summer.mqtt.core.MqttQualityOfService;
import org.slf4j.Logger; | /*******************************************************************************
* Copyright (c) 2019 Christopher Smith - https://github.com/christophersmith
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.github.christophersmith.summer.mqtt.core.util;
/**
* A utility class that provides values and commons methods for dealing with {@link Message} header
* values.
*/
public final class MqttHeaderHelper
{
private static final Logger LOG = LoggerFactory.getLogger(MqttHeaderHelper.class);
/**
* The {@link Message} header key for whether the in-coming message is likely a duplicate.
* <p>
* This header value should always be present for in-coming messages. If this value isn't
* specifically set, a default value of false will be sent.
*/
public static final String DUPLICATE = "mqtt_duplicate";
/**
* The {@link Message} header key for Message ID for the in-coming message.
* <p>
* This header value should always be present for in-coming messages and is set by the MQTT
* Client.
*/
public static final String ID = "mqtt_id";
/**
* The {@link Message} header key for the Quality of Service (QoS) the message was received as,
* or should be published with.
* <p>
* This header value should always be present for in-coming and out-going messages. If this
* value isn't specifically set for out-going message, a defined default value will be sent.
*/
public static final String QOS = "mqtt_qos";
/**
* The {@link Message} header key for whether the message was, or should, be retained.
* <p>
* This header value should always be present for in-coming and out-going messages. If this
* value isn't specifically set, a default value of false will be sent.
*/
public static final String RETAINED = "mqtt_retained";
/**
* The {@link Message} header key for the Topic the message was received from or should be
* published to.
* <p>
* This header value should always be present for in-coming and out-going messages.
*/
public static final String TOPIC = "mqtt_topic";
/**
* The {@link Message} header key for an optional Correlation ID.
* <p>
* This can be assigned to published messages for the purpose of associating Message Status
* Events back to a specific message.
*/
public static final String CORRELATION_ID = "mqtt_correlation_id";
/**
* Retrieves the {@link #TOPIC} value from the {@code message} parameter.
* <p>
* If the {@code message} parameter is null or doesn't contain the {@link #TOPIC} header, a null
* value is returned.
*
* @param message a {@link Message} value
* @return the Topic
*/
public static String getTopicHeaderValue(Message<?> message)
{
String value = null;
if (message != null
&& message.getHeaders().containsKey(TOPIC))
{
value = message.getHeaders().get(TOPIC, String.class);
}
return value;
}
/**
* Retrieves the {@link #QOS} value from the {@code message} parameter.
* <p>
* If the {@code message} parameter is null, doesn't contain the {@link #QOS} header or the
* value cannot be converted to an Integer, the {@code defaultLevelIdentifier} value is
* returned.
*
* @param message a {@link Message} value
* @param defaultLevelIdentifier a default {@link MqttQualityOfService} value if value wasn't
* found or couldn't be parsed
* @return a {@link MqttQualityOfService} value
*/ | // Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/MqttQualityOfService.java
// public enum MqttQualityOfService
// {
// /**
// * Represents a Quality of Service (Qos) of 0, for At Most Once.
// */
// QOS_0(0),
// /**
// * Represents a Quality of Service (Qos) of 1, for At Least Once.
// */
// QOS_1(1),
// /**
// * Represents a Quality of Service (Qos) of 2, for Exactly Once.
// */
// QOS_2(2);
//
// private transient final int levelIdentifier;
//
// MqttQualityOfService(final int levelIdentifier)
// {
// this.levelIdentifier = levelIdentifier;
// }
//
// /**
// * Returns an {@code int} value representation of the Quality of Service Level for this
// * instance.
// *
// * @return the Level Identifier
// */
// public int getLevelIdentifier()
// {
// return levelIdentifier;
// }
//
// /**
// * Finds the {@link MqttQualityOfService} instance that matches the {@code levelIdentifier}
// * value.
// * <p>
// * If the {@code levelIdentifier} does not match a {@code MqttQualityOfService} instance, a
// * default value of {@link MqttQualityOfService#QOS_0} will be returned.
// *
// * @param levelIdentifier the Level Identifier to search by
// * @return a {@code MqttQualityOfService} value
// */
// public static final MqttQualityOfService findByLevelIdentifier(final int levelIdentifier)
// {
// MqttQualityOfService record = QOS_0;
// for (MqttQualityOfService value : values())
// {
// if (value.getLevelIdentifier() == levelIdentifier)
// {
// record = value;
// break;
// }
// }
// return record;
// }
// }
// Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/util/MqttHeaderHelper.java
import org.slf4j.LoggerFactory;
import org.springframework.messaging.Message;
import com.github.christophersmith.summer.mqtt.core.MqttQualityOfService;
import org.slf4j.Logger;
/*******************************************************************************
* Copyright (c) 2019 Christopher Smith - https://github.com/christophersmith
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.github.christophersmith.summer.mqtt.core.util;
/**
* A utility class that provides values and commons methods for dealing with {@link Message} header
* values.
*/
public final class MqttHeaderHelper
{
private static final Logger LOG = LoggerFactory.getLogger(MqttHeaderHelper.class);
/**
* The {@link Message} header key for whether the in-coming message is likely a duplicate.
* <p>
* This header value should always be present for in-coming messages. If this value isn't
* specifically set, a default value of false will be sent.
*/
public static final String DUPLICATE = "mqtt_duplicate";
/**
* The {@link Message} header key for Message ID for the in-coming message.
* <p>
* This header value should always be present for in-coming messages and is set by the MQTT
* Client.
*/
public static final String ID = "mqtt_id";
/**
* The {@link Message} header key for the Quality of Service (QoS) the message was received as,
* or should be published with.
* <p>
* This header value should always be present for in-coming and out-going messages. If this
* value isn't specifically set for out-going message, a defined default value will be sent.
*/
public static final String QOS = "mqtt_qos";
/**
* The {@link Message} header key for whether the message was, or should, be retained.
* <p>
* This header value should always be present for in-coming and out-going messages. If this
* value isn't specifically set, a default value of false will be sent.
*/
public static final String RETAINED = "mqtt_retained";
/**
* The {@link Message} header key for the Topic the message was received from or should be
* published to.
* <p>
* This header value should always be present for in-coming and out-going messages.
*/
public static final String TOPIC = "mqtt_topic";
/**
* The {@link Message} header key for an optional Correlation ID.
* <p>
* This can be assigned to published messages for the purpose of associating Message Status
* Events back to a specific message.
*/
public static final String CORRELATION_ID = "mqtt_correlation_id";
/**
* Retrieves the {@link #TOPIC} value from the {@code message} parameter.
* <p>
* If the {@code message} parameter is null or doesn't contain the {@link #TOPIC} header, a null
* value is returned.
*
* @param message a {@link Message} value
* @return the Topic
*/
public static String getTopicHeaderValue(Message<?> message)
{
String value = null;
if (message != null
&& message.getHeaders().containsKey(TOPIC))
{
value = message.getHeaders().get(TOPIC, String.class);
}
return value;
}
/**
* Retrieves the {@link #QOS} value from the {@code message} parameter.
* <p>
* If the {@code message} parameter is null, doesn't contain the {@link #QOS} header or the
* value cannot be converted to an Integer, the {@code defaultLevelIdentifier} value is
* returned.
*
* @param message a {@link Message} value
* @param defaultLevelIdentifier a default {@link MqttQualityOfService} value if value wasn't
* found or couldn't be parsed
* @return a {@link MqttQualityOfService} value
*/ | public static MqttQualityOfService getMqttQualityOfServiceHeaderValue(Message<?> message, |
christophersmith/summer-mqtt | summer-mqtt-core/src/test/java/com/github/christophersmith/summer/mqtt/core/service/AbstractMqttClientServiceTest.java | // Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/MqttClientConnectionType.java
// public enum MqttClientConnectionType
// {
// /**
// * Represents a connection type that can only publish messages.
// */
// PUBLISHER,
// /**
// * Represents a connection type that can both publish and receive messages.
// */
// PUBSUB,
// /**
// * Represents a connection type can only receive messages.
// */
// SUBSCRIBER;
// }
//
// Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/MqttQualityOfService.java
// public enum MqttQualityOfService
// {
// /**
// * Represents a Quality of Service (Qos) of 0, for At Most Once.
// */
// QOS_0(0),
// /**
// * Represents a Quality of Service (Qos) of 1, for At Least Once.
// */
// QOS_1(1),
// /**
// * Represents a Quality of Service (Qos) of 2, for Exactly Once.
// */
// QOS_2(2);
//
// private transient final int levelIdentifier;
//
// MqttQualityOfService(final int levelIdentifier)
// {
// this.levelIdentifier = levelIdentifier;
// }
//
// /**
// * Returns an {@code int} value representation of the Quality of Service Level for this
// * instance.
// *
// * @return the Level Identifier
// */
// public int getLevelIdentifier()
// {
// return levelIdentifier;
// }
//
// /**
// * Finds the {@link MqttQualityOfService} instance that matches the {@code levelIdentifier}
// * value.
// * <p>
// * If the {@code levelIdentifier} does not match a {@code MqttQualityOfService} instance, a
// * default value of {@link MqttQualityOfService#QOS_0} will be returned.
// *
// * @param levelIdentifier the Level Identifier to search by
// * @return a {@code MqttQualityOfService} value
// */
// public static final MqttQualityOfService findByLevelIdentifier(final int levelIdentifier)
// {
// MqttQualityOfService record = QOS_0;
// for (MqttQualityOfService value : values())
// {
// if (value.getLevelIdentifier() == levelIdentifier)
// {
// record = value;
// break;
// }
// }
// return record;
// }
// }
//
// Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/TopicSubscription.java
// public final class TopicSubscription
// {
// private transient final String topicFilter;
// private transient final MqttQualityOfService qualityOfService;
// private boolean subscribed;
//
// /**
// * Creates a new {@code TopicSubscription} object that represents the Topic Filter and
// * subscription information.
// *
// * @param topicFilter the Topic Filter to subscribe to, which can include wildcards
// * @param qualityOfService the maximum QoS to use for this Topic Filter
// *
// * @throws IllegalArgumentException if the {@code topicFilter} is null or empty, or if the
// * {@code qualityOfService} is null
// */
// public TopicSubscription(final String topicFilter, final MqttQualityOfService qualityOfService)
// {
// Assert.hasText(topicFilter, "'topicFilter' must be set!");
// Assert.notNull(qualityOfService, "'qualityOfService' must be set!");
// this.topicFilter = topicFilter;
// this.qualityOfService = qualityOfService;
// }
//
// /**
// * Returns the Topic Filter for this instance.
// *
// * @return the Topic Filter for this instance
// */
// public String getTopicFilter()
// {
// return topicFilter;
// }
//
// /**
// * Returns the {@link MqttQualityOfService} for this instance.
// *
// * @return a {@link MqttQualityOfService} value
// */
// public MqttQualityOfService getQualityOfService()
// {
// return qualityOfService;
// }
//
// /**
// * Returns whether the Topic Filter is subscribed to.
// *
// * @return true if the Topic Filter is subscribed to, otherwise false
// */
// public boolean isSubscribed()
// {
// return subscribed;
// }
//
// /**
// * Sets whether the Topic Filter is currently subscribed to.
// *
// * @param subscribed true if the Topic Filter is subscribed to, otherwise false
// */
// public void setSubscribed(boolean subscribed)
// {
// this.subscribed = subscribed;
// }
//
// /**
// * Returns a deep copy of this instance.
// */
// @Override
// public TopicSubscription clone()
// {
// TopicSubscription record = new TopicSubscription(this.topicFilter, this.qualityOfService);
// record.setSubscribed(this.subscribed);
// return record;
// }
// }
| import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mockito;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.messaging.MessageChannel;
import org.springframework.scheduling.TaskScheduler;
import com.github.christophersmith.summer.mqtt.core.MqttClientConnectionType;
import com.github.christophersmith.summer.mqtt.core.MqttQualityOfService;
import com.github.christophersmith.summer.mqtt.core.TopicSubscription; | /*******************************************************************************
* Copyright (c) 2019 Christopher Smith - https://github.com/christophersmith
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.github.christophersmith.summer.mqtt.core.service;
public class AbstractMqttClientServiceTest
{
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void test()
{
AbstractMqttClientService clientService = Mockito.mock(AbstractMqttClientService.class, | // Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/MqttClientConnectionType.java
// public enum MqttClientConnectionType
// {
// /**
// * Represents a connection type that can only publish messages.
// */
// PUBLISHER,
// /**
// * Represents a connection type that can both publish and receive messages.
// */
// PUBSUB,
// /**
// * Represents a connection type can only receive messages.
// */
// SUBSCRIBER;
// }
//
// Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/MqttQualityOfService.java
// public enum MqttQualityOfService
// {
// /**
// * Represents a Quality of Service (Qos) of 0, for At Most Once.
// */
// QOS_0(0),
// /**
// * Represents a Quality of Service (Qos) of 1, for At Least Once.
// */
// QOS_1(1),
// /**
// * Represents a Quality of Service (Qos) of 2, for Exactly Once.
// */
// QOS_2(2);
//
// private transient final int levelIdentifier;
//
// MqttQualityOfService(final int levelIdentifier)
// {
// this.levelIdentifier = levelIdentifier;
// }
//
// /**
// * Returns an {@code int} value representation of the Quality of Service Level for this
// * instance.
// *
// * @return the Level Identifier
// */
// public int getLevelIdentifier()
// {
// return levelIdentifier;
// }
//
// /**
// * Finds the {@link MqttQualityOfService} instance that matches the {@code levelIdentifier}
// * value.
// * <p>
// * If the {@code levelIdentifier} does not match a {@code MqttQualityOfService} instance, a
// * default value of {@link MqttQualityOfService#QOS_0} will be returned.
// *
// * @param levelIdentifier the Level Identifier to search by
// * @return a {@code MqttQualityOfService} value
// */
// public static final MqttQualityOfService findByLevelIdentifier(final int levelIdentifier)
// {
// MqttQualityOfService record = QOS_0;
// for (MqttQualityOfService value : values())
// {
// if (value.getLevelIdentifier() == levelIdentifier)
// {
// record = value;
// break;
// }
// }
// return record;
// }
// }
//
// Path: summer-mqtt-core/src/main/java/com/github/christophersmith/summer/mqtt/core/TopicSubscription.java
// public final class TopicSubscription
// {
// private transient final String topicFilter;
// private transient final MqttQualityOfService qualityOfService;
// private boolean subscribed;
//
// /**
// * Creates a new {@code TopicSubscription} object that represents the Topic Filter and
// * subscription information.
// *
// * @param topicFilter the Topic Filter to subscribe to, which can include wildcards
// * @param qualityOfService the maximum QoS to use for this Topic Filter
// *
// * @throws IllegalArgumentException if the {@code topicFilter} is null or empty, or if the
// * {@code qualityOfService} is null
// */
// public TopicSubscription(final String topicFilter, final MqttQualityOfService qualityOfService)
// {
// Assert.hasText(topicFilter, "'topicFilter' must be set!");
// Assert.notNull(qualityOfService, "'qualityOfService' must be set!");
// this.topicFilter = topicFilter;
// this.qualityOfService = qualityOfService;
// }
//
// /**
// * Returns the Topic Filter for this instance.
// *
// * @return the Topic Filter for this instance
// */
// public String getTopicFilter()
// {
// return topicFilter;
// }
//
// /**
// * Returns the {@link MqttQualityOfService} for this instance.
// *
// * @return a {@link MqttQualityOfService} value
// */
// public MqttQualityOfService getQualityOfService()
// {
// return qualityOfService;
// }
//
// /**
// * Returns whether the Topic Filter is subscribed to.
// *
// * @return true if the Topic Filter is subscribed to, otherwise false
// */
// public boolean isSubscribed()
// {
// return subscribed;
// }
//
// /**
// * Sets whether the Topic Filter is currently subscribed to.
// *
// * @param subscribed true if the Topic Filter is subscribed to, otherwise false
// */
// public void setSubscribed(boolean subscribed)
// {
// this.subscribed = subscribed;
// }
//
// /**
// * Returns a deep copy of this instance.
// */
// @Override
// public TopicSubscription clone()
// {
// TopicSubscription record = new TopicSubscription(this.topicFilter, this.qualityOfService);
// record.setSubscribed(this.subscribed);
// return record;
// }
// }
// Path: summer-mqtt-core/src/test/java/com/github/christophersmith/summer/mqtt/core/service/AbstractMqttClientServiceTest.java
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mockito;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.messaging.MessageChannel;
import org.springframework.scheduling.TaskScheduler;
import com.github.christophersmith.summer.mqtt.core.MqttClientConnectionType;
import com.github.christophersmith.summer.mqtt.core.MqttQualityOfService;
import com.github.christophersmith.summer.mqtt.core.TopicSubscription;
/*******************************************************************************
* Copyright (c) 2019 Christopher Smith - https://github.com/christophersmith
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.github.christophersmith.summer.mqtt.core.service;
public class AbstractMqttClientServiceTest
{
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void test()
{
AbstractMqttClientService clientService = Mockito.mock(AbstractMqttClientService.class, | Mockito.withSettings().useConstructor(MqttClientConnectionType.PUBSUB) |
GitLqr/LQRBiliBlili | app/src/main/java/com/lqr/biliblili/mvp/ui/activity/SplashActivity.java | // Path: app/src/main/java/com/lqr/biliblili/app/utils/SystemUiVisibilityUtil.java
// public class SystemUiVisibilityUtil {
// public static void addFlags(View view, int flags) {
// view.setSystemUiVisibility(view.getSystemUiVisibility() | flags);
// }
//
// public static void clearFlags(View view, int flags) {
// view.setSystemUiVisibility(view.getSystemUiVisibility() & ~flags);
// }
//
// public static boolean hasFlags(View view, int flags) {
// return (view.getSystemUiVisibility() & flags) == flags;
// }
//
// /**
// * * 显示或隐藏StatusBar
// *
// * @param enable false 显示,true 隐藏
// */
// public static void hideStatusBar(Window window, boolean enable) {
// WindowManager.LayoutParams p = window.getAttributes();
// if (enable)
// //|=:或等于,取其一
// {
// p.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
// } else
// //&=:与等于,取其二同时满足, ~ : 取反
// {
// p.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
// }
//
// window.setAttributes(p);
// window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
// }
// }
| import android.os.Bundle;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.RxLifecycleUtils;
import com.lqr.biliblili.R;
import com.lqr.biliblili.app.utils.SystemUiVisibilityUtil;
import java.util.concurrent.TimeUnit;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers; | package com.lqr.biliblili.mvp.ui.activity;
/**
* @创建者 CSDN_LQR
* @描述 启动页面
*/
@Route(path = "/app/splash")
public class SplashActivity extends BaseActivity {
@Override
public void setupActivityComponent(AppComponent appComponent) {
}
@Override
public int initView(Bundle savedInstanceState) { | // Path: app/src/main/java/com/lqr/biliblili/app/utils/SystemUiVisibilityUtil.java
// public class SystemUiVisibilityUtil {
// public static void addFlags(View view, int flags) {
// view.setSystemUiVisibility(view.getSystemUiVisibility() | flags);
// }
//
// public static void clearFlags(View view, int flags) {
// view.setSystemUiVisibility(view.getSystemUiVisibility() & ~flags);
// }
//
// public static boolean hasFlags(View view, int flags) {
// return (view.getSystemUiVisibility() & flags) == flags;
// }
//
// /**
// * * 显示或隐藏StatusBar
// *
// * @param enable false 显示,true 隐藏
// */
// public static void hideStatusBar(Window window, boolean enable) {
// WindowManager.LayoutParams p = window.getAttributes();
// if (enable)
// //|=:或等于,取其一
// {
// p.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
// } else
// //&=:与等于,取其二同时满足, ~ : 取反
// {
// p.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
// }
//
// window.setAttributes(p);
// window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
// }
// }
// Path: app/src/main/java/com/lqr/biliblili/mvp/ui/activity/SplashActivity.java
import android.os.Bundle;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.RxLifecycleUtils;
import com.lqr.biliblili.R;
import com.lqr.biliblili.app.utils.SystemUiVisibilityUtil;
import java.util.concurrent.TimeUnit;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
package com.lqr.biliblili.mvp.ui.activity;
/**
* @创建者 CSDN_LQR
* @描述 启动页面
*/
@Route(path = "/app/splash")
public class SplashActivity extends BaseActivity {
@Override
public void setupActivityComponent(AppComponent appComponent) {
}
@Override
public int initView(Bundle savedInstanceState) { | SystemUiVisibilityUtil.hideStatusBar(getWindow(), true); |
GitLqr/LQRBiliBlili | app/src/main/java/com/lqr/biliblili/di/module/MainModule.java | // Path: app/src/main/java/com/lqr/biliblili/mvp/contract/MainContract.java
// public interface MainContract {
// //对于经常使用的关于UI的方法可以定义到IView中,如显示隐藏进度条,和显示文字消息
// interface View extends IView {
//
// }
//
// //Model层定义接口,外部只需关心Model返回的数据,无需关心内部细节,即是否使用缓存
// interface Model extends IModel {
//
// }
// }
//
// Path: app/src/main/java/com/lqr/biliblili/mvp/model/MainModel.java
// @ActivityScope
// public class MainModel extends BaseModel implements MainContract.Model {
// private Gson mGson;
// private Application mApplication;
//
// @Inject
// public MainModel(IRepositoryManager repositoryManager, Gson gson, Application application) {
// super(repositoryManager);
// this.mGson = gson;
// this.mApplication = application;
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// this.mGson = null;
// this.mApplication = null;
// }
//
// }
| import com.jess.arms.di.scope.ActivityScope;
import com.lqr.biliblili.mvp.contract.MainContract;
import com.lqr.biliblili.mvp.model.MainModel;
import dagger.Module;
import dagger.Provides; | package com.lqr.biliblili.di.module;
@Module
public class MainModule { | // Path: app/src/main/java/com/lqr/biliblili/mvp/contract/MainContract.java
// public interface MainContract {
// //对于经常使用的关于UI的方法可以定义到IView中,如显示隐藏进度条,和显示文字消息
// interface View extends IView {
//
// }
//
// //Model层定义接口,外部只需关心Model返回的数据,无需关心内部细节,即是否使用缓存
// interface Model extends IModel {
//
// }
// }
//
// Path: app/src/main/java/com/lqr/biliblili/mvp/model/MainModel.java
// @ActivityScope
// public class MainModel extends BaseModel implements MainContract.Model {
// private Gson mGson;
// private Application mApplication;
//
// @Inject
// public MainModel(IRepositoryManager repositoryManager, Gson gson, Application application) {
// super(repositoryManager);
// this.mGson = gson;
// this.mApplication = application;
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// this.mGson = null;
// this.mApplication = null;
// }
//
// }
// Path: app/src/main/java/com/lqr/biliblili/di/module/MainModule.java
import com.jess.arms.di.scope.ActivityScope;
import com.lqr.biliblili.mvp.contract.MainContract;
import com.lqr.biliblili.mvp.model.MainModel;
import dagger.Module;
import dagger.Provides;
package com.lqr.biliblili.di.module;
@Module
public class MainModule { | private MainContract.View view; |
GitLqr/LQRBiliBlili | app/src/main/java/com/lqr/biliblili/di/module/MainModule.java | // Path: app/src/main/java/com/lqr/biliblili/mvp/contract/MainContract.java
// public interface MainContract {
// //对于经常使用的关于UI的方法可以定义到IView中,如显示隐藏进度条,和显示文字消息
// interface View extends IView {
//
// }
//
// //Model层定义接口,外部只需关心Model返回的数据,无需关心内部细节,即是否使用缓存
// interface Model extends IModel {
//
// }
// }
//
// Path: app/src/main/java/com/lqr/biliblili/mvp/model/MainModel.java
// @ActivityScope
// public class MainModel extends BaseModel implements MainContract.Model {
// private Gson mGson;
// private Application mApplication;
//
// @Inject
// public MainModel(IRepositoryManager repositoryManager, Gson gson, Application application) {
// super(repositoryManager);
// this.mGson = gson;
// this.mApplication = application;
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// this.mGson = null;
// this.mApplication = null;
// }
//
// }
| import com.jess.arms.di.scope.ActivityScope;
import com.lqr.biliblili.mvp.contract.MainContract;
import com.lqr.biliblili.mvp.model.MainModel;
import dagger.Module;
import dagger.Provides; | package com.lqr.biliblili.di.module;
@Module
public class MainModule {
private MainContract.View view;
/**
* 构建MainModule时,将View的实现类传进来,这样就可以提供View的实现类给presenter
*
* @param view
*/
public MainModule(MainContract.View view) {
this.view = view;
}
@ActivityScope
@Provides
MainContract.View provideMainView() {
return this.view;
}
@ActivityScope
@Provides | // Path: app/src/main/java/com/lqr/biliblili/mvp/contract/MainContract.java
// public interface MainContract {
// //对于经常使用的关于UI的方法可以定义到IView中,如显示隐藏进度条,和显示文字消息
// interface View extends IView {
//
// }
//
// //Model层定义接口,外部只需关心Model返回的数据,无需关心内部细节,即是否使用缓存
// interface Model extends IModel {
//
// }
// }
//
// Path: app/src/main/java/com/lqr/biliblili/mvp/model/MainModel.java
// @ActivityScope
// public class MainModel extends BaseModel implements MainContract.Model {
// private Gson mGson;
// private Application mApplication;
//
// @Inject
// public MainModel(IRepositoryManager repositoryManager, Gson gson, Application application) {
// super(repositoryManager);
// this.mGson = gson;
// this.mApplication = application;
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// this.mGson = null;
// this.mApplication = null;
// }
//
// }
// Path: app/src/main/java/com/lqr/biliblili/di/module/MainModule.java
import com.jess.arms.di.scope.ActivityScope;
import com.lqr.biliblili.mvp.contract.MainContract;
import com.lqr.biliblili.mvp.model.MainModel;
import dagger.Module;
import dagger.Provides;
package com.lqr.biliblili.di.module;
@Module
public class MainModule {
private MainContract.View view;
/**
* 构建MainModule时,将View的实现类传进来,这样就可以提供View的实现类给presenter
*
* @param view
*/
public MainModule(MainContract.View view) {
this.view = view;
}
@ActivityScope
@Provides
MainContract.View provideMainView() {
return this.view;
}
@ActivityScope
@Provides | MainContract.Model provideMainModel(MainModel model) { |
GitLqr/LQRBiliBlili | app/src/main/java/com/lqr/biliblili/di/module/MainCategoryModule.java | // Path: app/src/main/java/com/lqr/biliblili/mvp/contract/MainCategoryContract.java
// public interface MainCategoryContract {
// //对于经常使用的关于UI的方法可以定义到IView中,如显示隐藏进度条,和显示文字消息
// interface View extends IView {
//
// }
//
// //Model层定义接口,外部只需关心Model返回的数据,无需关心内部细节,即是否使用缓存
// interface Model extends IModel {
//
// }
// }
//
// Path: app/src/main/java/com/lqr/biliblili/mvp/model/MainCategoryModel.java
// @FragmentScope
// public class MainCategoryModel extends BaseModel implements MainCategoryContract.Model {
//
// private Gson mGson;
// private Application mApplication;
//
// @Inject
// public MainCategoryModel(IRepositoryManager repositoryManager, Gson gson, Application application) {
// super(repositoryManager);
// mGson = gson;
// mApplication = application;
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// this.mGson = null;
// this.mApplication = null;
// }
// }
| import com.jess.arms.di.scope.FragmentScope;
import com.lqr.biliblili.mvp.contract.MainCategoryContract;
import com.lqr.biliblili.mvp.model.MainCategoryModel;
import dagger.Module;
import dagger.Provides; | package com.lqr.biliblili.di.module;
@Module
public class MainCategoryModule { | // Path: app/src/main/java/com/lqr/biliblili/mvp/contract/MainCategoryContract.java
// public interface MainCategoryContract {
// //对于经常使用的关于UI的方法可以定义到IView中,如显示隐藏进度条,和显示文字消息
// interface View extends IView {
//
// }
//
// //Model层定义接口,外部只需关心Model返回的数据,无需关心内部细节,即是否使用缓存
// interface Model extends IModel {
//
// }
// }
//
// Path: app/src/main/java/com/lqr/biliblili/mvp/model/MainCategoryModel.java
// @FragmentScope
// public class MainCategoryModel extends BaseModel implements MainCategoryContract.Model {
//
// private Gson mGson;
// private Application mApplication;
//
// @Inject
// public MainCategoryModel(IRepositoryManager repositoryManager, Gson gson, Application application) {
// super(repositoryManager);
// mGson = gson;
// mApplication = application;
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// this.mGson = null;
// this.mApplication = null;
// }
// }
// Path: app/src/main/java/com/lqr/biliblili/di/module/MainCategoryModule.java
import com.jess.arms.di.scope.FragmentScope;
import com.lqr.biliblili.mvp.contract.MainCategoryContract;
import com.lqr.biliblili.mvp.model.MainCategoryModel;
import dagger.Module;
import dagger.Provides;
package com.lqr.biliblili.di.module;
@Module
public class MainCategoryModule { | private MainCategoryContract.View view; |
GitLqr/LQRBiliBlili | app/src/main/java/com/lqr/biliblili/di/module/MainCategoryModule.java | // Path: app/src/main/java/com/lqr/biliblili/mvp/contract/MainCategoryContract.java
// public interface MainCategoryContract {
// //对于经常使用的关于UI的方法可以定义到IView中,如显示隐藏进度条,和显示文字消息
// interface View extends IView {
//
// }
//
// //Model层定义接口,外部只需关心Model返回的数据,无需关心内部细节,即是否使用缓存
// interface Model extends IModel {
//
// }
// }
//
// Path: app/src/main/java/com/lqr/biliblili/mvp/model/MainCategoryModel.java
// @FragmentScope
// public class MainCategoryModel extends BaseModel implements MainCategoryContract.Model {
//
// private Gson mGson;
// private Application mApplication;
//
// @Inject
// public MainCategoryModel(IRepositoryManager repositoryManager, Gson gson, Application application) {
// super(repositoryManager);
// mGson = gson;
// mApplication = application;
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// this.mGson = null;
// this.mApplication = null;
// }
// }
| import com.jess.arms.di.scope.FragmentScope;
import com.lqr.biliblili.mvp.contract.MainCategoryContract;
import com.lqr.biliblili.mvp.model.MainCategoryModel;
import dagger.Module;
import dagger.Provides; | package com.lqr.biliblili.di.module;
@Module
public class MainCategoryModule {
private MainCategoryContract.View view;
public MainCategoryModule(MainCategoryContract.View view) {
this.view = view;
}
@FragmentScope
@Provides
MainCategoryContract.View provideMainCategoryView() {
return this.view;
}
@FragmentScope
@Provides | // Path: app/src/main/java/com/lqr/biliblili/mvp/contract/MainCategoryContract.java
// public interface MainCategoryContract {
// //对于经常使用的关于UI的方法可以定义到IView中,如显示隐藏进度条,和显示文字消息
// interface View extends IView {
//
// }
//
// //Model层定义接口,外部只需关心Model返回的数据,无需关心内部细节,即是否使用缓存
// interface Model extends IModel {
//
// }
// }
//
// Path: app/src/main/java/com/lqr/biliblili/mvp/model/MainCategoryModel.java
// @FragmentScope
// public class MainCategoryModel extends BaseModel implements MainCategoryContract.Model {
//
// private Gson mGson;
// private Application mApplication;
//
// @Inject
// public MainCategoryModel(IRepositoryManager repositoryManager, Gson gson, Application application) {
// super(repositoryManager);
// mGson = gson;
// mApplication = application;
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// this.mGson = null;
// this.mApplication = null;
// }
// }
// Path: app/src/main/java/com/lqr/biliblili/di/module/MainCategoryModule.java
import com.jess.arms.di.scope.FragmentScope;
import com.lqr.biliblili.mvp.contract.MainCategoryContract;
import com.lqr.biliblili.mvp.model.MainCategoryModel;
import dagger.Module;
import dagger.Provides;
package com.lqr.biliblili.di.module;
@Module
public class MainCategoryModule {
private MainCategoryContract.View view;
public MainCategoryModule(MainCategoryContract.View view) {
this.view = view;
}
@FragmentScope
@Provides
MainCategoryContract.View provideMainCategoryView() {
return this.view;
}
@FragmentScope
@Provides | MainCategoryContract.Model provideMainCategoryModel(MainCategoryModel model) { |
GitLqr/LQRBiliBlili | app/src/main/java/com/lqr/biliblili/di/component/RecommendComponent.java | // Path: app/src/main/java/com/lqr/biliblili/di/module/RecommendModule.java
// @Module
// public class RecommendModule {
//
// private RecommendContract.View view;
//
// public RecommendModule(RecommendContract.View view) {
// this.view = view;
// }
//
// @FragmentScope
// @Provides
// public RecommendContract.View provideView() {
// return view;
// }
//
// @FragmentScope
// @Provides
// public RecommendContract.Model provideModel(RecommendModel model) {
// return model;
// }
// }
//
// Path: app/src/main/java/com/lqr/biliblili/mvp/ui/fragment/main/home/RecommendFragment.java
// public class RecommendFragment extends MySupportFragment<RecommendPresenter> implements RecommendContract.View {
//
// private View mRootView;
//
// @BindView(R.id.refresh_layout)
// SwipeRefreshLayout mRefreshLayout;
// @BindView(R.id.recyclerview)
// RecyclerView mRecyclerView;
//
// public static RecommendFragment newInstance() {
// return new RecommendFragment();
// }
//
// @Override
// public void setupFragmentComponent(AppComponent appComponent) {
// DaggerRecommendComponent
// .builder()
// .recommendModule(new RecommendModule(this))
// .appComponent(appComponent)
// .build()
// .inject(this);
// }
//
// @Override
// public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// if (mRootView == null)
// mRootView = inflater.inflate(R.layout.fragment_recommend_main_home, container, false);
// return mRootView;
// }
//
// @Override
// public void initData(Bundle savedInstanceState) {
// initRefreshLayout();
// }
//
// @Override
// public void setData(Object data) {
//
// }
//
// @Override
// public void onLazyInitView(@Nullable Bundle savedInstanceState) {
// super.onLazyInitView(savedInstanceState);
// mPresenter.loadData(0, false, true);
// }
//
// @Override
// public void showLoading() {
// mRefreshLayout.setRefreshing(true);
// }
//
// @Override
// public void hideLoading() {
// mRefreshLayout.setRefreshing(false);
// }
//
// @Override
// public void showMessage(String message) {
//
// }
//
// @Override
// public void launchActivity(Intent intent) {
//
// }
//
// @Override
// public void killMyself() {
//
// }
//
// private void initRefreshLayout() {
// mRefreshLayout.setColorSchemeColors(ArmsUtils.getColor(_mActivity, R.color.colorPrimary));
// mRefreshLayout.setOnRefreshListener(() -> mPresenter.loadData(mPresenter.getIdx(true), true, false));
// }
//
// @Override
// public void setRecyclerAdapter(RecommendMultiItemAdapter adapter) {
// GridLayoutManager gridLayoutManager = new GridLayoutManager(_mActivity, 2);
// mRecyclerView.setLayoutManager(gridLayoutManager);
// mRecyclerView.setAdapter(adapter);
// gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
// @Override
// public int getSpanSize(int position) {
// // 上拉加载更多视图
// if (position == adapter.getData().size()) {
// return 2;
// }
// return adapter.getData().get(position).getSpanSize();
// }
// });
// }
//
// @Override
// public void recyclerScrollToPosition(int position) {
// mRecyclerView.scrollToPosition(position);
// }
// }
| import com.jess.arms.di.component.AppComponent;
import com.jess.arms.di.scope.FragmentScope;
import com.lqr.biliblili.di.module.RecommendModule;
import com.lqr.biliblili.mvp.ui.fragment.main.home.RecommendFragment;
import dagger.Component; | package com.lqr.biliblili.di.component;
@FragmentScope
@Component(modules = RecommendModule.class, dependencies = AppComponent.class)
public interface RecommendComponent { | // Path: app/src/main/java/com/lqr/biliblili/di/module/RecommendModule.java
// @Module
// public class RecommendModule {
//
// private RecommendContract.View view;
//
// public RecommendModule(RecommendContract.View view) {
// this.view = view;
// }
//
// @FragmentScope
// @Provides
// public RecommendContract.View provideView() {
// return view;
// }
//
// @FragmentScope
// @Provides
// public RecommendContract.Model provideModel(RecommendModel model) {
// return model;
// }
// }
//
// Path: app/src/main/java/com/lqr/biliblili/mvp/ui/fragment/main/home/RecommendFragment.java
// public class RecommendFragment extends MySupportFragment<RecommendPresenter> implements RecommendContract.View {
//
// private View mRootView;
//
// @BindView(R.id.refresh_layout)
// SwipeRefreshLayout mRefreshLayout;
// @BindView(R.id.recyclerview)
// RecyclerView mRecyclerView;
//
// public static RecommendFragment newInstance() {
// return new RecommendFragment();
// }
//
// @Override
// public void setupFragmentComponent(AppComponent appComponent) {
// DaggerRecommendComponent
// .builder()
// .recommendModule(new RecommendModule(this))
// .appComponent(appComponent)
// .build()
// .inject(this);
// }
//
// @Override
// public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// if (mRootView == null)
// mRootView = inflater.inflate(R.layout.fragment_recommend_main_home, container, false);
// return mRootView;
// }
//
// @Override
// public void initData(Bundle savedInstanceState) {
// initRefreshLayout();
// }
//
// @Override
// public void setData(Object data) {
//
// }
//
// @Override
// public void onLazyInitView(@Nullable Bundle savedInstanceState) {
// super.onLazyInitView(savedInstanceState);
// mPresenter.loadData(0, false, true);
// }
//
// @Override
// public void showLoading() {
// mRefreshLayout.setRefreshing(true);
// }
//
// @Override
// public void hideLoading() {
// mRefreshLayout.setRefreshing(false);
// }
//
// @Override
// public void showMessage(String message) {
//
// }
//
// @Override
// public void launchActivity(Intent intent) {
//
// }
//
// @Override
// public void killMyself() {
//
// }
//
// private void initRefreshLayout() {
// mRefreshLayout.setColorSchemeColors(ArmsUtils.getColor(_mActivity, R.color.colorPrimary));
// mRefreshLayout.setOnRefreshListener(() -> mPresenter.loadData(mPresenter.getIdx(true), true, false));
// }
//
// @Override
// public void setRecyclerAdapter(RecommendMultiItemAdapter adapter) {
// GridLayoutManager gridLayoutManager = new GridLayoutManager(_mActivity, 2);
// mRecyclerView.setLayoutManager(gridLayoutManager);
// mRecyclerView.setAdapter(adapter);
// gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
// @Override
// public int getSpanSize(int position) {
// // 上拉加载更多视图
// if (position == adapter.getData().size()) {
// return 2;
// }
// return adapter.getData().get(position).getSpanSize();
// }
// });
// }
//
// @Override
// public void recyclerScrollToPosition(int position) {
// mRecyclerView.scrollToPosition(position);
// }
// }
// Path: app/src/main/java/com/lqr/biliblili/di/component/RecommendComponent.java
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.di.scope.FragmentScope;
import com.lqr.biliblili.di.module.RecommendModule;
import com.lqr.biliblili.mvp.ui.fragment.main.home.RecommendFragment;
import dagger.Component;
package com.lqr.biliblili.di.component;
@FragmentScope
@Component(modules = RecommendModule.class, dependencies = AppComponent.class)
public interface RecommendComponent { | void inject(RecommendFragment fragment); |
GitLqr/LQRBiliBlili | app/src/main/java/com/lqr/biliblili/di/module/VideoDetailModule.java | // Path: app/src/main/java/com/lqr/biliblili/mvp/contract/VideoDetailContract.java
// public interface VideoDetailContract {
// //对于经常使用的关于UI的方法可以定义到IView中,如显示隐藏进度条,和显示文字消息
// interface View extends IView {
// void setTvAvStr(String av);
//
// ImageView getIvCover();
//
// void initViewPager(VideoDetail videoDetail);
//
// void setTvVideoStartInfoStr(String tip);
//
// void playVideo(PlayUrl playUrl);
//
// }
//
// //Model层定义接口,外部只需关心Model返回的数据,无需关心内部细节,即是否使用缓存
// interface Model extends IModel {
// Observable<Summary> getSummaryData(String aid);
//
// Observable<Reply> getReplyData(String aid, int pn, int ps);
//
// Observable<PlayUrl> getPlayurl(String aid);
// }
// }
//
// Path: app/src/main/java/com/lqr/biliblili/mvp/model/VideoDetailModel.java
// @ActivityScope
// public class VideoDetailModel extends BaseModel implements VideoDetailContract.Model {
// private Gson mGson;
// private Application mApplication;
//
// @Inject
// public VideoDetailModel(IRepositoryManager repositoryManager, Gson gson, Application application) {
// super(repositoryManager);
// this.mGson = gson;
// this.mApplication = application;
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// this.mGson = null;
// this.mApplication = null;
// }
//
// @Override
// public Observable<Summary> getSummaryData(String aid) {
// return mRepositoryManager.obtainRetrofitService(VideoDetailService.class).getSummaryData(aid);
// }
//
// @Override
// public Observable<Reply> getReplyData(String oid, int pn, int ps) {
// return mRepositoryManager.obtainRetrofitService(VideoDetailService.class).getReplyData(oid, pn, ps);
// }
//
// @Override
// public Observable<PlayUrl> getPlayurl(String aid) {
// return mRepositoryManager.obtainRetrofitService(VideoDetailService.class).getPlayurl(aid);
// }
// }
| import com.jess.arms.di.scope.ActivityScope;
import dagger.Module;
import dagger.Provides;
import com.lqr.biliblili.mvp.contract.VideoDetailContract;
import com.lqr.biliblili.mvp.model.VideoDetailModel; | package com.lqr.biliblili.di.module;
@Module
public class VideoDetailModule { | // Path: app/src/main/java/com/lqr/biliblili/mvp/contract/VideoDetailContract.java
// public interface VideoDetailContract {
// //对于经常使用的关于UI的方法可以定义到IView中,如显示隐藏进度条,和显示文字消息
// interface View extends IView {
// void setTvAvStr(String av);
//
// ImageView getIvCover();
//
// void initViewPager(VideoDetail videoDetail);
//
// void setTvVideoStartInfoStr(String tip);
//
// void playVideo(PlayUrl playUrl);
//
// }
//
// //Model层定义接口,外部只需关心Model返回的数据,无需关心内部细节,即是否使用缓存
// interface Model extends IModel {
// Observable<Summary> getSummaryData(String aid);
//
// Observable<Reply> getReplyData(String aid, int pn, int ps);
//
// Observable<PlayUrl> getPlayurl(String aid);
// }
// }
//
// Path: app/src/main/java/com/lqr/biliblili/mvp/model/VideoDetailModel.java
// @ActivityScope
// public class VideoDetailModel extends BaseModel implements VideoDetailContract.Model {
// private Gson mGson;
// private Application mApplication;
//
// @Inject
// public VideoDetailModel(IRepositoryManager repositoryManager, Gson gson, Application application) {
// super(repositoryManager);
// this.mGson = gson;
// this.mApplication = application;
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// this.mGson = null;
// this.mApplication = null;
// }
//
// @Override
// public Observable<Summary> getSummaryData(String aid) {
// return mRepositoryManager.obtainRetrofitService(VideoDetailService.class).getSummaryData(aid);
// }
//
// @Override
// public Observable<Reply> getReplyData(String oid, int pn, int ps) {
// return mRepositoryManager.obtainRetrofitService(VideoDetailService.class).getReplyData(oid, pn, ps);
// }
//
// @Override
// public Observable<PlayUrl> getPlayurl(String aid) {
// return mRepositoryManager.obtainRetrofitService(VideoDetailService.class).getPlayurl(aid);
// }
// }
// Path: app/src/main/java/com/lqr/biliblili/di/module/VideoDetailModule.java
import com.jess.arms.di.scope.ActivityScope;
import dagger.Module;
import dagger.Provides;
import com.lqr.biliblili.mvp.contract.VideoDetailContract;
import com.lqr.biliblili.mvp.model.VideoDetailModel;
package com.lqr.biliblili.di.module;
@Module
public class VideoDetailModule { | private VideoDetailContract.View view; |
GitLqr/LQRBiliBlili | app/src/main/java/com/lqr/biliblili/di/module/VideoDetailModule.java | // Path: app/src/main/java/com/lqr/biliblili/mvp/contract/VideoDetailContract.java
// public interface VideoDetailContract {
// //对于经常使用的关于UI的方法可以定义到IView中,如显示隐藏进度条,和显示文字消息
// interface View extends IView {
// void setTvAvStr(String av);
//
// ImageView getIvCover();
//
// void initViewPager(VideoDetail videoDetail);
//
// void setTvVideoStartInfoStr(String tip);
//
// void playVideo(PlayUrl playUrl);
//
// }
//
// //Model层定义接口,外部只需关心Model返回的数据,无需关心内部细节,即是否使用缓存
// interface Model extends IModel {
// Observable<Summary> getSummaryData(String aid);
//
// Observable<Reply> getReplyData(String aid, int pn, int ps);
//
// Observable<PlayUrl> getPlayurl(String aid);
// }
// }
//
// Path: app/src/main/java/com/lqr/biliblili/mvp/model/VideoDetailModel.java
// @ActivityScope
// public class VideoDetailModel extends BaseModel implements VideoDetailContract.Model {
// private Gson mGson;
// private Application mApplication;
//
// @Inject
// public VideoDetailModel(IRepositoryManager repositoryManager, Gson gson, Application application) {
// super(repositoryManager);
// this.mGson = gson;
// this.mApplication = application;
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// this.mGson = null;
// this.mApplication = null;
// }
//
// @Override
// public Observable<Summary> getSummaryData(String aid) {
// return mRepositoryManager.obtainRetrofitService(VideoDetailService.class).getSummaryData(aid);
// }
//
// @Override
// public Observable<Reply> getReplyData(String oid, int pn, int ps) {
// return mRepositoryManager.obtainRetrofitService(VideoDetailService.class).getReplyData(oid, pn, ps);
// }
//
// @Override
// public Observable<PlayUrl> getPlayurl(String aid) {
// return mRepositoryManager.obtainRetrofitService(VideoDetailService.class).getPlayurl(aid);
// }
// }
| import com.jess.arms.di.scope.ActivityScope;
import dagger.Module;
import dagger.Provides;
import com.lqr.biliblili.mvp.contract.VideoDetailContract;
import com.lqr.biliblili.mvp.model.VideoDetailModel; | package com.lqr.biliblili.di.module;
@Module
public class VideoDetailModule {
private VideoDetailContract.View view;
/**
* 构建VideoDetailModule时,将View的实现类传进来,这样就可以提供View的实现类给presenter
*
* @param view
*/
public VideoDetailModule(VideoDetailContract.View view) {
this.view = view;
}
@ActivityScope
@Provides
VideoDetailContract.View provideVideoDetailView() {
return this.view;
}
@ActivityScope
@Provides | // Path: app/src/main/java/com/lqr/biliblili/mvp/contract/VideoDetailContract.java
// public interface VideoDetailContract {
// //对于经常使用的关于UI的方法可以定义到IView中,如显示隐藏进度条,和显示文字消息
// interface View extends IView {
// void setTvAvStr(String av);
//
// ImageView getIvCover();
//
// void initViewPager(VideoDetail videoDetail);
//
// void setTvVideoStartInfoStr(String tip);
//
// void playVideo(PlayUrl playUrl);
//
// }
//
// //Model层定义接口,外部只需关心Model返回的数据,无需关心内部细节,即是否使用缓存
// interface Model extends IModel {
// Observable<Summary> getSummaryData(String aid);
//
// Observable<Reply> getReplyData(String aid, int pn, int ps);
//
// Observable<PlayUrl> getPlayurl(String aid);
// }
// }
//
// Path: app/src/main/java/com/lqr/biliblili/mvp/model/VideoDetailModel.java
// @ActivityScope
// public class VideoDetailModel extends BaseModel implements VideoDetailContract.Model {
// private Gson mGson;
// private Application mApplication;
//
// @Inject
// public VideoDetailModel(IRepositoryManager repositoryManager, Gson gson, Application application) {
// super(repositoryManager);
// this.mGson = gson;
// this.mApplication = application;
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// this.mGson = null;
// this.mApplication = null;
// }
//
// @Override
// public Observable<Summary> getSummaryData(String aid) {
// return mRepositoryManager.obtainRetrofitService(VideoDetailService.class).getSummaryData(aid);
// }
//
// @Override
// public Observable<Reply> getReplyData(String oid, int pn, int ps) {
// return mRepositoryManager.obtainRetrofitService(VideoDetailService.class).getReplyData(oid, pn, ps);
// }
//
// @Override
// public Observable<PlayUrl> getPlayurl(String aid) {
// return mRepositoryManager.obtainRetrofitService(VideoDetailService.class).getPlayurl(aid);
// }
// }
// Path: app/src/main/java/com/lqr/biliblili/di/module/VideoDetailModule.java
import com.jess.arms.di.scope.ActivityScope;
import dagger.Module;
import dagger.Provides;
import com.lqr.biliblili.mvp.contract.VideoDetailContract;
import com.lqr.biliblili.mvp.model.VideoDetailModel;
package com.lqr.biliblili.di.module;
@Module
public class VideoDetailModule {
private VideoDetailContract.View view;
/**
* 构建VideoDetailModule时,将View的实现类传进来,这样就可以提供View的实现类给presenter
*
* @param view
*/
public VideoDetailModule(VideoDetailContract.View view) {
this.view = view;
}
@ActivityScope
@Provides
VideoDetailContract.View provideVideoDetailView() {
return this.view;
}
@ActivityScope
@Provides | VideoDetailContract.Model provideVideoDetailModel(VideoDetailModel model) { |
GitLqr/LQRBiliBlili | app/src/main/java/com/lqr/biliblili/di/module/RecommendModule.java | // Path: app/src/main/java/com/lqr/biliblili/mvp/contract/RecommendContract.java
// public interface RecommendContract {
//
// interface View extends IView {
//
// void setRecyclerAdapter(RecommendMultiItemAdapter adapter);
//
// void recyclerScrollToPosition(int position);
// }
//
// interface Model extends IModel {
// /**
// * @param idx 下拉刷新时取第一个数据的idx,上拉加载更多时取最后一个数据的idx
// * @param refresh 下拉刷新时取"true",上拉加载更多时取"false"
// * @param clearCache 第一次加载数据时为true,其他时候为false(对应的true时,login_event的值为1[获取banner],为false时,login_event的值为0)
// * @return
// */
// Observable<IndexData> getRecommendIndexData(int idx, boolean refresh, boolean clearCache);
//
// List<RecommendMultiItem> parseIndexData(IndexData indexData);
//
// }
// }
//
// Path: app/src/main/java/com/lqr/biliblili/mvp/model/RecommendModel.java
// @FragmentScope
// public class RecommendModel extends BaseModel implements RecommendContract.Model {
//
// private boolean isOdd = true;
// private Gson mGson;
// private Application mApplication;
//
// @Inject
// public RecommendModel(IRepositoryManager repositoryManager, Gson gson, Application application) {
// super(repositoryManager);
// mGson = gson;
// mApplication = application;
// RetrofitUrlManager.getInstance().putDomain("recommend", Api.RECOMMEND_BASE_URL);
// }
//
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// this.mGson = null;
// this.mApplication = null;
// }
//
// @Override
// public Observable<IndexData> getRecommendIndexData(int idx, boolean refresh, boolean clearCache) {
// return Observable.just(mRepositoryManager
// .obtainRetrofitService(RecommendService.class)
// .getRecommendIndexData(idx, refresh ? "true" : "false", clearCache ? 1 : 0))
// .flatMap(new Function<Observable<IndexData>, ObservableSource<IndexData>>() {
// @Override
// public ObservableSource<IndexData> apply(@NonNull Observable<IndexData> indexDataObservable) throws Exception {
// return mRepositoryManager
// .obtainCacheService(RecommendCache.class)
// .getRecommendIndexData(indexDataObservable, new DynamicKey(idx), new EvictProvider(clearCache))
// .map(indexDataReply -> indexDataReply.getData());
// }
// });
// }
//
//
// @Override
// public List<RecommendMultiItem> parseIndexData(IndexData indexData) {
// List<RecommendMultiItem> list = new ArrayList<>();
// List<IndexData.DataBean> data = indexData.getData();
// if (data != null) {
// for (int i = 0; i < data.size(); i++) {
// IndexData.DataBean dataBean = data.get(i);
// if (dataBean != null) {
// String gotoX = dataBean.getGotoX();
// if (RecommendMultiItem.isWeNeed(gotoX)) {
// RecommendMultiItem item = new RecommendMultiItem();
// item.setItemTypeWithGoto(gotoX, dataBean.getRcmd_reason() == null);
// item.setIndexDataBean(dataBean);
// if (RecommendMultiItem.isItemData(gotoX)) {
// item.setOdd(isOdd);
// isOdd = !isOdd;
// } else {
// isOdd = true;
// }
// list.add(item);
// }
// }
// }
// }
// return list;
// }
// }
| import com.jess.arms.di.scope.FragmentScope;
import com.lqr.biliblili.mvp.contract.RecommendContract;
import com.lqr.biliblili.mvp.model.RecommendModel;
import dagger.Module;
import dagger.Provides; | package com.lqr.biliblili.di.module;
@Module
public class RecommendModule {
| // Path: app/src/main/java/com/lqr/biliblili/mvp/contract/RecommendContract.java
// public interface RecommendContract {
//
// interface View extends IView {
//
// void setRecyclerAdapter(RecommendMultiItemAdapter adapter);
//
// void recyclerScrollToPosition(int position);
// }
//
// interface Model extends IModel {
// /**
// * @param idx 下拉刷新时取第一个数据的idx,上拉加载更多时取最后一个数据的idx
// * @param refresh 下拉刷新时取"true",上拉加载更多时取"false"
// * @param clearCache 第一次加载数据时为true,其他时候为false(对应的true时,login_event的值为1[获取banner],为false时,login_event的值为0)
// * @return
// */
// Observable<IndexData> getRecommendIndexData(int idx, boolean refresh, boolean clearCache);
//
// List<RecommendMultiItem> parseIndexData(IndexData indexData);
//
// }
// }
//
// Path: app/src/main/java/com/lqr/biliblili/mvp/model/RecommendModel.java
// @FragmentScope
// public class RecommendModel extends BaseModel implements RecommendContract.Model {
//
// private boolean isOdd = true;
// private Gson mGson;
// private Application mApplication;
//
// @Inject
// public RecommendModel(IRepositoryManager repositoryManager, Gson gson, Application application) {
// super(repositoryManager);
// mGson = gson;
// mApplication = application;
// RetrofitUrlManager.getInstance().putDomain("recommend", Api.RECOMMEND_BASE_URL);
// }
//
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// this.mGson = null;
// this.mApplication = null;
// }
//
// @Override
// public Observable<IndexData> getRecommendIndexData(int idx, boolean refresh, boolean clearCache) {
// return Observable.just(mRepositoryManager
// .obtainRetrofitService(RecommendService.class)
// .getRecommendIndexData(idx, refresh ? "true" : "false", clearCache ? 1 : 0))
// .flatMap(new Function<Observable<IndexData>, ObservableSource<IndexData>>() {
// @Override
// public ObservableSource<IndexData> apply(@NonNull Observable<IndexData> indexDataObservable) throws Exception {
// return mRepositoryManager
// .obtainCacheService(RecommendCache.class)
// .getRecommendIndexData(indexDataObservable, new DynamicKey(idx), new EvictProvider(clearCache))
// .map(indexDataReply -> indexDataReply.getData());
// }
// });
// }
//
//
// @Override
// public List<RecommendMultiItem> parseIndexData(IndexData indexData) {
// List<RecommendMultiItem> list = new ArrayList<>();
// List<IndexData.DataBean> data = indexData.getData();
// if (data != null) {
// for (int i = 0; i < data.size(); i++) {
// IndexData.DataBean dataBean = data.get(i);
// if (dataBean != null) {
// String gotoX = dataBean.getGotoX();
// if (RecommendMultiItem.isWeNeed(gotoX)) {
// RecommendMultiItem item = new RecommendMultiItem();
// item.setItemTypeWithGoto(gotoX, dataBean.getRcmd_reason() == null);
// item.setIndexDataBean(dataBean);
// if (RecommendMultiItem.isItemData(gotoX)) {
// item.setOdd(isOdd);
// isOdd = !isOdd;
// } else {
// isOdd = true;
// }
// list.add(item);
// }
// }
// }
// }
// return list;
// }
// }
// Path: app/src/main/java/com/lqr/biliblili/di/module/RecommendModule.java
import com.jess.arms.di.scope.FragmentScope;
import com.lqr.biliblili.mvp.contract.RecommendContract;
import com.lqr.biliblili.mvp.model.RecommendModel;
import dagger.Module;
import dagger.Provides;
package com.lqr.biliblili.di.module;
@Module
public class RecommendModule {
| private RecommendContract.View view; |
GitLqr/LQRBiliBlili | app/src/main/java/com/lqr/biliblili/di/module/RecommendModule.java | // Path: app/src/main/java/com/lqr/biliblili/mvp/contract/RecommendContract.java
// public interface RecommendContract {
//
// interface View extends IView {
//
// void setRecyclerAdapter(RecommendMultiItemAdapter adapter);
//
// void recyclerScrollToPosition(int position);
// }
//
// interface Model extends IModel {
// /**
// * @param idx 下拉刷新时取第一个数据的idx,上拉加载更多时取最后一个数据的idx
// * @param refresh 下拉刷新时取"true",上拉加载更多时取"false"
// * @param clearCache 第一次加载数据时为true,其他时候为false(对应的true时,login_event的值为1[获取banner],为false时,login_event的值为0)
// * @return
// */
// Observable<IndexData> getRecommendIndexData(int idx, boolean refresh, boolean clearCache);
//
// List<RecommendMultiItem> parseIndexData(IndexData indexData);
//
// }
// }
//
// Path: app/src/main/java/com/lqr/biliblili/mvp/model/RecommendModel.java
// @FragmentScope
// public class RecommendModel extends BaseModel implements RecommendContract.Model {
//
// private boolean isOdd = true;
// private Gson mGson;
// private Application mApplication;
//
// @Inject
// public RecommendModel(IRepositoryManager repositoryManager, Gson gson, Application application) {
// super(repositoryManager);
// mGson = gson;
// mApplication = application;
// RetrofitUrlManager.getInstance().putDomain("recommend", Api.RECOMMEND_BASE_URL);
// }
//
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// this.mGson = null;
// this.mApplication = null;
// }
//
// @Override
// public Observable<IndexData> getRecommendIndexData(int idx, boolean refresh, boolean clearCache) {
// return Observable.just(mRepositoryManager
// .obtainRetrofitService(RecommendService.class)
// .getRecommendIndexData(idx, refresh ? "true" : "false", clearCache ? 1 : 0))
// .flatMap(new Function<Observable<IndexData>, ObservableSource<IndexData>>() {
// @Override
// public ObservableSource<IndexData> apply(@NonNull Observable<IndexData> indexDataObservable) throws Exception {
// return mRepositoryManager
// .obtainCacheService(RecommendCache.class)
// .getRecommendIndexData(indexDataObservable, new DynamicKey(idx), new EvictProvider(clearCache))
// .map(indexDataReply -> indexDataReply.getData());
// }
// });
// }
//
//
// @Override
// public List<RecommendMultiItem> parseIndexData(IndexData indexData) {
// List<RecommendMultiItem> list = new ArrayList<>();
// List<IndexData.DataBean> data = indexData.getData();
// if (data != null) {
// for (int i = 0; i < data.size(); i++) {
// IndexData.DataBean dataBean = data.get(i);
// if (dataBean != null) {
// String gotoX = dataBean.getGotoX();
// if (RecommendMultiItem.isWeNeed(gotoX)) {
// RecommendMultiItem item = new RecommendMultiItem();
// item.setItemTypeWithGoto(gotoX, dataBean.getRcmd_reason() == null);
// item.setIndexDataBean(dataBean);
// if (RecommendMultiItem.isItemData(gotoX)) {
// item.setOdd(isOdd);
// isOdd = !isOdd;
// } else {
// isOdd = true;
// }
// list.add(item);
// }
// }
// }
// }
// return list;
// }
// }
| import com.jess.arms.di.scope.FragmentScope;
import com.lqr.biliblili.mvp.contract.RecommendContract;
import com.lqr.biliblili.mvp.model.RecommendModel;
import dagger.Module;
import dagger.Provides; | package com.lqr.biliblili.di.module;
@Module
public class RecommendModule {
private RecommendContract.View view;
public RecommendModule(RecommendContract.View view) {
this.view = view;
}
@FragmentScope
@Provides
public RecommendContract.View provideView() {
return view;
}
@FragmentScope
@Provides | // Path: app/src/main/java/com/lqr/biliblili/mvp/contract/RecommendContract.java
// public interface RecommendContract {
//
// interface View extends IView {
//
// void setRecyclerAdapter(RecommendMultiItemAdapter adapter);
//
// void recyclerScrollToPosition(int position);
// }
//
// interface Model extends IModel {
// /**
// * @param idx 下拉刷新时取第一个数据的idx,上拉加载更多时取最后一个数据的idx
// * @param refresh 下拉刷新时取"true",上拉加载更多时取"false"
// * @param clearCache 第一次加载数据时为true,其他时候为false(对应的true时,login_event的值为1[获取banner],为false时,login_event的值为0)
// * @return
// */
// Observable<IndexData> getRecommendIndexData(int idx, boolean refresh, boolean clearCache);
//
// List<RecommendMultiItem> parseIndexData(IndexData indexData);
//
// }
// }
//
// Path: app/src/main/java/com/lqr/biliblili/mvp/model/RecommendModel.java
// @FragmentScope
// public class RecommendModel extends BaseModel implements RecommendContract.Model {
//
// private boolean isOdd = true;
// private Gson mGson;
// private Application mApplication;
//
// @Inject
// public RecommendModel(IRepositoryManager repositoryManager, Gson gson, Application application) {
// super(repositoryManager);
// mGson = gson;
// mApplication = application;
// RetrofitUrlManager.getInstance().putDomain("recommend", Api.RECOMMEND_BASE_URL);
// }
//
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// this.mGson = null;
// this.mApplication = null;
// }
//
// @Override
// public Observable<IndexData> getRecommendIndexData(int idx, boolean refresh, boolean clearCache) {
// return Observable.just(mRepositoryManager
// .obtainRetrofitService(RecommendService.class)
// .getRecommendIndexData(idx, refresh ? "true" : "false", clearCache ? 1 : 0))
// .flatMap(new Function<Observable<IndexData>, ObservableSource<IndexData>>() {
// @Override
// public ObservableSource<IndexData> apply(@NonNull Observable<IndexData> indexDataObservable) throws Exception {
// return mRepositoryManager
// .obtainCacheService(RecommendCache.class)
// .getRecommendIndexData(indexDataObservable, new DynamicKey(idx), new EvictProvider(clearCache))
// .map(indexDataReply -> indexDataReply.getData());
// }
// });
// }
//
//
// @Override
// public List<RecommendMultiItem> parseIndexData(IndexData indexData) {
// List<RecommendMultiItem> list = new ArrayList<>();
// List<IndexData.DataBean> data = indexData.getData();
// if (data != null) {
// for (int i = 0; i < data.size(); i++) {
// IndexData.DataBean dataBean = data.get(i);
// if (dataBean != null) {
// String gotoX = dataBean.getGotoX();
// if (RecommendMultiItem.isWeNeed(gotoX)) {
// RecommendMultiItem item = new RecommendMultiItem();
// item.setItemTypeWithGoto(gotoX, dataBean.getRcmd_reason() == null);
// item.setIndexDataBean(dataBean);
// if (RecommendMultiItem.isItemData(gotoX)) {
// item.setOdd(isOdd);
// isOdd = !isOdd;
// } else {
// isOdd = true;
// }
// list.add(item);
// }
// }
// }
// }
// return list;
// }
// }
// Path: app/src/main/java/com/lqr/biliblili/di/module/RecommendModule.java
import com.jess.arms.di.scope.FragmentScope;
import com.lqr.biliblili.mvp.contract.RecommendContract;
import com.lqr.biliblili.mvp.model.RecommendModel;
import dagger.Module;
import dagger.Provides;
package com.lqr.biliblili.di.module;
@Module
public class RecommendModule {
private RecommendContract.View view;
public RecommendModule(RecommendContract.View view) {
this.view = view;
}
@FragmentScope
@Provides
public RecommendContract.View provideView() {
return view;
}
@FragmentScope
@Provides | public RecommendContract.Model provideModel(RecommendModel model) { |
GitLqr/LQRBiliBlili | app/src/main/java/com/lqr/biliblili/app/config/applyOptions/MyRetrofitConfiguration.java | // Path: app/src/main/java/com/lqr/biliblili/app/config/applyOptions/intercept/LoggingInterceptor.java
// public class LoggingInterceptor implements Interceptor {
// @Override
// public Response intercept(Chain chain) throws IOException {
// //这个chain里面包含了request和response,所以你要什么都可以从这里拿
// Request request = chain.request();
// long t1 = System.nanoTime();//请求发起的时间
//
// String method = request.method();
// if ("POST".equals(method)) {
// StringBuilder sb = new StringBuilder();
// if (request.body() instanceof FormBody) {
// FormBody body = (FormBody) request.body();
// for (int i = 0; i < body.size(); i++) {
// sb.append(body.encodedName(i) + "=" + body.encodedValue(i) + ",");
// }
// sb.delete(sb.length() - 1, sb.length());
// Log.d("CSDN_LQR", String.format("发送请求 %s on %s %n%s %nRequestParams:{%s}",
// request.url(), chain.connection(), request.headers(), sb.toString()));
// }
// } else {
// Log.d("CSDN_LQR", String.format("发送请求 %s on %s%n%s",
// request.url(), chain.connection(), request.headers()));
// }
// Response response = chain.proceed(request);
// long t2 = System.nanoTime();//收到响应的时间
// //这里不能直接使用response.body().string()的方式输出日志
// //因为response.body().string()之后,response中的流会被关闭,程序会报错,我们需要创建出一
// //个新的response给应用层处理
// ResponseBody responseBody = response.peekBody(1024 * 1024);
// Log.d("CSDN_LQR",
// String.format("接收响应: [%s] %n返回json:【%s】 %.1fms %n%s",
// response.request().url(),
// responseBody.string(),
// (t2 - t1) / 1e6d,
// response.headers()
// ));
// return response;
// }
// }
//
// Path: app/src/main/java/com/lqr/biliblili/app/config/applyOptions/intercept/UserAgentInterceptor.java
// public class UserAgentInterceptor implements Interceptor {
// @Override
// public Response intercept(Chain chain) throws IOException {
// Request originalRequest = chain.request();
// Request requestWithUserAgent = originalRequest.newBuilder()
// .removeHeader("User-Agent")
// .addHeader("User-Agent", Api.COMMON_UA_STR)
// .build();
// return chain.proceed(requestWithUserAgent);
// }
// }
| import android.content.Context;
import com.jess.arms.di.module.ClientModule;
import com.lqr.biliblili.BuildConfig;
import com.lqr.biliblili.app.config.applyOptions.intercept.LoggingInterceptor;
import com.lqr.biliblili.app.config.applyOptions.intercept.UserAgentInterceptor;
import me.jessyan.retrofiturlmanager.RetrofitUrlManager;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit; | package com.lqr.biliblili.app.config.applyOptions;
public class MyRetrofitConfiguration implements ClientModule.RetrofitConfiguration {
@Override
public void configRetrofit(Context context, Retrofit.Builder builder) {
// 配置多BaseUrl支持
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
if (BuildConfig.DEBUG) { | // Path: app/src/main/java/com/lqr/biliblili/app/config/applyOptions/intercept/LoggingInterceptor.java
// public class LoggingInterceptor implements Interceptor {
// @Override
// public Response intercept(Chain chain) throws IOException {
// //这个chain里面包含了request和response,所以你要什么都可以从这里拿
// Request request = chain.request();
// long t1 = System.nanoTime();//请求发起的时间
//
// String method = request.method();
// if ("POST".equals(method)) {
// StringBuilder sb = new StringBuilder();
// if (request.body() instanceof FormBody) {
// FormBody body = (FormBody) request.body();
// for (int i = 0; i < body.size(); i++) {
// sb.append(body.encodedName(i) + "=" + body.encodedValue(i) + ",");
// }
// sb.delete(sb.length() - 1, sb.length());
// Log.d("CSDN_LQR", String.format("发送请求 %s on %s %n%s %nRequestParams:{%s}",
// request.url(), chain.connection(), request.headers(), sb.toString()));
// }
// } else {
// Log.d("CSDN_LQR", String.format("发送请求 %s on %s%n%s",
// request.url(), chain.connection(), request.headers()));
// }
// Response response = chain.proceed(request);
// long t2 = System.nanoTime();//收到响应的时间
// //这里不能直接使用response.body().string()的方式输出日志
// //因为response.body().string()之后,response中的流会被关闭,程序会报错,我们需要创建出一
// //个新的response给应用层处理
// ResponseBody responseBody = response.peekBody(1024 * 1024);
// Log.d("CSDN_LQR",
// String.format("接收响应: [%s] %n返回json:【%s】 %.1fms %n%s",
// response.request().url(),
// responseBody.string(),
// (t2 - t1) / 1e6d,
// response.headers()
// ));
// return response;
// }
// }
//
// Path: app/src/main/java/com/lqr/biliblili/app/config/applyOptions/intercept/UserAgentInterceptor.java
// public class UserAgentInterceptor implements Interceptor {
// @Override
// public Response intercept(Chain chain) throws IOException {
// Request originalRequest = chain.request();
// Request requestWithUserAgent = originalRequest.newBuilder()
// .removeHeader("User-Agent")
// .addHeader("User-Agent", Api.COMMON_UA_STR)
// .build();
// return chain.proceed(requestWithUserAgent);
// }
// }
// Path: app/src/main/java/com/lqr/biliblili/app/config/applyOptions/MyRetrofitConfiguration.java
import android.content.Context;
import com.jess.arms.di.module.ClientModule;
import com.lqr.biliblili.BuildConfig;
import com.lqr.biliblili.app.config.applyOptions.intercept.LoggingInterceptor;
import com.lqr.biliblili.app.config.applyOptions.intercept.UserAgentInterceptor;
import me.jessyan.retrofiturlmanager.RetrofitUrlManager;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
package com.lqr.biliblili.app.config.applyOptions;
public class MyRetrofitConfiguration implements ClientModule.RetrofitConfiguration {
@Override
public void configRetrofit(Context context, Retrofit.Builder builder) {
// 配置多BaseUrl支持
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
if (BuildConfig.DEBUG) { | clientBuilder.addInterceptor(new LoggingInterceptor());//使用自定义的Log拦截器 |
GitLqr/LQRBiliBlili | app/src/main/java/com/lqr/biliblili/app/config/applyOptions/MyRetrofitConfiguration.java | // Path: app/src/main/java/com/lqr/biliblili/app/config/applyOptions/intercept/LoggingInterceptor.java
// public class LoggingInterceptor implements Interceptor {
// @Override
// public Response intercept(Chain chain) throws IOException {
// //这个chain里面包含了request和response,所以你要什么都可以从这里拿
// Request request = chain.request();
// long t1 = System.nanoTime();//请求发起的时间
//
// String method = request.method();
// if ("POST".equals(method)) {
// StringBuilder sb = new StringBuilder();
// if (request.body() instanceof FormBody) {
// FormBody body = (FormBody) request.body();
// for (int i = 0; i < body.size(); i++) {
// sb.append(body.encodedName(i) + "=" + body.encodedValue(i) + ",");
// }
// sb.delete(sb.length() - 1, sb.length());
// Log.d("CSDN_LQR", String.format("发送请求 %s on %s %n%s %nRequestParams:{%s}",
// request.url(), chain.connection(), request.headers(), sb.toString()));
// }
// } else {
// Log.d("CSDN_LQR", String.format("发送请求 %s on %s%n%s",
// request.url(), chain.connection(), request.headers()));
// }
// Response response = chain.proceed(request);
// long t2 = System.nanoTime();//收到响应的时间
// //这里不能直接使用response.body().string()的方式输出日志
// //因为response.body().string()之后,response中的流会被关闭,程序会报错,我们需要创建出一
// //个新的response给应用层处理
// ResponseBody responseBody = response.peekBody(1024 * 1024);
// Log.d("CSDN_LQR",
// String.format("接收响应: [%s] %n返回json:【%s】 %.1fms %n%s",
// response.request().url(),
// responseBody.string(),
// (t2 - t1) / 1e6d,
// response.headers()
// ));
// return response;
// }
// }
//
// Path: app/src/main/java/com/lqr/biliblili/app/config/applyOptions/intercept/UserAgentInterceptor.java
// public class UserAgentInterceptor implements Interceptor {
// @Override
// public Response intercept(Chain chain) throws IOException {
// Request originalRequest = chain.request();
// Request requestWithUserAgent = originalRequest.newBuilder()
// .removeHeader("User-Agent")
// .addHeader("User-Agent", Api.COMMON_UA_STR)
// .build();
// return chain.proceed(requestWithUserAgent);
// }
// }
| import android.content.Context;
import com.jess.arms.di.module.ClientModule;
import com.lqr.biliblili.BuildConfig;
import com.lqr.biliblili.app.config.applyOptions.intercept.LoggingInterceptor;
import com.lqr.biliblili.app.config.applyOptions.intercept.UserAgentInterceptor;
import me.jessyan.retrofiturlmanager.RetrofitUrlManager;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit; | package com.lqr.biliblili.app.config.applyOptions;
public class MyRetrofitConfiguration implements ClientModule.RetrofitConfiguration {
@Override
public void configRetrofit(Context context, Retrofit.Builder builder) {
// 配置多BaseUrl支持
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
if (BuildConfig.DEBUG) {
clientBuilder.addInterceptor(new LoggingInterceptor());//使用自定义的Log拦截器
} | // Path: app/src/main/java/com/lqr/biliblili/app/config/applyOptions/intercept/LoggingInterceptor.java
// public class LoggingInterceptor implements Interceptor {
// @Override
// public Response intercept(Chain chain) throws IOException {
// //这个chain里面包含了request和response,所以你要什么都可以从这里拿
// Request request = chain.request();
// long t1 = System.nanoTime();//请求发起的时间
//
// String method = request.method();
// if ("POST".equals(method)) {
// StringBuilder sb = new StringBuilder();
// if (request.body() instanceof FormBody) {
// FormBody body = (FormBody) request.body();
// for (int i = 0; i < body.size(); i++) {
// sb.append(body.encodedName(i) + "=" + body.encodedValue(i) + ",");
// }
// sb.delete(sb.length() - 1, sb.length());
// Log.d("CSDN_LQR", String.format("发送请求 %s on %s %n%s %nRequestParams:{%s}",
// request.url(), chain.connection(), request.headers(), sb.toString()));
// }
// } else {
// Log.d("CSDN_LQR", String.format("发送请求 %s on %s%n%s",
// request.url(), chain.connection(), request.headers()));
// }
// Response response = chain.proceed(request);
// long t2 = System.nanoTime();//收到响应的时间
// //这里不能直接使用response.body().string()的方式输出日志
// //因为response.body().string()之后,response中的流会被关闭,程序会报错,我们需要创建出一
// //个新的response给应用层处理
// ResponseBody responseBody = response.peekBody(1024 * 1024);
// Log.d("CSDN_LQR",
// String.format("接收响应: [%s] %n返回json:【%s】 %.1fms %n%s",
// response.request().url(),
// responseBody.string(),
// (t2 - t1) / 1e6d,
// response.headers()
// ));
// return response;
// }
// }
//
// Path: app/src/main/java/com/lqr/biliblili/app/config/applyOptions/intercept/UserAgentInterceptor.java
// public class UserAgentInterceptor implements Interceptor {
// @Override
// public Response intercept(Chain chain) throws IOException {
// Request originalRequest = chain.request();
// Request requestWithUserAgent = originalRequest.newBuilder()
// .removeHeader("User-Agent")
// .addHeader("User-Agent", Api.COMMON_UA_STR)
// .build();
// return chain.proceed(requestWithUserAgent);
// }
// }
// Path: app/src/main/java/com/lqr/biliblili/app/config/applyOptions/MyRetrofitConfiguration.java
import android.content.Context;
import com.jess.arms.di.module.ClientModule;
import com.lqr.biliblili.BuildConfig;
import com.lqr.biliblili.app.config.applyOptions.intercept.LoggingInterceptor;
import com.lqr.biliblili.app.config.applyOptions.intercept.UserAgentInterceptor;
import me.jessyan.retrofiturlmanager.RetrofitUrlManager;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
package com.lqr.biliblili.app.config.applyOptions;
public class MyRetrofitConfiguration implements ClientModule.RetrofitConfiguration {
@Override
public void configRetrofit(Context context, Retrofit.Builder builder) {
// 配置多BaseUrl支持
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
if (BuildConfig.DEBUG) {
clientBuilder.addInterceptor(new LoggingInterceptor());//使用自定义的Log拦截器
} | clientBuilder.addInterceptor(new UserAgentInterceptor());//使用自定义User-Agent |
GitLqr/LQRBiliBlili | app/src/main/java/com/lqr/biliblili/di/component/MainCategoryComponent.java | // Path: app/src/main/java/com/lqr/biliblili/di/module/MainCategoryModule.java
// @Module
// public class MainCategoryModule {
// private MainCategoryContract.View view;
//
// public MainCategoryModule(MainCategoryContract.View view) {
// this.view = view;
// }
//
// @FragmentScope
// @Provides
// MainCategoryContract.View provideMainCategoryView() {
// return this.view;
// }
//
// @FragmentScope
// @Provides
// MainCategoryContract.Model provideMainCategoryModel(MainCategoryModel model) {
// return model;
// }
// }
//
// Path: app/src/main/java/com/lqr/biliblili/mvp/ui/fragment/main/MainCategoryFragment.java
// public class MainCategoryFragment extends MySupportFragment<MainCategoryPresenter> implements MainCategoryContract.View {
//
// @BindView(R.id.toolbar)
// Toolbar mToolbar;
// @BindView(R.id.recyclerview)
// RecyclerView mRecyclerView;
//
// @OnClick(R.id.ll_toolbar)
// void openDrawer() {
// EventBus.getDefault().post(new MainTag(), "openDrawer");
// }
//
// public static MainCategoryFragment newInstance() {
// return new MainCategoryFragment();
// }
//
// @Override
// public void setupFragmentComponent(AppComponent appComponent) {
// DaggerMainCategoryComponent.builder()
// .appComponent(appComponent)
// .mainCategoryModule(new MainCategoryModule(this))
// .build()
// .inject(this);
// }
//
// @Override
// public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// // 要让Fragment中的onCreateOptionsMenu()被回调,必须调用setHasOptionsMenu(true);
// setHasOptionsMenu(true);
// View view = inflater.inflate(R.layout.fragment_category_main, container, false);
// return view;
// }
//
// @Override
// public void initData(Bundle savedInstanceState) {
// }
//
// @Override
// public void setData(Object data) {
// }
//
// @Override
// public void onSupportVisible() {
// super.onSupportVisible();
// // 必须让Fragment中的Toolbar成为Activity的ActionBar,否则setHasOptionsMenu(true)就没有意义了。
// ((AppCompatActivity) _mActivity).setSupportActionBar(mToolbar);
// ((AppCompatActivity) _mActivity).getSupportActionBar().setDisplayShowTitleEnabled(false);
// }
//
// @Override
// public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// // 必须调用menu.clear();清空菜单栏,否则可能会出现Activity中的menu与Fragment中的menu重叠。
// menu.clear();
// inflater.inflate(R.menu.main_category_menu, menu);
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// switch (item.getItemId()) {
// case R.id.main_download:
// break;
// case R.id.main_search:
// break;
// }
// return super.onOptionsItemSelected(item);
// }
//
// @Override
// public void showLoading() {
//
// }
//
// @Override
// public void hideLoading() {
//
// }
//
// @Override
// public void showMessage(String message) {
//
// }
//
// @Override
// public void launchActivity(Intent intent) {
//
// }
//
// @Override
// public void killMyself() {
//
// }
// }
| import com.jess.arms.di.component.AppComponent;
import com.jess.arms.di.scope.FragmentScope;
import com.lqr.biliblili.di.module.MainCategoryModule;
import com.lqr.biliblili.mvp.ui.fragment.main.MainCategoryFragment;
import dagger.Component; | package com.lqr.biliblili.di.component;
@FragmentScope
@Component(modules = MainCategoryModule.class, dependencies = AppComponent.class)
public interface MainCategoryComponent { | // Path: app/src/main/java/com/lqr/biliblili/di/module/MainCategoryModule.java
// @Module
// public class MainCategoryModule {
// private MainCategoryContract.View view;
//
// public MainCategoryModule(MainCategoryContract.View view) {
// this.view = view;
// }
//
// @FragmentScope
// @Provides
// MainCategoryContract.View provideMainCategoryView() {
// return this.view;
// }
//
// @FragmentScope
// @Provides
// MainCategoryContract.Model provideMainCategoryModel(MainCategoryModel model) {
// return model;
// }
// }
//
// Path: app/src/main/java/com/lqr/biliblili/mvp/ui/fragment/main/MainCategoryFragment.java
// public class MainCategoryFragment extends MySupportFragment<MainCategoryPresenter> implements MainCategoryContract.View {
//
// @BindView(R.id.toolbar)
// Toolbar mToolbar;
// @BindView(R.id.recyclerview)
// RecyclerView mRecyclerView;
//
// @OnClick(R.id.ll_toolbar)
// void openDrawer() {
// EventBus.getDefault().post(new MainTag(), "openDrawer");
// }
//
// public static MainCategoryFragment newInstance() {
// return new MainCategoryFragment();
// }
//
// @Override
// public void setupFragmentComponent(AppComponent appComponent) {
// DaggerMainCategoryComponent.builder()
// .appComponent(appComponent)
// .mainCategoryModule(new MainCategoryModule(this))
// .build()
// .inject(this);
// }
//
// @Override
// public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// // 要让Fragment中的onCreateOptionsMenu()被回调,必须调用setHasOptionsMenu(true);
// setHasOptionsMenu(true);
// View view = inflater.inflate(R.layout.fragment_category_main, container, false);
// return view;
// }
//
// @Override
// public void initData(Bundle savedInstanceState) {
// }
//
// @Override
// public void setData(Object data) {
// }
//
// @Override
// public void onSupportVisible() {
// super.onSupportVisible();
// // 必须让Fragment中的Toolbar成为Activity的ActionBar,否则setHasOptionsMenu(true)就没有意义了。
// ((AppCompatActivity) _mActivity).setSupportActionBar(mToolbar);
// ((AppCompatActivity) _mActivity).getSupportActionBar().setDisplayShowTitleEnabled(false);
// }
//
// @Override
// public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// // 必须调用menu.clear();清空菜单栏,否则可能会出现Activity中的menu与Fragment中的menu重叠。
// menu.clear();
// inflater.inflate(R.menu.main_category_menu, menu);
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// switch (item.getItemId()) {
// case R.id.main_download:
// break;
// case R.id.main_search:
// break;
// }
// return super.onOptionsItemSelected(item);
// }
//
// @Override
// public void showLoading() {
//
// }
//
// @Override
// public void hideLoading() {
//
// }
//
// @Override
// public void showMessage(String message) {
//
// }
//
// @Override
// public void launchActivity(Intent intent) {
//
// }
//
// @Override
// public void killMyself() {
//
// }
// }
// Path: app/src/main/java/com/lqr/biliblili/di/component/MainCategoryComponent.java
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.di.scope.FragmentScope;
import com.lqr.biliblili.di.module.MainCategoryModule;
import com.lqr.biliblili.mvp.ui.fragment.main.MainCategoryFragment;
import dagger.Component;
package com.lqr.biliblili.di.component;
@FragmentScope
@Component(modules = MainCategoryModule.class, dependencies = AppComponent.class)
public interface MainCategoryComponent { | void inject(MainCategoryFragment fragment); |
GitLqr/LQRBiliBlili | app/src/main/java/com/lqr/biliblili/app/config/applyOptions/intercept/UserAgentInterceptor.java | // Path: app/src/main/java/com/lqr/biliblili/app/data/api/Api.java
// public interface Api {
// String LIVE_BASE_URL = "http://api.live.bilibili.com/";
// String RECOMMEND_BASE_URL = "https://app.bilibili.com/";
// String VIDEO_DETAIL_SUMMARY_BASE_URL = "https://app.bilibili.com/";
// String VIDEO_DETAIL_REPLY_BASE_URL = "https://api.bilibili.com/";
//
// // 没有登录的情况下,使用这个User-Agent
// String COMMON_UA_STR = "Mozilla/5.0 BiliDroid/5.15.0 (bbcallen@gmail.com)";
// }
| import com.lqr.biliblili.app.data.api.Api;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response; | package com.lqr.biliblili.app.config.applyOptions.intercept;
/**
* 添加UA拦截器,B站请求API需要加上UA才能正常使用
*/
public class UserAgentInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
Request requestWithUserAgent = originalRequest.newBuilder()
.removeHeader("User-Agent") | // Path: app/src/main/java/com/lqr/biliblili/app/data/api/Api.java
// public interface Api {
// String LIVE_BASE_URL = "http://api.live.bilibili.com/";
// String RECOMMEND_BASE_URL = "https://app.bilibili.com/";
// String VIDEO_DETAIL_SUMMARY_BASE_URL = "https://app.bilibili.com/";
// String VIDEO_DETAIL_REPLY_BASE_URL = "https://api.bilibili.com/";
//
// // 没有登录的情况下,使用这个User-Agent
// String COMMON_UA_STR = "Mozilla/5.0 BiliDroid/5.15.0 (bbcallen@gmail.com)";
// }
// Path: app/src/main/java/com/lqr/biliblili/app/config/applyOptions/intercept/UserAgentInterceptor.java
import com.lqr.biliblili.app.data.api.Api;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
package com.lqr.biliblili.app.config.applyOptions.intercept;
/**
* 添加UA拦截器,B站请求API需要加上UA才能正常使用
*/
public class UserAgentInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
Request requestWithUserAgent = originalRequest.newBuilder()
.removeHeader("User-Agent") | .addHeader("User-Agent", Api.COMMON_UA_STR) |
AdamBien/headlands | headlands/src/main/java/com/airhacks/headlands/engine/control/NashornEngine.java | // Path: headlands/src/main/java/com/airhacks/headlands/processors/boundary/EntryProcessorExecutor.java
// public class EntryProcessorExecutor {
//
// @Inject
// Initializer discoverer;
//
// @Inject
// NashornEngine engine;
//
// public Map<String, EntryProcessorResult<String>> execute(String cacheName,
// String script, Set<String> keys, Set<String> arguments) {
// Cache<String, String> cache = discoverer.getCache(cacheName);
// if (cache == null) {
// throw new IllegalArgumentException("Cache " + cacheName + " does not exist!");
// }
// Object[] args = arguments.toArray();
// EntryProcessor<String, String, String> processor = engine.evalScript(script, EntryProcessor.class);
// return cache.invokeAll(keys, processor, args);
// }
//
// public boolean cacheExists(String name) {
// return discoverer.cacheExists(name);
// }
//
// }
| import com.airhacks.headlands.processors.boundary.EntryProcessorExecutor;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException; | package com.airhacks.headlands.engine.control;
/**
*
* @author airhacks.com
*/
public class NashornEngine {
private Invocable invocable;
private ScriptEngine scriptEngine;
@PostConstruct
public void initializeEngine() {
ScriptEngineManager manager = new ScriptEngineManager();
this.scriptEngine = manager.getEngineByName("javascript");
this.invocable = (Invocable) scriptEngine;
}
public <T> T evalScript(String script, Class<T> interfaze) {
try {
this.scriptEngine.eval(script);
} catch (ScriptException ex) { | // Path: headlands/src/main/java/com/airhacks/headlands/processors/boundary/EntryProcessorExecutor.java
// public class EntryProcessorExecutor {
//
// @Inject
// Initializer discoverer;
//
// @Inject
// NashornEngine engine;
//
// public Map<String, EntryProcessorResult<String>> execute(String cacheName,
// String script, Set<String> keys, Set<String> arguments) {
// Cache<String, String> cache = discoverer.getCache(cacheName);
// if (cache == null) {
// throw new IllegalArgumentException("Cache " + cacheName + " does not exist!");
// }
// Object[] args = arguments.toArray();
// EntryProcessor<String, String, String> processor = engine.evalScript(script, EntryProcessor.class);
// return cache.invokeAll(keys, processor, args);
// }
//
// public boolean cacheExists(String name) {
// return discoverer.cacheExists(name);
// }
//
// }
// Path: headlands/src/main/java/com/airhacks/headlands/engine/control/NashornEngine.java
import com.airhacks.headlands.processors.boundary.EntryProcessorExecutor;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
package com.airhacks.headlands.engine.control;
/**
*
* @author airhacks.com
*/
public class NashornEngine {
private Invocable invocable;
private ScriptEngine scriptEngine;
@PostConstruct
public void initializeEngine() {
ScriptEngineManager manager = new ScriptEngineManager();
this.scriptEngine = manager.getEngineByName("javascript");
this.invocable = (Invocable) scriptEngine;
}
public <T> T evalScript(String script, Class<T> interfaze) {
try {
this.scriptEngine.eval(script);
} catch (ScriptException ex) { | Logger.getLogger(EntryProcessorExecutor.class.getName()).log(Level.SEVERE, null, ex); |
AdamBien/headlands | headlands-ui/src/main/java/com/airhacks/headlands/AppPresenter.java | // Path: headlands-ui/src/main/java/com/airhacks/headlands/caches/CachesView.java
// public class CachesView extends FXMLView {
//
// }
//
// Path: headlands-ui/src/main/java/com/airhacks/headlands/entries/EntriesView.java
// public class EntriesView extends FXMLView {
//
// }
//
// Path: headlands-ui/src/main/java/com/airhacks/headlands/sync/SyncView.java
// public class SyncView extends FXMLView {
//
// }
| import com.airhacks.headlands.caches.CachesView;
import com.airhacks.headlands.entries.EntriesView;
import com.airhacks.headlands.sync.SyncView;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.layout.AnchorPane; | package com.airhacks.headlands;
/**
*
* @author airhacks.com
*/
public class AppPresenter implements Initializable {
@FXML
AnchorPane caches;
@FXML
AnchorPane entries;
@FXML
AnchorPane sync;
@Override
public void initialize(URL location, ResourceBundle resources) { | // Path: headlands-ui/src/main/java/com/airhacks/headlands/caches/CachesView.java
// public class CachesView extends FXMLView {
//
// }
//
// Path: headlands-ui/src/main/java/com/airhacks/headlands/entries/EntriesView.java
// public class EntriesView extends FXMLView {
//
// }
//
// Path: headlands-ui/src/main/java/com/airhacks/headlands/sync/SyncView.java
// public class SyncView extends FXMLView {
//
// }
// Path: headlands-ui/src/main/java/com/airhacks/headlands/AppPresenter.java
import com.airhacks.headlands.caches.CachesView;
import com.airhacks.headlands.entries.EntriesView;
import com.airhacks.headlands.sync.SyncView;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.layout.AnchorPane;
package com.airhacks.headlands;
/**
*
* @author airhacks.com
*/
public class AppPresenter implements Initializable {
@FXML
AnchorPane caches;
@FXML
AnchorPane entries;
@FXML
AnchorPane sync;
@Override
public void initialize(URL location, ResourceBundle resources) { | CachesView cachesView = new CachesView(); |
AdamBien/headlands | headlands-ui/src/main/java/com/airhacks/headlands/AppPresenter.java | // Path: headlands-ui/src/main/java/com/airhacks/headlands/caches/CachesView.java
// public class CachesView extends FXMLView {
//
// }
//
// Path: headlands-ui/src/main/java/com/airhacks/headlands/entries/EntriesView.java
// public class EntriesView extends FXMLView {
//
// }
//
// Path: headlands-ui/src/main/java/com/airhacks/headlands/sync/SyncView.java
// public class SyncView extends FXMLView {
//
// }
| import com.airhacks.headlands.caches.CachesView;
import com.airhacks.headlands.entries.EntriesView;
import com.airhacks.headlands.sync.SyncView;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.layout.AnchorPane; | package com.airhacks.headlands;
/**
*
* @author airhacks.com
*/
public class AppPresenter implements Initializable {
@FXML
AnchorPane caches;
@FXML
AnchorPane entries;
@FXML
AnchorPane sync;
@Override
public void initialize(URL location, ResourceBundle resources) {
CachesView cachesView = new CachesView();
caches.getChildren().add(cachesView.getView()); | // Path: headlands-ui/src/main/java/com/airhacks/headlands/caches/CachesView.java
// public class CachesView extends FXMLView {
//
// }
//
// Path: headlands-ui/src/main/java/com/airhacks/headlands/entries/EntriesView.java
// public class EntriesView extends FXMLView {
//
// }
//
// Path: headlands-ui/src/main/java/com/airhacks/headlands/sync/SyncView.java
// public class SyncView extends FXMLView {
//
// }
// Path: headlands-ui/src/main/java/com/airhacks/headlands/AppPresenter.java
import com.airhacks.headlands.caches.CachesView;
import com.airhacks.headlands.entries.EntriesView;
import com.airhacks.headlands.sync.SyncView;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.layout.AnchorPane;
package com.airhacks.headlands;
/**
*
* @author airhacks.com
*/
public class AppPresenter implements Initializable {
@FXML
AnchorPane caches;
@FXML
AnchorPane entries;
@FXML
AnchorPane sync;
@Override
public void initialize(URL location, ResourceBundle resources) {
CachesView cachesView = new CachesView();
caches.getChildren().add(cachesView.getView()); | EntriesView entriesView = new EntriesView(); |
AdamBien/headlands | headlands-ui/src/main/java/com/airhacks/headlands/AppPresenter.java | // Path: headlands-ui/src/main/java/com/airhacks/headlands/caches/CachesView.java
// public class CachesView extends FXMLView {
//
// }
//
// Path: headlands-ui/src/main/java/com/airhacks/headlands/entries/EntriesView.java
// public class EntriesView extends FXMLView {
//
// }
//
// Path: headlands-ui/src/main/java/com/airhacks/headlands/sync/SyncView.java
// public class SyncView extends FXMLView {
//
// }
| import com.airhacks.headlands.caches.CachesView;
import com.airhacks.headlands.entries.EntriesView;
import com.airhacks.headlands.sync.SyncView;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.layout.AnchorPane; | package com.airhacks.headlands;
/**
*
* @author airhacks.com
*/
public class AppPresenter implements Initializable {
@FXML
AnchorPane caches;
@FXML
AnchorPane entries;
@FXML
AnchorPane sync;
@Override
public void initialize(URL location, ResourceBundle resources) {
CachesView cachesView = new CachesView();
caches.getChildren().add(cachesView.getView());
EntriesView entriesView = new EntriesView();
entries.getChildren().add(entriesView.getView()); | // Path: headlands-ui/src/main/java/com/airhacks/headlands/caches/CachesView.java
// public class CachesView extends FXMLView {
//
// }
//
// Path: headlands-ui/src/main/java/com/airhacks/headlands/entries/EntriesView.java
// public class EntriesView extends FXMLView {
//
// }
//
// Path: headlands-ui/src/main/java/com/airhacks/headlands/sync/SyncView.java
// public class SyncView extends FXMLView {
//
// }
// Path: headlands-ui/src/main/java/com/airhacks/headlands/AppPresenter.java
import com.airhacks.headlands.caches.CachesView;
import com.airhacks.headlands.entries.EntriesView;
import com.airhacks.headlands.sync.SyncView;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.layout.AnchorPane;
package com.airhacks.headlands;
/**
*
* @author airhacks.com
*/
public class AppPresenter implements Initializable {
@FXML
AnchorPane caches;
@FXML
AnchorPane entries;
@FXML
AnchorPane sync;
@Override
public void initialize(URL location, ResourceBundle resources) {
CachesView cachesView = new CachesView();
caches.getChildren().add(cachesView.getView());
EntriesView entriesView = new EntriesView();
entries.getChildren().add(entriesView.getView()); | SyncView syncView = new SyncView(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.