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
|
---|---|---|---|---|---|---|
mpusher/mpush-client-java | src/main/java/com/mpush/client/ConnectThread.java | // Path: src/main/java/com/mpush/util/thread/EventLock.java
// public final class EventLock {
// private final ReentrantLock lock;
// private final Condition cond;
//
// public EventLock() {
// lock = new ReentrantLock();
// cond = lock.newCondition();
// }
//
// public void lock() {
// lock.lock();
// }
//
// public void unlock() {
// lock.unlock();
// }
//
// public void signal() {
// cond.signal();
// }
//
// public void signalAll() {
// cond.signalAll();
// }
//
// public void broadcast() {
// lock.lock();
// cond.signalAll();
// lock.unlock();
// }
//
// public boolean await(long timeout) {
// lock.lock();
// try {
// cond.awaitNanos(TimeUnit.MILLISECONDS.toNanos(timeout));
// } catch (InterruptedException e) {
// return true;
// } finally {
// lock.unlock();
// }
// return false;
// }
//
// public boolean await() {
// lock.lock();
// try {
// cond.await();
// } catch (InterruptedException e) {
// return true;
// } finally {
// lock.unlock();
// }
// return false;
// }
//
// public ReentrantLock getLock() {
// return lock;
// }
//
// public Condition getCond() {
// return cond;
// }
// }
//
// Path: src/main/java/com/mpush/util/thread/ExecutorManager.java
// public final class ExecutorManager {
// public static final String THREAD_NAME_PREFIX = "mp-client-";
// public static final String WRITE_THREAD_NAME = THREAD_NAME_PREFIX + "write-t";
// public static final String READ_THREAD_NAME = THREAD_NAME_PREFIX + "read-t";
// public static final String DISPATCH_THREAD_NAME = THREAD_NAME_PREFIX + "dispatch-t";
// public static final String START_THREAD_NAME = THREAD_NAME_PREFIX + "start-t";
// public static final String TIMER_THREAD_NAME = THREAD_NAME_PREFIX + "timer-t";
// public static final ExecutorManager INSTANCE = new ExecutorManager();
// private ThreadPoolExecutor writeThread;
// private ThreadPoolExecutor dispatchThread;
// private ScheduledExecutorService timerThread;
//
// public ThreadPoolExecutor getWriteThread() {
// if (writeThread == null || writeThread.isShutdown()) {
// writeThread = new ThreadPoolExecutor(1, 1,
// 0L, TimeUnit.MILLISECONDS,
// new LinkedBlockingQueue<Runnable>(100),
// new NamedThreadFactory(WRITE_THREAD_NAME),
// new RejectedHandler());
// }
// return writeThread;
// }
//
// public ThreadPoolExecutor getDispatchThread() {
// if (dispatchThread == null || dispatchThread.isShutdown()) {
// dispatchThread = new ThreadPoolExecutor(2, 4,
// 1L, TimeUnit.SECONDS,
// new LinkedBlockingQueue<Runnable>(100),
// new NamedThreadFactory(DISPATCH_THREAD_NAME),
// new RejectedHandler());
// }
// return dispatchThread;
// }
//
// public ScheduledExecutorService getTimerThread() {
// if (timerThread == null || timerThread.isShutdown()) {
// timerThread = new ScheduledThreadPoolExecutor(1,
// new NamedThreadFactory(TIMER_THREAD_NAME),
// new RejectedHandler());
// }
// return timerThread;
// }
//
// public synchronized void shutdown() {
// if (writeThread != null) {
// writeThread.shutdownNow();
// writeThread = null;
// }
// if (dispatchThread != null) {
// dispatchThread.shutdownNow();
// dispatchThread = null;
// }
// if (timerThread != null) {
// timerThread.shutdownNow();
// timerThread = null;
// }
// }
//
// public static boolean isMPThread() {
// return Thread.currentThread().getName().startsWith(THREAD_NAME_PREFIX);
// }
//
// private static class RejectedHandler implements RejectedExecutionHandler {
//
// @Override
// public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
// ClientConfig.I.getLogger().w("a task was rejected r=%s", r);
// }
// }
// }
| import java.util.concurrent.Callable;
import com.mpush.util.thread.EventLock;
import com.mpush.util.thread.ExecutorManager; | /*
* (C) Copyright 2015-2016 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.
*
* Contributors:
* [email protected] (夜色)
*/
package com.mpush.client;
/**
* Created by yxx on 2016/6/9.
*
* @author [email protected] (夜色)
*/
public class ConnectThread extends Thread {
private volatile Callable<Boolean> runningTask;
private volatile boolean runningFlag = true;
private final EventLock connLock;
public ConnectThread(EventLock connLock) {
this.connLock = connLock; | // Path: src/main/java/com/mpush/util/thread/EventLock.java
// public final class EventLock {
// private final ReentrantLock lock;
// private final Condition cond;
//
// public EventLock() {
// lock = new ReentrantLock();
// cond = lock.newCondition();
// }
//
// public void lock() {
// lock.lock();
// }
//
// public void unlock() {
// lock.unlock();
// }
//
// public void signal() {
// cond.signal();
// }
//
// public void signalAll() {
// cond.signalAll();
// }
//
// public void broadcast() {
// lock.lock();
// cond.signalAll();
// lock.unlock();
// }
//
// public boolean await(long timeout) {
// lock.lock();
// try {
// cond.awaitNanos(TimeUnit.MILLISECONDS.toNanos(timeout));
// } catch (InterruptedException e) {
// return true;
// } finally {
// lock.unlock();
// }
// return false;
// }
//
// public boolean await() {
// lock.lock();
// try {
// cond.await();
// } catch (InterruptedException e) {
// return true;
// } finally {
// lock.unlock();
// }
// return false;
// }
//
// public ReentrantLock getLock() {
// return lock;
// }
//
// public Condition getCond() {
// return cond;
// }
// }
//
// Path: src/main/java/com/mpush/util/thread/ExecutorManager.java
// public final class ExecutorManager {
// public static final String THREAD_NAME_PREFIX = "mp-client-";
// public static final String WRITE_THREAD_NAME = THREAD_NAME_PREFIX + "write-t";
// public static final String READ_THREAD_NAME = THREAD_NAME_PREFIX + "read-t";
// public static final String DISPATCH_THREAD_NAME = THREAD_NAME_PREFIX + "dispatch-t";
// public static final String START_THREAD_NAME = THREAD_NAME_PREFIX + "start-t";
// public static final String TIMER_THREAD_NAME = THREAD_NAME_PREFIX + "timer-t";
// public static final ExecutorManager INSTANCE = new ExecutorManager();
// private ThreadPoolExecutor writeThread;
// private ThreadPoolExecutor dispatchThread;
// private ScheduledExecutorService timerThread;
//
// public ThreadPoolExecutor getWriteThread() {
// if (writeThread == null || writeThread.isShutdown()) {
// writeThread = new ThreadPoolExecutor(1, 1,
// 0L, TimeUnit.MILLISECONDS,
// new LinkedBlockingQueue<Runnable>(100),
// new NamedThreadFactory(WRITE_THREAD_NAME),
// new RejectedHandler());
// }
// return writeThread;
// }
//
// public ThreadPoolExecutor getDispatchThread() {
// if (dispatchThread == null || dispatchThread.isShutdown()) {
// dispatchThread = new ThreadPoolExecutor(2, 4,
// 1L, TimeUnit.SECONDS,
// new LinkedBlockingQueue<Runnable>(100),
// new NamedThreadFactory(DISPATCH_THREAD_NAME),
// new RejectedHandler());
// }
// return dispatchThread;
// }
//
// public ScheduledExecutorService getTimerThread() {
// if (timerThread == null || timerThread.isShutdown()) {
// timerThread = new ScheduledThreadPoolExecutor(1,
// new NamedThreadFactory(TIMER_THREAD_NAME),
// new RejectedHandler());
// }
// return timerThread;
// }
//
// public synchronized void shutdown() {
// if (writeThread != null) {
// writeThread.shutdownNow();
// writeThread = null;
// }
// if (dispatchThread != null) {
// dispatchThread.shutdownNow();
// dispatchThread = null;
// }
// if (timerThread != null) {
// timerThread.shutdownNow();
// timerThread = null;
// }
// }
//
// public static boolean isMPThread() {
// return Thread.currentThread().getName().startsWith(THREAD_NAME_PREFIX);
// }
//
// private static class RejectedHandler implements RejectedExecutionHandler {
//
// @Override
// public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
// ClientConfig.I.getLogger().w("a task was rejected r=%s", r);
// }
// }
// }
// Path: src/main/java/com/mpush/client/ConnectThread.java
import java.util.concurrent.Callable;
import com.mpush.util.thread.EventLock;
import com.mpush.util.thread.ExecutorManager;
/*
* (C) Copyright 2015-2016 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.
*
* Contributors:
* [email protected] (夜色)
*/
package com.mpush.client;
/**
* Created by yxx on 2016/6/9.
*
* @author [email protected] (夜色)
*/
public class ConnectThread extends Thread {
private volatile Callable<Boolean> runningTask;
private volatile boolean runningFlag = true;
private final EventLock connLock;
public ConnectThread(EventLock connLock) {
this.connLock = connLock; | this.setName(ExecutorManager.START_THREAD_NAME); |
mpusher/mpush-client-java | src/main/java/com/mpush/api/push/PushContext.java | // Path: src/main/java/com/mpush/api/Constants.java
// public interface Constants {
// Charset UTF_8 = Charset.forName("UTF-8");
//
// int DEFAULT_SO_TIMEOUT = 1000 * 3;//客户端连接超时时间
//
// int DEFAULT_WRITE_TIMEOUT = 1000 * 10;//10s默认packet写超时
//
// byte[] EMPTY_BYTES = new byte[0];
//
// int DEF_HEARTBEAT = 4 * 60 * 1000;//5min 默认心跳时间
//
// int DEF_COMPRESS_LIMIT = 1024;//1k 启用压缩阈值
//
// String DEF_OS_NAME = "android";//客户端OS
//
// int MAX_RESTART_COUNT = 10;//客户端重连次数超过该值,重连线程休眠10min后再重试
// int MAX_TOTAL_RESTART_COUNT = 1000;//客户端重连次数超过该值,将不再尝试重连
//
// int MAX_HB_TIMEOUT_COUNT = 2;
//
// String HTTP_HEAD_READ_TIMEOUT = "readTimeout";
// }
//
// Path: src/main/java/com/mpush/api/ack/AckContext.java
// public class AckContext {
// public AckCallback callback;
// public AckModel ackModel = AckModel.AUTO_ACK;
// public int timeout = 1000;
// public Packet request;
// public int retryCount;
// public RetryCondition retryCondition;
//
// public static AckContext build(AckCallback callback) {
// AckContext context = new AckContext();
// context.setCallback(callback);
// return context;
// }
//
// public AckCallback getCallback() {
// return callback;
// }
//
// public AckContext setCallback(AckCallback callback) {
// this.callback = callback;
// return this;
// }
//
// public AckModel getAckModel() {
// return ackModel;
// }
//
// public AckContext setAckModel(AckModel ackModel) {
// this.ackModel = ackModel;
// return this;
// }
//
// public int getTimeout() {
// return timeout;
// }
//
// public AckContext setTimeout(int timeout) {
// this.timeout = timeout;
// return this;
// }
//
// public Packet getRequest() {
// return request;
// }
//
// public AckContext setRequest(Packet request) {
// this.request = request;
// return this;
// }
//
// public int getRetryCount() {
// return retryCount;
// }
//
// public AckContext setRetryCount(int retryCount) {
// this.retryCount = retryCount;
// return this;
// }
//
// public RetryCondition getRetryCondition() {
// return retryCondition;
// }
//
// public AckContext setRetryCondition(RetryCondition retryCondition) {
// this.retryCondition = retryCondition;
// return this;
// }
// }
//
// Path: src/main/java/com/mpush/api/ack/AckModel.java
// public enum AckModel {
// NO_ACK((byte) 0),//不需要ACK
// AUTO_ACK(Packet.FLAG_AUTO_ACK),//客户端收到消息后自动确认消息
// BIZ_ACK(Packet.FLAG_BIZ_ACK);//由客户端业务自己确认消息是否到达
// public final byte flag;
//
// AckModel(byte flag) {
// this.flag = flag;
// }
// }
| import com.mpush.api.Constants;
import com.mpush.api.ack.AckContext;
import com.mpush.api.ack.AckModel; | /*
* (C) Copyright 2015-2016 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.
*
* Contributors:
* [email protected] (夜色)
*/
package com.mpush.api.push;
/**
* Created by ohun on 16/10/13.
*
* @author [email protected] (夜色)
*/
public final class PushContext extends AckContext {
public byte[] content;
public PushContext(byte[] content) {
this.content = content;
}
public static PushContext build(byte[] content) {
return new PushContext(content);
}
public static PushContext build(String content) { | // Path: src/main/java/com/mpush/api/Constants.java
// public interface Constants {
// Charset UTF_8 = Charset.forName("UTF-8");
//
// int DEFAULT_SO_TIMEOUT = 1000 * 3;//客户端连接超时时间
//
// int DEFAULT_WRITE_TIMEOUT = 1000 * 10;//10s默认packet写超时
//
// byte[] EMPTY_BYTES = new byte[0];
//
// int DEF_HEARTBEAT = 4 * 60 * 1000;//5min 默认心跳时间
//
// int DEF_COMPRESS_LIMIT = 1024;//1k 启用压缩阈值
//
// String DEF_OS_NAME = "android";//客户端OS
//
// int MAX_RESTART_COUNT = 10;//客户端重连次数超过该值,重连线程休眠10min后再重试
// int MAX_TOTAL_RESTART_COUNT = 1000;//客户端重连次数超过该值,将不再尝试重连
//
// int MAX_HB_TIMEOUT_COUNT = 2;
//
// String HTTP_HEAD_READ_TIMEOUT = "readTimeout";
// }
//
// Path: src/main/java/com/mpush/api/ack/AckContext.java
// public class AckContext {
// public AckCallback callback;
// public AckModel ackModel = AckModel.AUTO_ACK;
// public int timeout = 1000;
// public Packet request;
// public int retryCount;
// public RetryCondition retryCondition;
//
// public static AckContext build(AckCallback callback) {
// AckContext context = new AckContext();
// context.setCallback(callback);
// return context;
// }
//
// public AckCallback getCallback() {
// return callback;
// }
//
// public AckContext setCallback(AckCallback callback) {
// this.callback = callback;
// return this;
// }
//
// public AckModel getAckModel() {
// return ackModel;
// }
//
// public AckContext setAckModel(AckModel ackModel) {
// this.ackModel = ackModel;
// return this;
// }
//
// public int getTimeout() {
// return timeout;
// }
//
// public AckContext setTimeout(int timeout) {
// this.timeout = timeout;
// return this;
// }
//
// public Packet getRequest() {
// return request;
// }
//
// public AckContext setRequest(Packet request) {
// this.request = request;
// return this;
// }
//
// public int getRetryCount() {
// return retryCount;
// }
//
// public AckContext setRetryCount(int retryCount) {
// this.retryCount = retryCount;
// return this;
// }
//
// public RetryCondition getRetryCondition() {
// return retryCondition;
// }
//
// public AckContext setRetryCondition(RetryCondition retryCondition) {
// this.retryCondition = retryCondition;
// return this;
// }
// }
//
// Path: src/main/java/com/mpush/api/ack/AckModel.java
// public enum AckModel {
// NO_ACK((byte) 0),//不需要ACK
// AUTO_ACK(Packet.FLAG_AUTO_ACK),//客户端收到消息后自动确认消息
// BIZ_ACK(Packet.FLAG_BIZ_ACK);//由客户端业务自己确认消息是否到达
// public final byte flag;
//
// AckModel(byte flag) {
// this.flag = flag;
// }
// }
// Path: src/main/java/com/mpush/api/push/PushContext.java
import com.mpush.api.Constants;
import com.mpush.api.ack.AckContext;
import com.mpush.api.ack.AckModel;
/*
* (C) Copyright 2015-2016 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.
*
* Contributors:
* [email protected] (夜色)
*/
package com.mpush.api.push;
/**
* Created by ohun on 16/10/13.
*
* @author [email protected] (夜色)
*/
public final class PushContext extends AckContext {
public byte[] content;
public PushContext(byte[] content) {
this.content = content;
}
public static PushContext build(byte[] content) {
return new PushContext(content);
}
public static PushContext build(String content) { | return new PushContext(content.getBytes(Constants.UTF_8)); |
mpusher/mpush-client-java | src/main/java/com/mpush/api/push/PushContext.java | // Path: src/main/java/com/mpush/api/Constants.java
// public interface Constants {
// Charset UTF_8 = Charset.forName("UTF-8");
//
// int DEFAULT_SO_TIMEOUT = 1000 * 3;//客户端连接超时时间
//
// int DEFAULT_WRITE_TIMEOUT = 1000 * 10;//10s默认packet写超时
//
// byte[] EMPTY_BYTES = new byte[0];
//
// int DEF_HEARTBEAT = 4 * 60 * 1000;//5min 默认心跳时间
//
// int DEF_COMPRESS_LIMIT = 1024;//1k 启用压缩阈值
//
// String DEF_OS_NAME = "android";//客户端OS
//
// int MAX_RESTART_COUNT = 10;//客户端重连次数超过该值,重连线程休眠10min后再重试
// int MAX_TOTAL_RESTART_COUNT = 1000;//客户端重连次数超过该值,将不再尝试重连
//
// int MAX_HB_TIMEOUT_COUNT = 2;
//
// String HTTP_HEAD_READ_TIMEOUT = "readTimeout";
// }
//
// Path: src/main/java/com/mpush/api/ack/AckContext.java
// public class AckContext {
// public AckCallback callback;
// public AckModel ackModel = AckModel.AUTO_ACK;
// public int timeout = 1000;
// public Packet request;
// public int retryCount;
// public RetryCondition retryCondition;
//
// public static AckContext build(AckCallback callback) {
// AckContext context = new AckContext();
// context.setCallback(callback);
// return context;
// }
//
// public AckCallback getCallback() {
// return callback;
// }
//
// public AckContext setCallback(AckCallback callback) {
// this.callback = callback;
// return this;
// }
//
// public AckModel getAckModel() {
// return ackModel;
// }
//
// public AckContext setAckModel(AckModel ackModel) {
// this.ackModel = ackModel;
// return this;
// }
//
// public int getTimeout() {
// return timeout;
// }
//
// public AckContext setTimeout(int timeout) {
// this.timeout = timeout;
// return this;
// }
//
// public Packet getRequest() {
// return request;
// }
//
// public AckContext setRequest(Packet request) {
// this.request = request;
// return this;
// }
//
// public int getRetryCount() {
// return retryCount;
// }
//
// public AckContext setRetryCount(int retryCount) {
// this.retryCount = retryCount;
// return this;
// }
//
// public RetryCondition getRetryCondition() {
// return retryCondition;
// }
//
// public AckContext setRetryCondition(RetryCondition retryCondition) {
// this.retryCondition = retryCondition;
// return this;
// }
// }
//
// Path: src/main/java/com/mpush/api/ack/AckModel.java
// public enum AckModel {
// NO_ACK((byte) 0),//不需要ACK
// AUTO_ACK(Packet.FLAG_AUTO_ACK),//客户端收到消息后自动确认消息
// BIZ_ACK(Packet.FLAG_BIZ_ACK);//由客户端业务自己确认消息是否到达
// public final byte flag;
//
// AckModel(byte flag) {
// this.flag = flag;
// }
// }
| import com.mpush.api.Constants;
import com.mpush.api.ack.AckContext;
import com.mpush.api.ack.AckModel; | /*
* (C) Copyright 2015-2016 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.
*
* Contributors:
* [email protected] (夜色)
*/
package com.mpush.api.push;
/**
* Created by ohun on 16/10/13.
*
* @author [email protected] (夜色)
*/
public final class PushContext extends AckContext {
public byte[] content;
public PushContext(byte[] content) {
this.content = content;
}
public static PushContext build(byte[] content) {
return new PushContext(content);
}
public static PushContext build(String content) {
return new PushContext(content.getBytes(Constants.UTF_8));
}
public byte[] getContent() {
return content;
}
public PushContext setContent(byte[] content) {
this.content = content;
return this;
}
| // Path: src/main/java/com/mpush/api/Constants.java
// public interface Constants {
// Charset UTF_8 = Charset.forName("UTF-8");
//
// int DEFAULT_SO_TIMEOUT = 1000 * 3;//客户端连接超时时间
//
// int DEFAULT_WRITE_TIMEOUT = 1000 * 10;//10s默认packet写超时
//
// byte[] EMPTY_BYTES = new byte[0];
//
// int DEF_HEARTBEAT = 4 * 60 * 1000;//5min 默认心跳时间
//
// int DEF_COMPRESS_LIMIT = 1024;//1k 启用压缩阈值
//
// String DEF_OS_NAME = "android";//客户端OS
//
// int MAX_RESTART_COUNT = 10;//客户端重连次数超过该值,重连线程休眠10min后再重试
// int MAX_TOTAL_RESTART_COUNT = 1000;//客户端重连次数超过该值,将不再尝试重连
//
// int MAX_HB_TIMEOUT_COUNT = 2;
//
// String HTTP_HEAD_READ_TIMEOUT = "readTimeout";
// }
//
// Path: src/main/java/com/mpush/api/ack/AckContext.java
// public class AckContext {
// public AckCallback callback;
// public AckModel ackModel = AckModel.AUTO_ACK;
// public int timeout = 1000;
// public Packet request;
// public int retryCount;
// public RetryCondition retryCondition;
//
// public static AckContext build(AckCallback callback) {
// AckContext context = new AckContext();
// context.setCallback(callback);
// return context;
// }
//
// public AckCallback getCallback() {
// return callback;
// }
//
// public AckContext setCallback(AckCallback callback) {
// this.callback = callback;
// return this;
// }
//
// public AckModel getAckModel() {
// return ackModel;
// }
//
// public AckContext setAckModel(AckModel ackModel) {
// this.ackModel = ackModel;
// return this;
// }
//
// public int getTimeout() {
// return timeout;
// }
//
// public AckContext setTimeout(int timeout) {
// this.timeout = timeout;
// return this;
// }
//
// public Packet getRequest() {
// return request;
// }
//
// public AckContext setRequest(Packet request) {
// this.request = request;
// return this;
// }
//
// public int getRetryCount() {
// return retryCount;
// }
//
// public AckContext setRetryCount(int retryCount) {
// this.retryCount = retryCount;
// return this;
// }
//
// public RetryCondition getRetryCondition() {
// return retryCondition;
// }
//
// public AckContext setRetryCondition(RetryCondition retryCondition) {
// this.retryCondition = retryCondition;
// return this;
// }
// }
//
// Path: src/main/java/com/mpush/api/ack/AckModel.java
// public enum AckModel {
// NO_ACK((byte) 0),//不需要ACK
// AUTO_ACK(Packet.FLAG_AUTO_ACK),//客户端收到消息后自动确认消息
// BIZ_ACK(Packet.FLAG_BIZ_ACK);//由客户端业务自己确认消息是否到达
// public final byte flag;
//
// AckModel(byte flag) {
// this.flag = flag;
// }
// }
// Path: src/main/java/com/mpush/api/push/PushContext.java
import com.mpush.api.Constants;
import com.mpush.api.ack.AckContext;
import com.mpush.api.ack.AckModel;
/*
* (C) Copyright 2015-2016 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.
*
* Contributors:
* [email protected] (夜色)
*/
package com.mpush.api.push;
/**
* Created by ohun on 16/10/13.
*
* @author [email protected] (夜色)
*/
public final class PushContext extends AckContext {
public byte[] content;
public PushContext(byte[] content) {
this.content = content;
}
public static PushContext build(byte[] content) {
return new PushContext(content);
}
public static PushContext build(String content) {
return new PushContext(content.getBytes(Constants.UTF_8));
}
public byte[] getContent() {
return content;
}
public PushContext setContent(byte[] content) {
this.content = content;
return this;
}
| public AckModel getAckModel() { |
mpusher/mpush-client-java | src/main/java/com/mpush/util/crypto/Base64Utils.java | // Path: src/main/java/com/mpush/api/Constants.java
// public interface Constants {
// Charset UTF_8 = Charset.forName("UTF-8");
//
// int DEFAULT_SO_TIMEOUT = 1000 * 3;//客户端连接超时时间
//
// int DEFAULT_WRITE_TIMEOUT = 1000 * 10;//10s默认packet写超时
//
// byte[] EMPTY_BYTES = new byte[0];
//
// int DEF_HEARTBEAT = 4 * 60 * 1000;//5min 默认心跳时间
//
// int DEF_COMPRESS_LIMIT = 1024;//1k 启用压缩阈值
//
// String DEF_OS_NAME = "android";//客户端OS
//
// int MAX_RESTART_COUNT = 10;//客户端重连次数超过该值,重连线程休眠10min后再重试
// int MAX_TOTAL_RESTART_COUNT = 1000;//客户端重连次数超过该值,将不再尝试重连
//
// int MAX_HB_TIMEOUT_COUNT = 2;
//
// String HTTP_HEAD_READ_TIMEOUT = "readTimeout";
// }
| import java.io.*;
import com.mpush.api.Constants; | /*
* (C) Copyright 2015-2016 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.
*
* Contributors:
* [email protected] (夜色)
*/
package com.mpush.util.crypto;
/**
* <p>
* BASE64编码解码工具包
* </p>
* <p>
* 依赖javabase64-1.3.1.jar
* </p>
*/
public class Base64Utils {
/**
* 文件读取缓冲区大小
*/
private static final int CACHE_SIZE = 1024;
/**
* <p>
* BASE64字符串解码为二进制数据
* </p>
*
* @param base64 xxx
* @return return
* @throws Exception xxx
*/
public static byte[] decode(String base64) throws Exception {
return Base64.getDecoder().decode(base64);
}
/**
* <p>
* 二进制数据编码为BASE64字符串
* </p>
*
* @param bytes xxx
* @return return
* @throws Exception xxx
*/
public static String encode(byte[] bytes) throws Exception { | // Path: src/main/java/com/mpush/api/Constants.java
// public interface Constants {
// Charset UTF_8 = Charset.forName("UTF-8");
//
// int DEFAULT_SO_TIMEOUT = 1000 * 3;//客户端连接超时时间
//
// int DEFAULT_WRITE_TIMEOUT = 1000 * 10;//10s默认packet写超时
//
// byte[] EMPTY_BYTES = new byte[0];
//
// int DEF_HEARTBEAT = 4 * 60 * 1000;//5min 默认心跳时间
//
// int DEF_COMPRESS_LIMIT = 1024;//1k 启用压缩阈值
//
// String DEF_OS_NAME = "android";//客户端OS
//
// int MAX_RESTART_COUNT = 10;//客户端重连次数超过该值,重连线程休眠10min后再重试
// int MAX_TOTAL_RESTART_COUNT = 1000;//客户端重连次数超过该值,将不再尝试重连
//
// int MAX_HB_TIMEOUT_COUNT = 2;
//
// String HTTP_HEAD_READ_TIMEOUT = "readTimeout";
// }
// Path: src/main/java/com/mpush/util/crypto/Base64Utils.java
import java.io.*;
import com.mpush.api.Constants;
/*
* (C) Copyright 2015-2016 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.
*
* Contributors:
* [email protected] (夜色)
*/
package com.mpush.util.crypto;
/**
* <p>
* BASE64编码解码工具包
* </p>
* <p>
* 依赖javabase64-1.3.1.jar
* </p>
*/
public class Base64Utils {
/**
* 文件读取缓冲区大小
*/
private static final int CACHE_SIZE = 1024;
/**
* <p>
* BASE64字符串解码为二进制数据
* </p>
*
* @param base64 xxx
* @return return
* @throws Exception xxx
*/
public static byte[] decode(String base64) throws Exception {
return Base64.getDecoder().decode(base64);
}
/**
* <p>
* 二进制数据编码为BASE64字符串
* </p>
*
* @param bytes xxx
* @return return
* @throws Exception xxx
*/
public static String encode(byte[] bytes) throws Exception { | return new String(Base64.getEncoder().encode(bytes), Constants.UTF_8); |
mpusher/mpush-client-java | src/main/java/com/mpush/util/IOUtils.java | // Path: src/main/java/com/mpush/api/Constants.java
// public interface Constants {
// Charset UTF_8 = Charset.forName("UTF-8");
//
// int DEFAULT_SO_TIMEOUT = 1000 * 3;//客户端连接超时时间
//
// int DEFAULT_WRITE_TIMEOUT = 1000 * 10;//10s默认packet写超时
//
// byte[] EMPTY_BYTES = new byte[0];
//
// int DEF_HEARTBEAT = 4 * 60 * 1000;//5min 默认心跳时间
//
// int DEF_COMPRESS_LIMIT = 1024;//1k 启用压缩阈值
//
// String DEF_OS_NAME = "android";//客户端OS
//
// int MAX_RESTART_COUNT = 10;//客户端重连次数超过该值,重连线程休眠10min后再重试
// int MAX_TOTAL_RESTART_COUNT = 1000;//客户端重连次数超过该值,将不再尝试重连
//
// int MAX_HB_TIMEOUT_COUNT = 2;
//
// String HTTP_HEAD_READ_TIMEOUT = "readTimeout";
// }
| import com.mpush.api.Constants;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream; | /*
* (C) Copyright 2015-2016 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.
*
* Contributors:
* [email protected] (夜色)
*/
package com.mpush.util;
/**
* Created by ohun on 2015/12/25.
*
* @author [email protected] (夜色)
*/
public final class IOUtils {
public static void close(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (Exception e) {
}
}
}
public static byte[] compress(byte[] data) {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream(data.length / 4);
DeflaterOutputStream zipOut = new DeflaterOutputStream(byteStream);
try {
zipOut.write(data);
zipOut.finish();
zipOut.close();
} catch (IOException e) { | // Path: src/main/java/com/mpush/api/Constants.java
// public interface Constants {
// Charset UTF_8 = Charset.forName("UTF-8");
//
// int DEFAULT_SO_TIMEOUT = 1000 * 3;//客户端连接超时时间
//
// int DEFAULT_WRITE_TIMEOUT = 1000 * 10;//10s默认packet写超时
//
// byte[] EMPTY_BYTES = new byte[0];
//
// int DEF_HEARTBEAT = 4 * 60 * 1000;//5min 默认心跳时间
//
// int DEF_COMPRESS_LIMIT = 1024;//1k 启用压缩阈值
//
// String DEF_OS_NAME = "android";//客户端OS
//
// int MAX_RESTART_COUNT = 10;//客户端重连次数超过该值,重连线程休眠10min后再重试
// int MAX_TOTAL_RESTART_COUNT = 1000;//客户端重连次数超过该值,将不再尝试重连
//
// int MAX_HB_TIMEOUT_COUNT = 2;
//
// String HTTP_HEAD_READ_TIMEOUT = "readTimeout";
// }
// Path: src/main/java/com/mpush/util/IOUtils.java
import com.mpush.api.Constants;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;
/*
* (C) Copyright 2015-2016 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.
*
* Contributors:
* [email protected] (夜色)
*/
package com.mpush.util;
/**
* Created by ohun on 2015/12/25.
*
* @author [email protected] (夜色)
*/
public final class IOUtils {
public static void close(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (Exception e) {
}
}
}
public static byte[] compress(byte[] data) {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream(data.length / 4);
DeflaterOutputStream zipOut = new DeflaterOutputStream(byteStream);
try {
zipOut.write(data);
zipOut.finish();
zipOut.close();
} catch (IOException e) { | return Constants.EMPTY_BYTES; |
mpusher/mpush-client-java | src/main/java/com/mpush/api/http/HttpRequest.java | // Path: src/main/java/com/mpush/api/Constants.java
// public interface Constants {
// Charset UTF_8 = Charset.forName("UTF-8");
//
// int DEFAULT_SO_TIMEOUT = 1000 * 3;//客户端连接超时时间
//
// int DEFAULT_WRITE_TIMEOUT = 1000 * 10;//10s默认packet写超时
//
// byte[] EMPTY_BYTES = new byte[0];
//
// int DEF_HEARTBEAT = 4 * 60 * 1000;//5min 默认心跳时间
//
// int DEF_COMPRESS_LIMIT = 1024;//1k 启用压缩阈值
//
// String DEF_OS_NAME = "android";//客户端OS
//
// int MAX_RESTART_COUNT = 10;//客户端重连次数超过该值,重连线程休眠10min后再重试
// int MAX_TOTAL_RESTART_COUNT = 1000;//客户端重连次数超过该值,将不再尝试重连
//
// int MAX_HB_TIMEOUT_COUNT = 2;
//
// String HTTP_HEAD_READ_TIMEOUT = "readTimeout";
// }
| import com.mpush.api.Constants;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import static com.mpush.api.Constants.HTTP_HEAD_READ_TIMEOUT; | return uri;
}
public Map<String, String> getHeaders() {
headers.put(HTTP_HEAD_READ_TIMEOUT, Integer.toString(timeout));
return headers;
}
public HttpRequest setHeaders(Map<String, String> headers) {
this.getHeaders().putAll(headers);
return this;
}
public byte[] getBody() {
return body;
}
public HttpRequest setBody(byte[] body, String contentType) {
this.body = body;
this.headers.put(CONTENT_TYPE, contentType);
return this;
}
public HttpRequest setPostParam(Map<String, String> headers, Charset paramsEncoding) {
byte[] bytes = encodeParameters(headers, paramsEncoding.name());
setBody(bytes, CONTENT_TYPE_FORM + paramsEncoding.name());
return this;
}
public HttpRequest setPostParam(Map<String, String> headers) { | // Path: src/main/java/com/mpush/api/Constants.java
// public interface Constants {
// Charset UTF_8 = Charset.forName("UTF-8");
//
// int DEFAULT_SO_TIMEOUT = 1000 * 3;//客户端连接超时时间
//
// int DEFAULT_WRITE_TIMEOUT = 1000 * 10;//10s默认packet写超时
//
// byte[] EMPTY_BYTES = new byte[0];
//
// int DEF_HEARTBEAT = 4 * 60 * 1000;//5min 默认心跳时间
//
// int DEF_COMPRESS_LIMIT = 1024;//1k 启用压缩阈值
//
// String DEF_OS_NAME = "android";//客户端OS
//
// int MAX_RESTART_COUNT = 10;//客户端重连次数超过该值,重连线程休眠10min后再重试
// int MAX_TOTAL_RESTART_COUNT = 1000;//客户端重连次数超过该值,将不再尝试重连
//
// int MAX_HB_TIMEOUT_COUNT = 2;
//
// String HTTP_HEAD_READ_TIMEOUT = "readTimeout";
// }
// Path: src/main/java/com/mpush/api/http/HttpRequest.java
import com.mpush.api.Constants;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import static com.mpush.api.Constants.HTTP_HEAD_READ_TIMEOUT;
return uri;
}
public Map<String, String> getHeaders() {
headers.put(HTTP_HEAD_READ_TIMEOUT, Integer.toString(timeout));
return headers;
}
public HttpRequest setHeaders(Map<String, String> headers) {
this.getHeaders().putAll(headers);
return this;
}
public byte[] getBody() {
return body;
}
public HttpRequest setBody(byte[] body, String contentType) {
this.body = body;
this.headers.put(CONTENT_TYPE, contentType);
return this;
}
public HttpRequest setPostParam(Map<String, String> headers, Charset paramsEncoding) {
byte[] bytes = encodeParameters(headers, paramsEncoding.name());
setBody(bytes, CONTENT_TYPE_FORM + paramsEncoding.name());
return this;
}
public HttpRequest setPostParam(Map<String, String> headers) { | setPostParam(headers, Constants.UTF_8); |
mpusher/mpush-client-java | src/main/java/com/mpush/api/http/HttpResponse.java | // Path: src/main/java/com/mpush/api/Constants.java
// public interface Constants {
// Charset UTF_8 = Charset.forName("UTF-8");
//
// int DEFAULT_SO_TIMEOUT = 1000 * 3;//客户端连接超时时间
//
// int DEFAULT_WRITE_TIMEOUT = 1000 * 10;//10s默认packet写超时
//
// byte[] EMPTY_BYTES = new byte[0];
//
// int DEF_HEARTBEAT = 4 * 60 * 1000;//5min 默认心跳时间
//
// int DEF_COMPRESS_LIMIT = 1024;//1k 启用压缩阈值
//
// String DEF_OS_NAME = "android";//客户端OS
//
// int MAX_RESTART_COUNT = 10;//客户端重连次数超过该值,重连线程休眠10min后再重试
// int MAX_TOTAL_RESTART_COUNT = 1000;//客户端重连次数超过该值,将不再尝试重连
//
// int MAX_HB_TIMEOUT_COUNT = 2;
//
// String HTTP_HEAD_READ_TIMEOUT = "readTimeout";
// }
| import java.util.Map;
import com.mpush.api.Constants; | /*
* (C) Copyright 2015-2016 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.
*
* Contributors:
* [email protected] (夜色)
*/
package com.mpush.api.http;
/**
* Created by yxx on 2016/2/16.
*
* @author [email protected]
*/
public final class HttpResponse {
public final int statusCode;
public final String reasonPhrase;
public final Map<String, String> headers;
public final byte[] body;
public HttpResponse(int statusCode, String reasonPhrase, Map<String, String> headers, byte[] body) {
this.statusCode = statusCode;
this.reasonPhrase = reasonPhrase;
this.headers = headers;
this.body = body;
}
@Override
public String toString() {
return "HttpResponse{" +
"statusCode=" + statusCode +
", reasonPhrase='" + reasonPhrase + '\'' +
", headers=" + headers + | // Path: src/main/java/com/mpush/api/Constants.java
// public interface Constants {
// Charset UTF_8 = Charset.forName("UTF-8");
//
// int DEFAULT_SO_TIMEOUT = 1000 * 3;//客户端连接超时时间
//
// int DEFAULT_WRITE_TIMEOUT = 1000 * 10;//10s默认packet写超时
//
// byte[] EMPTY_BYTES = new byte[0];
//
// int DEF_HEARTBEAT = 4 * 60 * 1000;//5min 默认心跳时间
//
// int DEF_COMPRESS_LIMIT = 1024;//1k 启用压缩阈值
//
// String DEF_OS_NAME = "android";//客户端OS
//
// int MAX_RESTART_COUNT = 10;//客户端重连次数超过该值,重连线程休眠10min后再重试
// int MAX_TOTAL_RESTART_COUNT = 1000;//客户端重连次数超过该值,将不再尝试重连
//
// int MAX_HB_TIMEOUT_COUNT = 2;
//
// String HTTP_HEAD_READ_TIMEOUT = "readTimeout";
// }
// Path: src/main/java/com/mpush/api/http/HttpResponse.java
import java.util.Map;
import com.mpush.api.Constants;
/*
* (C) Copyright 2015-2016 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.
*
* Contributors:
* [email protected] (夜色)
*/
package com.mpush.api.http;
/**
* Created by yxx on 2016/2/16.
*
* @author [email protected]
*/
public final class HttpResponse {
public final int statusCode;
public final String reasonPhrase;
public final Map<String, String> headers;
public final byte[] body;
public HttpResponse(int statusCode, String reasonPhrase, Map<String, String> headers, byte[] body) {
this.statusCode = statusCode;
this.reasonPhrase = reasonPhrase;
this.headers = headers;
this.body = body;
}
@Override
public String toString() {
return "HttpResponse{" +
"statusCode=" + statusCode +
", reasonPhrase='" + reasonPhrase + '\'' +
", headers=" + headers + | ", body=" + (body == null ? "" : new String(body, Constants.UTF_8)) + |
azinik/ADRMine | release/v1/java_src/rnlp/src/main/java/rainbownlp/analyzer/ml/LearnerCommon.java | // Path: release/v1/java_src/rnlp/src/main/java/rainbownlp/core/Setting.java
// public class Setting {
// public static final String RuleSureCorpus = "RuleSure";
// public static boolean SaveInGetInstance = true;
// static Properties configFile;
// public enum OperationMode
// {
// TRIGGER,
// EDGE,
// ARTIFACT
// }
// public static OperationMode Mode = OperationMode.TRIGGER;
// public static boolean TrainingMode = true;
// // This switch between using Development set or Test set for evaluation, set to true if you want to generate test submission files
// public static boolean ReleaseMode = false;
// public static int NotTriggerNumericValue = 10;
// public static int NotEdgeNumericValue = 9;
// public static int MinInstancePerLeaf;
// public static Double SVMCostParameter;
// public static Double SVMPolyCParameter;
// public static enum SVMKernels {
// Linear, //0: linear (default)
// Polynomial, //1: polynomial (s a*b+c)^d
// Radial, //2: radial basis function exp(-gamma ||a-b||^2)
// SigmoidTanh //3: sigmoid tanh(s a*b + c)
// };
// public static SVMKernels SVMKernel;
//
// public static boolean batchMode = false;
// public static int crossValidationFold;
// public static int crossFoldCurrent = 0;
//
// // public static String[] getClasses()
// // {
// // String[] classes = getValue("classes").split("|");
// // return classes;
// // }
// public static void init()
// {
// if(configFile == null){
// configFile = new Properties();
// try {
// //File currentDirectory = new File(new File(".").getAbsolutePath());
//
// // InputStream config_file = new FileInputStream(currentDirectory.getCanonicalPath()+
// // "/examples/adrmineevaluation/src/main/resources/configuration.conf");//
// // InputStream config_file = new FileInputStream(currentDirectory.getCanonicalPath()+
// // "/configuration.conf");
// InputStream config_file =Setting.class.getClassLoader()
// .getResourceAsStream("configuration.conf");
// configFile.load(config_file);
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// MinInstancePerLeaf = Integer.parseInt(configFile.getProperty("MinInstancePerLeaf"));
// SVMCostParameter = Double.parseDouble(configFile.getProperty("SVMCostParameter"));
// SVMPolyCParameter = Double.parseDouble(configFile.getProperty("SVMPolyCParameter"));
// ReleaseMode = Boolean.parseBoolean(configFile.getProperty("ReleaseMode"));
// SVMKernel = SVMKernels.values()[Integer.parseInt(configFile.getProperty("SVMKernel"))];
// }
// }
//
// public static String getValue(String key){
// init();
// return configFile.getProperty(key);
// }
//
// public static int getValueInteger(String key) {
// int result = Integer.parseInt(getValue(key));
// return result;
// }
//
//
//
//
// }
//
// Path: release/v1/java_src/rnlp/src/main/java/rainbownlp/core/Setting.java
// public enum OperationMode
// {
// TRIGGER,
// EDGE,
// ARTIFACT
// }
| import java.sql.SQLException;
import rainbownlp.core.Setting;
import rainbownlp.core.Setting.OperationMode; | package rainbownlp.analyzer.ml;
//import rainbownlp.db.entities.ArtifactTable;
//import rainbownlp.db.entities.RelationExampleTable;
//import rainbownlp.db.entities.ArtifactExampleTable;
public class LearnerCommon {
public static void includeExamples(String updateTo) throws SQLException {
// if(Setting.Mode==OperationMode.EDGE)
// {
// RelationExampleTable.setTestAsTrain();
// RelationExampleTable.include(updateTo);
// }
// if(Setting.Mode==OperationMode.TRIGGER)
// {
// ArtifactExampleTable.setTestAsTrain();
// ArtifactExampleTable.include(updateTo);
// }
}
public static String[] getClassTitles() {
String[] class_titles = new String[1]; | // Path: release/v1/java_src/rnlp/src/main/java/rainbownlp/core/Setting.java
// public class Setting {
// public static final String RuleSureCorpus = "RuleSure";
// public static boolean SaveInGetInstance = true;
// static Properties configFile;
// public enum OperationMode
// {
// TRIGGER,
// EDGE,
// ARTIFACT
// }
// public static OperationMode Mode = OperationMode.TRIGGER;
// public static boolean TrainingMode = true;
// // This switch between using Development set or Test set for evaluation, set to true if you want to generate test submission files
// public static boolean ReleaseMode = false;
// public static int NotTriggerNumericValue = 10;
// public static int NotEdgeNumericValue = 9;
// public static int MinInstancePerLeaf;
// public static Double SVMCostParameter;
// public static Double SVMPolyCParameter;
// public static enum SVMKernels {
// Linear, //0: linear (default)
// Polynomial, //1: polynomial (s a*b+c)^d
// Radial, //2: radial basis function exp(-gamma ||a-b||^2)
// SigmoidTanh //3: sigmoid tanh(s a*b + c)
// };
// public static SVMKernels SVMKernel;
//
// public static boolean batchMode = false;
// public static int crossValidationFold;
// public static int crossFoldCurrent = 0;
//
// // public static String[] getClasses()
// // {
// // String[] classes = getValue("classes").split("|");
// // return classes;
// // }
// public static void init()
// {
// if(configFile == null){
// configFile = new Properties();
// try {
// //File currentDirectory = new File(new File(".").getAbsolutePath());
//
// // InputStream config_file = new FileInputStream(currentDirectory.getCanonicalPath()+
// // "/examples/adrmineevaluation/src/main/resources/configuration.conf");//
// // InputStream config_file = new FileInputStream(currentDirectory.getCanonicalPath()+
// // "/configuration.conf");
// InputStream config_file =Setting.class.getClassLoader()
// .getResourceAsStream("configuration.conf");
// configFile.load(config_file);
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// MinInstancePerLeaf = Integer.parseInt(configFile.getProperty("MinInstancePerLeaf"));
// SVMCostParameter = Double.parseDouble(configFile.getProperty("SVMCostParameter"));
// SVMPolyCParameter = Double.parseDouble(configFile.getProperty("SVMPolyCParameter"));
// ReleaseMode = Boolean.parseBoolean(configFile.getProperty("ReleaseMode"));
// SVMKernel = SVMKernels.values()[Integer.parseInt(configFile.getProperty("SVMKernel"))];
// }
// }
//
// public static String getValue(String key){
// init();
// return configFile.getProperty(key);
// }
//
// public static int getValueInteger(String key) {
// int result = Integer.parseInt(getValue(key));
// return result;
// }
//
//
//
//
// }
//
// Path: release/v1/java_src/rnlp/src/main/java/rainbownlp/core/Setting.java
// public enum OperationMode
// {
// TRIGGER,
// EDGE,
// ARTIFACT
// }
// Path: release/v1/java_src/rnlp/src/main/java/rainbownlp/analyzer/ml/LearnerCommon.java
import java.sql.SQLException;
import rainbownlp.core.Setting;
import rainbownlp.core.Setting.OperationMode;
package rainbownlp.analyzer.ml;
//import rainbownlp.db.entities.ArtifactTable;
//import rainbownlp.db.entities.RelationExampleTable;
//import rainbownlp.db.entities.ArtifactExampleTable;
public class LearnerCommon {
public static void includeExamples(String updateTo) throws SQLException {
// if(Setting.Mode==OperationMode.EDGE)
// {
// RelationExampleTable.setTestAsTrain();
// RelationExampleTable.include(updateTo);
// }
// if(Setting.Mode==OperationMode.TRIGGER)
// {
// ArtifactExampleTable.setTestAsTrain();
// ArtifactExampleTable.include(updateTo);
// }
}
public static String[] getClassTitles() {
String[] class_titles = new String[1]; | if (Setting.getValue("RelationMode").equals("BioNLP")) { |
omacarena/only-short-poc | java.multiversion/v3/src/main/sample/multiversion/ImportantCore.java | // Path: java.multiversion/v2dep/src/main/sample/multiversion/deps/CoreDependency.java
// public class CoreDependency {
//
// public String getVersion() {
// return "core-dep-v2";
// }
// }
| import sample.multiversion.deps.CoreDependency; | package sample.multiversion;
public class ImportantCore implements Core {
private Utility utility; | // Path: java.multiversion/v2dep/src/main/sample/multiversion/deps/CoreDependency.java
// public class CoreDependency {
//
// public String getVersion() {
// return "core-dep-v2";
// }
// }
// Path: java.multiversion/v3/src/main/sample/multiversion/ImportantCore.java
import sample.multiversion.deps.CoreDependency;
package sample.multiversion;
public class ImportantCore implements Core {
private Utility utility; | private CoreDependency coreDependency; |
omacarena/only-short-poc | java.multiversion/versiontest/src/main/sample/multiversion/versiontext/TestMain.java | // Path: java.multiversion/v1/src/main/sample/multiversion/Core.java
// public interface Core {
//
// String getVersion();
// String getDependencyVersion();
// }
//
// Path: java.multiversion/v3/src/main/sample/multiversion/ImportantCore.java
// public class ImportantCore implements Core {
//
// private Utility utility;
// private CoreDependency coreDependency;
//
// public ImportantCore() {
// utility = new Utility();
// coreDependency = new CoreDependency();
// }
//
// public String getVersion() {
// return utility.getVersion();
// }
//
// public String getDependencyVersion() {
// return coreDependency.getVersion();
// }
// }
| import sample.multiversion.Core;
import sample.multiversion.ImportantCore;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Paths; | package sample.multiversion.versiontext;
public class TestMain {
public static void main(String[] args)
throws MalformedURLException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
// multiple versions of the same library to be used at the same time
URL v1 = Paths.get("./../v1/build/libs/v1.jar").toUri().toURL();
URL v2 = Paths.get("./../v2/build/libs/v2.jar").toUri().toURL();
// library dependencies
URL v1Dep = Paths.get("./../v1dep/build/libs/v1dep.jar").toUri().toURL();
URL v2Dep = Paths.get("./../v2dep/build/libs/v2dep.jar").toUri().toURL();
/**
* version 1 and 2 loaders
* - these loaders do not use the root loader - Thread.currentThread().getContextClassLoader()
* - using the root loader new URLClassLoader(new URL[]{v1, v1Dep}, Thread.currentThread().getContextClassLoader());
* will solve any class with the root loader and if no class is found then the child loader will be used
* - because version 3 is loaded from classpath, the root loader should not be used to load version 1 and 2
* - null needs to be passed to parent argument, else will not work
*/
URLClassLoader loaderV1 = new URLClassLoader(new URL[]{v1, v1Dep}, null);
URLClassLoader loaderV2 = new URLClassLoader(new URL[]{v2, v2Dep}, null);
/**
* Use custom class loader for loading classes first from children and last from parent
*/
ParentLastClassLoader loaderV1Alt = new ParentLastClassLoader(new URL[]{v1, v1Dep});
ParentLastClassLoader loaderV2Alt = new ParentLastClassLoader(new URL[]{v2, v2Dep});
ParentLastClassLoader loaderV3Alt = new ParentLastClassLoader(new URL[]{});
// get class from loader
Class<?> coreV1Class = loaderV1.loadClass("sample.multiversion.ImportantCore");
Class<?> coreV2Class = loaderV2.loadClass("sample.multiversion.ImportantCore");
// get class from loader - custom version
Class<?> coreV1AltClass = loaderV1Alt.loadClass("sample.multiversion.ImportantCore");
Class<?> coreV2AltClass = loaderV2Alt.loadClass("sample.multiversion.ImportantCore");
Class<?> coreV3AltClass = loaderV3Alt.loadClass("sample.multiversion.ImportantCore");
// create class instance
Object coreV1Instance = coreV1Class.newInstance();
Object coreV2Instance = coreV2Class.newInstance();
// create class instance - obtained from custom class loader
Object coreV1AltInstance = coreV1AltClass.newInstance();
Object coreV2AltInstance = coreV2AltClass.newInstance();
// note that this is loaded from classpath | // Path: java.multiversion/v1/src/main/sample/multiversion/Core.java
// public interface Core {
//
// String getVersion();
// String getDependencyVersion();
// }
//
// Path: java.multiversion/v3/src/main/sample/multiversion/ImportantCore.java
// public class ImportantCore implements Core {
//
// private Utility utility;
// private CoreDependency coreDependency;
//
// public ImportantCore() {
// utility = new Utility();
// coreDependency = new CoreDependency();
// }
//
// public String getVersion() {
// return utility.getVersion();
// }
//
// public String getDependencyVersion() {
// return coreDependency.getVersion();
// }
// }
// Path: java.multiversion/versiontest/src/main/sample/multiversion/versiontext/TestMain.java
import sample.multiversion.Core;
import sample.multiversion.ImportantCore;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Paths;
package sample.multiversion.versiontext;
public class TestMain {
public static void main(String[] args)
throws MalformedURLException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
// multiple versions of the same library to be used at the same time
URL v1 = Paths.get("./../v1/build/libs/v1.jar").toUri().toURL();
URL v2 = Paths.get("./../v2/build/libs/v2.jar").toUri().toURL();
// library dependencies
URL v1Dep = Paths.get("./../v1dep/build/libs/v1dep.jar").toUri().toURL();
URL v2Dep = Paths.get("./../v2dep/build/libs/v2dep.jar").toUri().toURL();
/**
* version 1 and 2 loaders
* - these loaders do not use the root loader - Thread.currentThread().getContextClassLoader()
* - using the root loader new URLClassLoader(new URL[]{v1, v1Dep}, Thread.currentThread().getContextClassLoader());
* will solve any class with the root loader and if no class is found then the child loader will be used
* - because version 3 is loaded from classpath, the root loader should not be used to load version 1 and 2
* - null needs to be passed to parent argument, else will not work
*/
URLClassLoader loaderV1 = new URLClassLoader(new URL[]{v1, v1Dep}, null);
URLClassLoader loaderV2 = new URLClassLoader(new URL[]{v2, v2Dep}, null);
/**
* Use custom class loader for loading classes first from children and last from parent
*/
ParentLastClassLoader loaderV1Alt = new ParentLastClassLoader(new URL[]{v1, v1Dep});
ParentLastClassLoader loaderV2Alt = new ParentLastClassLoader(new URL[]{v2, v2Dep});
ParentLastClassLoader loaderV3Alt = new ParentLastClassLoader(new URL[]{});
// get class from loader
Class<?> coreV1Class = loaderV1.loadClass("sample.multiversion.ImportantCore");
Class<?> coreV2Class = loaderV2.loadClass("sample.multiversion.ImportantCore");
// get class from loader - custom version
Class<?> coreV1AltClass = loaderV1Alt.loadClass("sample.multiversion.ImportantCore");
Class<?> coreV2AltClass = loaderV2Alt.loadClass("sample.multiversion.ImportantCore");
Class<?> coreV3AltClass = loaderV3Alt.loadClass("sample.multiversion.ImportantCore");
// create class instance
Object coreV1Instance = coreV1Class.newInstance();
Object coreV2Instance = coreV2Class.newInstance();
// create class instance - obtained from custom class loader
Object coreV1AltInstance = coreV1AltClass.newInstance();
Object coreV2AltInstance = coreV2AltClass.newInstance();
// note that this is loaded from classpath | Core coreV3Instance = new ImportantCore(); |
omacarena/only-short-poc | java.multiversion/versiontest/src/main/sample/multiversion/versiontext/TestMain.java | // Path: java.multiversion/v1/src/main/sample/multiversion/Core.java
// public interface Core {
//
// String getVersion();
// String getDependencyVersion();
// }
//
// Path: java.multiversion/v3/src/main/sample/multiversion/ImportantCore.java
// public class ImportantCore implements Core {
//
// private Utility utility;
// private CoreDependency coreDependency;
//
// public ImportantCore() {
// utility = new Utility();
// coreDependency = new CoreDependency();
// }
//
// public String getVersion() {
// return utility.getVersion();
// }
//
// public String getDependencyVersion() {
// return coreDependency.getVersion();
// }
// }
| import sample.multiversion.Core;
import sample.multiversion.ImportantCore;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Paths; | package sample.multiversion.versiontext;
public class TestMain {
public static void main(String[] args)
throws MalformedURLException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
// multiple versions of the same library to be used at the same time
URL v1 = Paths.get("./../v1/build/libs/v1.jar").toUri().toURL();
URL v2 = Paths.get("./../v2/build/libs/v2.jar").toUri().toURL();
// library dependencies
URL v1Dep = Paths.get("./../v1dep/build/libs/v1dep.jar").toUri().toURL();
URL v2Dep = Paths.get("./../v2dep/build/libs/v2dep.jar").toUri().toURL();
/**
* version 1 and 2 loaders
* - these loaders do not use the root loader - Thread.currentThread().getContextClassLoader()
* - using the root loader new URLClassLoader(new URL[]{v1, v1Dep}, Thread.currentThread().getContextClassLoader());
* will solve any class with the root loader and if no class is found then the child loader will be used
* - because version 3 is loaded from classpath, the root loader should not be used to load version 1 and 2
* - null needs to be passed to parent argument, else will not work
*/
URLClassLoader loaderV1 = new URLClassLoader(new URL[]{v1, v1Dep}, null);
URLClassLoader loaderV2 = new URLClassLoader(new URL[]{v2, v2Dep}, null);
/**
* Use custom class loader for loading classes first from children and last from parent
*/
ParentLastClassLoader loaderV1Alt = new ParentLastClassLoader(new URL[]{v1, v1Dep});
ParentLastClassLoader loaderV2Alt = new ParentLastClassLoader(new URL[]{v2, v2Dep});
ParentLastClassLoader loaderV3Alt = new ParentLastClassLoader(new URL[]{});
// get class from loader
Class<?> coreV1Class = loaderV1.loadClass("sample.multiversion.ImportantCore");
Class<?> coreV2Class = loaderV2.loadClass("sample.multiversion.ImportantCore");
// get class from loader - custom version
Class<?> coreV1AltClass = loaderV1Alt.loadClass("sample.multiversion.ImportantCore");
Class<?> coreV2AltClass = loaderV2Alt.loadClass("sample.multiversion.ImportantCore");
Class<?> coreV3AltClass = loaderV3Alt.loadClass("sample.multiversion.ImportantCore");
// create class instance
Object coreV1Instance = coreV1Class.newInstance();
Object coreV2Instance = coreV2Class.newInstance();
// create class instance - obtained from custom class loader
Object coreV1AltInstance = coreV1AltClass.newInstance();
Object coreV2AltInstance = coreV2AltClass.newInstance();
// note that this is loaded from classpath | // Path: java.multiversion/v1/src/main/sample/multiversion/Core.java
// public interface Core {
//
// String getVersion();
// String getDependencyVersion();
// }
//
// Path: java.multiversion/v3/src/main/sample/multiversion/ImportantCore.java
// public class ImportantCore implements Core {
//
// private Utility utility;
// private CoreDependency coreDependency;
//
// public ImportantCore() {
// utility = new Utility();
// coreDependency = new CoreDependency();
// }
//
// public String getVersion() {
// return utility.getVersion();
// }
//
// public String getDependencyVersion() {
// return coreDependency.getVersion();
// }
// }
// Path: java.multiversion/versiontest/src/main/sample/multiversion/versiontext/TestMain.java
import sample.multiversion.Core;
import sample.multiversion.ImportantCore;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Paths;
package sample.multiversion.versiontext;
public class TestMain {
public static void main(String[] args)
throws MalformedURLException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
// multiple versions of the same library to be used at the same time
URL v1 = Paths.get("./../v1/build/libs/v1.jar").toUri().toURL();
URL v2 = Paths.get("./../v2/build/libs/v2.jar").toUri().toURL();
// library dependencies
URL v1Dep = Paths.get("./../v1dep/build/libs/v1dep.jar").toUri().toURL();
URL v2Dep = Paths.get("./../v2dep/build/libs/v2dep.jar").toUri().toURL();
/**
* version 1 and 2 loaders
* - these loaders do not use the root loader - Thread.currentThread().getContextClassLoader()
* - using the root loader new URLClassLoader(new URL[]{v1, v1Dep}, Thread.currentThread().getContextClassLoader());
* will solve any class with the root loader and if no class is found then the child loader will be used
* - because version 3 is loaded from classpath, the root loader should not be used to load version 1 and 2
* - null needs to be passed to parent argument, else will not work
*/
URLClassLoader loaderV1 = new URLClassLoader(new URL[]{v1, v1Dep}, null);
URLClassLoader loaderV2 = new URLClassLoader(new URL[]{v2, v2Dep}, null);
/**
* Use custom class loader for loading classes first from children and last from parent
*/
ParentLastClassLoader loaderV1Alt = new ParentLastClassLoader(new URL[]{v1, v1Dep});
ParentLastClassLoader loaderV2Alt = new ParentLastClassLoader(new URL[]{v2, v2Dep});
ParentLastClassLoader loaderV3Alt = new ParentLastClassLoader(new URL[]{});
// get class from loader
Class<?> coreV1Class = loaderV1.loadClass("sample.multiversion.ImportantCore");
Class<?> coreV2Class = loaderV2.loadClass("sample.multiversion.ImportantCore");
// get class from loader - custom version
Class<?> coreV1AltClass = loaderV1Alt.loadClass("sample.multiversion.ImportantCore");
Class<?> coreV2AltClass = loaderV2Alt.loadClass("sample.multiversion.ImportantCore");
Class<?> coreV3AltClass = loaderV3Alt.loadClass("sample.multiversion.ImportantCore");
// create class instance
Object coreV1Instance = coreV1Class.newInstance();
Object coreV2Instance = coreV2Class.newInstance();
// create class instance - obtained from custom class loader
Object coreV1AltInstance = coreV1AltClass.newInstance();
Object coreV2AltInstance = coreV2AltClass.newInstance();
// note that this is loaded from classpath | Core coreV3Instance = new ImportantCore(); |
omacarena/only-short-poc | java.spring.jpa.multi/myapp/src/main/my/java/spring/jpa/multi/repositories/config/MySqlSource1Config.java | // Path: java.spring.jpa.multi/myapp/src/main/my/java/spring/jpa/multi/models/Organization.java
// @Entity
// @Table(name = "Organization", schema = "mytest")
// public class Organization {
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private Integer id;
//
// @Column(unique = true, nullable = false)
// private String name;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
// }
//
// Path: java.spring.jpa.multi/myapp/src/main/my/java/spring/jpa/multi/repositories/interfaces/OrganizationRepository.java
// public interface OrganizationRepository extends JpaRepository<Organization, Integer> {
// }
//
// Path: java.spring.jpa.multi/myapp/src/main/my/java/spring/jpa/multi/repositories/source1/Source1OrganizationRepositoryImpl.java
// public class Source1OrganizationRepositoryImpl {
// }
| import my.java.spring.jpa.multi.models.Organization;
import my.java.spring.jpa.multi.repositories.interfaces.OrganizationRepository;
import my.java.spring.jpa.multi.repositories.source1.Source1OrganizationRepositoryImpl;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaDialect;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource; | package my.java.spring.jpa.multi.repositories.config;
/**
* Repository configuration.
* @EnableJpaRepositories to enable JPA automatic repositories.
*/
@Configuration
@EnableJpaRepositories( | // Path: java.spring.jpa.multi/myapp/src/main/my/java/spring/jpa/multi/models/Organization.java
// @Entity
// @Table(name = "Organization", schema = "mytest")
// public class Organization {
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private Integer id;
//
// @Column(unique = true, nullable = false)
// private String name;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
// }
//
// Path: java.spring.jpa.multi/myapp/src/main/my/java/spring/jpa/multi/repositories/interfaces/OrganizationRepository.java
// public interface OrganizationRepository extends JpaRepository<Organization, Integer> {
// }
//
// Path: java.spring.jpa.multi/myapp/src/main/my/java/spring/jpa/multi/repositories/source1/Source1OrganizationRepositoryImpl.java
// public class Source1OrganizationRepositoryImpl {
// }
// Path: java.spring.jpa.multi/myapp/src/main/my/java/spring/jpa/multi/repositories/config/MySqlSource1Config.java
import my.java.spring.jpa.multi.models.Organization;
import my.java.spring.jpa.multi.repositories.interfaces.OrganizationRepository;
import my.java.spring.jpa.multi.repositories.source1.Source1OrganizationRepositoryImpl;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaDialect;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
package my.java.spring.jpa.multi.repositories.config;
/**
* Repository configuration.
* @EnableJpaRepositories to enable JPA automatic repositories.
*/
@Configuration
@EnableJpaRepositories( | basePackageClasses = { Source1OrganizationRepositoryImpl.class }, |
omacarena/only-short-poc | java.spring.jpa.multi/myapp/src/main/my/java/spring/jpa/multi/repositories/config/MySqlSource1Config.java | // Path: java.spring.jpa.multi/myapp/src/main/my/java/spring/jpa/multi/models/Organization.java
// @Entity
// @Table(name = "Organization", schema = "mytest")
// public class Organization {
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private Integer id;
//
// @Column(unique = true, nullable = false)
// private String name;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
// }
//
// Path: java.spring.jpa.multi/myapp/src/main/my/java/spring/jpa/multi/repositories/interfaces/OrganizationRepository.java
// public interface OrganizationRepository extends JpaRepository<Organization, Integer> {
// }
//
// Path: java.spring.jpa.multi/myapp/src/main/my/java/spring/jpa/multi/repositories/source1/Source1OrganizationRepositoryImpl.java
// public class Source1OrganizationRepositoryImpl {
// }
| import my.java.spring.jpa.multi.models.Organization;
import my.java.spring.jpa.multi.repositories.interfaces.OrganizationRepository;
import my.java.spring.jpa.multi.repositories.source1.Source1OrganizationRepositoryImpl;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaDialect;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource; | package my.java.spring.jpa.multi.repositories.config;
/**
* Repository configuration.
* @EnableJpaRepositories to enable JPA automatic repositories.
*/
@Configuration
@EnableJpaRepositories(
basePackageClasses = { Source1OrganizationRepositoryImpl.class },
entityManagerFactoryRef = MySqlSource1Config.EntityManagerFactoryBeanName,
transactionManagerRef = MySqlSource1Config.TransactionManagerBeanName
)
public class MySqlSource1Config {
public static final String PrefixName = "source1";
public static final String DataSourceBeanName = PrefixName + ".data-source";
public static final String JpaVendorAdapterBeanName = PrefixName + "jpa-vendor-adapter";
public static final String EntityManagerFactoryBeanName = PrefixName + ".entity-manager-factory";
public static final String TransactionManagerBeanName = PrefixName + ".transaction-manager";
public static final String RepositoryBeanName = PrefixName + ".repository";
@Bean(TransactionManagerBeanName)
@Primary
public PlatformTransactionManager transactionManager(
@Qualifier(EntityManagerFactoryBeanName) EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
@Bean(EntityManagerFactoryBeanName)
@Primary
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
@Qualifier(DataSourceBeanName) DataSource dataSource,
@Qualifier(JpaVendorAdapterBeanName) JpaVendorAdapter vendorAdapter) {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource);
entityManagerFactoryBean.setJpaVendorAdapter(vendorAdapter);
entityManagerFactoryBean.setJpaDialect(new HibernateJpaDialect()); | // Path: java.spring.jpa.multi/myapp/src/main/my/java/spring/jpa/multi/models/Organization.java
// @Entity
// @Table(name = "Organization", schema = "mytest")
// public class Organization {
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private Integer id;
//
// @Column(unique = true, nullable = false)
// private String name;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
// }
//
// Path: java.spring.jpa.multi/myapp/src/main/my/java/spring/jpa/multi/repositories/interfaces/OrganizationRepository.java
// public interface OrganizationRepository extends JpaRepository<Organization, Integer> {
// }
//
// Path: java.spring.jpa.multi/myapp/src/main/my/java/spring/jpa/multi/repositories/source1/Source1OrganizationRepositoryImpl.java
// public class Source1OrganizationRepositoryImpl {
// }
// Path: java.spring.jpa.multi/myapp/src/main/my/java/spring/jpa/multi/repositories/config/MySqlSource1Config.java
import my.java.spring.jpa.multi.models.Organization;
import my.java.spring.jpa.multi.repositories.interfaces.OrganizationRepository;
import my.java.spring.jpa.multi.repositories.source1.Source1OrganizationRepositoryImpl;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaDialect;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
package my.java.spring.jpa.multi.repositories.config;
/**
* Repository configuration.
* @EnableJpaRepositories to enable JPA automatic repositories.
*/
@Configuration
@EnableJpaRepositories(
basePackageClasses = { Source1OrganizationRepositoryImpl.class },
entityManagerFactoryRef = MySqlSource1Config.EntityManagerFactoryBeanName,
transactionManagerRef = MySqlSource1Config.TransactionManagerBeanName
)
public class MySqlSource1Config {
public static final String PrefixName = "source1";
public static final String DataSourceBeanName = PrefixName + ".data-source";
public static final String JpaVendorAdapterBeanName = PrefixName + "jpa-vendor-adapter";
public static final String EntityManagerFactoryBeanName = PrefixName + ".entity-manager-factory";
public static final String TransactionManagerBeanName = PrefixName + ".transaction-manager";
public static final String RepositoryBeanName = PrefixName + ".repository";
@Bean(TransactionManagerBeanName)
@Primary
public PlatformTransactionManager transactionManager(
@Qualifier(EntityManagerFactoryBeanName) EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
@Bean(EntityManagerFactoryBeanName)
@Primary
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
@Qualifier(DataSourceBeanName) DataSource dataSource,
@Qualifier(JpaVendorAdapterBeanName) JpaVendorAdapter vendorAdapter) {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource);
entityManagerFactoryBean.setJpaVendorAdapter(vendorAdapter);
entityManagerFactoryBean.setJpaDialect(new HibernateJpaDialect()); | entityManagerFactoryBean.setPackagesToScan(Organization.class.getPackage().getName()); |
omacarena/only-short-poc | java.spring.jpa.multi/myapp/src/main/my/java/spring/jpa/multi/repositories/config/MySqlSource2Config.java | // Path: java.spring.jpa.multi/myapp/src/main/my/java/spring/jpa/multi/models/Organization.java
// @Entity
// @Table(name = "Organization", schema = "mytest")
// public class Organization {
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private Integer id;
//
// @Column(unique = true, nullable = false)
// private String name;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
// }
//
// Path: java.spring.jpa.multi/myapp/src/main/my/java/spring/jpa/multi/repositories/interfaces/OrganizationRepository.java
// public interface OrganizationRepository extends JpaRepository<Organization, Integer> {
// }
//
// Path: java.spring.jpa.multi/myapp/src/main/my/java/spring/jpa/multi/repositories/source2/Source2OrganizationRepositoryImpl.java
// public class Source2OrganizationRepositoryImpl {
// }
| import my.java.spring.jpa.multi.models.Organization;
import my.java.spring.jpa.multi.repositories.interfaces.OrganizationRepository;
import my.java.spring.jpa.multi.repositories.source2.Source2OrganizationRepositoryImpl;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaDialect;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource; | package my.java.spring.jpa.multi.repositories.config;
/**
* Repository configuration.
* @EnableJpaRepositories to enable JPA automatic repositories.
*/
@Configuration
@EnableJpaRepositories( | // Path: java.spring.jpa.multi/myapp/src/main/my/java/spring/jpa/multi/models/Organization.java
// @Entity
// @Table(name = "Organization", schema = "mytest")
// public class Organization {
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private Integer id;
//
// @Column(unique = true, nullable = false)
// private String name;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
// }
//
// Path: java.spring.jpa.multi/myapp/src/main/my/java/spring/jpa/multi/repositories/interfaces/OrganizationRepository.java
// public interface OrganizationRepository extends JpaRepository<Organization, Integer> {
// }
//
// Path: java.spring.jpa.multi/myapp/src/main/my/java/spring/jpa/multi/repositories/source2/Source2OrganizationRepositoryImpl.java
// public class Source2OrganizationRepositoryImpl {
// }
// Path: java.spring.jpa.multi/myapp/src/main/my/java/spring/jpa/multi/repositories/config/MySqlSource2Config.java
import my.java.spring.jpa.multi.models.Organization;
import my.java.spring.jpa.multi.repositories.interfaces.OrganizationRepository;
import my.java.spring.jpa.multi.repositories.source2.Source2OrganizationRepositoryImpl;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaDialect;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
package my.java.spring.jpa.multi.repositories.config;
/**
* Repository configuration.
* @EnableJpaRepositories to enable JPA automatic repositories.
*/
@Configuration
@EnableJpaRepositories( | basePackageClasses = { Source2OrganizationRepositoryImpl.class }, |
omacarena/only-short-poc | java.spring.jpa.multi/myapp/src/main/my/java/spring/jpa/multi/repositories/config/MySqlSource2Config.java | // Path: java.spring.jpa.multi/myapp/src/main/my/java/spring/jpa/multi/models/Organization.java
// @Entity
// @Table(name = "Organization", schema = "mytest")
// public class Organization {
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private Integer id;
//
// @Column(unique = true, nullable = false)
// private String name;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
// }
//
// Path: java.spring.jpa.multi/myapp/src/main/my/java/spring/jpa/multi/repositories/interfaces/OrganizationRepository.java
// public interface OrganizationRepository extends JpaRepository<Organization, Integer> {
// }
//
// Path: java.spring.jpa.multi/myapp/src/main/my/java/spring/jpa/multi/repositories/source2/Source2OrganizationRepositoryImpl.java
// public class Source2OrganizationRepositoryImpl {
// }
| import my.java.spring.jpa.multi.models.Organization;
import my.java.spring.jpa.multi.repositories.interfaces.OrganizationRepository;
import my.java.spring.jpa.multi.repositories.source2.Source2OrganizationRepositoryImpl;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaDialect;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource; | package my.java.spring.jpa.multi.repositories.config;
/**
* Repository configuration.
* @EnableJpaRepositories to enable JPA automatic repositories.
*/
@Configuration
@EnableJpaRepositories(
basePackageClasses = { Source2OrganizationRepositoryImpl.class },
entityManagerFactoryRef = MySqlSource2Config.EntityManagerFactoryBeanName,
transactionManagerRef = MySqlSource2Config.TransactionManagerBeanName
)
public class MySqlSource2Config {
public static final String PrefixName = "source2";
public static final String DataSourceBeanName = PrefixName + ".data-source";
public static final String JpaVendorAdapterBeanName = PrefixName + "jpa-vendor-adapter";
public static final String EntityManagerFactoryBeanName = PrefixName + ".entity-manager-factory";
public static final String TransactionManagerBeanName = PrefixName + ".transaction-manager";
public static final String RepositoryBeanName = PrefixName + ".repository";
@Bean(TransactionManagerBeanName)
public PlatformTransactionManager transactionManager(
@Qualifier(EntityManagerFactoryBeanName) EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
@Bean(EntityManagerFactoryBeanName)
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
@Qualifier(DataSourceBeanName) DataSource dataSource,
@Qualifier(JpaVendorAdapterBeanName) JpaVendorAdapter vendorAdapter) {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource);
entityManagerFactoryBean.setJpaVendorAdapter(vendorAdapter);
entityManagerFactoryBean.setJpaDialect(new HibernateJpaDialect()); | // Path: java.spring.jpa.multi/myapp/src/main/my/java/spring/jpa/multi/models/Organization.java
// @Entity
// @Table(name = "Organization", schema = "mytest")
// public class Organization {
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private Integer id;
//
// @Column(unique = true, nullable = false)
// private String name;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
// }
//
// Path: java.spring.jpa.multi/myapp/src/main/my/java/spring/jpa/multi/repositories/interfaces/OrganizationRepository.java
// public interface OrganizationRepository extends JpaRepository<Organization, Integer> {
// }
//
// Path: java.spring.jpa.multi/myapp/src/main/my/java/spring/jpa/multi/repositories/source2/Source2OrganizationRepositoryImpl.java
// public class Source2OrganizationRepositoryImpl {
// }
// Path: java.spring.jpa.multi/myapp/src/main/my/java/spring/jpa/multi/repositories/config/MySqlSource2Config.java
import my.java.spring.jpa.multi.models.Organization;
import my.java.spring.jpa.multi.repositories.interfaces.OrganizationRepository;
import my.java.spring.jpa.multi.repositories.source2.Source2OrganizationRepositoryImpl;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaDialect;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
package my.java.spring.jpa.multi.repositories.config;
/**
* Repository configuration.
* @EnableJpaRepositories to enable JPA automatic repositories.
*/
@Configuration
@EnableJpaRepositories(
basePackageClasses = { Source2OrganizationRepositoryImpl.class },
entityManagerFactoryRef = MySqlSource2Config.EntityManagerFactoryBeanName,
transactionManagerRef = MySqlSource2Config.TransactionManagerBeanName
)
public class MySqlSource2Config {
public static final String PrefixName = "source2";
public static final String DataSourceBeanName = PrefixName + ".data-source";
public static final String JpaVendorAdapterBeanName = PrefixName + "jpa-vendor-adapter";
public static final String EntityManagerFactoryBeanName = PrefixName + ".entity-manager-factory";
public static final String TransactionManagerBeanName = PrefixName + ".transaction-manager";
public static final String RepositoryBeanName = PrefixName + ".repository";
@Bean(TransactionManagerBeanName)
public PlatformTransactionManager transactionManager(
@Qualifier(EntityManagerFactoryBeanName) EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
@Bean(EntityManagerFactoryBeanName)
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
@Qualifier(DataSourceBeanName) DataSource dataSource,
@Qualifier(JpaVendorAdapterBeanName) JpaVendorAdapter vendorAdapter) {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource);
entityManagerFactoryBean.setJpaVendorAdapter(vendorAdapter);
entityManagerFactoryBean.setJpaDialect(new HibernateJpaDialect()); | entityManagerFactoryBean.setPackagesToScan(Organization.class.getPackage().getName()); |
omacarena/only-short-poc | java.spring.mongo/myapp/src/main/my/java/spring/mongo/myapp/controllers/MyController.java | // Path: java.spring.mongo/myapp/src/main/my/java/spring/mongo/myapp/repositories/MyMongoRepository.java
// @Repository
// public class MyMongoRepository {
//
// private final MongoTemplate mongoTemplate;
//
// @Autowired
// public MyMongoRepository(MongoTemplate mongoTemplate) {
// this.mongoTemplate = mongoTemplate;
// }
//
// public boolean canConnect() {
// try {
// mongoTemplate.getDb().getStats();
// }
// catch (MongoException ex) {
// ex.printStackTrace();
// return false;
// }
//
// return true;
// }
// }
| import my.java.spring.mongo.myapp.repositories.MyMongoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; | package my.java.spring.mongo.myapp.controllers;
@RestController
@RequestMapping("/v1/my")
public class MyController {
| // Path: java.spring.mongo/myapp/src/main/my/java/spring/mongo/myapp/repositories/MyMongoRepository.java
// @Repository
// public class MyMongoRepository {
//
// private final MongoTemplate mongoTemplate;
//
// @Autowired
// public MyMongoRepository(MongoTemplate mongoTemplate) {
// this.mongoTemplate = mongoTemplate;
// }
//
// public boolean canConnect() {
// try {
// mongoTemplate.getDb().getStats();
// }
// catch (MongoException ex) {
// ex.printStackTrace();
// return false;
// }
//
// return true;
// }
// }
// Path: java.spring.mongo/myapp/src/main/my/java/spring/mongo/myapp/controllers/MyController.java
import my.java.spring.mongo.myapp.repositories.MyMongoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
package my.java.spring.mongo.myapp.controllers;
@RestController
@RequestMapping("/v1/my")
public class MyController {
| private final MyMongoRepository myMongoRepository; |
yshrsmz/simple-preferences | processor/src/main/java/net/yslibrary/simplepreferences/processor/writer/StringSetTypeWriter.java | // Path: processor/src/main/java/net/yslibrary/simplepreferences/processor/KeyAnnotatedField.java
// public class KeyAnnotatedField {
//
// public final VariableElement annotatedElement;
// public final TypeName type;
// public final String name;
// public final String preferenceKey;
// public final boolean omitGetterPrefix;
// public final boolean needCommitMethod;
//
// public KeyAnnotatedField(VariableElement element) throws ProcessingException {
// if (element.getModifiers().contains(Modifier.PRIVATE)) {
// throw new ProcessingException(element,
// "Field %s is private, must be accessible from inherited class", element.getSimpleName());
// }
// annotatedElement = element;
//
// type = TypeName.get(element.asType());
//
// Key annotation = element.getAnnotation(Key.class);
// name = element.getSimpleName().toString();
// preferenceKey = Strings.isNullOrEmpty(annotation.name()) ? Utils.lowerCamelToLowerSnake(name)
// : annotation.name();
// omitGetterPrefix = annotation.omitGetterPrefix();
// needCommitMethod = annotation.needCommitMethod();
// }
// }
//
// Path: processor/src/main/java/net/yslibrary/simplepreferences/processor/Utils.java
// public class Utils {
//
// public static String lowerToUpperCamel(String name) {
// return CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, name);
// }
//
// public static String lowerCamelToLowerSnake(String name) {
// return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, name);
// }
// }
| import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeName;
import net.yslibrary.simplepreferences.processor.KeyAnnotatedField;
import net.yslibrary.simplepreferences.processor.Utils;
import javax.lang.model.element.Modifier; | package net.yslibrary.simplepreferences.processor.writer;
/**
* Created by yshrsmz on 2016/02/23.
*/
public class StringSetTypeWriter extends BaseTypeWriter {
protected StringSetTypeWriter(TypeName enclosingClassName, KeyAnnotatedField keyAnnotatedField) {
super(enclosingClassName, keyAnnotatedField);
}
@Override
public MethodSpec writeGetter(FieldSpec prefs) {
return getBaseGetterBuilder()
.addStatement("return $N.getStringSet($S, $L)", prefs, annotatedField.preferenceKey, annotatedField.name)
.build();
}
@Override
public MethodSpec writeGetterWithDefaultValue(FieldSpec prefs) {
return getBaseGetterBuilder()
.addParameter(annotatedField.type, PARAM_DEFAULT_VALUE)
.addStatement("return $N.getStringSet($S, $L)", prefs, annotatedField.preferenceKey, PARAM_DEFAULT_VALUE)
.build();
}
@Override
public MethodSpec writeSetter(FieldSpec prefs) {
return MethodSpec | // Path: processor/src/main/java/net/yslibrary/simplepreferences/processor/KeyAnnotatedField.java
// public class KeyAnnotatedField {
//
// public final VariableElement annotatedElement;
// public final TypeName type;
// public final String name;
// public final String preferenceKey;
// public final boolean omitGetterPrefix;
// public final boolean needCommitMethod;
//
// public KeyAnnotatedField(VariableElement element) throws ProcessingException {
// if (element.getModifiers().contains(Modifier.PRIVATE)) {
// throw new ProcessingException(element,
// "Field %s is private, must be accessible from inherited class", element.getSimpleName());
// }
// annotatedElement = element;
//
// type = TypeName.get(element.asType());
//
// Key annotation = element.getAnnotation(Key.class);
// name = element.getSimpleName().toString();
// preferenceKey = Strings.isNullOrEmpty(annotation.name()) ? Utils.lowerCamelToLowerSnake(name)
// : annotation.name();
// omitGetterPrefix = annotation.omitGetterPrefix();
// needCommitMethod = annotation.needCommitMethod();
// }
// }
//
// Path: processor/src/main/java/net/yslibrary/simplepreferences/processor/Utils.java
// public class Utils {
//
// public static String lowerToUpperCamel(String name) {
// return CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, name);
// }
//
// public static String lowerCamelToLowerSnake(String name) {
// return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, name);
// }
// }
// Path: processor/src/main/java/net/yslibrary/simplepreferences/processor/writer/StringSetTypeWriter.java
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeName;
import net.yslibrary.simplepreferences.processor.KeyAnnotatedField;
import net.yslibrary.simplepreferences.processor.Utils;
import javax.lang.model.element.Modifier;
package net.yslibrary.simplepreferences.processor.writer;
/**
* Created by yshrsmz on 2016/02/23.
*/
public class StringSetTypeWriter extends BaseTypeWriter {
protected StringSetTypeWriter(TypeName enclosingClassName, KeyAnnotatedField keyAnnotatedField) {
super(enclosingClassName, keyAnnotatedField);
}
@Override
public MethodSpec writeGetter(FieldSpec prefs) {
return getBaseGetterBuilder()
.addStatement("return $N.getStringSet($S, $L)", prefs, annotatedField.preferenceKey, annotatedField.name)
.build();
}
@Override
public MethodSpec writeGetterWithDefaultValue(FieldSpec prefs) {
return getBaseGetterBuilder()
.addParameter(annotatedField.type, PARAM_DEFAULT_VALUE)
.addStatement("return $N.getStringSet($S, $L)", prefs, annotatedField.preferenceKey, PARAM_DEFAULT_VALUE)
.build();
}
@Override
public MethodSpec writeSetter(FieldSpec prefs) {
return MethodSpec | .methodBuilder(BaseTypeWriter.SETTER_PREFIX + Utils.lowerToUpperCamel(annotatedField.name)) |
yshrsmz/simple-preferences | processor/src/main/java/net/yslibrary/simplepreferences/processor/KeyAnnotatedField.java | // Path: processor/src/main/java/net/yslibrary/simplepreferences/processor/exception/ProcessingException.java
// public class ProcessingException extends Exception {
//
// public final Element element;
//
// public ProcessingException(Element element, String message, Object... args) {
// super(String.format(message, args));
//
// this.element = element;
// }
// }
| import com.google.common.base.Strings;
import com.squareup.javapoet.TypeName;
import net.yslibrary.simplepreferences.annotation.Key;
import net.yslibrary.simplepreferences.processor.exception.ProcessingException;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.VariableElement; | package net.yslibrary.simplepreferences.processor;
/**
* Created by yshrsmz on 2016/02/21.
*/
public class KeyAnnotatedField {
public final VariableElement annotatedElement;
public final TypeName type;
public final String name;
public final String preferenceKey;
public final boolean omitGetterPrefix;
public final boolean needCommitMethod;
| // Path: processor/src/main/java/net/yslibrary/simplepreferences/processor/exception/ProcessingException.java
// public class ProcessingException extends Exception {
//
// public final Element element;
//
// public ProcessingException(Element element, String message, Object... args) {
// super(String.format(message, args));
//
// this.element = element;
// }
// }
// Path: processor/src/main/java/net/yslibrary/simplepreferences/processor/KeyAnnotatedField.java
import com.google.common.base.Strings;
import com.squareup.javapoet.TypeName;
import net.yslibrary.simplepreferences.annotation.Key;
import net.yslibrary.simplepreferences.processor.exception.ProcessingException;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.VariableElement;
package net.yslibrary.simplepreferences.processor;
/**
* Created by yshrsmz on 2016/02/21.
*/
public class KeyAnnotatedField {
public final VariableElement annotatedElement;
public final TypeName type;
public final String name;
public final String preferenceKey;
public final boolean omitGetterPrefix;
public final boolean needCommitMethod;
| public KeyAnnotatedField(VariableElement element) throws ProcessingException { |
yshrsmz/simple-preferences | processor/src/main/java/net/yslibrary/simplepreferences/processor/SimplePreferencesProcessor.java | // Path: processor/src/main/java/net/yslibrary/simplepreferences/processor/exception/ProcessingException.java
// public class ProcessingException extends Exception {
//
// public final Element element;
//
// public ProcessingException(Element element, String message, Object... args) {
// super(String.format(message, args));
//
// this.element = element;
// }
// }
//
// Path: processor/src/main/java/net/yslibrary/simplepreferences/processor/writer/PreferenceWriter.java
// public class PreferenceWriter {
//
// private final PreferenceAnnotatedClass annotatedClass;
//
// public PreferenceWriter(PreferenceAnnotatedClass annotatedClass) {
// this.annotatedClass = annotatedClass;
// }
//
// public TypeSpec write() {
// boolean useDefaultPreferences = annotatedClass.useDefaultPreferences();
// String preferenceName = annotatedClass.preferenceName;
// String preferenceClassName = annotatedClass.preferenceClassName;
// String packageName = annotatedClass.packageName;
// TypeElement annotatedElement = annotatedClass.annotatedElement;
//
// TypeSpec.Builder classBuilder = TypeSpec.classBuilder(preferenceClassName)
// .superclass(ClassName.get(annotatedElement));
//
// if (annotatedClass.shouldBeExposed) {
// classBuilder.addModifiers(Modifier.PUBLIC);
// }
//
// TypeName generatingClass = ClassName.get(packageName, preferenceClassName);
//
// // SharedPreferences field ---
// FieldSpec prefsField =
// FieldSpec.builder(SharedPreferences.class, "prefs", Modifier.PRIVATE, Modifier.FINAL)
// .build();
// classBuilder.addField(prefsField);
//
// // constructor
// classBuilder.addMethod(writeConstructor(preferenceName, useDefaultPreferences));
//
// // create method
// classBuilder.addMethod(writeFactory(generatingClass));
//
// // clear method
// classBuilder.addMethod(writeClear());
//
// if (annotatedClass.needCommitMethodForClear) {
// classBuilder.addMethod(writeClearWithCommit());
// }
//
// // keys
// annotatedClass.keys.forEach(keyAnnotatedField -> {
// List<MethodSpec> methods =
// TypeWriter.create(generatingClass, keyAnnotatedField).writeMethods(prefsField);
//
// classBuilder.addMethods(methods);
// });
//
// return classBuilder.build();
// }
//
//
// private MethodSpec writeConstructor(String preferenceName, boolean useDefaultPreferences) {
// MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder()
// .addModifiers(Modifier.PRIVATE)
// .addParameter(
// ParameterSpec.builder(Context.class, "context").addAnnotation(NonNull.class).build());
//
// if (useDefaultPreferences) {
// constructorBuilder.addStatement(
// "prefs = $T.getDefaultSharedPreferences(context.getApplicationContext())",
// PreferenceManager.class);
// } else {
// constructorBuilder.addStatement(
// "prefs = context.getApplicationContext().getSharedPreferences($S, Context.MODE_PRIVATE)",
// preferenceName);
// }
//
// return constructorBuilder.build();
// }
//
// private MethodSpec writeFactory(TypeName generatingClass) {
// MethodSpec.Builder createMethod = MethodSpec.methodBuilder("create")
// .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
// .addParameter(
// ParameterSpec.builder(Context.class, "context").addAnnotation(NonNull.class).build())
// .returns(generatingClass);
//
// createMethod.beginControlFlow("if (context == null)")
// .addStatement("throw new NullPointerException($S)", "Context is Null!")
// .endControlFlow();
// createMethod.addStatement("return new $T(context)", generatingClass);
//
// return createMethod.build();
// }
//
// private MethodSpec writeClear() {
// MethodSpec.Builder clearMethod = MethodSpec.methodBuilder("clear")
// .addModifiers(Modifier.PUBLIC);
// clearMethod.addStatement("prefs.edit().clear().apply()");
//
// return clearMethod.build();
// }
//
// private MethodSpec writeClearWithCommit() {
// MethodSpec.Builder clearWithCommitMethod = MethodSpec.methodBuilder("clearWithCommit")
// .addModifiers(Modifier.PUBLIC)
// .addStatement("prefs.edit().clear().commit()");
//
// return clearWithCommitMethod.build();
// }
// }
| import com.google.auto.service.AutoService;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.TypeSpec;
import net.yslibrary.simplepreferences.annotation.Preferences;
import net.yslibrary.simplepreferences.processor.exception.ProcessingException;
import net.yslibrary.simplepreferences.processor.writer.PreferenceWriter;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import javax.tools.Diagnostic; | elementUtils = processingEnv.getElementUtils();
typeUtils = processingEnv.getTypeUtils();
filer = processingEnv.getFiler();
messager = processingEnv.getMessager();
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
messager.printMessage(Diagnostic.Kind.NOTE, "start processor");
if (annotations.isEmpty()) {
return true;
}
// prepare
roundEnv.getElementsAnnotatedWith(Preferences.class).forEach(element -> {
if (!element.getKind().isClass()) {
error(element, "Only classes can be annotated with @%s", Preferences.class.getSimpleName());
return;
}
try {
TypeElement typeElement = (TypeElement) element;
PreferenceAnnotatedClass model = new PreferenceAnnotatedClass(typeElement, elementUtils);
checkValid(model);
PreferenceAnnotatedClass existing = items.get(model.preferenceName);
if (existing != null) { | // Path: processor/src/main/java/net/yslibrary/simplepreferences/processor/exception/ProcessingException.java
// public class ProcessingException extends Exception {
//
// public final Element element;
//
// public ProcessingException(Element element, String message, Object... args) {
// super(String.format(message, args));
//
// this.element = element;
// }
// }
//
// Path: processor/src/main/java/net/yslibrary/simplepreferences/processor/writer/PreferenceWriter.java
// public class PreferenceWriter {
//
// private final PreferenceAnnotatedClass annotatedClass;
//
// public PreferenceWriter(PreferenceAnnotatedClass annotatedClass) {
// this.annotatedClass = annotatedClass;
// }
//
// public TypeSpec write() {
// boolean useDefaultPreferences = annotatedClass.useDefaultPreferences();
// String preferenceName = annotatedClass.preferenceName;
// String preferenceClassName = annotatedClass.preferenceClassName;
// String packageName = annotatedClass.packageName;
// TypeElement annotatedElement = annotatedClass.annotatedElement;
//
// TypeSpec.Builder classBuilder = TypeSpec.classBuilder(preferenceClassName)
// .superclass(ClassName.get(annotatedElement));
//
// if (annotatedClass.shouldBeExposed) {
// classBuilder.addModifiers(Modifier.PUBLIC);
// }
//
// TypeName generatingClass = ClassName.get(packageName, preferenceClassName);
//
// // SharedPreferences field ---
// FieldSpec prefsField =
// FieldSpec.builder(SharedPreferences.class, "prefs", Modifier.PRIVATE, Modifier.FINAL)
// .build();
// classBuilder.addField(prefsField);
//
// // constructor
// classBuilder.addMethod(writeConstructor(preferenceName, useDefaultPreferences));
//
// // create method
// classBuilder.addMethod(writeFactory(generatingClass));
//
// // clear method
// classBuilder.addMethod(writeClear());
//
// if (annotatedClass.needCommitMethodForClear) {
// classBuilder.addMethod(writeClearWithCommit());
// }
//
// // keys
// annotatedClass.keys.forEach(keyAnnotatedField -> {
// List<MethodSpec> methods =
// TypeWriter.create(generatingClass, keyAnnotatedField).writeMethods(prefsField);
//
// classBuilder.addMethods(methods);
// });
//
// return classBuilder.build();
// }
//
//
// private MethodSpec writeConstructor(String preferenceName, boolean useDefaultPreferences) {
// MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder()
// .addModifiers(Modifier.PRIVATE)
// .addParameter(
// ParameterSpec.builder(Context.class, "context").addAnnotation(NonNull.class).build());
//
// if (useDefaultPreferences) {
// constructorBuilder.addStatement(
// "prefs = $T.getDefaultSharedPreferences(context.getApplicationContext())",
// PreferenceManager.class);
// } else {
// constructorBuilder.addStatement(
// "prefs = context.getApplicationContext().getSharedPreferences($S, Context.MODE_PRIVATE)",
// preferenceName);
// }
//
// return constructorBuilder.build();
// }
//
// private MethodSpec writeFactory(TypeName generatingClass) {
// MethodSpec.Builder createMethod = MethodSpec.methodBuilder("create")
// .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
// .addParameter(
// ParameterSpec.builder(Context.class, "context").addAnnotation(NonNull.class).build())
// .returns(generatingClass);
//
// createMethod.beginControlFlow("if (context == null)")
// .addStatement("throw new NullPointerException($S)", "Context is Null!")
// .endControlFlow();
// createMethod.addStatement("return new $T(context)", generatingClass);
//
// return createMethod.build();
// }
//
// private MethodSpec writeClear() {
// MethodSpec.Builder clearMethod = MethodSpec.methodBuilder("clear")
// .addModifiers(Modifier.PUBLIC);
// clearMethod.addStatement("prefs.edit().clear().apply()");
//
// return clearMethod.build();
// }
//
// private MethodSpec writeClearWithCommit() {
// MethodSpec.Builder clearWithCommitMethod = MethodSpec.methodBuilder("clearWithCommit")
// .addModifiers(Modifier.PUBLIC)
// .addStatement("prefs.edit().clear().commit()");
//
// return clearWithCommitMethod.build();
// }
// }
// Path: processor/src/main/java/net/yslibrary/simplepreferences/processor/SimplePreferencesProcessor.java
import com.google.auto.service.AutoService;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.TypeSpec;
import net.yslibrary.simplepreferences.annotation.Preferences;
import net.yslibrary.simplepreferences.processor.exception.ProcessingException;
import net.yslibrary.simplepreferences.processor.writer.PreferenceWriter;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import javax.tools.Diagnostic;
elementUtils = processingEnv.getElementUtils();
typeUtils = processingEnv.getTypeUtils();
filer = processingEnv.getFiler();
messager = processingEnv.getMessager();
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
messager.printMessage(Diagnostic.Kind.NOTE, "start processor");
if (annotations.isEmpty()) {
return true;
}
// prepare
roundEnv.getElementsAnnotatedWith(Preferences.class).forEach(element -> {
if (!element.getKind().isClass()) {
error(element, "Only classes can be annotated with @%s", Preferences.class.getSimpleName());
return;
}
try {
TypeElement typeElement = (TypeElement) element;
PreferenceAnnotatedClass model = new PreferenceAnnotatedClass(typeElement, elementUtils);
checkValid(model);
PreferenceAnnotatedClass existing = items.get(model.preferenceName);
if (existing != null) { | throw new ProcessingException(typeElement, |
yshrsmz/simple-preferences | processor/src/main/java/net/yslibrary/simplepreferences/processor/SimplePreferencesProcessor.java | // Path: processor/src/main/java/net/yslibrary/simplepreferences/processor/exception/ProcessingException.java
// public class ProcessingException extends Exception {
//
// public final Element element;
//
// public ProcessingException(Element element, String message, Object... args) {
// super(String.format(message, args));
//
// this.element = element;
// }
// }
//
// Path: processor/src/main/java/net/yslibrary/simplepreferences/processor/writer/PreferenceWriter.java
// public class PreferenceWriter {
//
// private final PreferenceAnnotatedClass annotatedClass;
//
// public PreferenceWriter(PreferenceAnnotatedClass annotatedClass) {
// this.annotatedClass = annotatedClass;
// }
//
// public TypeSpec write() {
// boolean useDefaultPreferences = annotatedClass.useDefaultPreferences();
// String preferenceName = annotatedClass.preferenceName;
// String preferenceClassName = annotatedClass.preferenceClassName;
// String packageName = annotatedClass.packageName;
// TypeElement annotatedElement = annotatedClass.annotatedElement;
//
// TypeSpec.Builder classBuilder = TypeSpec.classBuilder(preferenceClassName)
// .superclass(ClassName.get(annotatedElement));
//
// if (annotatedClass.shouldBeExposed) {
// classBuilder.addModifiers(Modifier.PUBLIC);
// }
//
// TypeName generatingClass = ClassName.get(packageName, preferenceClassName);
//
// // SharedPreferences field ---
// FieldSpec prefsField =
// FieldSpec.builder(SharedPreferences.class, "prefs", Modifier.PRIVATE, Modifier.FINAL)
// .build();
// classBuilder.addField(prefsField);
//
// // constructor
// classBuilder.addMethod(writeConstructor(preferenceName, useDefaultPreferences));
//
// // create method
// classBuilder.addMethod(writeFactory(generatingClass));
//
// // clear method
// classBuilder.addMethod(writeClear());
//
// if (annotatedClass.needCommitMethodForClear) {
// classBuilder.addMethod(writeClearWithCommit());
// }
//
// // keys
// annotatedClass.keys.forEach(keyAnnotatedField -> {
// List<MethodSpec> methods =
// TypeWriter.create(generatingClass, keyAnnotatedField).writeMethods(prefsField);
//
// classBuilder.addMethods(methods);
// });
//
// return classBuilder.build();
// }
//
//
// private MethodSpec writeConstructor(String preferenceName, boolean useDefaultPreferences) {
// MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder()
// .addModifiers(Modifier.PRIVATE)
// .addParameter(
// ParameterSpec.builder(Context.class, "context").addAnnotation(NonNull.class).build());
//
// if (useDefaultPreferences) {
// constructorBuilder.addStatement(
// "prefs = $T.getDefaultSharedPreferences(context.getApplicationContext())",
// PreferenceManager.class);
// } else {
// constructorBuilder.addStatement(
// "prefs = context.getApplicationContext().getSharedPreferences($S, Context.MODE_PRIVATE)",
// preferenceName);
// }
//
// return constructorBuilder.build();
// }
//
// private MethodSpec writeFactory(TypeName generatingClass) {
// MethodSpec.Builder createMethod = MethodSpec.methodBuilder("create")
// .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
// .addParameter(
// ParameterSpec.builder(Context.class, "context").addAnnotation(NonNull.class).build())
// .returns(generatingClass);
//
// createMethod.beginControlFlow("if (context == null)")
// .addStatement("throw new NullPointerException($S)", "Context is Null!")
// .endControlFlow();
// createMethod.addStatement("return new $T(context)", generatingClass);
//
// return createMethod.build();
// }
//
// private MethodSpec writeClear() {
// MethodSpec.Builder clearMethod = MethodSpec.methodBuilder("clear")
// .addModifiers(Modifier.PUBLIC);
// clearMethod.addStatement("prefs.edit().clear().apply()");
//
// return clearMethod.build();
// }
//
// private MethodSpec writeClearWithCommit() {
// MethodSpec.Builder clearWithCommitMethod = MethodSpec.methodBuilder("clearWithCommit")
// .addModifiers(Modifier.PUBLIC)
// .addStatement("prefs.edit().clear().commit()");
//
// return clearWithCommitMethod.build();
// }
// }
| import com.google.auto.service.AutoService;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.TypeSpec;
import net.yslibrary.simplepreferences.annotation.Preferences;
import net.yslibrary.simplepreferences.processor.exception.ProcessingException;
import net.yslibrary.simplepreferences.processor.writer.PreferenceWriter;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import javax.tools.Diagnostic; | return;
}
try {
TypeElement typeElement = (TypeElement) element;
PreferenceAnnotatedClass model = new PreferenceAnnotatedClass(typeElement, elementUtils);
checkValid(model);
PreferenceAnnotatedClass existing = items.get(model.preferenceName);
if (existing != null) {
throw new ProcessingException(typeElement,
"Conflict: Class %s is annotated with @%s with value='%s', but %s already uses same value",
model.annotatedElement, Preferences.class.getSimpleName(), model.preferenceName,
existing.annotatedElement.getQualifiedName().toString());
}
items.put(model.preferenceName, model);
} catch (ProcessingException e) {
error(e.element, e.getMessage());
} catch (IllegalStateException e) {
error(null, e.getMessage());
}
});
// generate
items.forEach((key, preferenceAnnotatedClass) -> {
try { | // Path: processor/src/main/java/net/yslibrary/simplepreferences/processor/exception/ProcessingException.java
// public class ProcessingException extends Exception {
//
// public final Element element;
//
// public ProcessingException(Element element, String message, Object... args) {
// super(String.format(message, args));
//
// this.element = element;
// }
// }
//
// Path: processor/src/main/java/net/yslibrary/simplepreferences/processor/writer/PreferenceWriter.java
// public class PreferenceWriter {
//
// private final PreferenceAnnotatedClass annotatedClass;
//
// public PreferenceWriter(PreferenceAnnotatedClass annotatedClass) {
// this.annotatedClass = annotatedClass;
// }
//
// public TypeSpec write() {
// boolean useDefaultPreferences = annotatedClass.useDefaultPreferences();
// String preferenceName = annotatedClass.preferenceName;
// String preferenceClassName = annotatedClass.preferenceClassName;
// String packageName = annotatedClass.packageName;
// TypeElement annotatedElement = annotatedClass.annotatedElement;
//
// TypeSpec.Builder classBuilder = TypeSpec.classBuilder(preferenceClassName)
// .superclass(ClassName.get(annotatedElement));
//
// if (annotatedClass.shouldBeExposed) {
// classBuilder.addModifiers(Modifier.PUBLIC);
// }
//
// TypeName generatingClass = ClassName.get(packageName, preferenceClassName);
//
// // SharedPreferences field ---
// FieldSpec prefsField =
// FieldSpec.builder(SharedPreferences.class, "prefs", Modifier.PRIVATE, Modifier.FINAL)
// .build();
// classBuilder.addField(prefsField);
//
// // constructor
// classBuilder.addMethod(writeConstructor(preferenceName, useDefaultPreferences));
//
// // create method
// classBuilder.addMethod(writeFactory(generatingClass));
//
// // clear method
// classBuilder.addMethod(writeClear());
//
// if (annotatedClass.needCommitMethodForClear) {
// classBuilder.addMethod(writeClearWithCommit());
// }
//
// // keys
// annotatedClass.keys.forEach(keyAnnotatedField -> {
// List<MethodSpec> methods =
// TypeWriter.create(generatingClass, keyAnnotatedField).writeMethods(prefsField);
//
// classBuilder.addMethods(methods);
// });
//
// return classBuilder.build();
// }
//
//
// private MethodSpec writeConstructor(String preferenceName, boolean useDefaultPreferences) {
// MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder()
// .addModifiers(Modifier.PRIVATE)
// .addParameter(
// ParameterSpec.builder(Context.class, "context").addAnnotation(NonNull.class).build());
//
// if (useDefaultPreferences) {
// constructorBuilder.addStatement(
// "prefs = $T.getDefaultSharedPreferences(context.getApplicationContext())",
// PreferenceManager.class);
// } else {
// constructorBuilder.addStatement(
// "prefs = context.getApplicationContext().getSharedPreferences($S, Context.MODE_PRIVATE)",
// preferenceName);
// }
//
// return constructorBuilder.build();
// }
//
// private MethodSpec writeFactory(TypeName generatingClass) {
// MethodSpec.Builder createMethod = MethodSpec.methodBuilder("create")
// .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
// .addParameter(
// ParameterSpec.builder(Context.class, "context").addAnnotation(NonNull.class).build())
// .returns(generatingClass);
//
// createMethod.beginControlFlow("if (context == null)")
// .addStatement("throw new NullPointerException($S)", "Context is Null!")
// .endControlFlow();
// createMethod.addStatement("return new $T(context)", generatingClass);
//
// return createMethod.build();
// }
//
// private MethodSpec writeClear() {
// MethodSpec.Builder clearMethod = MethodSpec.methodBuilder("clear")
// .addModifiers(Modifier.PUBLIC);
// clearMethod.addStatement("prefs.edit().clear().apply()");
//
// return clearMethod.build();
// }
//
// private MethodSpec writeClearWithCommit() {
// MethodSpec.Builder clearWithCommitMethod = MethodSpec.methodBuilder("clearWithCommit")
// .addModifiers(Modifier.PUBLIC)
// .addStatement("prefs.edit().clear().commit()");
//
// return clearWithCommitMethod.build();
// }
// }
// Path: processor/src/main/java/net/yslibrary/simplepreferences/processor/SimplePreferencesProcessor.java
import com.google.auto.service.AutoService;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.TypeSpec;
import net.yslibrary.simplepreferences.annotation.Preferences;
import net.yslibrary.simplepreferences.processor.exception.ProcessingException;
import net.yslibrary.simplepreferences.processor.writer.PreferenceWriter;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import javax.tools.Diagnostic;
return;
}
try {
TypeElement typeElement = (TypeElement) element;
PreferenceAnnotatedClass model = new PreferenceAnnotatedClass(typeElement, elementUtils);
checkValid(model);
PreferenceAnnotatedClass existing = items.get(model.preferenceName);
if (existing != null) {
throw new ProcessingException(typeElement,
"Conflict: Class %s is annotated with @%s with value='%s', but %s already uses same value",
model.annotatedElement, Preferences.class.getSimpleName(), model.preferenceName,
existing.annotatedElement.getQualifiedName().toString());
}
items.put(model.preferenceName, model);
} catch (ProcessingException e) {
error(e.element, e.getMessage());
} catch (IllegalStateException e) {
error(null, e.getMessage());
}
});
// generate
items.forEach((key, preferenceAnnotatedClass) -> {
try { | TypeSpec clazz = (new PreferenceWriter(preferenceAnnotatedClass)).write(); |
yshrsmz/simple-preferences | processor/src/main/java/net/yslibrary/simplepreferences/processor/PreferenceAnnotatedClass.java | // Path: processor/src/main/java/net/yslibrary/simplepreferences/processor/exception/ProcessingException.java
// public class ProcessingException extends Exception {
//
// public final Element element;
//
// public ProcessingException(Element element, String message, Object... args) {
// super(String.format(message, args));
//
// this.element = element;
// }
// }
| import com.google.common.base.Strings;
import net.yslibrary.simplepreferences.annotation.Key;
import net.yslibrary.simplepreferences.annotation.Preferences;
import net.yslibrary.simplepreferences.processor.exception.ProcessingException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.util.Elements; | package net.yslibrary.simplepreferences.processor;
/**
* Created by yshrsmz on 2016/02/21.
*/
public class PreferenceAnnotatedClass {
public final static String DEFAULT_PREFS = "net.yslibrary.simplepreferences.default_name";
private final static String SUFFIX = "Prefs";
public final TypeElement annotatedElement;
// used as SharedPreferences' name
public final String preferenceName;
// generated class name
public final String preferenceClassName;
public final String qualifiedPreferenceClassName;
public final String packageName;
public final List<KeyAnnotatedField> keys = new ArrayList<>();
public final boolean needCommitMethodForClear;
public final boolean shouldBeExposed;
public PreferenceAnnotatedClass(TypeElement element, Elements elementUtils) | // Path: processor/src/main/java/net/yslibrary/simplepreferences/processor/exception/ProcessingException.java
// public class ProcessingException extends Exception {
//
// public final Element element;
//
// public ProcessingException(Element element, String message, Object... args) {
// super(String.format(message, args));
//
// this.element = element;
// }
// }
// Path: processor/src/main/java/net/yslibrary/simplepreferences/processor/PreferenceAnnotatedClass.java
import com.google.common.base.Strings;
import net.yslibrary.simplepreferences.annotation.Key;
import net.yslibrary.simplepreferences.annotation.Preferences;
import net.yslibrary.simplepreferences.processor.exception.ProcessingException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.util.Elements;
package net.yslibrary.simplepreferences.processor;
/**
* Created by yshrsmz on 2016/02/21.
*/
public class PreferenceAnnotatedClass {
public final static String DEFAULT_PREFS = "net.yslibrary.simplepreferences.default_name";
private final static String SUFFIX = "Prefs";
public final TypeElement annotatedElement;
// used as SharedPreferences' name
public final String preferenceName;
// generated class name
public final String preferenceClassName;
public final String qualifiedPreferenceClassName;
public final String packageName;
public final List<KeyAnnotatedField> keys = new ArrayList<>();
public final boolean needCommitMethodForClear;
public final boolean shouldBeExposed;
public PreferenceAnnotatedClass(TypeElement element, Elements elementUtils) | throws IllegalStateException, ProcessingException { |
yshrsmz/simple-preferences | processor/src/main/java/net/yslibrary/simplepreferences/processor/writer/BaseTypeWriter.java | // Path: processor/src/main/java/net/yslibrary/simplepreferences/processor/KeyAnnotatedField.java
// public class KeyAnnotatedField {
//
// public final VariableElement annotatedElement;
// public final TypeName type;
// public final String name;
// public final String preferenceKey;
// public final boolean omitGetterPrefix;
// public final boolean needCommitMethod;
//
// public KeyAnnotatedField(VariableElement element) throws ProcessingException {
// if (element.getModifiers().contains(Modifier.PRIVATE)) {
// throw new ProcessingException(element,
// "Field %s is private, must be accessible from inherited class", element.getSimpleName());
// }
// annotatedElement = element;
//
// type = TypeName.get(element.asType());
//
// Key annotation = element.getAnnotation(Key.class);
// name = element.getSimpleName().toString();
// preferenceKey = Strings.isNullOrEmpty(annotation.name()) ? Utils.lowerCamelToLowerSnake(name)
// : annotation.name();
// omitGetterPrefix = annotation.omitGetterPrefix();
// needCommitMethod = annotation.needCommitMethod();
// }
// }
//
// Path: processor/src/main/java/net/yslibrary/simplepreferences/processor/Utils.java
// public class Utils {
//
// public static String lowerToUpperCamel(String name) {
// return CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, name);
// }
//
// public static String lowerCamelToLowerSnake(String name) {
// return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, name);
// }
// }
| import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeName;
import net.yslibrary.simplepreferences.processor.KeyAnnotatedField;
import net.yslibrary.simplepreferences.processor.Utils;
import java.util.ArrayList;
import java.util.List;
import javax.lang.model.element.Modifier; | package net.yslibrary.simplepreferences.processor.writer;
/**
* Created by yshrsmz on 2016/02/23.
*/
public abstract class BaseTypeWriter implements TypeWriter {
final static String BOOLEAN_GETTER_PREFIX = "is";
final static String SETTER_PREFIX = "set";
final static String WITH_COMMIT_SUFFIX = "WithCommit";
final static String PARAM_VALUE = "value";
final static String PARAM_DEFAULT_VALUE = "defaultValue";
final static String GETTER_PREFIX = "get";
private final static String EXIST_PREFIX = "has";
private final static String REMOVE_PREFIX = "remove";
final TypeName enclosingClassName; | // Path: processor/src/main/java/net/yslibrary/simplepreferences/processor/KeyAnnotatedField.java
// public class KeyAnnotatedField {
//
// public final VariableElement annotatedElement;
// public final TypeName type;
// public final String name;
// public final String preferenceKey;
// public final boolean omitGetterPrefix;
// public final boolean needCommitMethod;
//
// public KeyAnnotatedField(VariableElement element) throws ProcessingException {
// if (element.getModifiers().contains(Modifier.PRIVATE)) {
// throw new ProcessingException(element,
// "Field %s is private, must be accessible from inherited class", element.getSimpleName());
// }
// annotatedElement = element;
//
// type = TypeName.get(element.asType());
//
// Key annotation = element.getAnnotation(Key.class);
// name = element.getSimpleName().toString();
// preferenceKey = Strings.isNullOrEmpty(annotation.name()) ? Utils.lowerCamelToLowerSnake(name)
// : annotation.name();
// omitGetterPrefix = annotation.omitGetterPrefix();
// needCommitMethod = annotation.needCommitMethod();
// }
// }
//
// Path: processor/src/main/java/net/yslibrary/simplepreferences/processor/Utils.java
// public class Utils {
//
// public static String lowerToUpperCamel(String name) {
// return CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, name);
// }
//
// public static String lowerCamelToLowerSnake(String name) {
// return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, name);
// }
// }
// Path: processor/src/main/java/net/yslibrary/simplepreferences/processor/writer/BaseTypeWriter.java
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeName;
import net.yslibrary.simplepreferences.processor.KeyAnnotatedField;
import net.yslibrary.simplepreferences.processor.Utils;
import java.util.ArrayList;
import java.util.List;
import javax.lang.model.element.Modifier;
package net.yslibrary.simplepreferences.processor.writer;
/**
* Created by yshrsmz on 2016/02/23.
*/
public abstract class BaseTypeWriter implements TypeWriter {
final static String BOOLEAN_GETTER_PREFIX = "is";
final static String SETTER_PREFIX = "set";
final static String WITH_COMMIT_SUFFIX = "WithCommit";
final static String PARAM_VALUE = "value";
final static String PARAM_DEFAULT_VALUE = "defaultValue";
final static String GETTER_PREFIX = "get";
private final static String EXIST_PREFIX = "has";
private final static String REMOVE_PREFIX = "remove";
final TypeName enclosingClassName; | final KeyAnnotatedField annotatedField; |
yshrsmz/simple-preferences | processor/src/main/java/net/yslibrary/simplepreferences/processor/writer/BaseTypeWriter.java | // Path: processor/src/main/java/net/yslibrary/simplepreferences/processor/KeyAnnotatedField.java
// public class KeyAnnotatedField {
//
// public final VariableElement annotatedElement;
// public final TypeName type;
// public final String name;
// public final String preferenceKey;
// public final boolean omitGetterPrefix;
// public final boolean needCommitMethod;
//
// public KeyAnnotatedField(VariableElement element) throws ProcessingException {
// if (element.getModifiers().contains(Modifier.PRIVATE)) {
// throw new ProcessingException(element,
// "Field %s is private, must be accessible from inherited class", element.getSimpleName());
// }
// annotatedElement = element;
//
// type = TypeName.get(element.asType());
//
// Key annotation = element.getAnnotation(Key.class);
// name = element.getSimpleName().toString();
// preferenceKey = Strings.isNullOrEmpty(annotation.name()) ? Utils.lowerCamelToLowerSnake(name)
// : annotation.name();
// omitGetterPrefix = annotation.omitGetterPrefix();
// needCommitMethod = annotation.needCommitMethod();
// }
// }
//
// Path: processor/src/main/java/net/yslibrary/simplepreferences/processor/Utils.java
// public class Utils {
//
// public static String lowerToUpperCamel(String name) {
// return CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, name);
// }
//
// public static String lowerCamelToLowerSnake(String name) {
// return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, name);
// }
// }
| import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeName;
import net.yslibrary.simplepreferences.processor.KeyAnnotatedField;
import net.yslibrary.simplepreferences.processor.Utils;
import java.util.ArrayList;
import java.util.List;
import javax.lang.model.element.Modifier; | package net.yslibrary.simplepreferences.processor.writer;
/**
* Created by yshrsmz on 2016/02/23.
*/
public abstract class BaseTypeWriter implements TypeWriter {
final static String BOOLEAN_GETTER_PREFIX = "is";
final static String SETTER_PREFIX = "set";
final static String WITH_COMMIT_SUFFIX = "WithCommit";
final static String PARAM_VALUE = "value";
final static String PARAM_DEFAULT_VALUE = "defaultValue";
final static String GETTER_PREFIX = "get";
private final static String EXIST_PREFIX = "has";
private final static String REMOVE_PREFIX = "remove";
final TypeName enclosingClassName;
final KeyAnnotatedField annotatedField;
BaseTypeWriter(TypeName enclosingClassName, KeyAnnotatedField annotatedField) {
this.enclosingClassName = enclosingClassName;
this.annotatedField = annotatedField;
}
public abstract MethodSpec writeGetter(FieldSpec prefs);
public abstract MethodSpec writeSetter(FieldSpec prefs);
@Override
public MethodSpec writeExists(FieldSpec prefs) { | // Path: processor/src/main/java/net/yslibrary/simplepreferences/processor/KeyAnnotatedField.java
// public class KeyAnnotatedField {
//
// public final VariableElement annotatedElement;
// public final TypeName type;
// public final String name;
// public final String preferenceKey;
// public final boolean omitGetterPrefix;
// public final boolean needCommitMethod;
//
// public KeyAnnotatedField(VariableElement element) throws ProcessingException {
// if (element.getModifiers().contains(Modifier.PRIVATE)) {
// throw new ProcessingException(element,
// "Field %s is private, must be accessible from inherited class", element.getSimpleName());
// }
// annotatedElement = element;
//
// type = TypeName.get(element.asType());
//
// Key annotation = element.getAnnotation(Key.class);
// name = element.getSimpleName().toString();
// preferenceKey = Strings.isNullOrEmpty(annotation.name()) ? Utils.lowerCamelToLowerSnake(name)
// : annotation.name();
// omitGetterPrefix = annotation.omitGetterPrefix();
// needCommitMethod = annotation.needCommitMethod();
// }
// }
//
// Path: processor/src/main/java/net/yslibrary/simplepreferences/processor/Utils.java
// public class Utils {
//
// public static String lowerToUpperCamel(String name) {
// return CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, name);
// }
//
// public static String lowerCamelToLowerSnake(String name) {
// return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, name);
// }
// }
// Path: processor/src/main/java/net/yslibrary/simplepreferences/processor/writer/BaseTypeWriter.java
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeName;
import net.yslibrary.simplepreferences.processor.KeyAnnotatedField;
import net.yslibrary.simplepreferences.processor.Utils;
import java.util.ArrayList;
import java.util.List;
import javax.lang.model.element.Modifier;
package net.yslibrary.simplepreferences.processor.writer;
/**
* Created by yshrsmz on 2016/02/23.
*/
public abstract class BaseTypeWriter implements TypeWriter {
final static String BOOLEAN_GETTER_PREFIX = "is";
final static String SETTER_PREFIX = "set";
final static String WITH_COMMIT_SUFFIX = "WithCommit";
final static String PARAM_VALUE = "value";
final static String PARAM_DEFAULT_VALUE = "defaultValue";
final static String GETTER_PREFIX = "get";
private final static String EXIST_PREFIX = "has";
private final static String REMOVE_PREFIX = "remove";
final TypeName enclosingClassName;
final KeyAnnotatedField annotatedField;
BaseTypeWriter(TypeName enclosingClassName, KeyAnnotatedField annotatedField) {
this.enclosingClassName = enclosingClassName;
this.annotatedField = annotatedField;
}
public abstract MethodSpec writeGetter(FieldSpec prefs);
public abstract MethodSpec writeSetter(FieldSpec prefs);
@Override
public MethodSpec writeExists(FieldSpec prefs) { | return MethodSpec.methodBuilder(EXIST_PREFIX + Utils.lowerToUpperCamel(annotatedField.name)) |
mojohaus/extra-enforcer-rules | src/test/java/org/apache/maven/plugins/enforcer/JarUtilsTest.java | // Path: src/test/java/org/apache/maven/plugins/enforcer/ArtifactBuilder.java
// public static ArtifactBuilder newBuilder()
// {
// return new ArtifactBuilder();
// }
| import org.apache.maven.artifact.Artifact;
import org.junit.Test;
import static org.apache.maven.plugins.enforcer.ArtifactBuilder.newBuilder;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; | package org.apache.maven.plugins.enforcer;
public class JarUtilsTest
{
/**
* "Sunny day" test: the method should return true for a jar artifact.
*/
@Test
public void isJarFileShouldReturnTrueForJarFile()
{ | // Path: src/test/java/org/apache/maven/plugins/enforcer/ArtifactBuilder.java
// public static ArtifactBuilder newBuilder()
// {
// return new ArtifactBuilder();
// }
// Path: src/test/java/org/apache/maven/plugins/enforcer/JarUtilsTest.java
import org.apache.maven.artifact.Artifact;
import org.junit.Test;
import static org.apache.maven.plugins.enforcer.ArtifactBuilder.newBuilder;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
package org.apache.maven.plugins.enforcer;
public class JarUtilsTest
{
/**
* "Sunny day" test: the method should return true for a jar artifact.
*/
@Test
public void isJarFileShouldReturnTrueForJarFile()
{ | Artifact artifact = newBuilder().withType( "jar" ).build(); |
mojohaus/extra-enforcer-rules | src/main/java/org/apache/maven/plugins/enforcer/Hasher.java | // Path: src/main/java/org/apache/maven/plugins/enforcer/JarUtils.java
// public static boolean isJarFile( Artifact artifact )
// {
// return artifact.getFile().isFile() && "jar".equals( artifact.getType() );
// }
| import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.jar.JarFile;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.maven.artifact.Artifact;
import static org.apache.maven.plugins.enforcer.JarUtils.isJarFile; | package org.apache.maven.plugins.enforcer;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/**
* Utility class to generate hashes/checksums for binary files.
* Typically used to generate a hashes for .class files to compare
* those files for equality.
*/
public class Hasher
{
/** the path to the .class file. Example: org/apache/maven/Stuff.class */
private final String classFilePath;
/**
* Constructor.
* @param classFilePath The path to the .class file. This is the file we'll generate a hash for.
* Example: org/apache/maven/Stuff.class
*/
public Hasher( String classFilePath )
{
this.classFilePath = classFilePath;
}
/**
* @param artifact The artifact (example: jar file) which contains the {@link #classFilePath}.
* We'll generate a hash for the class file inside this artifact.
* @return generate a hash/checksum for the .class file in the provided artifact.
*/
public String generateHash( Artifact artifact )
{
File artifactFile = artifact.getFile();
try
{
if ( artifactFile.isDirectory() )
{
return hashForFileInDirectory( artifactFile );
} | // Path: src/main/java/org/apache/maven/plugins/enforcer/JarUtils.java
// public static boolean isJarFile( Artifact artifact )
// {
// return artifact.getFile().isFile() && "jar".equals( artifact.getType() );
// }
// Path: src/main/java/org/apache/maven/plugins/enforcer/Hasher.java
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.jar.JarFile;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.maven.artifact.Artifact;
import static org.apache.maven.plugins.enforcer.JarUtils.isJarFile;
package org.apache.maven.plugins.enforcer;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/**
* Utility class to generate hashes/checksums for binary files.
* Typically used to generate a hashes for .class files to compare
* those files for equality.
*/
public class Hasher
{
/** the path to the .class file. Example: org/apache/maven/Stuff.class */
private final String classFilePath;
/**
* Constructor.
* @param classFilePath The path to the .class file. This is the file we'll generate a hash for.
* Example: org/apache/maven/Stuff.class
*/
public Hasher( String classFilePath )
{
this.classFilePath = classFilePath;
}
/**
* @param artifact The artifact (example: jar file) which contains the {@link #classFilePath}.
* We'll generate a hash for the class file inside this artifact.
* @return generate a hash/checksum for the .class file in the provided artifact.
*/
public String generateHash( Artifact artifact )
{
File artifactFile = artifact.getFile();
try
{
if ( artifactFile.isDirectory() )
{
return hashForFileInDirectory( artifactFile );
} | else if ( isJarFile( artifact ) ) |
mojohaus/extra-enforcer-rules | src/main/java/org/apache/maven/plugins/enforcer/BanDuplicateClasses.java | // Path: src/main/java/org/codehaus/mojo/enforcer/Dependency.java
// public class Dependency
// {
//
// private String groupId;
//
// private String artifactId;
//
// private String classifier;
//
// private String type;
//
// /**
// * List of classes to ignore. Wildcard at the end accepted
// */
// private String[] ignoreClasses;
//
// /**
// * <p>Getter for the field <code>groupId</code>.</p>
// *
// * @return a {@link java.lang.String} object.
// */
// public String getGroupId()
// {
// return groupId;
// }
//
// /**
// * <p>Setter for the field <code>groupId</code>.</p>
// *
// * @param groupId a {@link java.lang.String} object.
// */
// public void setGroupId( String groupId )
// {
// this.groupId = groupId;
// }
//
// /**
// * <p>Getter for the field <code>artifactId</code>.</p>
// *
// * @return a {@link java.lang.String} object.
// */
// public String getArtifactId()
// {
// return artifactId;
// }
//
// /**
// * <p>Setter for the field <code>artifactId</code>.</p>
// *
// * @param artifactId a {@link java.lang.String} object.
// */
// public void setArtifactId( String artifactId )
// {
// this.artifactId = artifactId;
// }
//
// /**
// * <p>Getter for the field <code>classifier</code>.</p>
// *
// * @return a {@link java.lang.String} object.
// */
// public String getClassifier()
// {
// return classifier;
// }
//
// /**
// * <p>Setter for the field <code>classifier</code>.</p>
// *
// * @param classifier a {@link java.lang.String} object.
// */
// public void setClassifier( String classifier )
// {
// this.classifier = classifier;
// }
//
// /**
// * <p>Getter for the field <code>type</code>.</p>
// *
// * @return a {@link java.lang.String} object.
// */
// public String getType()
// {
// return type;
// }
//
// /**
// * <p>Setter for the field <code>type</code>.</p>
// *
// * @param type a {@link java.lang.String} object.
// */
// public void setType( String type )
// {
// this.type = type;
// }
//
// /**
// * <p>Getter for the field <code>ignoreClasses</code>.</p>
// *
// * @return an array of {@link java.lang.String} objects.
// */
// public String[] getIgnoreClasses()
// {
// return ignoreClasses;
// }
//
// /**
// * <p>Setter for the field <code>ignoreClasses</code>.</p>
// *
// * @param ignoreClasses an array of {@link java.lang.String} objects.
// */
// public void setIgnoreClasses( String[] ignoreClasses )
// {
// this.ignoreClasses = ignoreClasses;
// }
//
// /** {@inheritDoc} */
// @Override
// public String toString()
// {
// StringBuilder sb = new StringBuilder();
// sb.append( groupId ).append( ':' ).append( artifactId ).append( ':' ).append( type );
// if ( classifier != null )
// {
// sb.append( ':' ).append( classifier );
// }
// return sb.toString();
// }
// }
//
// Path: src/main/java/org/apache/maven/plugins/enforcer/JarUtils.java
// public static boolean isJarFile( Artifact artifact )
// {
// return artifact.getFile().isFile() && "jar".equals( artifact.getType() );
// }
| import java.util.jar.JarFile;
import java.util.regex.Pattern;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.enforcer.rule.api.EnforcerRuleException;
import org.codehaus.mojo.enforcer.Dependency;
import org.codehaus.plexus.util.FileUtils;
import static org.apache.maven.plugins.enforcer.JarUtils.isJarFile;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.JarEntry; | package org.apache.maven.plugins.enforcer;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/**
* Bans duplicate classes on the classpath.
*/
public class BanDuplicateClasses
extends AbstractResolveDependencies
{
/**
* Default ignores which are needed for JDK 9, cause in JDK 9 and above the <code>module-info.class</code> will be
* duplicated in any jar file. Furthermore in use cases for multi release jars the <code>module-info.class</code> is
* also contained several times.
*/
private static final String[] DEFAULT_CLASSES_IGNORES = { "module-info", "META-INF/versions/*/module-info" };
/**
* The failure message
*/
private String message;
/**
* List of classes to ignore. Wildcard at the end accepted
*/
private String[] ignoreClasses;
/**
* If {@code false} then the rule will fail at the first duplicate, if {@code true} then the rule will fail at
* the end.
*/
private boolean findAllDuplicates;
/**
* List of dependencies for which you want to ignore specific classes.
*/ | // Path: src/main/java/org/codehaus/mojo/enforcer/Dependency.java
// public class Dependency
// {
//
// private String groupId;
//
// private String artifactId;
//
// private String classifier;
//
// private String type;
//
// /**
// * List of classes to ignore. Wildcard at the end accepted
// */
// private String[] ignoreClasses;
//
// /**
// * <p>Getter for the field <code>groupId</code>.</p>
// *
// * @return a {@link java.lang.String} object.
// */
// public String getGroupId()
// {
// return groupId;
// }
//
// /**
// * <p>Setter for the field <code>groupId</code>.</p>
// *
// * @param groupId a {@link java.lang.String} object.
// */
// public void setGroupId( String groupId )
// {
// this.groupId = groupId;
// }
//
// /**
// * <p>Getter for the field <code>artifactId</code>.</p>
// *
// * @return a {@link java.lang.String} object.
// */
// public String getArtifactId()
// {
// return artifactId;
// }
//
// /**
// * <p>Setter for the field <code>artifactId</code>.</p>
// *
// * @param artifactId a {@link java.lang.String} object.
// */
// public void setArtifactId( String artifactId )
// {
// this.artifactId = artifactId;
// }
//
// /**
// * <p>Getter for the field <code>classifier</code>.</p>
// *
// * @return a {@link java.lang.String} object.
// */
// public String getClassifier()
// {
// return classifier;
// }
//
// /**
// * <p>Setter for the field <code>classifier</code>.</p>
// *
// * @param classifier a {@link java.lang.String} object.
// */
// public void setClassifier( String classifier )
// {
// this.classifier = classifier;
// }
//
// /**
// * <p>Getter for the field <code>type</code>.</p>
// *
// * @return a {@link java.lang.String} object.
// */
// public String getType()
// {
// return type;
// }
//
// /**
// * <p>Setter for the field <code>type</code>.</p>
// *
// * @param type a {@link java.lang.String} object.
// */
// public void setType( String type )
// {
// this.type = type;
// }
//
// /**
// * <p>Getter for the field <code>ignoreClasses</code>.</p>
// *
// * @return an array of {@link java.lang.String} objects.
// */
// public String[] getIgnoreClasses()
// {
// return ignoreClasses;
// }
//
// /**
// * <p>Setter for the field <code>ignoreClasses</code>.</p>
// *
// * @param ignoreClasses an array of {@link java.lang.String} objects.
// */
// public void setIgnoreClasses( String[] ignoreClasses )
// {
// this.ignoreClasses = ignoreClasses;
// }
//
// /** {@inheritDoc} */
// @Override
// public String toString()
// {
// StringBuilder sb = new StringBuilder();
// sb.append( groupId ).append( ':' ).append( artifactId ).append( ':' ).append( type );
// if ( classifier != null )
// {
// sb.append( ':' ).append( classifier );
// }
// return sb.toString();
// }
// }
//
// Path: src/main/java/org/apache/maven/plugins/enforcer/JarUtils.java
// public static boolean isJarFile( Artifact artifact )
// {
// return artifact.getFile().isFile() && "jar".equals( artifact.getType() );
// }
// Path: src/main/java/org/apache/maven/plugins/enforcer/BanDuplicateClasses.java
import java.util.jar.JarFile;
import java.util.regex.Pattern;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.enforcer.rule.api.EnforcerRuleException;
import org.codehaus.mojo.enforcer.Dependency;
import org.codehaus.plexus.util.FileUtils;
import static org.apache.maven.plugins.enforcer.JarUtils.isJarFile;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.JarEntry;
package org.apache.maven.plugins.enforcer;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/**
* Bans duplicate classes on the classpath.
*/
public class BanDuplicateClasses
extends AbstractResolveDependencies
{
/**
* Default ignores which are needed for JDK 9, cause in JDK 9 and above the <code>module-info.class</code> will be
* duplicated in any jar file. Furthermore in use cases for multi release jars the <code>module-info.class</code> is
* also contained several times.
*/
private static final String[] DEFAULT_CLASSES_IGNORES = { "module-info", "META-INF/versions/*/module-info" };
/**
* The failure message
*/
private String message;
/**
* List of classes to ignore. Wildcard at the end accepted
*/
private String[] ignoreClasses;
/**
* If {@code false} then the rule will fail at the first duplicate, if {@code true} then the rule will fail at
* the end.
*/
private boolean findAllDuplicates;
/**
* List of dependencies for which you want to ignore specific classes.
*/ | private List<Dependency> dependencies; |
mojohaus/extra-enforcer-rules | src/main/java/org/apache/maven/plugins/enforcer/BanDuplicateClasses.java | // Path: src/main/java/org/codehaus/mojo/enforcer/Dependency.java
// public class Dependency
// {
//
// private String groupId;
//
// private String artifactId;
//
// private String classifier;
//
// private String type;
//
// /**
// * List of classes to ignore. Wildcard at the end accepted
// */
// private String[] ignoreClasses;
//
// /**
// * <p>Getter for the field <code>groupId</code>.</p>
// *
// * @return a {@link java.lang.String} object.
// */
// public String getGroupId()
// {
// return groupId;
// }
//
// /**
// * <p>Setter for the field <code>groupId</code>.</p>
// *
// * @param groupId a {@link java.lang.String} object.
// */
// public void setGroupId( String groupId )
// {
// this.groupId = groupId;
// }
//
// /**
// * <p>Getter for the field <code>artifactId</code>.</p>
// *
// * @return a {@link java.lang.String} object.
// */
// public String getArtifactId()
// {
// return artifactId;
// }
//
// /**
// * <p>Setter for the field <code>artifactId</code>.</p>
// *
// * @param artifactId a {@link java.lang.String} object.
// */
// public void setArtifactId( String artifactId )
// {
// this.artifactId = artifactId;
// }
//
// /**
// * <p>Getter for the field <code>classifier</code>.</p>
// *
// * @return a {@link java.lang.String} object.
// */
// public String getClassifier()
// {
// return classifier;
// }
//
// /**
// * <p>Setter for the field <code>classifier</code>.</p>
// *
// * @param classifier a {@link java.lang.String} object.
// */
// public void setClassifier( String classifier )
// {
// this.classifier = classifier;
// }
//
// /**
// * <p>Getter for the field <code>type</code>.</p>
// *
// * @return a {@link java.lang.String} object.
// */
// public String getType()
// {
// return type;
// }
//
// /**
// * <p>Setter for the field <code>type</code>.</p>
// *
// * @param type a {@link java.lang.String} object.
// */
// public void setType( String type )
// {
// this.type = type;
// }
//
// /**
// * <p>Getter for the field <code>ignoreClasses</code>.</p>
// *
// * @return an array of {@link java.lang.String} objects.
// */
// public String[] getIgnoreClasses()
// {
// return ignoreClasses;
// }
//
// /**
// * <p>Setter for the field <code>ignoreClasses</code>.</p>
// *
// * @param ignoreClasses an array of {@link java.lang.String} objects.
// */
// public void setIgnoreClasses( String[] ignoreClasses )
// {
// this.ignoreClasses = ignoreClasses;
// }
//
// /** {@inheritDoc} */
// @Override
// public String toString()
// {
// StringBuilder sb = new StringBuilder();
// sb.append( groupId ).append( ':' ).append( artifactId ).append( ':' ).append( type );
// if ( classifier != null )
// {
// sb.append( ':' ).append( classifier );
// }
// return sb.toString();
// }
// }
//
// Path: src/main/java/org/apache/maven/plugins/enforcer/JarUtils.java
// public static boolean isJarFile( Artifact artifact )
// {
// return artifact.getFile().isFile() && "jar".equals( artifact.getType() );
// }
| import java.util.jar.JarFile;
import java.util.regex.Pattern;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.enforcer.rule.api.EnforcerRuleException;
import org.codehaus.mojo.enforcer.Dependency;
import org.codehaus.plexus.util.FileUtils;
import static org.apache.maven.plugins.enforcer.JarUtils.isJarFile;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.JarEntry; | if( scopes != null && !scopes.contains( o.getScope() ) )
{
if( getLog().isDebugEnabled() )
{
getLog().debug( "Skipping " + o + " due to scope" );
}
continue;
}
File file = o.getFile();
getLog().debug( "Searching for duplicate classes in " + file );
if ( file == null || !file.exists() )
{
getLog().warn( "Could not find " + o + " at " + file );
}
else if ( file.isDirectory() )
{
try
{
for ( String name : FileUtils.getFileNames( file, null, null, false ) )
{
getLog().debug( " " + name );
checkAndAddName( o, name, classesSeen, duplicateClassNames, ignorableDependencies );
}
}
catch ( IOException e )
{
throw new EnforcerRuleException(
"Unable to process dependency " + o + " due to " + e.getLocalizedMessage(), e );
}
} | // Path: src/main/java/org/codehaus/mojo/enforcer/Dependency.java
// public class Dependency
// {
//
// private String groupId;
//
// private String artifactId;
//
// private String classifier;
//
// private String type;
//
// /**
// * List of classes to ignore. Wildcard at the end accepted
// */
// private String[] ignoreClasses;
//
// /**
// * <p>Getter for the field <code>groupId</code>.</p>
// *
// * @return a {@link java.lang.String} object.
// */
// public String getGroupId()
// {
// return groupId;
// }
//
// /**
// * <p>Setter for the field <code>groupId</code>.</p>
// *
// * @param groupId a {@link java.lang.String} object.
// */
// public void setGroupId( String groupId )
// {
// this.groupId = groupId;
// }
//
// /**
// * <p>Getter for the field <code>artifactId</code>.</p>
// *
// * @return a {@link java.lang.String} object.
// */
// public String getArtifactId()
// {
// return artifactId;
// }
//
// /**
// * <p>Setter for the field <code>artifactId</code>.</p>
// *
// * @param artifactId a {@link java.lang.String} object.
// */
// public void setArtifactId( String artifactId )
// {
// this.artifactId = artifactId;
// }
//
// /**
// * <p>Getter for the field <code>classifier</code>.</p>
// *
// * @return a {@link java.lang.String} object.
// */
// public String getClassifier()
// {
// return classifier;
// }
//
// /**
// * <p>Setter for the field <code>classifier</code>.</p>
// *
// * @param classifier a {@link java.lang.String} object.
// */
// public void setClassifier( String classifier )
// {
// this.classifier = classifier;
// }
//
// /**
// * <p>Getter for the field <code>type</code>.</p>
// *
// * @return a {@link java.lang.String} object.
// */
// public String getType()
// {
// return type;
// }
//
// /**
// * <p>Setter for the field <code>type</code>.</p>
// *
// * @param type a {@link java.lang.String} object.
// */
// public void setType( String type )
// {
// this.type = type;
// }
//
// /**
// * <p>Getter for the field <code>ignoreClasses</code>.</p>
// *
// * @return an array of {@link java.lang.String} objects.
// */
// public String[] getIgnoreClasses()
// {
// return ignoreClasses;
// }
//
// /**
// * <p>Setter for the field <code>ignoreClasses</code>.</p>
// *
// * @param ignoreClasses an array of {@link java.lang.String} objects.
// */
// public void setIgnoreClasses( String[] ignoreClasses )
// {
// this.ignoreClasses = ignoreClasses;
// }
//
// /** {@inheritDoc} */
// @Override
// public String toString()
// {
// StringBuilder sb = new StringBuilder();
// sb.append( groupId ).append( ':' ).append( artifactId ).append( ':' ).append( type );
// if ( classifier != null )
// {
// sb.append( ':' ).append( classifier );
// }
// return sb.toString();
// }
// }
//
// Path: src/main/java/org/apache/maven/plugins/enforcer/JarUtils.java
// public static boolean isJarFile( Artifact artifact )
// {
// return artifact.getFile().isFile() && "jar".equals( artifact.getType() );
// }
// Path: src/main/java/org/apache/maven/plugins/enforcer/BanDuplicateClasses.java
import java.util.jar.JarFile;
import java.util.regex.Pattern;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.enforcer.rule.api.EnforcerRuleException;
import org.codehaus.mojo.enforcer.Dependency;
import org.codehaus.plexus.util.FileUtils;
import static org.apache.maven.plugins.enforcer.JarUtils.isJarFile;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.JarEntry;
if( scopes != null && !scopes.contains( o.getScope() ) )
{
if( getLog().isDebugEnabled() )
{
getLog().debug( "Skipping " + o + " due to scope" );
}
continue;
}
File file = o.getFile();
getLog().debug( "Searching for duplicate classes in " + file );
if ( file == null || !file.exists() )
{
getLog().warn( "Could not find " + o + " at " + file );
}
else if ( file.isDirectory() )
{
try
{
for ( String name : FileUtils.getFileNames( file, null, null, false ) )
{
getLog().debug( " " + name );
checkAndAddName( o, name, classesSeen, duplicateClassNames, ignorableDependencies );
}
}
catch ( IOException e )
{
throw new EnforcerRuleException(
"Unable to process dependency " + o + " due to " + e.getLocalizedMessage(), e );
}
} | else if ( isJarFile( o ) ) |
hansenji/PocketBus | compiler/src/main/java/pocketbus/internal/codegen/RegistryGenerator.java | // Path: core/src/main/java/pocketbus/SubscriptionRegistration.java
// public interface SubscriptionRegistration {
// /**
// * @return a list of subscriptions
// */
// List<Subscription<?>> getSubscriptions();
// }
//
// Path: core/src/main/java/pocketbus/internal/PocketBusConst.java
// public class PocketBusConst {
// public static final String ANDROID_PREFIX = "android.";
// public static final String JAVA_PREFIX = "java.";
//
// public static final String REGISTRATION_SUFFIX = "SubscriptionRegistration";
// public static final String REGISTRY_NAME = "BusRegistry";
//
// public static final String METHOD_HANDLE = "handle";
// public static final String METHOD_GET_SUBSCRIPTIONS = "getSubscriptions";
// public static final String METHOD_GET_EVENT_CLASS = "getEventClass";
// public static final String METHOD_GET_THREAD_MODE = "getThreadMode";
// public static final String METHOD_GET_TARGET = "getTarget";
// public static final String METHOD_EQUALS = "equals";
// public static final String METHOD_GET_REGISTRAR = "getRegistration";
//
// public static final String VAR_TARGET_REF = "targetRef";
// public static final String VAR_TARGET = "target";
// public static final String VAR_EVENT = "event";
// public static final String VAR_SUBSCRIPTION = "subscription";
// public static final String VAR_SUBSCRIPTIONS = "subscriptions";
// public static final String VAR_O = "o";
// }
//
// Path: core/src/main/java/pocketbus/internal/Registry.java
// public interface Registry {
// /**
// * @param target the target that has subscribe annotations
// * @return the SubscriptionRegistration for the given target
// */
// <T> SubscriptionRegistration getRegistration(T target);
// }
| import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeSpec;
import com.squareup.javapoet.TypeVariableName;
import java.util.List;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeMirror;
import pocketbus.SubscriptionRegistration;
import pocketbus.internal.PocketBusConst;
import pocketbus.internal.Registry; | package pocketbus.internal.codegen;
public class RegistryGenerator {
private final String packageName;
private final TypeElement typeElement;
private List<SubscriptionNode> subscriptionTrees;
public RegistryGenerator(TypeElement typeElement, String packageName) {
this.typeElement = typeElement;
this.packageName = packageName;
}
public JavaFile generate() { | // Path: core/src/main/java/pocketbus/SubscriptionRegistration.java
// public interface SubscriptionRegistration {
// /**
// * @return a list of subscriptions
// */
// List<Subscription<?>> getSubscriptions();
// }
//
// Path: core/src/main/java/pocketbus/internal/PocketBusConst.java
// public class PocketBusConst {
// public static final String ANDROID_PREFIX = "android.";
// public static final String JAVA_PREFIX = "java.";
//
// public static final String REGISTRATION_SUFFIX = "SubscriptionRegistration";
// public static final String REGISTRY_NAME = "BusRegistry";
//
// public static final String METHOD_HANDLE = "handle";
// public static final String METHOD_GET_SUBSCRIPTIONS = "getSubscriptions";
// public static final String METHOD_GET_EVENT_CLASS = "getEventClass";
// public static final String METHOD_GET_THREAD_MODE = "getThreadMode";
// public static final String METHOD_GET_TARGET = "getTarget";
// public static final String METHOD_EQUALS = "equals";
// public static final String METHOD_GET_REGISTRAR = "getRegistration";
//
// public static final String VAR_TARGET_REF = "targetRef";
// public static final String VAR_TARGET = "target";
// public static final String VAR_EVENT = "event";
// public static final String VAR_SUBSCRIPTION = "subscription";
// public static final String VAR_SUBSCRIPTIONS = "subscriptions";
// public static final String VAR_O = "o";
// }
//
// Path: core/src/main/java/pocketbus/internal/Registry.java
// public interface Registry {
// /**
// * @param target the target that has subscribe annotations
// * @return the SubscriptionRegistration for the given target
// */
// <T> SubscriptionRegistration getRegistration(T target);
// }
// Path: compiler/src/main/java/pocketbus/internal/codegen/RegistryGenerator.java
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeSpec;
import com.squareup.javapoet.TypeVariableName;
import java.util.List;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeMirror;
import pocketbus.SubscriptionRegistration;
import pocketbus.internal.PocketBusConst;
import pocketbus.internal.Registry;
package pocketbus.internal.codegen;
public class RegistryGenerator {
private final String packageName;
private final TypeElement typeElement;
private List<SubscriptionNode> subscriptionTrees;
public RegistryGenerator(TypeElement typeElement, String packageName) {
this.typeElement = typeElement;
this.packageName = packageName;
}
public JavaFile generate() { | TypeSpec.Builder classBuilder = TypeSpec.classBuilder(PocketBusConst.REGISTRY_NAME) |
hansenji/PocketBus | compiler/src/main/java/pocketbus/internal/codegen/RegistryGenerator.java | // Path: core/src/main/java/pocketbus/SubscriptionRegistration.java
// public interface SubscriptionRegistration {
// /**
// * @return a list of subscriptions
// */
// List<Subscription<?>> getSubscriptions();
// }
//
// Path: core/src/main/java/pocketbus/internal/PocketBusConst.java
// public class PocketBusConst {
// public static final String ANDROID_PREFIX = "android.";
// public static final String JAVA_PREFIX = "java.";
//
// public static final String REGISTRATION_SUFFIX = "SubscriptionRegistration";
// public static final String REGISTRY_NAME = "BusRegistry";
//
// public static final String METHOD_HANDLE = "handle";
// public static final String METHOD_GET_SUBSCRIPTIONS = "getSubscriptions";
// public static final String METHOD_GET_EVENT_CLASS = "getEventClass";
// public static final String METHOD_GET_THREAD_MODE = "getThreadMode";
// public static final String METHOD_GET_TARGET = "getTarget";
// public static final String METHOD_EQUALS = "equals";
// public static final String METHOD_GET_REGISTRAR = "getRegistration";
//
// public static final String VAR_TARGET_REF = "targetRef";
// public static final String VAR_TARGET = "target";
// public static final String VAR_EVENT = "event";
// public static final String VAR_SUBSCRIPTION = "subscription";
// public static final String VAR_SUBSCRIPTIONS = "subscriptions";
// public static final String VAR_O = "o";
// }
//
// Path: core/src/main/java/pocketbus/internal/Registry.java
// public interface Registry {
// /**
// * @param target the target that has subscribe annotations
// * @return the SubscriptionRegistration for the given target
// */
// <T> SubscriptionRegistration getRegistration(T target);
// }
| import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeSpec;
import com.squareup.javapoet.TypeVariableName;
import java.util.List;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeMirror;
import pocketbus.SubscriptionRegistration;
import pocketbus.internal.PocketBusConst;
import pocketbus.internal.Registry; | package pocketbus.internal.codegen;
public class RegistryGenerator {
private final String packageName;
private final TypeElement typeElement;
private List<SubscriptionNode> subscriptionTrees;
public RegistryGenerator(TypeElement typeElement, String packageName) {
this.typeElement = typeElement;
this.packageName = packageName;
}
public JavaFile generate() {
TypeSpec.Builder classBuilder = TypeSpec.classBuilder(PocketBusConst.REGISTRY_NAME)
.addModifiers(Modifier.PUBLIC) | // Path: core/src/main/java/pocketbus/SubscriptionRegistration.java
// public interface SubscriptionRegistration {
// /**
// * @return a list of subscriptions
// */
// List<Subscription<?>> getSubscriptions();
// }
//
// Path: core/src/main/java/pocketbus/internal/PocketBusConst.java
// public class PocketBusConst {
// public static final String ANDROID_PREFIX = "android.";
// public static final String JAVA_PREFIX = "java.";
//
// public static final String REGISTRATION_SUFFIX = "SubscriptionRegistration";
// public static final String REGISTRY_NAME = "BusRegistry";
//
// public static final String METHOD_HANDLE = "handle";
// public static final String METHOD_GET_SUBSCRIPTIONS = "getSubscriptions";
// public static final String METHOD_GET_EVENT_CLASS = "getEventClass";
// public static final String METHOD_GET_THREAD_MODE = "getThreadMode";
// public static final String METHOD_GET_TARGET = "getTarget";
// public static final String METHOD_EQUALS = "equals";
// public static final String METHOD_GET_REGISTRAR = "getRegistration";
//
// public static final String VAR_TARGET_REF = "targetRef";
// public static final String VAR_TARGET = "target";
// public static final String VAR_EVENT = "event";
// public static final String VAR_SUBSCRIPTION = "subscription";
// public static final String VAR_SUBSCRIPTIONS = "subscriptions";
// public static final String VAR_O = "o";
// }
//
// Path: core/src/main/java/pocketbus/internal/Registry.java
// public interface Registry {
// /**
// * @param target the target that has subscribe annotations
// * @return the SubscriptionRegistration for the given target
// */
// <T> SubscriptionRegistration getRegistration(T target);
// }
// Path: compiler/src/main/java/pocketbus/internal/codegen/RegistryGenerator.java
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeSpec;
import com.squareup.javapoet.TypeVariableName;
import java.util.List;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeMirror;
import pocketbus.SubscriptionRegistration;
import pocketbus.internal.PocketBusConst;
import pocketbus.internal.Registry;
package pocketbus.internal.codegen;
public class RegistryGenerator {
private final String packageName;
private final TypeElement typeElement;
private List<SubscriptionNode> subscriptionTrees;
public RegistryGenerator(TypeElement typeElement, String packageName) {
this.typeElement = typeElement;
this.packageName = packageName;
}
public JavaFile generate() {
TypeSpec.Builder classBuilder = TypeSpec.classBuilder(PocketBusConst.REGISTRY_NAME)
.addModifiers(Modifier.PUBLIC) | .addSuperinterface(ClassName.get(Registry.class)); |
hansenji/PocketBus | compiler/src/main/java/pocketbus/internal/codegen/RegistryGenerator.java | // Path: core/src/main/java/pocketbus/SubscriptionRegistration.java
// public interface SubscriptionRegistration {
// /**
// * @return a list of subscriptions
// */
// List<Subscription<?>> getSubscriptions();
// }
//
// Path: core/src/main/java/pocketbus/internal/PocketBusConst.java
// public class PocketBusConst {
// public static final String ANDROID_PREFIX = "android.";
// public static final String JAVA_PREFIX = "java.";
//
// public static final String REGISTRATION_SUFFIX = "SubscriptionRegistration";
// public static final String REGISTRY_NAME = "BusRegistry";
//
// public static final String METHOD_HANDLE = "handle";
// public static final String METHOD_GET_SUBSCRIPTIONS = "getSubscriptions";
// public static final String METHOD_GET_EVENT_CLASS = "getEventClass";
// public static final String METHOD_GET_THREAD_MODE = "getThreadMode";
// public static final String METHOD_GET_TARGET = "getTarget";
// public static final String METHOD_EQUALS = "equals";
// public static final String METHOD_GET_REGISTRAR = "getRegistration";
//
// public static final String VAR_TARGET_REF = "targetRef";
// public static final String VAR_TARGET = "target";
// public static final String VAR_EVENT = "event";
// public static final String VAR_SUBSCRIPTION = "subscription";
// public static final String VAR_SUBSCRIPTIONS = "subscriptions";
// public static final String VAR_O = "o";
// }
//
// Path: core/src/main/java/pocketbus/internal/Registry.java
// public interface Registry {
// /**
// * @param target the target that has subscribe annotations
// * @return the SubscriptionRegistration for the given target
// */
// <T> SubscriptionRegistration getRegistration(T target);
// }
| import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeSpec;
import com.squareup.javapoet.TypeVariableName;
import java.util.List;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeMirror;
import pocketbus.SubscriptionRegistration;
import pocketbus.internal.PocketBusConst;
import pocketbus.internal.Registry; | package pocketbus.internal.codegen;
public class RegistryGenerator {
private final String packageName;
private final TypeElement typeElement;
private List<SubscriptionNode> subscriptionTrees;
public RegistryGenerator(TypeElement typeElement, String packageName) {
this.typeElement = typeElement;
this.packageName = packageName;
}
public JavaFile generate() {
TypeSpec.Builder classBuilder = TypeSpec.classBuilder(PocketBusConst.REGISTRY_NAME)
.addModifiers(Modifier.PUBLIC)
.addSuperinterface(ClassName.get(Registry.class));
generateMethod(classBuilder);
return JavaFile.builder(packageName, classBuilder.build()).build();
}
private void generateMethod(TypeSpec.Builder classBuilder) {
TypeVariableName t = TypeVariableName.get("T");
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(PocketBusConst.METHOD_GET_REGISTRAR)
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override.class)
.addTypeVariable(t)
.addParameter(t, PocketBusConst.VAR_TARGET) | // Path: core/src/main/java/pocketbus/SubscriptionRegistration.java
// public interface SubscriptionRegistration {
// /**
// * @return a list of subscriptions
// */
// List<Subscription<?>> getSubscriptions();
// }
//
// Path: core/src/main/java/pocketbus/internal/PocketBusConst.java
// public class PocketBusConst {
// public static final String ANDROID_PREFIX = "android.";
// public static final String JAVA_PREFIX = "java.";
//
// public static final String REGISTRATION_SUFFIX = "SubscriptionRegistration";
// public static final String REGISTRY_NAME = "BusRegistry";
//
// public static final String METHOD_HANDLE = "handle";
// public static final String METHOD_GET_SUBSCRIPTIONS = "getSubscriptions";
// public static final String METHOD_GET_EVENT_CLASS = "getEventClass";
// public static final String METHOD_GET_THREAD_MODE = "getThreadMode";
// public static final String METHOD_GET_TARGET = "getTarget";
// public static final String METHOD_EQUALS = "equals";
// public static final String METHOD_GET_REGISTRAR = "getRegistration";
//
// public static final String VAR_TARGET_REF = "targetRef";
// public static final String VAR_TARGET = "target";
// public static final String VAR_EVENT = "event";
// public static final String VAR_SUBSCRIPTION = "subscription";
// public static final String VAR_SUBSCRIPTIONS = "subscriptions";
// public static final String VAR_O = "o";
// }
//
// Path: core/src/main/java/pocketbus/internal/Registry.java
// public interface Registry {
// /**
// * @param target the target that has subscribe annotations
// * @return the SubscriptionRegistration for the given target
// */
// <T> SubscriptionRegistration getRegistration(T target);
// }
// Path: compiler/src/main/java/pocketbus/internal/codegen/RegistryGenerator.java
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeSpec;
import com.squareup.javapoet.TypeVariableName;
import java.util.List;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeMirror;
import pocketbus.SubscriptionRegistration;
import pocketbus.internal.PocketBusConst;
import pocketbus.internal.Registry;
package pocketbus.internal.codegen;
public class RegistryGenerator {
private final String packageName;
private final TypeElement typeElement;
private List<SubscriptionNode> subscriptionTrees;
public RegistryGenerator(TypeElement typeElement, String packageName) {
this.typeElement = typeElement;
this.packageName = packageName;
}
public JavaFile generate() {
TypeSpec.Builder classBuilder = TypeSpec.classBuilder(PocketBusConst.REGISTRY_NAME)
.addModifiers(Modifier.PUBLIC)
.addSuperinterface(ClassName.get(Registry.class));
generateMethod(classBuilder);
return JavaFile.builder(packageName, classBuilder.build()).build();
}
private void generateMethod(TypeSpec.Builder classBuilder) {
TypeVariableName t = TypeVariableName.get("T");
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(PocketBusConst.METHOD_GET_REGISTRAR)
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override.class)
.addTypeVariable(t)
.addParameter(t, PocketBusConst.VAR_TARGET) | .returns(SubscriptionRegistration.class); |
hansenji/PocketBus | compiler/src/main/java/pocketbus/internal/codegen/SubscriptionProcessor.java | // Path: core/src/main/java/pocketbus/internal/PocketBusConst.java
// public class PocketBusConst {
// public static final String ANDROID_PREFIX = "android.";
// public static final String JAVA_PREFIX = "java.";
//
// public static final String REGISTRATION_SUFFIX = "SubscriptionRegistration";
// public static final String REGISTRY_NAME = "BusRegistry";
//
// public static final String METHOD_HANDLE = "handle";
// public static final String METHOD_GET_SUBSCRIPTIONS = "getSubscriptions";
// public static final String METHOD_GET_EVENT_CLASS = "getEventClass";
// public static final String METHOD_GET_THREAD_MODE = "getThreadMode";
// public static final String METHOD_GET_TARGET = "getTarget";
// public static final String METHOD_EQUALS = "equals";
// public static final String METHOD_GET_REGISTRAR = "getRegistration";
//
// public static final String VAR_TARGET_REF = "targetRef";
// public static final String VAR_TARGET = "target";
// public static final String VAR_EVENT = "event";
// public static final String VAR_SUBSCRIPTION = "subscription";
// public static final String VAR_SUBSCRIPTIONS = "subscriptions";
// public static final String VAR_O = "o";
// }
| import com.google.common.collect.ImmutableSet;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.Messager;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;
import pocketbus.Subscribe;
import pocketbus.internal.PocketBusConst;
import static javax.tools.Diagnostic.Kind.ERROR;
import static javax.tools.Diagnostic.Kind.WARNING; | Subscribe subscribeAnnotation = element.getAnnotation(Subscribe.class);
if (subscribeAnnotation == null) {
messager.printMessage(WARNING, String.format("@%s annotation not found on %s", Subscribe.class.getSimpleName(), element), element);
continue;
}
if (!(element instanceof ExecutableElement) || element.getKind() != ElementKind.METHOD) {
error(String.format("@%s annotation must be on a method (%s.%s)", Subscribe.class.getSimpleName(), enclosingElement.getQualifiedName(),
element.getSimpleName()), element);
}
ExecutableElement executableElement = (ExecutableElement) element;
validateMethod(executableElement);
validateBindingPackage(element);
validateVisibility(element);
SubscriptionGenerator generator = getOrCreateTargetClass(targetMap, enclosingElement);
SubscriptionMethod method = new SubscriptionMethod(executableElement, subscribeAnnotation.value());
if (!generator.addMethod(method)) {
error(String.format("@%s method cannot have multiple subscriptions for type %s on ThreadMode.%s (%s.%s)",
Subscribe.class.getSimpleName(), method.getEventType(), method.getThreadMode(), enclosingElement.getQualifiedName(),
element.getSimpleName()), element);
}
erasedTargetNames.add(enclosingElement.toString());
}
for (Map.Entry<TypeElement, SubscriptionGenerator> entry : targetMap.entrySet()) {
TypeElement parentElement = findParent(entry.getKey(), erasedTargetNames);
if (parentElement != null) { | // Path: core/src/main/java/pocketbus/internal/PocketBusConst.java
// public class PocketBusConst {
// public static final String ANDROID_PREFIX = "android.";
// public static final String JAVA_PREFIX = "java.";
//
// public static final String REGISTRATION_SUFFIX = "SubscriptionRegistration";
// public static final String REGISTRY_NAME = "BusRegistry";
//
// public static final String METHOD_HANDLE = "handle";
// public static final String METHOD_GET_SUBSCRIPTIONS = "getSubscriptions";
// public static final String METHOD_GET_EVENT_CLASS = "getEventClass";
// public static final String METHOD_GET_THREAD_MODE = "getThreadMode";
// public static final String METHOD_GET_TARGET = "getTarget";
// public static final String METHOD_EQUALS = "equals";
// public static final String METHOD_GET_REGISTRAR = "getRegistration";
//
// public static final String VAR_TARGET_REF = "targetRef";
// public static final String VAR_TARGET = "target";
// public static final String VAR_EVENT = "event";
// public static final String VAR_SUBSCRIPTION = "subscription";
// public static final String VAR_SUBSCRIPTIONS = "subscriptions";
// public static final String VAR_O = "o";
// }
// Path: compiler/src/main/java/pocketbus/internal/codegen/SubscriptionProcessor.java
import com.google.common.collect.ImmutableSet;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.Messager;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;
import pocketbus.Subscribe;
import pocketbus.internal.PocketBusConst;
import static javax.tools.Diagnostic.Kind.ERROR;
import static javax.tools.Diagnostic.Kind.WARNING;
Subscribe subscribeAnnotation = element.getAnnotation(Subscribe.class);
if (subscribeAnnotation == null) {
messager.printMessage(WARNING, String.format("@%s annotation not found on %s", Subscribe.class.getSimpleName(), element), element);
continue;
}
if (!(element instanceof ExecutableElement) || element.getKind() != ElementKind.METHOD) {
error(String.format("@%s annotation must be on a method (%s.%s)", Subscribe.class.getSimpleName(), enclosingElement.getQualifiedName(),
element.getSimpleName()), element);
}
ExecutableElement executableElement = (ExecutableElement) element;
validateMethod(executableElement);
validateBindingPackage(element);
validateVisibility(element);
SubscriptionGenerator generator = getOrCreateTargetClass(targetMap, enclosingElement);
SubscriptionMethod method = new SubscriptionMethod(executableElement, subscribeAnnotation.value());
if (!generator.addMethod(method)) {
error(String.format("@%s method cannot have multiple subscriptions for type %s on ThreadMode.%s (%s.%s)",
Subscribe.class.getSimpleName(), method.getEventType(), method.getThreadMode(), enclosingElement.getQualifiedName(),
element.getSimpleName()), element);
}
erasedTargetNames.add(enclosingElement.toString());
}
for (Map.Entry<TypeElement, SubscriptionGenerator> entry : targetMap.entrySet()) {
TypeElement parentElement = findParent(entry.getKey(), erasedTargetNames);
if (parentElement != null) { | entry.getValue().setParentAdapter(getPackageName(parentElement), parentElement.getSimpleName() + PocketBusConst.REGISTRATION_SUFFIX); |
hansenji/PocketBus | library/src/main/java/pocketbus/Bus.java | // Path: core/src/main/java/pocketbus/internal/Registry.java
// public interface Registry {
// /**
// * @param target the target that has subscribe annotations
// * @return the SubscriptionRegistration for the given target
// */
// <T> SubscriptionRegistration getRegistration(T target);
// }
| import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import io.reactivex.Observable;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import pocketbus.internal.Registry; | package pocketbus;
public class Bus {
private static final String TAG = "PocketBus";
private static final Object DEFAULT_LOCK = new Object();
private static Bus defaultBus;
private static boolean debug = false;
@NonNull
private final Scheduler mainScheduler;
@NonNull
private final Scheduler currentScheduler;
@NonNull
private final Scheduler backgroundScheduler;
protected final int eventCleanupCount;
@NonNull
private final AtomicInteger eventCounter = new AtomicInteger();
@NonNull
private final Map<Class, List<Subscription>> mainThreadListeners = new LinkedHashMap<>();
@NonNull
private final Map<Class, List<Subscription>> backgroundThreadListeners = new LinkedHashMap<>();
@NonNull
private final Map<Class, List<Subscription>> currentThreadListeners = new LinkedHashMap<>();
@NonNull
private final Map<Class<?>, ? super Object> stickyEvents = new LinkedHashMap<>();
@NonNull
private final Object listenerLock = new Object();
@NonNull
private final Object stickyLock = new Object();
@Nullable | // Path: core/src/main/java/pocketbus/internal/Registry.java
// public interface Registry {
// /**
// * @param target the target that has subscribe annotations
// * @return the SubscriptionRegistration for the given target
// */
// <T> SubscriptionRegistration getRegistration(T target);
// }
// Path: library/src/main/java/pocketbus/Bus.java
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import io.reactivex.Observable;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import pocketbus.internal.Registry;
package pocketbus;
public class Bus {
private static final String TAG = "PocketBus";
private static final Object DEFAULT_LOCK = new Object();
private static Bus defaultBus;
private static boolean debug = false;
@NonNull
private final Scheduler mainScheduler;
@NonNull
private final Scheduler currentScheduler;
@NonNull
private final Scheduler backgroundScheduler;
protected final int eventCleanupCount;
@NonNull
private final AtomicInteger eventCounter = new AtomicInteger();
@NonNull
private final Map<Class, List<Subscription>> mainThreadListeners = new LinkedHashMap<>();
@NonNull
private final Map<Class, List<Subscription>> backgroundThreadListeners = new LinkedHashMap<>();
@NonNull
private final Map<Class, List<Subscription>> currentThreadListeners = new LinkedHashMap<>();
@NonNull
private final Map<Class<?>, ? super Object> stickyEvents = new LinkedHashMap<>();
@NonNull
private final Object listenerLock = new Object();
@NonNull
private final Object stickyLock = new Object();
@Nullable | private Registry registry = null; |
hansenji/PocketBus | compiler/src/main/java/pocketbus/internal/codegen/SubscriptionGenerator.java | // Path: core/src/main/java/pocketbus/SubscriptionRegistration.java
// public interface SubscriptionRegistration {
// /**
// * @return a list of subscriptions
// */
// List<Subscription<?>> getSubscriptions();
// }
//
// Path: core/src/main/java/pocketbus/Subscription.java
// public interface Subscription<T> {
// /**
// * Handle an event posted to the bus
// *
// * @param t event posted to the bus
// * @return false if subscription should be unregistered
// */
// boolean handle(T t);
//
// /**
// * @return Class of event this subscription handles
// */
// Class<T> getEventClass();
//
// /**
// * @return ThreadMode for this subscription
// */
// ThreadMode getThreadMode();
//
// /**
// * @return the target with which this subscription interacts
// */
// <E> E getTarget();
// }
//
// Path: core/src/main/java/pocketbus/ThreadMode.java
// public enum ThreadMode {
// /**
// * Subscription run on same thread as caller
// */
// CURRENT, // Schedulers.trampoline()
// /**
// * Subscription run on the main thread
// */
// MAIN, // AndroidSchedulers.mainThread()
// /**
// * Subscription run on a background thread
// */
// BACKGROUND // Schedulers.newThread()
// }
//
// Path: core/src/main/java/pocketbus/internal/PocketBusConst.java
// public class PocketBusConst {
// public static final String ANDROID_PREFIX = "android.";
// public static final String JAVA_PREFIX = "java.";
//
// public static final String REGISTRATION_SUFFIX = "SubscriptionRegistration";
// public static final String REGISTRY_NAME = "BusRegistry";
//
// public static final String METHOD_HANDLE = "handle";
// public static final String METHOD_GET_SUBSCRIPTIONS = "getSubscriptions";
// public static final String METHOD_GET_EVENT_CLASS = "getEventClass";
// public static final String METHOD_GET_THREAD_MODE = "getThreadMode";
// public static final String METHOD_GET_TARGET = "getTarget";
// public static final String METHOD_EQUALS = "equals";
// public static final String METHOD_GET_REGISTRAR = "getRegistration";
//
// public static final String VAR_TARGET_REF = "targetRef";
// public static final String VAR_TARGET = "target";
// public static final String VAR_EVENT = "event";
// public static final String VAR_SUBSCRIPTION = "subscription";
// public static final String VAR_SUBSCRIPTIONS = "subscriptions";
// public static final String VAR_O = "o";
// }
| import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import com.squareup.javapoet.WildcardTypeName;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.lang.model.element.Modifier;
import javax.lang.model.type.TypeMirror;
import pocketbus.SubscriptionRegistration;
import pocketbus.Subscription;
import pocketbus.ThreadMode;
import pocketbus.internal.PocketBusConst; | package pocketbus.internal.codegen;
public class SubscriptionGenerator {
private static final ParameterizedTypeName SUBSCRIPTION_TYPE = ParameterizedTypeName.get(ClassName.get(Subscription.class),
WildcardTypeName.subtypeOf(TypeName.OBJECT));
private static final ParameterizedTypeName LIST_TYPE = ParameterizedTypeName.get(ClassName.get(List.class), SUBSCRIPTION_TYPE);
Set<SubscriptionMethod> methods = new LinkedHashSet<>();
private final String classPackage;
private final String className;
private final TypeMirror targetType;
private ClassName parentAdapter;
private int idx = 1;
public SubscriptionGenerator(String classPackage, String className, TypeMirror targetType) {
this.classPackage = classPackage;
this.className = className;
this.targetType = targetType;
}
public boolean addMethod(SubscriptionMethod method) {
method.setIndex(idx++);
return this.methods.add(method);
}
public JavaFile generate() {
TypeSpec.Builder classBuilder = TypeSpec.classBuilder(className)
.addModifiers(Modifier.PUBLIC) | // Path: core/src/main/java/pocketbus/SubscriptionRegistration.java
// public interface SubscriptionRegistration {
// /**
// * @return a list of subscriptions
// */
// List<Subscription<?>> getSubscriptions();
// }
//
// Path: core/src/main/java/pocketbus/Subscription.java
// public interface Subscription<T> {
// /**
// * Handle an event posted to the bus
// *
// * @param t event posted to the bus
// * @return false if subscription should be unregistered
// */
// boolean handle(T t);
//
// /**
// * @return Class of event this subscription handles
// */
// Class<T> getEventClass();
//
// /**
// * @return ThreadMode for this subscription
// */
// ThreadMode getThreadMode();
//
// /**
// * @return the target with which this subscription interacts
// */
// <E> E getTarget();
// }
//
// Path: core/src/main/java/pocketbus/ThreadMode.java
// public enum ThreadMode {
// /**
// * Subscription run on same thread as caller
// */
// CURRENT, // Schedulers.trampoline()
// /**
// * Subscription run on the main thread
// */
// MAIN, // AndroidSchedulers.mainThread()
// /**
// * Subscription run on a background thread
// */
// BACKGROUND // Schedulers.newThread()
// }
//
// Path: core/src/main/java/pocketbus/internal/PocketBusConst.java
// public class PocketBusConst {
// public static final String ANDROID_PREFIX = "android.";
// public static final String JAVA_PREFIX = "java.";
//
// public static final String REGISTRATION_SUFFIX = "SubscriptionRegistration";
// public static final String REGISTRY_NAME = "BusRegistry";
//
// public static final String METHOD_HANDLE = "handle";
// public static final String METHOD_GET_SUBSCRIPTIONS = "getSubscriptions";
// public static final String METHOD_GET_EVENT_CLASS = "getEventClass";
// public static final String METHOD_GET_THREAD_MODE = "getThreadMode";
// public static final String METHOD_GET_TARGET = "getTarget";
// public static final String METHOD_EQUALS = "equals";
// public static final String METHOD_GET_REGISTRAR = "getRegistration";
//
// public static final String VAR_TARGET_REF = "targetRef";
// public static final String VAR_TARGET = "target";
// public static final String VAR_EVENT = "event";
// public static final String VAR_SUBSCRIPTION = "subscription";
// public static final String VAR_SUBSCRIPTIONS = "subscriptions";
// public static final String VAR_O = "o";
// }
// Path: compiler/src/main/java/pocketbus/internal/codegen/SubscriptionGenerator.java
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import com.squareup.javapoet.WildcardTypeName;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.lang.model.element.Modifier;
import javax.lang.model.type.TypeMirror;
import pocketbus.SubscriptionRegistration;
import pocketbus.Subscription;
import pocketbus.ThreadMode;
import pocketbus.internal.PocketBusConst;
package pocketbus.internal.codegen;
public class SubscriptionGenerator {
private static final ParameterizedTypeName SUBSCRIPTION_TYPE = ParameterizedTypeName.get(ClassName.get(Subscription.class),
WildcardTypeName.subtypeOf(TypeName.OBJECT));
private static final ParameterizedTypeName LIST_TYPE = ParameterizedTypeName.get(ClassName.get(List.class), SUBSCRIPTION_TYPE);
Set<SubscriptionMethod> methods = new LinkedHashSet<>();
private final String classPackage;
private final String className;
private final TypeMirror targetType;
private ClassName parentAdapter;
private int idx = 1;
public SubscriptionGenerator(String classPackage, String className, TypeMirror targetType) {
this.classPackage = classPackage;
this.className = className;
this.targetType = targetType;
}
public boolean addMethod(SubscriptionMethod method) {
method.setIndex(idx++);
return this.methods.add(method);
}
public JavaFile generate() {
TypeSpec.Builder classBuilder = TypeSpec.classBuilder(className)
.addModifiers(Modifier.PUBLIC) | .addField(getWeakReferenceType(), PocketBusConst.VAR_TARGET_REF, Modifier.PRIVATE, Modifier.FINAL) |
hansenji/PocketBus | compiler/src/main/java/pocketbus/internal/codegen/SubscriptionGenerator.java | // Path: core/src/main/java/pocketbus/SubscriptionRegistration.java
// public interface SubscriptionRegistration {
// /**
// * @return a list of subscriptions
// */
// List<Subscription<?>> getSubscriptions();
// }
//
// Path: core/src/main/java/pocketbus/Subscription.java
// public interface Subscription<T> {
// /**
// * Handle an event posted to the bus
// *
// * @param t event posted to the bus
// * @return false if subscription should be unregistered
// */
// boolean handle(T t);
//
// /**
// * @return Class of event this subscription handles
// */
// Class<T> getEventClass();
//
// /**
// * @return ThreadMode for this subscription
// */
// ThreadMode getThreadMode();
//
// /**
// * @return the target with which this subscription interacts
// */
// <E> E getTarget();
// }
//
// Path: core/src/main/java/pocketbus/ThreadMode.java
// public enum ThreadMode {
// /**
// * Subscription run on same thread as caller
// */
// CURRENT, // Schedulers.trampoline()
// /**
// * Subscription run on the main thread
// */
// MAIN, // AndroidSchedulers.mainThread()
// /**
// * Subscription run on a background thread
// */
// BACKGROUND // Schedulers.newThread()
// }
//
// Path: core/src/main/java/pocketbus/internal/PocketBusConst.java
// public class PocketBusConst {
// public static final String ANDROID_PREFIX = "android.";
// public static final String JAVA_PREFIX = "java.";
//
// public static final String REGISTRATION_SUFFIX = "SubscriptionRegistration";
// public static final String REGISTRY_NAME = "BusRegistry";
//
// public static final String METHOD_HANDLE = "handle";
// public static final String METHOD_GET_SUBSCRIPTIONS = "getSubscriptions";
// public static final String METHOD_GET_EVENT_CLASS = "getEventClass";
// public static final String METHOD_GET_THREAD_MODE = "getThreadMode";
// public static final String METHOD_GET_TARGET = "getTarget";
// public static final String METHOD_EQUALS = "equals";
// public static final String METHOD_GET_REGISTRAR = "getRegistration";
//
// public static final String VAR_TARGET_REF = "targetRef";
// public static final String VAR_TARGET = "target";
// public static final String VAR_EVENT = "event";
// public static final String VAR_SUBSCRIPTION = "subscription";
// public static final String VAR_SUBSCRIPTIONS = "subscriptions";
// public static final String VAR_O = "o";
// }
| import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import com.squareup.javapoet.WildcardTypeName;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.lang.model.element.Modifier;
import javax.lang.model.type.TypeMirror;
import pocketbus.SubscriptionRegistration;
import pocketbus.Subscription;
import pocketbus.ThreadMode;
import pocketbus.internal.PocketBusConst; | package pocketbus.internal.codegen;
public class SubscriptionGenerator {
private static final ParameterizedTypeName SUBSCRIPTION_TYPE = ParameterizedTypeName.get(ClassName.get(Subscription.class),
WildcardTypeName.subtypeOf(TypeName.OBJECT));
private static final ParameterizedTypeName LIST_TYPE = ParameterizedTypeName.get(ClassName.get(List.class), SUBSCRIPTION_TYPE);
Set<SubscriptionMethod> methods = new LinkedHashSet<>();
private final String classPackage;
private final String className;
private final TypeMirror targetType;
private ClassName parentAdapter;
private int idx = 1;
public SubscriptionGenerator(String classPackage, String className, TypeMirror targetType) {
this.classPackage = classPackage;
this.className = className;
this.targetType = targetType;
}
public boolean addMethod(SubscriptionMethod method) {
method.setIndex(idx++);
return this.methods.add(method);
}
public JavaFile generate() {
TypeSpec.Builder classBuilder = TypeSpec.classBuilder(className)
.addModifiers(Modifier.PUBLIC)
.addField(getWeakReferenceType(), PocketBusConst.VAR_TARGET_REF, Modifier.PRIVATE, Modifier.FINAL)
.addField(LIST_TYPE, PocketBusConst.VAR_SUBSCRIPTIONS, Modifier.PRIVATE, Modifier.FINAL);
if (parentAdapter != null) {
classBuilder.superclass(parentAdapter);
} else { | // Path: core/src/main/java/pocketbus/SubscriptionRegistration.java
// public interface SubscriptionRegistration {
// /**
// * @return a list of subscriptions
// */
// List<Subscription<?>> getSubscriptions();
// }
//
// Path: core/src/main/java/pocketbus/Subscription.java
// public interface Subscription<T> {
// /**
// * Handle an event posted to the bus
// *
// * @param t event posted to the bus
// * @return false if subscription should be unregistered
// */
// boolean handle(T t);
//
// /**
// * @return Class of event this subscription handles
// */
// Class<T> getEventClass();
//
// /**
// * @return ThreadMode for this subscription
// */
// ThreadMode getThreadMode();
//
// /**
// * @return the target with which this subscription interacts
// */
// <E> E getTarget();
// }
//
// Path: core/src/main/java/pocketbus/ThreadMode.java
// public enum ThreadMode {
// /**
// * Subscription run on same thread as caller
// */
// CURRENT, // Schedulers.trampoline()
// /**
// * Subscription run on the main thread
// */
// MAIN, // AndroidSchedulers.mainThread()
// /**
// * Subscription run on a background thread
// */
// BACKGROUND // Schedulers.newThread()
// }
//
// Path: core/src/main/java/pocketbus/internal/PocketBusConst.java
// public class PocketBusConst {
// public static final String ANDROID_PREFIX = "android.";
// public static final String JAVA_PREFIX = "java.";
//
// public static final String REGISTRATION_SUFFIX = "SubscriptionRegistration";
// public static final String REGISTRY_NAME = "BusRegistry";
//
// public static final String METHOD_HANDLE = "handle";
// public static final String METHOD_GET_SUBSCRIPTIONS = "getSubscriptions";
// public static final String METHOD_GET_EVENT_CLASS = "getEventClass";
// public static final String METHOD_GET_THREAD_MODE = "getThreadMode";
// public static final String METHOD_GET_TARGET = "getTarget";
// public static final String METHOD_EQUALS = "equals";
// public static final String METHOD_GET_REGISTRAR = "getRegistration";
//
// public static final String VAR_TARGET_REF = "targetRef";
// public static final String VAR_TARGET = "target";
// public static final String VAR_EVENT = "event";
// public static final String VAR_SUBSCRIPTION = "subscription";
// public static final String VAR_SUBSCRIPTIONS = "subscriptions";
// public static final String VAR_O = "o";
// }
// Path: compiler/src/main/java/pocketbus/internal/codegen/SubscriptionGenerator.java
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import com.squareup.javapoet.WildcardTypeName;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.lang.model.element.Modifier;
import javax.lang.model.type.TypeMirror;
import pocketbus.SubscriptionRegistration;
import pocketbus.Subscription;
import pocketbus.ThreadMode;
import pocketbus.internal.PocketBusConst;
package pocketbus.internal.codegen;
public class SubscriptionGenerator {
private static final ParameterizedTypeName SUBSCRIPTION_TYPE = ParameterizedTypeName.get(ClassName.get(Subscription.class),
WildcardTypeName.subtypeOf(TypeName.OBJECT));
private static final ParameterizedTypeName LIST_TYPE = ParameterizedTypeName.get(ClassName.get(List.class), SUBSCRIPTION_TYPE);
Set<SubscriptionMethod> methods = new LinkedHashSet<>();
private final String classPackage;
private final String className;
private final TypeMirror targetType;
private ClassName parentAdapter;
private int idx = 1;
public SubscriptionGenerator(String classPackage, String className, TypeMirror targetType) {
this.classPackage = classPackage;
this.className = className;
this.targetType = targetType;
}
public boolean addMethod(SubscriptionMethod method) {
method.setIndex(idx++);
return this.methods.add(method);
}
public JavaFile generate() {
TypeSpec.Builder classBuilder = TypeSpec.classBuilder(className)
.addModifiers(Modifier.PUBLIC)
.addField(getWeakReferenceType(), PocketBusConst.VAR_TARGET_REF, Modifier.PRIVATE, Modifier.FINAL)
.addField(LIST_TYPE, PocketBusConst.VAR_SUBSCRIPTIONS, Modifier.PRIVATE, Modifier.FINAL);
if (parentAdapter != null) {
classBuilder.superclass(parentAdapter);
} else { | classBuilder.addSuperinterface(ClassName.get(SubscriptionRegistration.class)); |
hansenji/PocketBus | compiler/src/main/java/pocketbus/internal/codegen/SubscriptionGenerator.java | // Path: core/src/main/java/pocketbus/SubscriptionRegistration.java
// public interface SubscriptionRegistration {
// /**
// * @return a list of subscriptions
// */
// List<Subscription<?>> getSubscriptions();
// }
//
// Path: core/src/main/java/pocketbus/Subscription.java
// public interface Subscription<T> {
// /**
// * Handle an event posted to the bus
// *
// * @param t event posted to the bus
// * @return false if subscription should be unregistered
// */
// boolean handle(T t);
//
// /**
// * @return Class of event this subscription handles
// */
// Class<T> getEventClass();
//
// /**
// * @return ThreadMode for this subscription
// */
// ThreadMode getThreadMode();
//
// /**
// * @return the target with which this subscription interacts
// */
// <E> E getTarget();
// }
//
// Path: core/src/main/java/pocketbus/ThreadMode.java
// public enum ThreadMode {
// /**
// * Subscription run on same thread as caller
// */
// CURRENT, // Schedulers.trampoline()
// /**
// * Subscription run on the main thread
// */
// MAIN, // AndroidSchedulers.mainThread()
// /**
// * Subscription run on a background thread
// */
// BACKGROUND // Schedulers.newThread()
// }
//
// Path: core/src/main/java/pocketbus/internal/PocketBusConst.java
// public class PocketBusConst {
// public static final String ANDROID_PREFIX = "android.";
// public static final String JAVA_PREFIX = "java.";
//
// public static final String REGISTRATION_SUFFIX = "SubscriptionRegistration";
// public static final String REGISTRY_NAME = "BusRegistry";
//
// public static final String METHOD_HANDLE = "handle";
// public static final String METHOD_GET_SUBSCRIPTIONS = "getSubscriptions";
// public static final String METHOD_GET_EVENT_CLASS = "getEventClass";
// public static final String METHOD_GET_THREAD_MODE = "getThreadMode";
// public static final String METHOD_GET_TARGET = "getTarget";
// public static final String METHOD_EQUALS = "equals";
// public static final String METHOD_GET_REGISTRAR = "getRegistration";
//
// public static final String VAR_TARGET_REF = "targetRef";
// public static final String VAR_TARGET = "target";
// public static final String VAR_EVENT = "event";
// public static final String VAR_SUBSCRIPTION = "subscription";
// public static final String VAR_SUBSCRIPTIONS = "subscriptions";
// public static final String VAR_O = "o";
// }
| import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import com.squareup.javapoet.WildcardTypeName;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.lang.model.element.Modifier;
import javax.lang.model.type.TypeMirror;
import pocketbus.SubscriptionRegistration;
import pocketbus.Subscription;
import pocketbus.ThreadMode;
import pocketbus.internal.PocketBusConst; | private void generateHandleMethod(TypeSpec.Builder classBuilder, SubscriptionMethod subscriptionMethod) {
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(PocketBusConst.METHOD_HANDLE)
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override.class)
.addParameter(TypeName.get(subscriptionMethod.getEventType()), PocketBusConst.VAR_EVENT)
.returns(TypeName.BOOLEAN)
.addStatement("$T $N = $N.get()", TypeName.get(targetType), PocketBusConst.VAR_TARGET, PocketBusConst.VAR_TARGET_REF)
.beginControlFlow("if ($N != null)", PocketBusConst.VAR_TARGET)
.addStatement("$N.$L($N)", PocketBusConst.VAR_TARGET, subscriptionMethod.getName(), PocketBusConst.VAR_EVENT)
.endControlFlow()
.addStatement("return $N != null", PocketBusConst.VAR_TARGET)
;
classBuilder.addMethod(methodBuilder.build());
}
private void generateClassMethod(TypeSpec.Builder classBuilder, SubscriptionMethod subscription) {
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(PocketBusConst.METHOD_GET_EVENT_CLASS)
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override.class)
.returns(ParameterizedTypeName.get(ClassName.get(Class.class), TypeName.get(subscription.getEventType())))
.addStatement("return $T.class", TypeName.get(subscription.getEventType()));
classBuilder.addMethod(methodBuilder.build());
}
private void generateThreadMethod(TypeSpec.Builder classBuilder, SubscriptionMethod subscription) {
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(PocketBusConst.METHOD_GET_THREAD_MODE)
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override.class) | // Path: core/src/main/java/pocketbus/SubscriptionRegistration.java
// public interface SubscriptionRegistration {
// /**
// * @return a list of subscriptions
// */
// List<Subscription<?>> getSubscriptions();
// }
//
// Path: core/src/main/java/pocketbus/Subscription.java
// public interface Subscription<T> {
// /**
// * Handle an event posted to the bus
// *
// * @param t event posted to the bus
// * @return false if subscription should be unregistered
// */
// boolean handle(T t);
//
// /**
// * @return Class of event this subscription handles
// */
// Class<T> getEventClass();
//
// /**
// * @return ThreadMode for this subscription
// */
// ThreadMode getThreadMode();
//
// /**
// * @return the target with which this subscription interacts
// */
// <E> E getTarget();
// }
//
// Path: core/src/main/java/pocketbus/ThreadMode.java
// public enum ThreadMode {
// /**
// * Subscription run on same thread as caller
// */
// CURRENT, // Schedulers.trampoline()
// /**
// * Subscription run on the main thread
// */
// MAIN, // AndroidSchedulers.mainThread()
// /**
// * Subscription run on a background thread
// */
// BACKGROUND // Schedulers.newThread()
// }
//
// Path: core/src/main/java/pocketbus/internal/PocketBusConst.java
// public class PocketBusConst {
// public static final String ANDROID_PREFIX = "android.";
// public static final String JAVA_PREFIX = "java.";
//
// public static final String REGISTRATION_SUFFIX = "SubscriptionRegistration";
// public static final String REGISTRY_NAME = "BusRegistry";
//
// public static final String METHOD_HANDLE = "handle";
// public static final String METHOD_GET_SUBSCRIPTIONS = "getSubscriptions";
// public static final String METHOD_GET_EVENT_CLASS = "getEventClass";
// public static final String METHOD_GET_THREAD_MODE = "getThreadMode";
// public static final String METHOD_GET_TARGET = "getTarget";
// public static final String METHOD_EQUALS = "equals";
// public static final String METHOD_GET_REGISTRAR = "getRegistration";
//
// public static final String VAR_TARGET_REF = "targetRef";
// public static final String VAR_TARGET = "target";
// public static final String VAR_EVENT = "event";
// public static final String VAR_SUBSCRIPTION = "subscription";
// public static final String VAR_SUBSCRIPTIONS = "subscriptions";
// public static final String VAR_O = "o";
// }
// Path: compiler/src/main/java/pocketbus/internal/codegen/SubscriptionGenerator.java
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import com.squareup.javapoet.WildcardTypeName;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.lang.model.element.Modifier;
import javax.lang.model.type.TypeMirror;
import pocketbus.SubscriptionRegistration;
import pocketbus.Subscription;
import pocketbus.ThreadMode;
import pocketbus.internal.PocketBusConst;
private void generateHandleMethod(TypeSpec.Builder classBuilder, SubscriptionMethod subscriptionMethod) {
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(PocketBusConst.METHOD_HANDLE)
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override.class)
.addParameter(TypeName.get(subscriptionMethod.getEventType()), PocketBusConst.VAR_EVENT)
.returns(TypeName.BOOLEAN)
.addStatement("$T $N = $N.get()", TypeName.get(targetType), PocketBusConst.VAR_TARGET, PocketBusConst.VAR_TARGET_REF)
.beginControlFlow("if ($N != null)", PocketBusConst.VAR_TARGET)
.addStatement("$N.$L($N)", PocketBusConst.VAR_TARGET, subscriptionMethod.getName(), PocketBusConst.VAR_EVENT)
.endControlFlow()
.addStatement("return $N != null", PocketBusConst.VAR_TARGET)
;
classBuilder.addMethod(methodBuilder.build());
}
private void generateClassMethod(TypeSpec.Builder classBuilder, SubscriptionMethod subscription) {
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(PocketBusConst.METHOD_GET_EVENT_CLASS)
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override.class)
.returns(ParameterizedTypeName.get(ClassName.get(Class.class), TypeName.get(subscription.getEventType())))
.addStatement("return $T.class", TypeName.get(subscription.getEventType()));
classBuilder.addMethod(methodBuilder.build());
}
private void generateThreadMethod(TypeSpec.Builder classBuilder, SubscriptionMethod subscription) {
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(PocketBusConst.METHOD_GET_THREAD_MODE)
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override.class) | .returns(TypeName.get(ThreadMode.class)) |
hansenji/PocketBus | compiler/src/main/java/pocketbus/internal/codegen/SubscriptionMethod.java | // Path: core/src/main/java/pocketbus/ThreadMode.java
// public enum ThreadMode {
// /**
// * Subscription run on same thread as caller
// */
// CURRENT, // Schedulers.trampoline()
// /**
// * Subscription run on the main thread
// */
// MAIN, // AndroidSchedulers.mainThread()
// /**
// * Subscription run on a background thread
// */
// BACKGROUND // Schedulers.newThread()
// }
| import javax.lang.model.element.ExecutableElement;
import javax.lang.model.type.TypeMirror;
import pocketbus.ThreadMode; | package pocketbus.internal.codegen;
public class SubscriptionMethod {
private final TypeMirror eventType;
private final String name; | // Path: core/src/main/java/pocketbus/ThreadMode.java
// public enum ThreadMode {
// /**
// * Subscription run on same thread as caller
// */
// CURRENT, // Schedulers.trampoline()
// /**
// * Subscription run on the main thread
// */
// MAIN, // AndroidSchedulers.mainThread()
// /**
// * Subscription run on a background thread
// */
// BACKGROUND // Schedulers.newThread()
// }
// Path: compiler/src/main/java/pocketbus/internal/codegen/SubscriptionMethod.java
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.type.TypeMirror;
import pocketbus.ThreadMode;
package pocketbus.internal.codegen;
public class SubscriptionMethod {
private final TypeMirror eventType;
private final String name; | private final ThreadMode threadMode; |
CreateChance/DoorGod | app/src/main/java/com/createchance/doorgod/fingerprint/MyAuthCallback.java | // Path: app/src/main/java/com/createchance/doorgod/util/FingerprintAuthResponse.java
// public class FingerprintAuthResponse {
// public static final int MSG_AUTH_SUCCESS = 100;
// public static final int MSG_AUTH_FAILED = 101;
// public static final int MSG_AUTH_ERROR = 102;
// public static final int MSG_AUTH_HELP = 103;
//
// private final int result;
//
// public FingerprintAuthResponse(int result) {
// this.result = result;
// }
//
// public int getResult() {
// return result;
// }
// }
| import android.support.v4.hardware.fingerprint.FingerprintManagerCompat;
import com.createchance.doorgod.util.FingerprintAuthResponse;
import org.greenrobot.eventbus.EventBus; | package com.createchance.doorgod.fingerprint;
/**
* Fingerprint auth result callback.
*/
public class MyAuthCallback extends FingerprintManagerCompat.AuthenticationCallback {
public MyAuthCallback() {
super();
}
@Override
public void onAuthenticationError(int errMsgId, CharSequence errString) {
super.onAuthenticationError(errMsgId, errString);
EventBus.getDefault(). | // Path: app/src/main/java/com/createchance/doorgod/util/FingerprintAuthResponse.java
// public class FingerprintAuthResponse {
// public static final int MSG_AUTH_SUCCESS = 100;
// public static final int MSG_AUTH_FAILED = 101;
// public static final int MSG_AUTH_ERROR = 102;
// public static final int MSG_AUTH_HELP = 103;
//
// private final int result;
//
// public FingerprintAuthResponse(int result) {
// this.result = result;
// }
//
// public int getResult() {
// return result;
// }
// }
// Path: app/src/main/java/com/createchance/doorgod/fingerprint/MyAuthCallback.java
import android.support.v4.hardware.fingerprint.FingerprintManagerCompat;
import com.createchance.doorgod.util.FingerprintAuthResponse;
import org.greenrobot.eventbus.EventBus;
package com.createchance.doorgod.fingerprint;
/**
* Fingerprint auth result callback.
*/
public class MyAuthCallback extends FingerprintManagerCompat.AuthenticationCallback {
public MyAuthCallback() {
super();
}
@Override
public void onAuthenticationError(int errMsgId, CharSequence errString) {
super.onAuthenticationError(errMsgId, errString);
EventBus.getDefault(). | post(new FingerprintAuthResponse(FingerprintAuthResponse.MSG_AUTH_ERROR)); |
CreateChance/DoorGod | app/src/main/java/com/createchance/doorgod/ui/IntrusionRecordDetailsActivity.java | // Path: app/src/main/java/com/createchance/doorgod/adapter/IntrusionRecordDetailsAdapter.java
// public class IntrusionRecordDetailsAdapter extends RecyclerView.Adapter<IntrusionRecordDetailsAdapter.ViewHolder> {
//
// private static final String TAG = "IntrusionRecordAdapter";
//
// private List<File> mPictureList;
//
// private Context mContext;
//
// static class ViewHolder extends RecyclerView.ViewHolder {
// TextView title;
// ImageView content;
//
// public ViewHolder(View view) {
// super(view);
//
// title = (TextView) view.findViewById(R.id.intru_details_title);
// content = (ImageView) view.findViewById(R.id.intru_details_content);
// }
// }
//
// public IntrusionRecordDetailsAdapter(File folder) {
// mPictureList = new ArrayList<>(Arrays.asList(folder.listFiles()));
// }
//
// @Override
// public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// if (mContext == null) {
// mContext = parent.getContext();
// }
//
// View view = LayoutInflater.from(mContext).inflate(R.layout.intru_details_item, parent, false);
// final IntrusionRecordDetailsAdapter.ViewHolder holder = new IntrusionRecordDetailsAdapter.ViewHolder(view);
//
// return holder;
// }
//
// @Override
// public void onBindViewHolder(IntrusionRecordDetailsAdapter.ViewHolder holder, final int position) {
// LogUtil.d(TAG, mPictureList.get(position).getAbsolutePath());
// String time = getDateFromMills(mPictureList.get(position).getName().split("_")[0]);
// String appName = mPictureList.get(position).getName().split("_")[1].substring(0, mPictureList.get(position).getName().split("_")[1].lastIndexOf("."));
// holder.title.setText(mContext.getString(R.string.settings_intru_rec_detail_item_title, time, appName));
// Glide.with(mContext).load(mPictureList.get(position).getAbsoluteFile()).into(holder.content);
// holder.content.setOnLongClickListener(new View.OnLongClickListener() {
// @Override
// public boolean onLongClick(View view) {
// showConfigChangedDialog(mPictureList.get(position));
// return true;
// }
// });
// }
//
// @Override
// public int getItemCount() {
// return mPictureList.size();
// }
//
// private void showConfigChangedDialog(final File picture) {
// AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
// builder.setIcon(R.drawable.ic_warning_white_48dp)
// .setTitle(R.string.settings_intru_rec_detail_dialog_title)
// .setPositiveButton(R.string.dialog_action_yes, new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// // User choose to delete this picture.
// picture.delete();
// mPictureList.remove(picture);
// dialog.dismiss();
// IntrusionRecordDetailsAdapter.this.notifyDataSetChanged();
// }
// })
// .setNegativeButton(R.string.dialog_action_no, new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// dialog.dismiss();
// }
// });
// builder.create().show();
// }
//
// private String getDateFromMills(String mills) {
// Date date = new Date(Long.valueOf(mills));
// SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// return formatter.format(date);
// }
// }
| import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import com.createchance.doorgod.R;
import com.createchance.doorgod.adapter.IntrusionRecordDetailsAdapter; | package com.createchance.doorgod.ui;
public class IntrusionRecordDetailsActivity extends AppCompatActivity {
private static final String TAG = "IntrusionRecordDetailsA";
private RecyclerView mDetailList; | // Path: app/src/main/java/com/createchance/doorgod/adapter/IntrusionRecordDetailsAdapter.java
// public class IntrusionRecordDetailsAdapter extends RecyclerView.Adapter<IntrusionRecordDetailsAdapter.ViewHolder> {
//
// private static final String TAG = "IntrusionRecordAdapter";
//
// private List<File> mPictureList;
//
// private Context mContext;
//
// static class ViewHolder extends RecyclerView.ViewHolder {
// TextView title;
// ImageView content;
//
// public ViewHolder(View view) {
// super(view);
//
// title = (TextView) view.findViewById(R.id.intru_details_title);
// content = (ImageView) view.findViewById(R.id.intru_details_content);
// }
// }
//
// public IntrusionRecordDetailsAdapter(File folder) {
// mPictureList = new ArrayList<>(Arrays.asList(folder.listFiles()));
// }
//
// @Override
// public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// if (mContext == null) {
// mContext = parent.getContext();
// }
//
// View view = LayoutInflater.from(mContext).inflate(R.layout.intru_details_item, parent, false);
// final IntrusionRecordDetailsAdapter.ViewHolder holder = new IntrusionRecordDetailsAdapter.ViewHolder(view);
//
// return holder;
// }
//
// @Override
// public void onBindViewHolder(IntrusionRecordDetailsAdapter.ViewHolder holder, final int position) {
// LogUtil.d(TAG, mPictureList.get(position).getAbsolutePath());
// String time = getDateFromMills(mPictureList.get(position).getName().split("_")[0]);
// String appName = mPictureList.get(position).getName().split("_")[1].substring(0, mPictureList.get(position).getName().split("_")[1].lastIndexOf("."));
// holder.title.setText(mContext.getString(R.string.settings_intru_rec_detail_item_title, time, appName));
// Glide.with(mContext).load(mPictureList.get(position).getAbsoluteFile()).into(holder.content);
// holder.content.setOnLongClickListener(new View.OnLongClickListener() {
// @Override
// public boolean onLongClick(View view) {
// showConfigChangedDialog(mPictureList.get(position));
// return true;
// }
// });
// }
//
// @Override
// public int getItemCount() {
// return mPictureList.size();
// }
//
// private void showConfigChangedDialog(final File picture) {
// AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
// builder.setIcon(R.drawable.ic_warning_white_48dp)
// .setTitle(R.string.settings_intru_rec_detail_dialog_title)
// .setPositiveButton(R.string.dialog_action_yes, new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// // User choose to delete this picture.
// picture.delete();
// mPictureList.remove(picture);
// dialog.dismiss();
// IntrusionRecordDetailsAdapter.this.notifyDataSetChanged();
// }
// })
// .setNegativeButton(R.string.dialog_action_no, new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// dialog.dismiss();
// }
// });
// builder.create().show();
// }
//
// private String getDateFromMills(String mills) {
// Date date = new Date(Long.valueOf(mills));
// SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// return formatter.format(date);
// }
// }
// Path: app/src/main/java/com/createchance/doorgod/ui/IntrusionRecordDetailsActivity.java
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import com.createchance.doorgod.R;
import com.createchance.doorgod.adapter.IntrusionRecordDetailsAdapter;
package com.createchance.doorgod.ui;
public class IntrusionRecordDetailsActivity extends AppCompatActivity {
private static final String TAG = "IntrusionRecordDetailsA";
private RecyclerView mDetailList; | private IntrusionRecordDetailsAdapter mAdapter; |
CreateChance/DoorGod | app/src/main/java/com/createchance/doorgod/service/BootUpReceiver.java | // Path: app/src/main/java/com/createchance/doorgod/util/LogUtil.java
// public class LogUtil {
// public static final int VERBOSE = 1;
//
// public static final int DEBUG = 2;
//
// public static final int INFO = 3;
//
// public static final int WARN = 4;
//
// public static final int ERROR = 5;
//
// public static final int NOTHING = 6;
//
// public static int level = VERBOSE;
//
// public static void v(String tag, String msg) {
// if (level <= VERBOSE) {
// Log.v(tag, msg);
// }
// }
//
// public static void d(String tag, String msg) {
// if (level <= DEBUG) {
// Log.d(tag, msg);
// }
// }
//
// public static void i(String tag, String msg) {
// if (level <= INFO) {
// Log.i(tag, msg);
// }
// }
//
// public static void w(String tag, String msg) {
// if (level <= WARN) {
// Log.w(tag, msg);
// }
// }
//
// public static void e(String tag, String msg) {
// if (level <= ERROR) {
// Log.e(tag, msg);
// }
// }
// }
| import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.createchance.doorgod.util.LogUtil; | package com.createchance.doorgod.service;
/**
*
*/
public class BootUpReceiver extends BroadcastReceiver {
private static final String TAG = "BootUpReceiver";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
| // Path: app/src/main/java/com/createchance/doorgod/util/LogUtil.java
// public class LogUtil {
// public static final int VERBOSE = 1;
//
// public static final int DEBUG = 2;
//
// public static final int INFO = 3;
//
// public static final int WARN = 4;
//
// public static final int ERROR = 5;
//
// public static final int NOTHING = 6;
//
// public static int level = VERBOSE;
//
// public static void v(String tag, String msg) {
// if (level <= VERBOSE) {
// Log.v(tag, msg);
// }
// }
//
// public static void d(String tag, String msg) {
// if (level <= DEBUG) {
// Log.d(tag, msg);
// }
// }
//
// public static void i(String tag, String msg) {
// if (level <= INFO) {
// Log.i(tag, msg);
// }
// }
//
// public static void w(String tag, String msg) {
// if (level <= WARN) {
// Log.w(tag, msg);
// }
// }
//
// public static void e(String tag, String msg) {
// if (level <= ERROR) {
// Log.e(tag, msg);
// }
// }
// }
// Path: app/src/main/java/com/createchance/doorgod/service/BootUpReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.createchance.doorgod.util.LogUtil;
package com.createchance.doorgod.service;
/**
*
*/
public class BootUpReceiver extends BroadcastReceiver {
private static final String TAG = "BootUpReceiver";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
| LogUtil.d(TAG, "action: " + action); |
CreateChance/DoorGod | app/src/main/java/com/createchance/doorgod/adapter/IntrusionRecordDetailsAdapter.java | // Path: app/src/main/java/com/createchance/doorgod/util/LogUtil.java
// public class LogUtil {
// public static final int VERBOSE = 1;
//
// public static final int DEBUG = 2;
//
// public static final int INFO = 3;
//
// public static final int WARN = 4;
//
// public static final int ERROR = 5;
//
// public static final int NOTHING = 6;
//
// public static int level = VERBOSE;
//
// public static void v(String tag, String msg) {
// if (level <= VERBOSE) {
// Log.v(tag, msg);
// }
// }
//
// public static void d(String tag, String msg) {
// if (level <= DEBUG) {
// Log.d(tag, msg);
// }
// }
//
// public static void i(String tag, String msg) {
// if (level <= INFO) {
// Log.i(tag, msg);
// }
// }
//
// public static void w(String tag, String msg) {
// if (level <= WARN) {
// Log.w(tag, msg);
// }
// }
//
// public static void e(String tag, String msg) {
// if (level <= ERROR) {
// Log.e(tag, msg);
// }
// }
// }
| import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.createchance.doorgod.R;
import com.createchance.doorgod.util.LogUtil;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List; | package com.createchance.doorgod.adapter;
/**
* Created by gaochao on 26/07/2017.
*/
public class IntrusionRecordDetailsAdapter extends RecyclerView.Adapter<IntrusionRecordDetailsAdapter.ViewHolder> {
private static final String TAG = "IntrusionRecordAdapter";
private List<File> mPictureList;
private Context mContext;
static class ViewHolder extends RecyclerView.ViewHolder {
TextView title;
ImageView content;
public ViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.intru_details_title);
content = (ImageView) view.findViewById(R.id.intru_details_content);
}
}
public IntrusionRecordDetailsAdapter(File folder) {
mPictureList = new ArrayList<>(Arrays.asList(folder.listFiles()));
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (mContext == null) {
mContext = parent.getContext();
}
View view = LayoutInflater.from(mContext).inflate(R.layout.intru_details_item, parent, false);
final IntrusionRecordDetailsAdapter.ViewHolder holder = new IntrusionRecordDetailsAdapter.ViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(IntrusionRecordDetailsAdapter.ViewHolder holder, final int position) { | // Path: app/src/main/java/com/createchance/doorgod/util/LogUtil.java
// public class LogUtil {
// public static final int VERBOSE = 1;
//
// public static final int DEBUG = 2;
//
// public static final int INFO = 3;
//
// public static final int WARN = 4;
//
// public static final int ERROR = 5;
//
// public static final int NOTHING = 6;
//
// public static int level = VERBOSE;
//
// public static void v(String tag, String msg) {
// if (level <= VERBOSE) {
// Log.v(tag, msg);
// }
// }
//
// public static void d(String tag, String msg) {
// if (level <= DEBUG) {
// Log.d(tag, msg);
// }
// }
//
// public static void i(String tag, String msg) {
// if (level <= INFO) {
// Log.i(tag, msg);
// }
// }
//
// public static void w(String tag, String msg) {
// if (level <= WARN) {
// Log.w(tag, msg);
// }
// }
//
// public static void e(String tag, String msg) {
// if (level <= ERROR) {
// Log.e(tag, msg);
// }
// }
// }
// Path: app/src/main/java/com/createchance/doorgod/adapter/IntrusionRecordDetailsAdapter.java
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.createchance.doorgod.R;
import com.createchance.doorgod.util.LogUtil;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
package com.createchance.doorgod.adapter;
/**
* Created by gaochao on 26/07/2017.
*/
public class IntrusionRecordDetailsAdapter extends RecyclerView.Adapter<IntrusionRecordDetailsAdapter.ViewHolder> {
private static final String TAG = "IntrusionRecordAdapter";
private List<File> mPictureList;
private Context mContext;
static class ViewHolder extends RecyclerView.ViewHolder {
TextView title;
ImageView content;
public ViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.intru_details_title);
content = (ImageView) view.findViewById(R.id.intru_details_content);
}
}
public IntrusionRecordDetailsAdapter(File folder) {
mPictureList = new ArrayList<>(Arrays.asList(folder.listFiles()));
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (mContext == null) {
mContext = parent.getContext();
}
View view = LayoutInflater.from(mContext).inflate(R.layout.intru_details_item, parent, false);
final IntrusionRecordDetailsAdapter.ViewHolder holder = new IntrusionRecordDetailsAdapter.ViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(IntrusionRecordDetailsAdapter.ViewHolder holder, final int position) { | LogUtil.d(TAG, mPictureList.get(position).getAbsolutePath()); |
antag99/aquarria | aquarria/tests/com/github/antag99/aquarria/tests/DirectionTests.java | // Path: aquarria/src/com/github/antag99/aquarria/Direction.java
// public enum Direction {
// // Note that the order is important
// NORTH(0, 1),
// NORTHEAST(1, 1),
// EAST(1, 0),
// SOUTHEAST(1, -1),
// SOUTH(0, -1),
// SOUTHWEST(-1, -1),
// WEST(-1, 0),
// NORTHWEST(-1, 1);
//
// private static Direction[] values = values();
//
// private final int horizontal;
// private final int vertical;
//
// private Direction(int horizontal, int vertical) {
// this.horizontal = horizontal;
// this.vertical = vertical;
// }
//
// public int getHorizontal() {
// return horizontal;
// }
//
// public int getVertical() {
// return vertical;
// }
//
// public int mask() {
// return 1 << ordinal();
// }
//
// public Direction opposite() {
// return values[(ordinal() + 4) % values.length];
// }
//
// public static Direction get(int x, int y) {
// x = x < 0 ? -1 : x > 0 ? 1 : 0;
// y = y < 0 ? -1 : y > 0 ? 1 : 0;
//
// for (Direction direction : values) {
// if (direction.getHorizontal() == x && direction.getVertical() == y) {
// return direction;
// }
// }
//
// // (0, 0)
// return null;
// }
//
// public static int maskOf(Direction... directions) {
// int mask = 0;
// for (Direction dir : directions)
// mask |= dir.mask();
// return mask;
// }
// }
| import org.junit.Test;
import com.github.antag99.aquarria.Direction;
import org.junit.Assert; | /*******************************************************************************
* Copyright (c) 2014-2015, Anton Gustafsson
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of Aquarria nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package com.github.antag99.aquarria.tests;
public class DirectionTests {
@Test
public void testOppositeDirections() { | // Path: aquarria/src/com/github/antag99/aquarria/Direction.java
// public enum Direction {
// // Note that the order is important
// NORTH(0, 1),
// NORTHEAST(1, 1),
// EAST(1, 0),
// SOUTHEAST(1, -1),
// SOUTH(0, -1),
// SOUTHWEST(-1, -1),
// WEST(-1, 0),
// NORTHWEST(-1, 1);
//
// private static Direction[] values = values();
//
// private final int horizontal;
// private final int vertical;
//
// private Direction(int horizontal, int vertical) {
// this.horizontal = horizontal;
// this.vertical = vertical;
// }
//
// public int getHorizontal() {
// return horizontal;
// }
//
// public int getVertical() {
// return vertical;
// }
//
// public int mask() {
// return 1 << ordinal();
// }
//
// public Direction opposite() {
// return values[(ordinal() + 4) % values.length];
// }
//
// public static Direction get(int x, int y) {
// x = x < 0 ? -1 : x > 0 ? 1 : 0;
// y = y < 0 ? -1 : y > 0 ? 1 : 0;
//
// for (Direction direction : values) {
// if (direction.getHorizontal() == x && direction.getVertical() == y) {
// return direction;
// }
// }
//
// // (0, 0)
// return null;
// }
//
// public static int maskOf(Direction... directions) {
// int mask = 0;
// for (Direction dir : directions)
// mask |= dir.mask();
// return mask;
// }
// }
// Path: aquarria/tests/com/github/antag99/aquarria/tests/DirectionTests.java
import org.junit.Test;
import com.github.antag99.aquarria.Direction;
import org.junit.Assert;
/*******************************************************************************
* Copyright (c) 2014-2015, Anton Gustafsson
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of Aquarria nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package com.github.antag99.aquarria.tests;
public class DirectionTests {
@Test
public void testOppositeDirections() { | Assert.assertEquals(Direction.SOUTH, Direction.NORTH.opposite()); |
wxiaoqi/ace-cache | src/main/java/com/ace/cache/annotation/CacheClear.java | // Path: src/main/java/com/ace/cache/parser/IKeyGenerator.java
// public abstract class IKeyGenerator {
// public static final String LINK = "_";
//
// /**
// * 获取动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public String getKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments) {
// StringBuffer sb = new StringBuffer("");
// key = buildKey(key, scope, parameterTypes, arguments);
// sb.append(key);
// if (CacheScope.user.equals(scope)) {
// if (getUserKeyGenerator() != null)
// sb.append(LINK)
// .append(getUserKeyGenerator().getCurrentUserAccount());
// }
// return sb.toString();
// }
//
// /**
// * 当前登陆人key
// *
// * @param userKeyGenerator
// */
// public abstract IUserKeyGenerator getUserKeyGenerator();
//
// /**
// * 生成动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public abstract String buildKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments);
// }
//
// Path: src/main/java/com/ace/cache/parser/impl/DefaultKeyGenerator.java
// @Service
// public class DefaultKeyGenerator extends IKeyGenerator {
// @Autowired
// RedisConfig redisConfig;
//
// @Autowired(required = false)
// private IUserKeyGenerator userKeyGenerator;
//
// @Override
// public String buildKey(String key, CacheScope scope, Class<?>[] parameterTypes, Object[] arguments) {
// boolean isFirst = true;
// if (key.indexOf("{") > 0) {
// key = key.replace("{", ":{");
// Pattern pattern = Pattern.compile("\\d+(\\.?[\\w]+)*");
// Matcher matcher = pattern.matcher(key);
// while (matcher.find()) {
// String tmp = matcher.group();
// String express[] = matcher.group().split("\\.");
// String i = express[0];
// int index = Integer.parseInt(i) - 1;
// Object value = arguments[index];
// if (parameterTypes[index].isAssignableFrom(List.class)) {
// List result = (List) arguments[index];
// value = result.get(0);
// }
// if (value == null || value.equals("null"))
// value = "";
// if (express.length > 1) {
// for (int idx = 1; idx < express.length; idx ++) {
// String field = express[idx];
// value = ReflectionUtils.getFieldValue(value, field);
// }
// }
// if (isFirst) {
// key = key.replace("{" + tmp + "}", value.toString());
// } else {
// key = key.replace("{" + tmp + "}", LINK + value.toString());
// }
// }
// }
// if (CacheScope.user.equals(scope) && StringUtils.isNotBlank(redisConfig.getUserKey())){
// ServletRequestAttributes servletContainer = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
// HttpServletRequest request = servletContainer.getRequest();
// String accessToken = request.getHeader(redisConfig.getUserKey());
// if(StringUtils.isBlank(accessToken)){
// accessToken = WebUtil.getCookieValue(request,redisConfig.getUserKey());
// }
// if (StringUtils.isNotBlank(accessToken)){
// key = key + accessToken;
// }
// }
// return key;
// }
//
// @Override
// public IUserKeyGenerator getUserKeyGenerator() {
// return userKeyGenerator;
// }
//
// }
| import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.ace.cache.parser.IKeyGenerator;
import com.ace.cache.parser.impl.DefaultKeyGenerator; | package com.ace.cache.annotation;
/**
* 解决问题:
*
* @author Ace
* @version 1.0
* @date 2017年5月4日
* @since 1.7
*/
@Retention(RetentionPolicy.RUNTIME)//在运行时可以获取
@Target(value = {ElementType.METHOD, ElementType.TYPE})//作用到类,方法,接口上等
public @interface CacheClear {
/**
* 缓存key的前缀
*
* @return
* @author Ace
* @date 2017年5月3日
*/
public String pre() default "";
/**
* 缓存key
*
* @return
* @author Ace
* @date 2017年5月3日
*/
public String key() default "";
/**
* 缓存keys
*
* @return
* @author Ace
* @date 2017年5月3日
*/
public String[] keys() default "";
/**
* 键值解析类
*
* @return
*/ | // Path: src/main/java/com/ace/cache/parser/IKeyGenerator.java
// public abstract class IKeyGenerator {
// public static final String LINK = "_";
//
// /**
// * 获取动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public String getKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments) {
// StringBuffer sb = new StringBuffer("");
// key = buildKey(key, scope, parameterTypes, arguments);
// sb.append(key);
// if (CacheScope.user.equals(scope)) {
// if (getUserKeyGenerator() != null)
// sb.append(LINK)
// .append(getUserKeyGenerator().getCurrentUserAccount());
// }
// return sb.toString();
// }
//
// /**
// * 当前登陆人key
// *
// * @param userKeyGenerator
// */
// public abstract IUserKeyGenerator getUserKeyGenerator();
//
// /**
// * 生成动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public abstract String buildKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments);
// }
//
// Path: src/main/java/com/ace/cache/parser/impl/DefaultKeyGenerator.java
// @Service
// public class DefaultKeyGenerator extends IKeyGenerator {
// @Autowired
// RedisConfig redisConfig;
//
// @Autowired(required = false)
// private IUserKeyGenerator userKeyGenerator;
//
// @Override
// public String buildKey(String key, CacheScope scope, Class<?>[] parameterTypes, Object[] arguments) {
// boolean isFirst = true;
// if (key.indexOf("{") > 0) {
// key = key.replace("{", ":{");
// Pattern pattern = Pattern.compile("\\d+(\\.?[\\w]+)*");
// Matcher matcher = pattern.matcher(key);
// while (matcher.find()) {
// String tmp = matcher.group();
// String express[] = matcher.group().split("\\.");
// String i = express[0];
// int index = Integer.parseInt(i) - 1;
// Object value = arguments[index];
// if (parameterTypes[index].isAssignableFrom(List.class)) {
// List result = (List) arguments[index];
// value = result.get(0);
// }
// if (value == null || value.equals("null"))
// value = "";
// if (express.length > 1) {
// for (int idx = 1; idx < express.length; idx ++) {
// String field = express[idx];
// value = ReflectionUtils.getFieldValue(value, field);
// }
// }
// if (isFirst) {
// key = key.replace("{" + tmp + "}", value.toString());
// } else {
// key = key.replace("{" + tmp + "}", LINK + value.toString());
// }
// }
// }
// if (CacheScope.user.equals(scope) && StringUtils.isNotBlank(redisConfig.getUserKey())){
// ServletRequestAttributes servletContainer = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
// HttpServletRequest request = servletContainer.getRequest();
// String accessToken = request.getHeader(redisConfig.getUserKey());
// if(StringUtils.isBlank(accessToken)){
// accessToken = WebUtil.getCookieValue(request,redisConfig.getUserKey());
// }
// if (StringUtils.isNotBlank(accessToken)){
// key = key + accessToken;
// }
// }
// return key;
// }
//
// @Override
// public IUserKeyGenerator getUserKeyGenerator() {
// return userKeyGenerator;
// }
//
// }
// Path: src/main/java/com/ace/cache/annotation/CacheClear.java
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.ace.cache.parser.IKeyGenerator;
import com.ace.cache.parser.impl.DefaultKeyGenerator;
package com.ace.cache.annotation;
/**
* 解决问题:
*
* @author Ace
* @version 1.0
* @date 2017年5月4日
* @since 1.7
*/
@Retention(RetentionPolicy.RUNTIME)//在运行时可以获取
@Target(value = {ElementType.METHOD, ElementType.TYPE})//作用到类,方法,接口上等
public @interface CacheClear {
/**
* 缓存key的前缀
*
* @return
* @author Ace
* @date 2017年5月3日
*/
public String pre() default "";
/**
* 缓存key
*
* @return
* @author Ace
* @date 2017年5月3日
*/
public String key() default "";
/**
* 缓存keys
*
* @return
* @author Ace
* @date 2017年5月3日
*/
public String[] keys() default "";
/**
* 键值解析类
*
* @return
*/ | public Class<? extends IKeyGenerator> generator() default DefaultKeyGenerator.class; |
wxiaoqi/ace-cache | src/main/java/com/ace/cache/annotation/CacheClear.java | // Path: src/main/java/com/ace/cache/parser/IKeyGenerator.java
// public abstract class IKeyGenerator {
// public static final String LINK = "_";
//
// /**
// * 获取动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public String getKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments) {
// StringBuffer sb = new StringBuffer("");
// key = buildKey(key, scope, parameterTypes, arguments);
// sb.append(key);
// if (CacheScope.user.equals(scope)) {
// if (getUserKeyGenerator() != null)
// sb.append(LINK)
// .append(getUserKeyGenerator().getCurrentUserAccount());
// }
// return sb.toString();
// }
//
// /**
// * 当前登陆人key
// *
// * @param userKeyGenerator
// */
// public abstract IUserKeyGenerator getUserKeyGenerator();
//
// /**
// * 生成动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public abstract String buildKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments);
// }
//
// Path: src/main/java/com/ace/cache/parser/impl/DefaultKeyGenerator.java
// @Service
// public class DefaultKeyGenerator extends IKeyGenerator {
// @Autowired
// RedisConfig redisConfig;
//
// @Autowired(required = false)
// private IUserKeyGenerator userKeyGenerator;
//
// @Override
// public String buildKey(String key, CacheScope scope, Class<?>[] parameterTypes, Object[] arguments) {
// boolean isFirst = true;
// if (key.indexOf("{") > 0) {
// key = key.replace("{", ":{");
// Pattern pattern = Pattern.compile("\\d+(\\.?[\\w]+)*");
// Matcher matcher = pattern.matcher(key);
// while (matcher.find()) {
// String tmp = matcher.group();
// String express[] = matcher.group().split("\\.");
// String i = express[0];
// int index = Integer.parseInt(i) - 1;
// Object value = arguments[index];
// if (parameterTypes[index].isAssignableFrom(List.class)) {
// List result = (List) arguments[index];
// value = result.get(0);
// }
// if (value == null || value.equals("null"))
// value = "";
// if (express.length > 1) {
// for (int idx = 1; idx < express.length; idx ++) {
// String field = express[idx];
// value = ReflectionUtils.getFieldValue(value, field);
// }
// }
// if (isFirst) {
// key = key.replace("{" + tmp + "}", value.toString());
// } else {
// key = key.replace("{" + tmp + "}", LINK + value.toString());
// }
// }
// }
// if (CacheScope.user.equals(scope) && StringUtils.isNotBlank(redisConfig.getUserKey())){
// ServletRequestAttributes servletContainer = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
// HttpServletRequest request = servletContainer.getRequest();
// String accessToken = request.getHeader(redisConfig.getUserKey());
// if(StringUtils.isBlank(accessToken)){
// accessToken = WebUtil.getCookieValue(request,redisConfig.getUserKey());
// }
// if (StringUtils.isNotBlank(accessToken)){
// key = key + accessToken;
// }
// }
// return key;
// }
//
// @Override
// public IUserKeyGenerator getUserKeyGenerator() {
// return userKeyGenerator;
// }
//
// }
| import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.ace.cache.parser.IKeyGenerator;
import com.ace.cache.parser.impl.DefaultKeyGenerator; | package com.ace.cache.annotation;
/**
* 解决问题:
*
* @author Ace
* @version 1.0
* @date 2017年5月4日
* @since 1.7
*/
@Retention(RetentionPolicy.RUNTIME)//在运行时可以获取
@Target(value = {ElementType.METHOD, ElementType.TYPE})//作用到类,方法,接口上等
public @interface CacheClear {
/**
* 缓存key的前缀
*
* @return
* @author Ace
* @date 2017年5月3日
*/
public String pre() default "";
/**
* 缓存key
*
* @return
* @author Ace
* @date 2017年5月3日
*/
public String key() default "";
/**
* 缓存keys
*
* @return
* @author Ace
* @date 2017年5月3日
*/
public String[] keys() default "";
/**
* 键值解析类
*
* @return
*/ | // Path: src/main/java/com/ace/cache/parser/IKeyGenerator.java
// public abstract class IKeyGenerator {
// public static final String LINK = "_";
//
// /**
// * 获取动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public String getKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments) {
// StringBuffer sb = new StringBuffer("");
// key = buildKey(key, scope, parameterTypes, arguments);
// sb.append(key);
// if (CacheScope.user.equals(scope)) {
// if (getUserKeyGenerator() != null)
// sb.append(LINK)
// .append(getUserKeyGenerator().getCurrentUserAccount());
// }
// return sb.toString();
// }
//
// /**
// * 当前登陆人key
// *
// * @param userKeyGenerator
// */
// public abstract IUserKeyGenerator getUserKeyGenerator();
//
// /**
// * 生成动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public abstract String buildKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments);
// }
//
// Path: src/main/java/com/ace/cache/parser/impl/DefaultKeyGenerator.java
// @Service
// public class DefaultKeyGenerator extends IKeyGenerator {
// @Autowired
// RedisConfig redisConfig;
//
// @Autowired(required = false)
// private IUserKeyGenerator userKeyGenerator;
//
// @Override
// public String buildKey(String key, CacheScope scope, Class<?>[] parameterTypes, Object[] arguments) {
// boolean isFirst = true;
// if (key.indexOf("{") > 0) {
// key = key.replace("{", ":{");
// Pattern pattern = Pattern.compile("\\d+(\\.?[\\w]+)*");
// Matcher matcher = pattern.matcher(key);
// while (matcher.find()) {
// String tmp = matcher.group();
// String express[] = matcher.group().split("\\.");
// String i = express[0];
// int index = Integer.parseInt(i) - 1;
// Object value = arguments[index];
// if (parameterTypes[index].isAssignableFrom(List.class)) {
// List result = (List) arguments[index];
// value = result.get(0);
// }
// if (value == null || value.equals("null"))
// value = "";
// if (express.length > 1) {
// for (int idx = 1; idx < express.length; idx ++) {
// String field = express[idx];
// value = ReflectionUtils.getFieldValue(value, field);
// }
// }
// if (isFirst) {
// key = key.replace("{" + tmp + "}", value.toString());
// } else {
// key = key.replace("{" + tmp + "}", LINK + value.toString());
// }
// }
// }
// if (CacheScope.user.equals(scope) && StringUtils.isNotBlank(redisConfig.getUserKey())){
// ServletRequestAttributes servletContainer = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
// HttpServletRequest request = servletContainer.getRequest();
// String accessToken = request.getHeader(redisConfig.getUserKey());
// if(StringUtils.isBlank(accessToken)){
// accessToken = WebUtil.getCookieValue(request,redisConfig.getUserKey());
// }
// if (StringUtils.isNotBlank(accessToken)){
// key = key + accessToken;
// }
// }
// return key;
// }
//
// @Override
// public IUserKeyGenerator getUserKeyGenerator() {
// return userKeyGenerator;
// }
//
// }
// Path: src/main/java/com/ace/cache/annotation/CacheClear.java
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.ace.cache.parser.IKeyGenerator;
import com.ace.cache.parser.impl.DefaultKeyGenerator;
package com.ace.cache.annotation;
/**
* 解决问题:
*
* @author Ace
* @version 1.0
* @date 2017年5月4日
* @since 1.7
*/
@Retention(RetentionPolicy.RUNTIME)//在运行时可以获取
@Target(value = {ElementType.METHOD, ElementType.TYPE})//作用到类,方法,接口上等
public @interface CacheClear {
/**
* 缓存key的前缀
*
* @return
* @author Ace
* @date 2017年5月3日
*/
public String pre() default "";
/**
* 缓存key
*
* @return
* @author Ace
* @date 2017年5月3日
*/
public String key() default "";
/**
* 缓存keys
*
* @return
* @author Ace
* @date 2017年5月3日
*/
public String[] keys() default "";
/**
* 键值解析类
*
* @return
*/ | public Class<? extends IKeyGenerator> generator() default DefaultKeyGenerator.class; |
wxiaoqi/ace-cache | src/main/java/com/ace/cache/parser/IKeyGenerator.java | // Path: src/main/java/com/ace/cache/constants/CacheScope.java
// public enum CacheScope {
// user, application
// }
| import com.ace.cache.constants.CacheScope; | package com.ace.cache.parser;
/**
* 缓存键值表达式
*
* @author 小郎君
* @description
* @date 2017年5月18日
* @since 1.7
*/
public abstract class IKeyGenerator {
public static final String LINK = "_";
/**
* 获取动态key
*
* @param key
* @param scope
* @param parameterTypes
* @param arguments
* @return
*/ | // Path: src/main/java/com/ace/cache/constants/CacheScope.java
// public enum CacheScope {
// user, application
// }
// Path: src/main/java/com/ace/cache/parser/IKeyGenerator.java
import com.ace.cache.constants.CacheScope;
package com.ace.cache.parser;
/**
* 缓存键值表达式
*
* @author 小郎君
* @description
* @date 2017年5月18日
* @since 1.7
*/
public abstract class IKeyGenerator {
public static final String LINK = "_";
/**
* 获取动态key
*
* @param key
* @param scope
* @param parameterTypes
* @param arguments
* @return
*/ | public String getKey(String key, CacheScope scope, |
wxiaoqi/ace-cache | src/test/java/com/ace/cache/test/service/impl/UserServiceImpl.java | // Path: src/main/java/com/ace/cache/parser/ICacheResultParser.java
// public interface ICacheResultParser {
// /**
// * 解析结果
// *
// * @param value
// * @param returnType
// * @param origins
// * @return
// */
// public Object parse(String value, Type returnType, Class<?>... origins);
// }
//
// Path: src/test/java/com/ace/cache/test/cache/MyKeyGenerator.java
// public class MyKeyGenerator extends IKeyGenerator {
// @Override
// public IUserKeyGenerator getUserKeyGenerator() {
// return null;
// }
//
// @Override
// public String buildKey(String key, CacheScope scope, Class<?>[] parameterTypes, Object[] arguments) {
// return "myKey_"+arguments[0];
// }
// }
//
// Path: src/test/java/com/ace/cache/test/entity/User.java
// public class User {
// private String name;
// private int age;
// private String account;
//
// public User(String name, int age, String account) {
// this.name = name;
// this.age = age;
// this.account = account;
// }
//
// public User() {
// }
//
// public String getAccount() {
// return account;
// }
//
// public void setAccount(String account) {
// this.account = account;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public int getAge() {
// return age;
// }
//
//
// public void setAge(int age) {
// this.age = age;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// User user = (User) o;
//
// if (age != user.age) return false;
// return account != null ? account.equals(user.account) : user.account == null;
//
// }
//
// @Override
// public int hashCode() {
// int result = age;
// result = 31 * result + (account != null ? account.hashCode() : 0);
// return result;
// }
// }
//
// Path: src/test/java/com/ace/cache/test/service/UserService.java
// public interface UserService {
//
// User get(String account);
//
// List<User> getLlist();
//
// Set<User> getSet();
//
// Map<String, User> getMap();
//
// void save(User user);
//
// User get(int age);
//
// void biz(String account);
//
// int getAge(String account);
//
// String getName(String account);
// }
| import com.ace.cache.annotation.Cache;
import com.ace.cache.annotation.CacheClear;
import com.ace.cache.annotation.CacheGlobalLock;
import com.ace.cache.parser.ICacheResultParser;
import com.ace.cache.test.cache.MyKeyGenerator;
import com.ace.cache.test.entity.User;
import com.ace.cache.test.service.UserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.lang.reflect.Type;
import java.util.*; | package com.ace.cache.test.service.impl;
/**
* Created by Ace on 2017/5/21.
*/
@Service
@Slf4j | // Path: src/main/java/com/ace/cache/parser/ICacheResultParser.java
// public interface ICacheResultParser {
// /**
// * 解析结果
// *
// * @param value
// * @param returnType
// * @param origins
// * @return
// */
// public Object parse(String value, Type returnType, Class<?>... origins);
// }
//
// Path: src/test/java/com/ace/cache/test/cache/MyKeyGenerator.java
// public class MyKeyGenerator extends IKeyGenerator {
// @Override
// public IUserKeyGenerator getUserKeyGenerator() {
// return null;
// }
//
// @Override
// public String buildKey(String key, CacheScope scope, Class<?>[] parameterTypes, Object[] arguments) {
// return "myKey_"+arguments[0];
// }
// }
//
// Path: src/test/java/com/ace/cache/test/entity/User.java
// public class User {
// private String name;
// private int age;
// private String account;
//
// public User(String name, int age, String account) {
// this.name = name;
// this.age = age;
// this.account = account;
// }
//
// public User() {
// }
//
// public String getAccount() {
// return account;
// }
//
// public void setAccount(String account) {
// this.account = account;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public int getAge() {
// return age;
// }
//
//
// public void setAge(int age) {
// this.age = age;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// User user = (User) o;
//
// if (age != user.age) return false;
// return account != null ? account.equals(user.account) : user.account == null;
//
// }
//
// @Override
// public int hashCode() {
// int result = age;
// result = 31 * result + (account != null ? account.hashCode() : 0);
// return result;
// }
// }
//
// Path: src/test/java/com/ace/cache/test/service/UserService.java
// public interface UserService {
//
// User get(String account);
//
// List<User> getLlist();
//
// Set<User> getSet();
//
// Map<String, User> getMap();
//
// void save(User user);
//
// User get(int age);
//
// void biz(String account);
//
// int getAge(String account);
//
// String getName(String account);
// }
// Path: src/test/java/com/ace/cache/test/service/impl/UserServiceImpl.java
import com.ace.cache.annotation.Cache;
import com.ace.cache.annotation.CacheClear;
import com.ace.cache.annotation.CacheGlobalLock;
import com.ace.cache.parser.ICacheResultParser;
import com.ace.cache.test.cache.MyKeyGenerator;
import com.ace.cache.test.entity.User;
import com.ace.cache.test.service.UserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.lang.reflect.Type;
import java.util.*;
package com.ace.cache.test.service.impl;
/**
* Created by Ace on 2017/5/21.
*/
@Service
@Slf4j | public class UserServiceImpl implements UserService { |
wxiaoqi/ace-cache | src/test/java/com/ace/cache/test/service/impl/UserServiceImpl.java | // Path: src/main/java/com/ace/cache/parser/ICacheResultParser.java
// public interface ICacheResultParser {
// /**
// * 解析结果
// *
// * @param value
// * @param returnType
// * @param origins
// * @return
// */
// public Object parse(String value, Type returnType, Class<?>... origins);
// }
//
// Path: src/test/java/com/ace/cache/test/cache/MyKeyGenerator.java
// public class MyKeyGenerator extends IKeyGenerator {
// @Override
// public IUserKeyGenerator getUserKeyGenerator() {
// return null;
// }
//
// @Override
// public String buildKey(String key, CacheScope scope, Class<?>[] parameterTypes, Object[] arguments) {
// return "myKey_"+arguments[0];
// }
// }
//
// Path: src/test/java/com/ace/cache/test/entity/User.java
// public class User {
// private String name;
// private int age;
// private String account;
//
// public User(String name, int age, String account) {
// this.name = name;
// this.age = age;
// this.account = account;
// }
//
// public User() {
// }
//
// public String getAccount() {
// return account;
// }
//
// public void setAccount(String account) {
// this.account = account;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public int getAge() {
// return age;
// }
//
//
// public void setAge(int age) {
// this.age = age;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// User user = (User) o;
//
// if (age != user.age) return false;
// return account != null ? account.equals(user.account) : user.account == null;
//
// }
//
// @Override
// public int hashCode() {
// int result = age;
// result = 31 * result + (account != null ? account.hashCode() : 0);
// return result;
// }
// }
//
// Path: src/test/java/com/ace/cache/test/service/UserService.java
// public interface UserService {
//
// User get(String account);
//
// List<User> getLlist();
//
// Set<User> getSet();
//
// Map<String, User> getMap();
//
// void save(User user);
//
// User get(int age);
//
// void biz(String account);
//
// int getAge(String account);
//
// String getName(String account);
// }
| import com.ace.cache.annotation.Cache;
import com.ace.cache.annotation.CacheClear;
import com.ace.cache.annotation.CacheGlobalLock;
import com.ace.cache.parser.ICacheResultParser;
import com.ace.cache.test.cache.MyKeyGenerator;
import com.ace.cache.test.entity.User;
import com.ace.cache.test.service.UserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.lang.reflect.Type;
import java.util.*; | package com.ace.cache.test.service.impl;
/**
* Created by Ace on 2017/5/21.
*/
@Service
@Slf4j
public class UserServiceImpl implements UserService {
@Override
@Cache(key = "user{1}",desc = "用户信息缓存") | // Path: src/main/java/com/ace/cache/parser/ICacheResultParser.java
// public interface ICacheResultParser {
// /**
// * 解析结果
// *
// * @param value
// * @param returnType
// * @param origins
// * @return
// */
// public Object parse(String value, Type returnType, Class<?>... origins);
// }
//
// Path: src/test/java/com/ace/cache/test/cache/MyKeyGenerator.java
// public class MyKeyGenerator extends IKeyGenerator {
// @Override
// public IUserKeyGenerator getUserKeyGenerator() {
// return null;
// }
//
// @Override
// public String buildKey(String key, CacheScope scope, Class<?>[] parameterTypes, Object[] arguments) {
// return "myKey_"+arguments[0];
// }
// }
//
// Path: src/test/java/com/ace/cache/test/entity/User.java
// public class User {
// private String name;
// private int age;
// private String account;
//
// public User(String name, int age, String account) {
// this.name = name;
// this.age = age;
// this.account = account;
// }
//
// public User() {
// }
//
// public String getAccount() {
// return account;
// }
//
// public void setAccount(String account) {
// this.account = account;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public int getAge() {
// return age;
// }
//
//
// public void setAge(int age) {
// this.age = age;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// User user = (User) o;
//
// if (age != user.age) return false;
// return account != null ? account.equals(user.account) : user.account == null;
//
// }
//
// @Override
// public int hashCode() {
// int result = age;
// result = 31 * result + (account != null ? account.hashCode() : 0);
// return result;
// }
// }
//
// Path: src/test/java/com/ace/cache/test/service/UserService.java
// public interface UserService {
//
// User get(String account);
//
// List<User> getLlist();
//
// Set<User> getSet();
//
// Map<String, User> getMap();
//
// void save(User user);
//
// User get(int age);
//
// void biz(String account);
//
// int getAge(String account);
//
// String getName(String account);
// }
// Path: src/test/java/com/ace/cache/test/service/impl/UserServiceImpl.java
import com.ace.cache.annotation.Cache;
import com.ace.cache.annotation.CacheClear;
import com.ace.cache.annotation.CacheGlobalLock;
import com.ace.cache.parser.ICacheResultParser;
import com.ace.cache.test.cache.MyKeyGenerator;
import com.ace.cache.test.entity.User;
import com.ace.cache.test.service.UserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.lang.reflect.Type;
import java.util.*;
package com.ace.cache.test.service.impl;
/**
* Created by Ace on 2017/5/21.
*/
@Service
@Slf4j
public class UserServiceImpl implements UserService {
@Override
@Cache(key = "user{1}",desc = "用户信息缓存") | public User get(String account) { |
wxiaoqi/ace-cache | src/test/java/com/ace/cache/test/service/impl/UserServiceImpl.java | // Path: src/main/java/com/ace/cache/parser/ICacheResultParser.java
// public interface ICacheResultParser {
// /**
// * 解析结果
// *
// * @param value
// * @param returnType
// * @param origins
// * @return
// */
// public Object parse(String value, Type returnType, Class<?>... origins);
// }
//
// Path: src/test/java/com/ace/cache/test/cache/MyKeyGenerator.java
// public class MyKeyGenerator extends IKeyGenerator {
// @Override
// public IUserKeyGenerator getUserKeyGenerator() {
// return null;
// }
//
// @Override
// public String buildKey(String key, CacheScope scope, Class<?>[] parameterTypes, Object[] arguments) {
// return "myKey_"+arguments[0];
// }
// }
//
// Path: src/test/java/com/ace/cache/test/entity/User.java
// public class User {
// private String name;
// private int age;
// private String account;
//
// public User(String name, int age, String account) {
// this.name = name;
// this.age = age;
// this.account = account;
// }
//
// public User() {
// }
//
// public String getAccount() {
// return account;
// }
//
// public void setAccount(String account) {
// this.account = account;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public int getAge() {
// return age;
// }
//
//
// public void setAge(int age) {
// this.age = age;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// User user = (User) o;
//
// if (age != user.age) return false;
// return account != null ? account.equals(user.account) : user.account == null;
//
// }
//
// @Override
// public int hashCode() {
// int result = age;
// result = 31 * result + (account != null ? account.hashCode() : 0);
// return result;
// }
// }
//
// Path: src/test/java/com/ace/cache/test/service/UserService.java
// public interface UserService {
//
// User get(String account);
//
// List<User> getLlist();
//
// Set<User> getSet();
//
// Map<String, User> getMap();
//
// void save(User user);
//
// User get(int age);
//
// void biz(String account);
//
// int getAge(String account);
//
// String getName(String account);
// }
| import com.ace.cache.annotation.Cache;
import com.ace.cache.annotation.CacheClear;
import com.ace.cache.annotation.CacheGlobalLock;
import com.ace.cache.parser.ICacheResultParser;
import com.ace.cache.test.cache.MyKeyGenerator;
import com.ace.cache.test.entity.User;
import com.ace.cache.test.service.UserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.lang.reflect.Type;
import java.util.*; | @Cache(key = "user:set", parser = SetCacheResultParser.class)
public Set<User> getSet() {
log.debug("从方法内读取....");
Set<User> users = new HashSet<User>();
for (int i = 0; i < 20; i++) {
User user = new User("Ace", i, "ace");
users.add(user);
}
return users;
}
@Override
@Cache(key = "user:map",parser = UserMapCacheResultParser.class)
public Map<String, User> getMap() {
log.debug("从方法内读取....");
Map<String,User> users = new HashMap<String, User>();
for (int i = 0; i < 20; i++) {
User user = new User("Ace", i, "ace");
users.put(user.getAccount() + i, user);
}
return users;
}
@Override
@CacheClear(pre = "user")
public void save(User user) {
}
@Override | // Path: src/main/java/com/ace/cache/parser/ICacheResultParser.java
// public interface ICacheResultParser {
// /**
// * 解析结果
// *
// * @param value
// * @param returnType
// * @param origins
// * @return
// */
// public Object parse(String value, Type returnType, Class<?>... origins);
// }
//
// Path: src/test/java/com/ace/cache/test/cache/MyKeyGenerator.java
// public class MyKeyGenerator extends IKeyGenerator {
// @Override
// public IUserKeyGenerator getUserKeyGenerator() {
// return null;
// }
//
// @Override
// public String buildKey(String key, CacheScope scope, Class<?>[] parameterTypes, Object[] arguments) {
// return "myKey_"+arguments[0];
// }
// }
//
// Path: src/test/java/com/ace/cache/test/entity/User.java
// public class User {
// private String name;
// private int age;
// private String account;
//
// public User(String name, int age, String account) {
// this.name = name;
// this.age = age;
// this.account = account;
// }
//
// public User() {
// }
//
// public String getAccount() {
// return account;
// }
//
// public void setAccount(String account) {
// this.account = account;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public int getAge() {
// return age;
// }
//
//
// public void setAge(int age) {
// this.age = age;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// User user = (User) o;
//
// if (age != user.age) return false;
// return account != null ? account.equals(user.account) : user.account == null;
//
// }
//
// @Override
// public int hashCode() {
// int result = age;
// result = 31 * result + (account != null ? account.hashCode() : 0);
// return result;
// }
// }
//
// Path: src/test/java/com/ace/cache/test/service/UserService.java
// public interface UserService {
//
// User get(String account);
//
// List<User> getLlist();
//
// Set<User> getSet();
//
// Map<String, User> getMap();
//
// void save(User user);
//
// User get(int age);
//
// void biz(String account);
//
// int getAge(String account);
//
// String getName(String account);
// }
// Path: src/test/java/com/ace/cache/test/service/impl/UserServiceImpl.java
import com.ace.cache.annotation.Cache;
import com.ace.cache.annotation.CacheClear;
import com.ace.cache.annotation.CacheGlobalLock;
import com.ace.cache.parser.ICacheResultParser;
import com.ace.cache.test.cache.MyKeyGenerator;
import com.ace.cache.test.entity.User;
import com.ace.cache.test.service.UserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.lang.reflect.Type;
import java.util.*;
@Cache(key = "user:set", parser = SetCacheResultParser.class)
public Set<User> getSet() {
log.debug("从方法内读取....");
Set<User> users = new HashSet<User>();
for (int i = 0; i < 20; i++) {
User user = new User("Ace", i, "ace");
users.add(user);
}
return users;
}
@Override
@Cache(key = "user:map",parser = UserMapCacheResultParser.class)
public Map<String, User> getMap() {
log.debug("从方法内读取....");
Map<String,User> users = new HashMap<String, User>();
for (int i = 0; i < 20; i++) {
User user = new User("Ace", i, "ace");
users.put(user.getAccount() + i, user);
}
return users;
}
@Override
@CacheClear(pre = "user")
public void save(User user) {
}
@Override | @Cache(key="user",generator = MyKeyGenerator.class) |
wxiaoqi/ace-cache | src/test/java/com/ace/cache/test/service/impl/UserServiceImpl.java | // Path: src/main/java/com/ace/cache/parser/ICacheResultParser.java
// public interface ICacheResultParser {
// /**
// * 解析结果
// *
// * @param value
// * @param returnType
// * @param origins
// * @return
// */
// public Object parse(String value, Type returnType, Class<?>... origins);
// }
//
// Path: src/test/java/com/ace/cache/test/cache/MyKeyGenerator.java
// public class MyKeyGenerator extends IKeyGenerator {
// @Override
// public IUserKeyGenerator getUserKeyGenerator() {
// return null;
// }
//
// @Override
// public String buildKey(String key, CacheScope scope, Class<?>[] parameterTypes, Object[] arguments) {
// return "myKey_"+arguments[0];
// }
// }
//
// Path: src/test/java/com/ace/cache/test/entity/User.java
// public class User {
// private String name;
// private int age;
// private String account;
//
// public User(String name, int age, String account) {
// this.name = name;
// this.age = age;
// this.account = account;
// }
//
// public User() {
// }
//
// public String getAccount() {
// return account;
// }
//
// public void setAccount(String account) {
// this.account = account;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public int getAge() {
// return age;
// }
//
//
// public void setAge(int age) {
// this.age = age;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// User user = (User) o;
//
// if (age != user.age) return false;
// return account != null ? account.equals(user.account) : user.account == null;
//
// }
//
// @Override
// public int hashCode() {
// int result = age;
// result = 31 * result + (account != null ? account.hashCode() : 0);
// return result;
// }
// }
//
// Path: src/test/java/com/ace/cache/test/service/UserService.java
// public interface UserService {
//
// User get(String account);
//
// List<User> getLlist();
//
// Set<User> getSet();
//
// Map<String, User> getMap();
//
// void save(User user);
//
// User get(int age);
//
// void biz(String account);
//
// int getAge(String account);
//
// String getName(String account);
// }
| import com.ace.cache.annotation.Cache;
import com.ace.cache.annotation.CacheClear;
import com.ace.cache.annotation.CacheGlobalLock;
import com.ace.cache.parser.ICacheResultParser;
import com.ace.cache.test.cache.MyKeyGenerator;
import com.ace.cache.test.entity.User;
import com.ace.cache.test.service.UserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.lang.reflect.Type;
import java.util.*; | public User get(int age) {
log.debug("从方法内读取....");
User user = new User("Ace", age, "Ace");
return user;
}
@Override
@CacheGlobalLock(key="user_lock{1}")
public void biz(String account) {
log.debug("注解分布式锁...");
}
@Override
@Cache(key="user:age{1}")
public int getAge(String account) {
log.debug("从方法内读取....");
return 11;
}
@Override
@Cache(key="user:name{1}")
public String getName(String account) {
log.debug("从方法内读取....");
return "小郎君";
}
/**
* 对map返回结果做处理
*
* @Created by Ace on 2017/5/22.
*/ | // Path: src/main/java/com/ace/cache/parser/ICacheResultParser.java
// public interface ICacheResultParser {
// /**
// * 解析结果
// *
// * @param value
// * @param returnType
// * @param origins
// * @return
// */
// public Object parse(String value, Type returnType, Class<?>... origins);
// }
//
// Path: src/test/java/com/ace/cache/test/cache/MyKeyGenerator.java
// public class MyKeyGenerator extends IKeyGenerator {
// @Override
// public IUserKeyGenerator getUserKeyGenerator() {
// return null;
// }
//
// @Override
// public String buildKey(String key, CacheScope scope, Class<?>[] parameterTypes, Object[] arguments) {
// return "myKey_"+arguments[0];
// }
// }
//
// Path: src/test/java/com/ace/cache/test/entity/User.java
// public class User {
// private String name;
// private int age;
// private String account;
//
// public User(String name, int age, String account) {
// this.name = name;
// this.age = age;
// this.account = account;
// }
//
// public User() {
// }
//
// public String getAccount() {
// return account;
// }
//
// public void setAccount(String account) {
// this.account = account;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public int getAge() {
// return age;
// }
//
//
// public void setAge(int age) {
// this.age = age;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// User user = (User) o;
//
// if (age != user.age) return false;
// return account != null ? account.equals(user.account) : user.account == null;
//
// }
//
// @Override
// public int hashCode() {
// int result = age;
// result = 31 * result + (account != null ? account.hashCode() : 0);
// return result;
// }
// }
//
// Path: src/test/java/com/ace/cache/test/service/UserService.java
// public interface UserService {
//
// User get(String account);
//
// List<User> getLlist();
//
// Set<User> getSet();
//
// Map<String, User> getMap();
//
// void save(User user);
//
// User get(int age);
//
// void biz(String account);
//
// int getAge(String account);
//
// String getName(String account);
// }
// Path: src/test/java/com/ace/cache/test/service/impl/UserServiceImpl.java
import com.ace.cache.annotation.Cache;
import com.ace.cache.annotation.CacheClear;
import com.ace.cache.annotation.CacheGlobalLock;
import com.ace.cache.parser.ICacheResultParser;
import com.ace.cache.test.cache.MyKeyGenerator;
import com.ace.cache.test.entity.User;
import com.ace.cache.test.service.UserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.lang.reflect.Type;
import java.util.*;
public User get(int age) {
log.debug("从方法内读取....");
User user = new User("Ace", age, "Ace");
return user;
}
@Override
@CacheGlobalLock(key="user_lock{1}")
public void biz(String account) {
log.debug("注解分布式锁...");
}
@Override
@Cache(key="user:age{1}")
public int getAge(String account) {
log.debug("从方法内读取....");
return 11;
}
@Override
@Cache(key="user:name{1}")
public String getName(String account) {
log.debug("从方法内读取....");
return "小郎君";
}
/**
* 对map返回结果做处理
*
* @Created by Ace on 2017/5/22.
*/ | public static class UserMapCacheResultParser implements ICacheResultParser { |
wxiaoqi/ace-cache | src/test/java/com/ace/cache/test/unit/UserServiceTest.java | // Path: src/test/java/com/ace/cache/test/CacheTest.java
// @SpringBootApplication
// @EnableAceCache
// public class CacheTest {
// public static void main(String args[]) {
// SpringApplication app = new SpringApplication(CacheTest.class);
// app.run(args);
// }
//
// }
//
// Path: src/test/java/com/ace/cache/test/entity/User.java
// public class User {
// private String name;
// private int age;
// private String account;
//
// public User(String name, int age, String account) {
// this.name = name;
// this.age = age;
// this.account = account;
// }
//
// public User() {
// }
//
// public String getAccount() {
// return account;
// }
//
// public void setAccount(String account) {
// this.account = account;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public int getAge() {
// return age;
// }
//
//
// public void setAge(int age) {
// this.age = age;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// User user = (User) o;
//
// if (age != user.age) return false;
// return account != null ? account.equals(user.account) : user.account == null;
//
// }
//
// @Override
// public int hashCode() {
// int result = age;
// result = 31 * result + (account != null ? account.hashCode() : 0);
// return result;
// }
// }
//
// Path: src/test/java/com/ace/cache/test/service/UserService.java
// public interface UserService {
//
// User get(String account);
//
// List<User> getLlist();
//
// Set<User> getSet();
//
// Map<String, User> getMap();
//
// void save(User user);
//
// User get(int age);
//
// void biz(String account);
//
// int getAge(String account);
//
// String getName(String account);
// }
| import com.ace.cache.test.CacheTest;
import com.ace.cache.test.entity.User;
import com.ace.cache.test.service.UserService;
import com.alibaba.fastjson.JSON;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; | package com.ace.cache.test.unit;
/**
* Created by Ace on 2017/5/21.
*/
@RunWith(SpringJUnit4ClassRunner.class) // SpringJUnit支持,由此引入Spring-Test框架支持!
@SpringBootTest(classes = CacheTest.class) // 指定我们SpringBoot工程的Application启动类
public class UserServiceTest {
@Autowired | // Path: src/test/java/com/ace/cache/test/CacheTest.java
// @SpringBootApplication
// @EnableAceCache
// public class CacheTest {
// public static void main(String args[]) {
// SpringApplication app = new SpringApplication(CacheTest.class);
// app.run(args);
// }
//
// }
//
// Path: src/test/java/com/ace/cache/test/entity/User.java
// public class User {
// private String name;
// private int age;
// private String account;
//
// public User(String name, int age, String account) {
// this.name = name;
// this.age = age;
// this.account = account;
// }
//
// public User() {
// }
//
// public String getAccount() {
// return account;
// }
//
// public void setAccount(String account) {
// this.account = account;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public int getAge() {
// return age;
// }
//
//
// public void setAge(int age) {
// this.age = age;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// User user = (User) o;
//
// if (age != user.age) return false;
// return account != null ? account.equals(user.account) : user.account == null;
//
// }
//
// @Override
// public int hashCode() {
// int result = age;
// result = 31 * result + (account != null ? account.hashCode() : 0);
// return result;
// }
// }
//
// Path: src/test/java/com/ace/cache/test/service/UserService.java
// public interface UserService {
//
// User get(String account);
//
// List<User> getLlist();
//
// Set<User> getSet();
//
// Map<String, User> getMap();
//
// void save(User user);
//
// User get(int age);
//
// void biz(String account);
//
// int getAge(String account);
//
// String getName(String account);
// }
// Path: src/test/java/com/ace/cache/test/unit/UserServiceTest.java
import com.ace.cache.test.CacheTest;
import com.ace.cache.test.entity.User;
import com.ace.cache.test.service.UserService;
import com.alibaba.fastjson.JSON;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
package com.ace.cache.test.unit;
/**
* Created by Ace on 2017/5/21.
*/
@RunWith(SpringJUnit4ClassRunner.class) // SpringJUnit支持,由此引入Spring-Test框架支持!
@SpringBootTest(classes = CacheTest.class) // 指定我们SpringBoot工程的Application启动类
public class UserServiceTest {
@Autowired | private UserService userService; |
wxiaoqi/ace-cache | src/test/java/com/ace/cache/test/unit/UserServiceTest.java | // Path: src/test/java/com/ace/cache/test/CacheTest.java
// @SpringBootApplication
// @EnableAceCache
// public class CacheTest {
// public static void main(String args[]) {
// SpringApplication app = new SpringApplication(CacheTest.class);
// app.run(args);
// }
//
// }
//
// Path: src/test/java/com/ace/cache/test/entity/User.java
// public class User {
// private String name;
// private int age;
// private String account;
//
// public User(String name, int age, String account) {
// this.name = name;
// this.age = age;
// this.account = account;
// }
//
// public User() {
// }
//
// public String getAccount() {
// return account;
// }
//
// public void setAccount(String account) {
// this.account = account;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public int getAge() {
// return age;
// }
//
//
// public void setAge(int age) {
// this.age = age;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// User user = (User) o;
//
// if (age != user.age) return false;
// return account != null ? account.equals(user.account) : user.account == null;
//
// }
//
// @Override
// public int hashCode() {
// int result = age;
// result = 31 * result + (account != null ? account.hashCode() : 0);
// return result;
// }
// }
//
// Path: src/test/java/com/ace/cache/test/service/UserService.java
// public interface UserService {
//
// User get(String account);
//
// List<User> getLlist();
//
// Set<User> getSet();
//
// Map<String, User> getMap();
//
// void save(User user);
//
// User get(int age);
//
// void biz(String account);
//
// int getAge(String account);
//
// String getName(String account);
// }
| import com.ace.cache.test.CacheTest;
import com.ace.cache.test.entity.User;
import com.ace.cache.test.service.UserService;
import com.alibaba.fastjson.JSON;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; | package com.ace.cache.test.unit;
/**
* Created by Ace on 2017/5/21.
*/
@RunWith(SpringJUnit4ClassRunner.class) // SpringJUnit支持,由此引入Spring-Test框架支持!
@SpringBootTest(classes = CacheTest.class) // 指定我们SpringBoot工程的Application启动类
public class UserServiceTest {
@Autowired
private UserService userService;
@Test
public void testGetAge(){
userService.getAge("test");
userService.getAge("test");
}
@Test
public void testGetName(){
String test = userService.getName("test");
System.out.println(test);
test = userService.getName("test");
System.out.println(test);
}
@Test
public void testGetUser() { | // Path: src/test/java/com/ace/cache/test/CacheTest.java
// @SpringBootApplication
// @EnableAceCache
// public class CacheTest {
// public static void main(String args[]) {
// SpringApplication app = new SpringApplication(CacheTest.class);
// app.run(args);
// }
//
// }
//
// Path: src/test/java/com/ace/cache/test/entity/User.java
// public class User {
// private String name;
// private int age;
// private String account;
//
// public User(String name, int age, String account) {
// this.name = name;
// this.age = age;
// this.account = account;
// }
//
// public User() {
// }
//
// public String getAccount() {
// return account;
// }
//
// public void setAccount(String account) {
// this.account = account;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public int getAge() {
// return age;
// }
//
//
// public void setAge(int age) {
// this.age = age;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// User user = (User) o;
//
// if (age != user.age) return false;
// return account != null ? account.equals(user.account) : user.account == null;
//
// }
//
// @Override
// public int hashCode() {
// int result = age;
// result = 31 * result + (account != null ? account.hashCode() : 0);
// return result;
// }
// }
//
// Path: src/test/java/com/ace/cache/test/service/UserService.java
// public interface UserService {
//
// User get(String account);
//
// List<User> getLlist();
//
// Set<User> getSet();
//
// Map<String, User> getMap();
//
// void save(User user);
//
// User get(int age);
//
// void biz(String account);
//
// int getAge(String account);
//
// String getName(String account);
// }
// Path: src/test/java/com/ace/cache/test/unit/UserServiceTest.java
import com.ace.cache.test.CacheTest;
import com.ace.cache.test.entity.User;
import com.ace.cache.test.service.UserService;
import com.alibaba.fastjson.JSON;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
package com.ace.cache.test.unit;
/**
* Created by Ace on 2017/5/21.
*/
@RunWith(SpringJUnit4ClassRunner.class) // SpringJUnit支持,由此引入Spring-Test框架支持!
@SpringBootTest(classes = CacheTest.class) // 指定我们SpringBoot工程的Application启动类
public class UserServiceTest {
@Autowired
private UserService userService;
@Test
public void testGetAge(){
userService.getAge("test");
userService.getAge("test");
}
@Test
public void testGetName(){
String test = userService.getName("test");
System.out.println(test);
test = userService.getName("test");
System.out.println(test);
}
@Test
public void testGetUser() { | User test = userService.get("test"); |
wxiaoqi/ace-cache | src/main/java/com/ace/cache/aspect/KeyGenerateService.java | // Path: src/main/java/com/ace/cache/parser/IKeyGenerator.java
// public abstract class IKeyGenerator {
// public static final String LINK = "_";
//
// /**
// * 获取动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public String getKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments) {
// StringBuffer sb = new StringBuffer("");
// key = buildKey(key, scope, parameterTypes, arguments);
// sb.append(key);
// if (CacheScope.user.equals(scope)) {
// if (getUserKeyGenerator() != null)
// sb.append(LINK)
// .append(getUserKeyGenerator().getCurrentUserAccount());
// }
// return sb.toString();
// }
//
// /**
// * 当前登陆人key
// *
// * @param userKeyGenerator
// */
// public abstract IUserKeyGenerator getUserKeyGenerator();
//
// /**
// * 生成动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public abstract String buildKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments);
// }
//
// Path: src/main/java/com/ace/cache/parser/impl/DefaultKeyGenerator.java
// @Service
// public class DefaultKeyGenerator extends IKeyGenerator {
// @Autowired
// RedisConfig redisConfig;
//
// @Autowired(required = false)
// private IUserKeyGenerator userKeyGenerator;
//
// @Override
// public String buildKey(String key, CacheScope scope, Class<?>[] parameterTypes, Object[] arguments) {
// boolean isFirst = true;
// if (key.indexOf("{") > 0) {
// key = key.replace("{", ":{");
// Pattern pattern = Pattern.compile("\\d+(\\.?[\\w]+)*");
// Matcher matcher = pattern.matcher(key);
// while (matcher.find()) {
// String tmp = matcher.group();
// String express[] = matcher.group().split("\\.");
// String i = express[0];
// int index = Integer.parseInt(i) - 1;
// Object value = arguments[index];
// if (parameterTypes[index].isAssignableFrom(List.class)) {
// List result = (List) arguments[index];
// value = result.get(0);
// }
// if (value == null || value.equals("null"))
// value = "";
// if (express.length > 1) {
// for (int idx = 1; idx < express.length; idx ++) {
// String field = express[idx];
// value = ReflectionUtils.getFieldValue(value, field);
// }
// }
// if (isFirst) {
// key = key.replace("{" + tmp + "}", value.toString());
// } else {
// key = key.replace("{" + tmp + "}", LINK + value.toString());
// }
// }
// }
// if (CacheScope.user.equals(scope) && StringUtils.isNotBlank(redisConfig.getUserKey())){
// ServletRequestAttributes servletContainer = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
// HttpServletRequest request = servletContainer.getRequest();
// String accessToken = request.getHeader(redisConfig.getUserKey());
// if(StringUtils.isBlank(accessToken)){
// accessToken = WebUtil.getCookieValue(request,redisConfig.getUserKey());
// }
// if (StringUtils.isNotBlank(accessToken)){
// key = key + accessToken;
// }
// }
// return key;
// }
//
// @Override
// public IUserKeyGenerator getUserKeyGenerator() {
// return userKeyGenerator;
// }
//
// }
| import com.ace.cache.annotation.Cache;
import com.ace.cache.annotation.CacheGlobalLock;
import com.ace.cache.parser.IKeyGenerator;
import com.ace.cache.parser.impl.DefaultKeyGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.concurrent.ConcurrentHashMap; | package com.ace.cache.aspect;
@Service
@Slf4j
public class KeyGenerateService {
@Autowired | // Path: src/main/java/com/ace/cache/parser/IKeyGenerator.java
// public abstract class IKeyGenerator {
// public static final String LINK = "_";
//
// /**
// * 获取动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public String getKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments) {
// StringBuffer sb = new StringBuffer("");
// key = buildKey(key, scope, parameterTypes, arguments);
// sb.append(key);
// if (CacheScope.user.equals(scope)) {
// if (getUserKeyGenerator() != null)
// sb.append(LINK)
// .append(getUserKeyGenerator().getCurrentUserAccount());
// }
// return sb.toString();
// }
//
// /**
// * 当前登陆人key
// *
// * @param userKeyGenerator
// */
// public abstract IUserKeyGenerator getUserKeyGenerator();
//
// /**
// * 生成动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public abstract String buildKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments);
// }
//
// Path: src/main/java/com/ace/cache/parser/impl/DefaultKeyGenerator.java
// @Service
// public class DefaultKeyGenerator extends IKeyGenerator {
// @Autowired
// RedisConfig redisConfig;
//
// @Autowired(required = false)
// private IUserKeyGenerator userKeyGenerator;
//
// @Override
// public String buildKey(String key, CacheScope scope, Class<?>[] parameterTypes, Object[] arguments) {
// boolean isFirst = true;
// if (key.indexOf("{") > 0) {
// key = key.replace("{", ":{");
// Pattern pattern = Pattern.compile("\\d+(\\.?[\\w]+)*");
// Matcher matcher = pattern.matcher(key);
// while (matcher.find()) {
// String tmp = matcher.group();
// String express[] = matcher.group().split("\\.");
// String i = express[0];
// int index = Integer.parseInt(i) - 1;
// Object value = arguments[index];
// if (parameterTypes[index].isAssignableFrom(List.class)) {
// List result = (List) arguments[index];
// value = result.get(0);
// }
// if (value == null || value.equals("null"))
// value = "";
// if (express.length > 1) {
// for (int idx = 1; idx < express.length; idx ++) {
// String field = express[idx];
// value = ReflectionUtils.getFieldValue(value, field);
// }
// }
// if (isFirst) {
// key = key.replace("{" + tmp + "}", value.toString());
// } else {
// key = key.replace("{" + tmp + "}", LINK + value.toString());
// }
// }
// }
// if (CacheScope.user.equals(scope) && StringUtils.isNotBlank(redisConfig.getUserKey())){
// ServletRequestAttributes servletContainer = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
// HttpServletRequest request = servletContainer.getRequest();
// String accessToken = request.getHeader(redisConfig.getUserKey());
// if(StringUtils.isBlank(accessToken)){
// accessToken = WebUtil.getCookieValue(request,redisConfig.getUserKey());
// }
// if (StringUtils.isNotBlank(accessToken)){
// key = key + accessToken;
// }
// }
// return key;
// }
//
// @Override
// public IUserKeyGenerator getUserKeyGenerator() {
// return userKeyGenerator;
// }
//
// }
// Path: src/main/java/com/ace/cache/aspect/KeyGenerateService.java
import com.ace.cache.annotation.Cache;
import com.ace.cache.annotation.CacheGlobalLock;
import com.ace.cache.parser.IKeyGenerator;
import com.ace.cache.parser.impl.DefaultKeyGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.concurrent.ConcurrentHashMap;
package com.ace.cache.aspect;
@Service
@Slf4j
public class KeyGenerateService {
@Autowired | private IKeyGenerator keyParser; |
wxiaoqi/ace-cache | src/main/java/com/ace/cache/aspect/KeyGenerateService.java | // Path: src/main/java/com/ace/cache/parser/IKeyGenerator.java
// public abstract class IKeyGenerator {
// public static final String LINK = "_";
//
// /**
// * 获取动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public String getKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments) {
// StringBuffer sb = new StringBuffer("");
// key = buildKey(key, scope, parameterTypes, arguments);
// sb.append(key);
// if (CacheScope.user.equals(scope)) {
// if (getUserKeyGenerator() != null)
// sb.append(LINK)
// .append(getUserKeyGenerator().getCurrentUserAccount());
// }
// return sb.toString();
// }
//
// /**
// * 当前登陆人key
// *
// * @param userKeyGenerator
// */
// public abstract IUserKeyGenerator getUserKeyGenerator();
//
// /**
// * 生成动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public abstract String buildKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments);
// }
//
// Path: src/main/java/com/ace/cache/parser/impl/DefaultKeyGenerator.java
// @Service
// public class DefaultKeyGenerator extends IKeyGenerator {
// @Autowired
// RedisConfig redisConfig;
//
// @Autowired(required = false)
// private IUserKeyGenerator userKeyGenerator;
//
// @Override
// public String buildKey(String key, CacheScope scope, Class<?>[] parameterTypes, Object[] arguments) {
// boolean isFirst = true;
// if (key.indexOf("{") > 0) {
// key = key.replace("{", ":{");
// Pattern pattern = Pattern.compile("\\d+(\\.?[\\w]+)*");
// Matcher matcher = pattern.matcher(key);
// while (matcher.find()) {
// String tmp = matcher.group();
// String express[] = matcher.group().split("\\.");
// String i = express[0];
// int index = Integer.parseInt(i) - 1;
// Object value = arguments[index];
// if (parameterTypes[index].isAssignableFrom(List.class)) {
// List result = (List) arguments[index];
// value = result.get(0);
// }
// if (value == null || value.equals("null"))
// value = "";
// if (express.length > 1) {
// for (int idx = 1; idx < express.length; idx ++) {
// String field = express[idx];
// value = ReflectionUtils.getFieldValue(value, field);
// }
// }
// if (isFirst) {
// key = key.replace("{" + tmp + "}", value.toString());
// } else {
// key = key.replace("{" + tmp + "}", LINK + value.toString());
// }
// }
// }
// if (CacheScope.user.equals(scope) && StringUtils.isNotBlank(redisConfig.getUserKey())){
// ServletRequestAttributes servletContainer = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
// HttpServletRequest request = servletContainer.getRequest();
// String accessToken = request.getHeader(redisConfig.getUserKey());
// if(StringUtils.isBlank(accessToken)){
// accessToken = WebUtil.getCookieValue(request,redisConfig.getUserKey());
// }
// if (StringUtils.isNotBlank(accessToken)){
// key = key + accessToken;
// }
// }
// return key;
// }
//
// @Override
// public IUserKeyGenerator getUserKeyGenerator() {
// return userKeyGenerator;
// }
//
// }
| import com.ace.cache.annotation.Cache;
import com.ace.cache.annotation.CacheGlobalLock;
import com.ace.cache.parser.IKeyGenerator;
import com.ace.cache.parser.impl.DefaultKeyGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.concurrent.ConcurrentHashMap; | package com.ace.cache.aspect;
@Service
@Slf4j
public class KeyGenerateService {
@Autowired
private IKeyGenerator keyParser;
private ConcurrentHashMap<String, IKeyGenerator> generatorMap = new ConcurrentHashMap<String, IKeyGenerator>();
/**
* 解析表达式
*
* @param anno
* @param parameterTypes
* @param arguments
* @return
* @throws InstantiationException
* @throws IllegalAccessException
*/
public String getKey(Cache anno, Class<?>[] parameterTypes,
Object[] arguments) throws InstantiationException,
IllegalAccessException {
String key;
String generatorClsName = anno.generator().getName();
IKeyGenerator keyGenerator = null; | // Path: src/main/java/com/ace/cache/parser/IKeyGenerator.java
// public abstract class IKeyGenerator {
// public static final String LINK = "_";
//
// /**
// * 获取动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public String getKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments) {
// StringBuffer sb = new StringBuffer("");
// key = buildKey(key, scope, parameterTypes, arguments);
// sb.append(key);
// if (CacheScope.user.equals(scope)) {
// if (getUserKeyGenerator() != null)
// sb.append(LINK)
// .append(getUserKeyGenerator().getCurrentUserAccount());
// }
// return sb.toString();
// }
//
// /**
// * 当前登陆人key
// *
// * @param userKeyGenerator
// */
// public abstract IUserKeyGenerator getUserKeyGenerator();
//
// /**
// * 生成动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public abstract String buildKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments);
// }
//
// Path: src/main/java/com/ace/cache/parser/impl/DefaultKeyGenerator.java
// @Service
// public class DefaultKeyGenerator extends IKeyGenerator {
// @Autowired
// RedisConfig redisConfig;
//
// @Autowired(required = false)
// private IUserKeyGenerator userKeyGenerator;
//
// @Override
// public String buildKey(String key, CacheScope scope, Class<?>[] parameterTypes, Object[] arguments) {
// boolean isFirst = true;
// if (key.indexOf("{") > 0) {
// key = key.replace("{", ":{");
// Pattern pattern = Pattern.compile("\\d+(\\.?[\\w]+)*");
// Matcher matcher = pattern.matcher(key);
// while (matcher.find()) {
// String tmp = matcher.group();
// String express[] = matcher.group().split("\\.");
// String i = express[0];
// int index = Integer.parseInt(i) - 1;
// Object value = arguments[index];
// if (parameterTypes[index].isAssignableFrom(List.class)) {
// List result = (List) arguments[index];
// value = result.get(0);
// }
// if (value == null || value.equals("null"))
// value = "";
// if (express.length > 1) {
// for (int idx = 1; idx < express.length; idx ++) {
// String field = express[idx];
// value = ReflectionUtils.getFieldValue(value, field);
// }
// }
// if (isFirst) {
// key = key.replace("{" + tmp + "}", value.toString());
// } else {
// key = key.replace("{" + tmp + "}", LINK + value.toString());
// }
// }
// }
// if (CacheScope.user.equals(scope) && StringUtils.isNotBlank(redisConfig.getUserKey())){
// ServletRequestAttributes servletContainer = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
// HttpServletRequest request = servletContainer.getRequest();
// String accessToken = request.getHeader(redisConfig.getUserKey());
// if(StringUtils.isBlank(accessToken)){
// accessToken = WebUtil.getCookieValue(request,redisConfig.getUserKey());
// }
// if (StringUtils.isNotBlank(accessToken)){
// key = key + accessToken;
// }
// }
// return key;
// }
//
// @Override
// public IUserKeyGenerator getUserKeyGenerator() {
// return userKeyGenerator;
// }
//
// }
// Path: src/main/java/com/ace/cache/aspect/KeyGenerateService.java
import com.ace.cache.annotation.Cache;
import com.ace.cache.annotation.CacheGlobalLock;
import com.ace.cache.parser.IKeyGenerator;
import com.ace.cache.parser.impl.DefaultKeyGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.concurrent.ConcurrentHashMap;
package com.ace.cache.aspect;
@Service
@Slf4j
public class KeyGenerateService {
@Autowired
private IKeyGenerator keyParser;
private ConcurrentHashMap<String, IKeyGenerator> generatorMap = new ConcurrentHashMap<String, IKeyGenerator>();
/**
* 解析表达式
*
* @param anno
* @param parameterTypes
* @param arguments
* @return
* @throws InstantiationException
* @throws IllegalAccessException
*/
public String getKey(Cache anno, Class<?>[] parameterTypes,
Object[] arguments) throws InstantiationException,
IllegalAccessException {
String key;
String generatorClsName = anno.generator().getName();
IKeyGenerator keyGenerator = null; | if (anno.generator().equals(DefaultKeyGenerator.class)) { |
wxiaoqi/ace-cache | src/main/java/com/ace/cache/annotation/CacheGlobalLock.java | // Path: src/main/java/com/ace/cache/constants/CacheScope.java
// public enum CacheScope {
// user, application
// }
//
// Path: src/main/java/com/ace/cache/parser/IKeyGenerator.java
// public abstract class IKeyGenerator {
// public static final String LINK = "_";
//
// /**
// * 获取动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public String getKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments) {
// StringBuffer sb = new StringBuffer("");
// key = buildKey(key, scope, parameterTypes, arguments);
// sb.append(key);
// if (CacheScope.user.equals(scope)) {
// if (getUserKeyGenerator() != null)
// sb.append(LINK)
// .append(getUserKeyGenerator().getCurrentUserAccount());
// }
// return sb.toString();
// }
//
// /**
// * 当前登陆人key
// *
// * @param userKeyGenerator
// */
// public abstract IUserKeyGenerator getUserKeyGenerator();
//
// /**
// * 生成动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public abstract String buildKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments);
// }
//
// Path: src/main/java/com/ace/cache/parser/impl/DefaultKeyGenerator.java
// @Service
// public class DefaultKeyGenerator extends IKeyGenerator {
// @Autowired
// RedisConfig redisConfig;
//
// @Autowired(required = false)
// private IUserKeyGenerator userKeyGenerator;
//
// @Override
// public String buildKey(String key, CacheScope scope, Class<?>[] parameterTypes, Object[] arguments) {
// boolean isFirst = true;
// if (key.indexOf("{") > 0) {
// key = key.replace("{", ":{");
// Pattern pattern = Pattern.compile("\\d+(\\.?[\\w]+)*");
// Matcher matcher = pattern.matcher(key);
// while (matcher.find()) {
// String tmp = matcher.group();
// String express[] = matcher.group().split("\\.");
// String i = express[0];
// int index = Integer.parseInt(i) - 1;
// Object value = arguments[index];
// if (parameterTypes[index].isAssignableFrom(List.class)) {
// List result = (List) arguments[index];
// value = result.get(0);
// }
// if (value == null || value.equals("null"))
// value = "";
// if (express.length > 1) {
// for (int idx = 1; idx < express.length; idx ++) {
// String field = express[idx];
// value = ReflectionUtils.getFieldValue(value, field);
// }
// }
// if (isFirst) {
// key = key.replace("{" + tmp + "}", value.toString());
// } else {
// key = key.replace("{" + tmp + "}", LINK + value.toString());
// }
// }
// }
// if (CacheScope.user.equals(scope) && StringUtils.isNotBlank(redisConfig.getUserKey())){
// ServletRequestAttributes servletContainer = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
// HttpServletRequest request = servletContainer.getRequest();
// String accessToken = request.getHeader(redisConfig.getUserKey());
// if(StringUtils.isBlank(accessToken)){
// accessToken = WebUtil.getCookieValue(request,redisConfig.getUserKey());
// }
// if (StringUtils.isNotBlank(accessToken)){
// key = key + accessToken;
// }
// }
// return key;
// }
//
// @Override
// public IUserKeyGenerator getUserKeyGenerator() {
// return userKeyGenerator;
// }
//
// }
| import com.ace.cache.constants.CacheScope;
import com.ace.cache.parser.IKeyGenerator;
import com.ace.cache.parser.impl.DefaultKeyGenerator;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; | package com.ace.cache.annotation;
/**
* 全局锁(基于redis缓存)
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD, ElementType.TYPE})
public @interface CacheGlobalLock {
public String key() default "";
/**
* 过期时间(单位分钟)
*/
public int expire() default 60;
/**
* 重试加锁时间间隔(单位ms)
* @return
*/
public int retry() default 5000;
/**
* 是否一直等待全局锁? 默认为否,获取不到锁则不执行程序。
*/
public boolean waitLock() default false;
/**
* 作用域
*
* @return
* @author Ace
* @date 2017年5月3日
*/ | // Path: src/main/java/com/ace/cache/constants/CacheScope.java
// public enum CacheScope {
// user, application
// }
//
// Path: src/main/java/com/ace/cache/parser/IKeyGenerator.java
// public abstract class IKeyGenerator {
// public static final String LINK = "_";
//
// /**
// * 获取动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public String getKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments) {
// StringBuffer sb = new StringBuffer("");
// key = buildKey(key, scope, parameterTypes, arguments);
// sb.append(key);
// if (CacheScope.user.equals(scope)) {
// if (getUserKeyGenerator() != null)
// sb.append(LINK)
// .append(getUserKeyGenerator().getCurrentUserAccount());
// }
// return sb.toString();
// }
//
// /**
// * 当前登陆人key
// *
// * @param userKeyGenerator
// */
// public abstract IUserKeyGenerator getUserKeyGenerator();
//
// /**
// * 生成动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public abstract String buildKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments);
// }
//
// Path: src/main/java/com/ace/cache/parser/impl/DefaultKeyGenerator.java
// @Service
// public class DefaultKeyGenerator extends IKeyGenerator {
// @Autowired
// RedisConfig redisConfig;
//
// @Autowired(required = false)
// private IUserKeyGenerator userKeyGenerator;
//
// @Override
// public String buildKey(String key, CacheScope scope, Class<?>[] parameterTypes, Object[] arguments) {
// boolean isFirst = true;
// if (key.indexOf("{") > 0) {
// key = key.replace("{", ":{");
// Pattern pattern = Pattern.compile("\\d+(\\.?[\\w]+)*");
// Matcher matcher = pattern.matcher(key);
// while (matcher.find()) {
// String tmp = matcher.group();
// String express[] = matcher.group().split("\\.");
// String i = express[0];
// int index = Integer.parseInt(i) - 1;
// Object value = arguments[index];
// if (parameterTypes[index].isAssignableFrom(List.class)) {
// List result = (List) arguments[index];
// value = result.get(0);
// }
// if (value == null || value.equals("null"))
// value = "";
// if (express.length > 1) {
// for (int idx = 1; idx < express.length; idx ++) {
// String field = express[idx];
// value = ReflectionUtils.getFieldValue(value, field);
// }
// }
// if (isFirst) {
// key = key.replace("{" + tmp + "}", value.toString());
// } else {
// key = key.replace("{" + tmp + "}", LINK + value.toString());
// }
// }
// }
// if (CacheScope.user.equals(scope) && StringUtils.isNotBlank(redisConfig.getUserKey())){
// ServletRequestAttributes servletContainer = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
// HttpServletRequest request = servletContainer.getRequest();
// String accessToken = request.getHeader(redisConfig.getUserKey());
// if(StringUtils.isBlank(accessToken)){
// accessToken = WebUtil.getCookieValue(request,redisConfig.getUserKey());
// }
// if (StringUtils.isNotBlank(accessToken)){
// key = key + accessToken;
// }
// }
// return key;
// }
//
// @Override
// public IUserKeyGenerator getUserKeyGenerator() {
// return userKeyGenerator;
// }
//
// }
// Path: src/main/java/com/ace/cache/annotation/CacheGlobalLock.java
import com.ace.cache.constants.CacheScope;
import com.ace.cache.parser.IKeyGenerator;
import com.ace.cache.parser.impl.DefaultKeyGenerator;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
package com.ace.cache.annotation;
/**
* 全局锁(基于redis缓存)
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD, ElementType.TYPE})
public @interface CacheGlobalLock {
public String key() default "";
/**
* 过期时间(单位分钟)
*/
public int expire() default 60;
/**
* 重试加锁时间间隔(单位ms)
* @return
*/
public int retry() default 5000;
/**
* 是否一直等待全局锁? 默认为否,获取不到锁则不执行程序。
*/
public boolean waitLock() default false;
/**
* 作用域
*
* @return
* @author Ace
* @date 2017年5月3日
*/ | public CacheScope scope() default CacheScope.application; |
wxiaoqi/ace-cache | src/main/java/com/ace/cache/annotation/CacheGlobalLock.java | // Path: src/main/java/com/ace/cache/constants/CacheScope.java
// public enum CacheScope {
// user, application
// }
//
// Path: src/main/java/com/ace/cache/parser/IKeyGenerator.java
// public abstract class IKeyGenerator {
// public static final String LINK = "_";
//
// /**
// * 获取动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public String getKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments) {
// StringBuffer sb = new StringBuffer("");
// key = buildKey(key, scope, parameterTypes, arguments);
// sb.append(key);
// if (CacheScope.user.equals(scope)) {
// if (getUserKeyGenerator() != null)
// sb.append(LINK)
// .append(getUserKeyGenerator().getCurrentUserAccount());
// }
// return sb.toString();
// }
//
// /**
// * 当前登陆人key
// *
// * @param userKeyGenerator
// */
// public abstract IUserKeyGenerator getUserKeyGenerator();
//
// /**
// * 生成动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public abstract String buildKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments);
// }
//
// Path: src/main/java/com/ace/cache/parser/impl/DefaultKeyGenerator.java
// @Service
// public class DefaultKeyGenerator extends IKeyGenerator {
// @Autowired
// RedisConfig redisConfig;
//
// @Autowired(required = false)
// private IUserKeyGenerator userKeyGenerator;
//
// @Override
// public String buildKey(String key, CacheScope scope, Class<?>[] parameterTypes, Object[] arguments) {
// boolean isFirst = true;
// if (key.indexOf("{") > 0) {
// key = key.replace("{", ":{");
// Pattern pattern = Pattern.compile("\\d+(\\.?[\\w]+)*");
// Matcher matcher = pattern.matcher(key);
// while (matcher.find()) {
// String tmp = matcher.group();
// String express[] = matcher.group().split("\\.");
// String i = express[0];
// int index = Integer.parseInt(i) - 1;
// Object value = arguments[index];
// if (parameterTypes[index].isAssignableFrom(List.class)) {
// List result = (List) arguments[index];
// value = result.get(0);
// }
// if (value == null || value.equals("null"))
// value = "";
// if (express.length > 1) {
// for (int idx = 1; idx < express.length; idx ++) {
// String field = express[idx];
// value = ReflectionUtils.getFieldValue(value, field);
// }
// }
// if (isFirst) {
// key = key.replace("{" + tmp + "}", value.toString());
// } else {
// key = key.replace("{" + tmp + "}", LINK + value.toString());
// }
// }
// }
// if (CacheScope.user.equals(scope) && StringUtils.isNotBlank(redisConfig.getUserKey())){
// ServletRequestAttributes servletContainer = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
// HttpServletRequest request = servletContainer.getRequest();
// String accessToken = request.getHeader(redisConfig.getUserKey());
// if(StringUtils.isBlank(accessToken)){
// accessToken = WebUtil.getCookieValue(request,redisConfig.getUserKey());
// }
// if (StringUtils.isNotBlank(accessToken)){
// key = key + accessToken;
// }
// }
// return key;
// }
//
// @Override
// public IUserKeyGenerator getUserKeyGenerator() {
// return userKeyGenerator;
// }
//
// }
| import com.ace.cache.constants.CacheScope;
import com.ace.cache.parser.IKeyGenerator;
import com.ace.cache.parser.impl.DefaultKeyGenerator;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; | package com.ace.cache.annotation;
/**
* 全局锁(基于redis缓存)
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD, ElementType.TYPE})
public @interface CacheGlobalLock {
public String key() default "";
/**
* 过期时间(单位分钟)
*/
public int expire() default 60;
/**
* 重试加锁时间间隔(单位ms)
* @return
*/
public int retry() default 5000;
/**
* 是否一直等待全局锁? 默认为否,获取不到锁则不执行程序。
*/
public boolean waitLock() default false;
/**
* 作用域
*
* @return
* @author Ace
* @date 2017年5月3日
*/
public CacheScope scope() default CacheScope.application;
/**
* 键值解析类
*
* @return
*/ | // Path: src/main/java/com/ace/cache/constants/CacheScope.java
// public enum CacheScope {
// user, application
// }
//
// Path: src/main/java/com/ace/cache/parser/IKeyGenerator.java
// public abstract class IKeyGenerator {
// public static final String LINK = "_";
//
// /**
// * 获取动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public String getKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments) {
// StringBuffer sb = new StringBuffer("");
// key = buildKey(key, scope, parameterTypes, arguments);
// sb.append(key);
// if (CacheScope.user.equals(scope)) {
// if (getUserKeyGenerator() != null)
// sb.append(LINK)
// .append(getUserKeyGenerator().getCurrentUserAccount());
// }
// return sb.toString();
// }
//
// /**
// * 当前登陆人key
// *
// * @param userKeyGenerator
// */
// public abstract IUserKeyGenerator getUserKeyGenerator();
//
// /**
// * 生成动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public abstract String buildKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments);
// }
//
// Path: src/main/java/com/ace/cache/parser/impl/DefaultKeyGenerator.java
// @Service
// public class DefaultKeyGenerator extends IKeyGenerator {
// @Autowired
// RedisConfig redisConfig;
//
// @Autowired(required = false)
// private IUserKeyGenerator userKeyGenerator;
//
// @Override
// public String buildKey(String key, CacheScope scope, Class<?>[] parameterTypes, Object[] arguments) {
// boolean isFirst = true;
// if (key.indexOf("{") > 0) {
// key = key.replace("{", ":{");
// Pattern pattern = Pattern.compile("\\d+(\\.?[\\w]+)*");
// Matcher matcher = pattern.matcher(key);
// while (matcher.find()) {
// String tmp = matcher.group();
// String express[] = matcher.group().split("\\.");
// String i = express[0];
// int index = Integer.parseInt(i) - 1;
// Object value = arguments[index];
// if (parameterTypes[index].isAssignableFrom(List.class)) {
// List result = (List) arguments[index];
// value = result.get(0);
// }
// if (value == null || value.equals("null"))
// value = "";
// if (express.length > 1) {
// for (int idx = 1; idx < express.length; idx ++) {
// String field = express[idx];
// value = ReflectionUtils.getFieldValue(value, field);
// }
// }
// if (isFirst) {
// key = key.replace("{" + tmp + "}", value.toString());
// } else {
// key = key.replace("{" + tmp + "}", LINK + value.toString());
// }
// }
// }
// if (CacheScope.user.equals(scope) && StringUtils.isNotBlank(redisConfig.getUserKey())){
// ServletRequestAttributes servletContainer = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
// HttpServletRequest request = servletContainer.getRequest();
// String accessToken = request.getHeader(redisConfig.getUserKey());
// if(StringUtils.isBlank(accessToken)){
// accessToken = WebUtil.getCookieValue(request,redisConfig.getUserKey());
// }
// if (StringUtils.isNotBlank(accessToken)){
// key = key + accessToken;
// }
// }
// return key;
// }
//
// @Override
// public IUserKeyGenerator getUserKeyGenerator() {
// return userKeyGenerator;
// }
//
// }
// Path: src/main/java/com/ace/cache/annotation/CacheGlobalLock.java
import com.ace.cache.constants.CacheScope;
import com.ace.cache.parser.IKeyGenerator;
import com.ace.cache.parser.impl.DefaultKeyGenerator;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
package com.ace.cache.annotation;
/**
* 全局锁(基于redis缓存)
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD, ElementType.TYPE})
public @interface CacheGlobalLock {
public String key() default "";
/**
* 过期时间(单位分钟)
*/
public int expire() default 60;
/**
* 重试加锁时间间隔(单位ms)
* @return
*/
public int retry() default 5000;
/**
* 是否一直等待全局锁? 默认为否,获取不到锁则不执行程序。
*/
public boolean waitLock() default false;
/**
* 作用域
*
* @return
* @author Ace
* @date 2017年5月3日
*/
public CacheScope scope() default CacheScope.application;
/**
* 键值解析类
*
* @return
*/ | public Class<? extends IKeyGenerator> generator() default DefaultKeyGenerator.class; |
wxiaoqi/ace-cache | src/main/java/com/ace/cache/annotation/CacheGlobalLock.java | // Path: src/main/java/com/ace/cache/constants/CacheScope.java
// public enum CacheScope {
// user, application
// }
//
// Path: src/main/java/com/ace/cache/parser/IKeyGenerator.java
// public abstract class IKeyGenerator {
// public static final String LINK = "_";
//
// /**
// * 获取动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public String getKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments) {
// StringBuffer sb = new StringBuffer("");
// key = buildKey(key, scope, parameterTypes, arguments);
// sb.append(key);
// if (CacheScope.user.equals(scope)) {
// if (getUserKeyGenerator() != null)
// sb.append(LINK)
// .append(getUserKeyGenerator().getCurrentUserAccount());
// }
// return sb.toString();
// }
//
// /**
// * 当前登陆人key
// *
// * @param userKeyGenerator
// */
// public abstract IUserKeyGenerator getUserKeyGenerator();
//
// /**
// * 生成动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public abstract String buildKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments);
// }
//
// Path: src/main/java/com/ace/cache/parser/impl/DefaultKeyGenerator.java
// @Service
// public class DefaultKeyGenerator extends IKeyGenerator {
// @Autowired
// RedisConfig redisConfig;
//
// @Autowired(required = false)
// private IUserKeyGenerator userKeyGenerator;
//
// @Override
// public String buildKey(String key, CacheScope scope, Class<?>[] parameterTypes, Object[] arguments) {
// boolean isFirst = true;
// if (key.indexOf("{") > 0) {
// key = key.replace("{", ":{");
// Pattern pattern = Pattern.compile("\\d+(\\.?[\\w]+)*");
// Matcher matcher = pattern.matcher(key);
// while (matcher.find()) {
// String tmp = matcher.group();
// String express[] = matcher.group().split("\\.");
// String i = express[0];
// int index = Integer.parseInt(i) - 1;
// Object value = arguments[index];
// if (parameterTypes[index].isAssignableFrom(List.class)) {
// List result = (List) arguments[index];
// value = result.get(0);
// }
// if (value == null || value.equals("null"))
// value = "";
// if (express.length > 1) {
// for (int idx = 1; idx < express.length; idx ++) {
// String field = express[idx];
// value = ReflectionUtils.getFieldValue(value, field);
// }
// }
// if (isFirst) {
// key = key.replace("{" + tmp + "}", value.toString());
// } else {
// key = key.replace("{" + tmp + "}", LINK + value.toString());
// }
// }
// }
// if (CacheScope.user.equals(scope) && StringUtils.isNotBlank(redisConfig.getUserKey())){
// ServletRequestAttributes servletContainer = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
// HttpServletRequest request = servletContainer.getRequest();
// String accessToken = request.getHeader(redisConfig.getUserKey());
// if(StringUtils.isBlank(accessToken)){
// accessToken = WebUtil.getCookieValue(request,redisConfig.getUserKey());
// }
// if (StringUtils.isNotBlank(accessToken)){
// key = key + accessToken;
// }
// }
// return key;
// }
//
// @Override
// public IUserKeyGenerator getUserKeyGenerator() {
// return userKeyGenerator;
// }
//
// }
| import com.ace.cache.constants.CacheScope;
import com.ace.cache.parser.IKeyGenerator;
import com.ace.cache.parser.impl.DefaultKeyGenerator;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; | package com.ace.cache.annotation;
/**
* 全局锁(基于redis缓存)
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD, ElementType.TYPE})
public @interface CacheGlobalLock {
public String key() default "";
/**
* 过期时间(单位分钟)
*/
public int expire() default 60;
/**
* 重试加锁时间间隔(单位ms)
* @return
*/
public int retry() default 5000;
/**
* 是否一直等待全局锁? 默认为否,获取不到锁则不执行程序。
*/
public boolean waitLock() default false;
/**
* 作用域
*
* @return
* @author Ace
* @date 2017年5月3日
*/
public CacheScope scope() default CacheScope.application;
/**
* 键值解析类
*
* @return
*/ | // Path: src/main/java/com/ace/cache/constants/CacheScope.java
// public enum CacheScope {
// user, application
// }
//
// Path: src/main/java/com/ace/cache/parser/IKeyGenerator.java
// public abstract class IKeyGenerator {
// public static final String LINK = "_";
//
// /**
// * 获取动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public String getKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments) {
// StringBuffer sb = new StringBuffer("");
// key = buildKey(key, scope, parameterTypes, arguments);
// sb.append(key);
// if (CacheScope.user.equals(scope)) {
// if (getUserKeyGenerator() != null)
// sb.append(LINK)
// .append(getUserKeyGenerator().getCurrentUserAccount());
// }
// return sb.toString();
// }
//
// /**
// * 当前登陆人key
// *
// * @param userKeyGenerator
// */
// public abstract IUserKeyGenerator getUserKeyGenerator();
//
// /**
// * 生成动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public abstract String buildKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments);
// }
//
// Path: src/main/java/com/ace/cache/parser/impl/DefaultKeyGenerator.java
// @Service
// public class DefaultKeyGenerator extends IKeyGenerator {
// @Autowired
// RedisConfig redisConfig;
//
// @Autowired(required = false)
// private IUserKeyGenerator userKeyGenerator;
//
// @Override
// public String buildKey(String key, CacheScope scope, Class<?>[] parameterTypes, Object[] arguments) {
// boolean isFirst = true;
// if (key.indexOf("{") > 0) {
// key = key.replace("{", ":{");
// Pattern pattern = Pattern.compile("\\d+(\\.?[\\w]+)*");
// Matcher matcher = pattern.matcher(key);
// while (matcher.find()) {
// String tmp = matcher.group();
// String express[] = matcher.group().split("\\.");
// String i = express[0];
// int index = Integer.parseInt(i) - 1;
// Object value = arguments[index];
// if (parameterTypes[index].isAssignableFrom(List.class)) {
// List result = (List) arguments[index];
// value = result.get(0);
// }
// if (value == null || value.equals("null"))
// value = "";
// if (express.length > 1) {
// for (int idx = 1; idx < express.length; idx ++) {
// String field = express[idx];
// value = ReflectionUtils.getFieldValue(value, field);
// }
// }
// if (isFirst) {
// key = key.replace("{" + tmp + "}", value.toString());
// } else {
// key = key.replace("{" + tmp + "}", LINK + value.toString());
// }
// }
// }
// if (CacheScope.user.equals(scope) && StringUtils.isNotBlank(redisConfig.getUserKey())){
// ServletRequestAttributes servletContainer = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
// HttpServletRequest request = servletContainer.getRequest();
// String accessToken = request.getHeader(redisConfig.getUserKey());
// if(StringUtils.isBlank(accessToken)){
// accessToken = WebUtil.getCookieValue(request,redisConfig.getUserKey());
// }
// if (StringUtils.isNotBlank(accessToken)){
// key = key + accessToken;
// }
// }
// return key;
// }
//
// @Override
// public IUserKeyGenerator getUserKeyGenerator() {
// return userKeyGenerator;
// }
//
// }
// Path: src/main/java/com/ace/cache/annotation/CacheGlobalLock.java
import com.ace.cache.constants.CacheScope;
import com.ace.cache.parser.IKeyGenerator;
import com.ace.cache.parser.impl.DefaultKeyGenerator;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
package com.ace.cache.annotation;
/**
* 全局锁(基于redis缓存)
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD, ElementType.TYPE})
public @interface CacheGlobalLock {
public String key() default "";
/**
* 过期时间(单位分钟)
*/
public int expire() default 60;
/**
* 重试加锁时间间隔(单位ms)
* @return
*/
public int retry() default 5000;
/**
* 是否一直等待全局锁? 默认为否,获取不到锁则不执行程序。
*/
public boolean waitLock() default false;
/**
* 作用域
*
* @return
* @author Ace
* @date 2017年5月3日
*/
public CacheScope scope() default CacheScope.application;
/**
* 键值解析类
*
* @return
*/ | public Class<? extends IKeyGenerator> generator() default DefaultKeyGenerator.class; |
wxiaoqi/ace-cache | src/main/java/com/ace/cache/rest/CacheRest.java | // Path: src/main/java/com/ace/cache/service/ICacheManager.java
// public interface ICacheManager {
// public void removeAll();
//
// public void remove(String key);
//
// public void remove(List<CacheBean> caches);
//
// public void removeByPre(String pre);
//
// public List<CacheTree> getAll();
//
// public List<CacheTree> getByPre(String pre);
//
// public void update(String key, int hour);
//
// public void update(List<CacheBean> caches, int hour);
//
// public String get(String key);
// }
//
// Path: src/main/java/com/ace/cache/utils/TreeUtils.java
// public class TreeUtils {
// public static List<CacheTree> buildTree(List<CacheTree> trees) {
// List<CacheTree> list = new ArrayList<CacheTree>();
// for (CacheTree tree : trees) {
// if (tree.getParentId().equals("-1")) {
// list.add(tree);
// }
// for (CacheTree t : trees) {
// if (t.getParentId().equals(tree.getId())) {
// if (tree.getNodes() == null) {
// List<CacheTree> myChildrens = new ArrayList<CacheTree>();
// myChildrens.add(t);
// tree.setNodes(myChildrens);
// } else {
// tree.getNodes().add(t);
// }
// }
// }
// }
// return list;
// }
//
// }
//
// Path: src/main/java/com/ace/cache/vo/CacheTree.java
// public class CacheTree extends CacheBean {
// private String id;
// private String parentId;
// private String text = null;
// private List<CacheTree> nodes = new ArrayList<CacheTree>();
//
// public CacheTree(CacheBean cache) {
// this.setKey(cache.getKey());
// this.setDesc(cache.getDesc());
// this.setExpireTime(cache.getExpireTime());
// }
//
// public CacheTree() {
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.text = id;
// this.id = id;
// }
//
// public String getParentId() {
// return parentId;
// }
//
// public void setParentId(String parentId) {
// this.parentId = parentId;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((id == null) ? 0 : id.hashCode());
// result = prime * result + ((parentId == null) ? 0 : parentId.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// CacheTree other = (CacheTree) obj;
// if (id == null) {
// if (other.id != null)
// return false;
// } else if (!id.equals(other.id))
// return false;
// if (parentId == null) {
// if (other.parentId != null)
// return false;
// } else if (!parentId.equals(other.parentId))
// return false;
// return true;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// public List<CacheTree> getNodes() {
// return nodes;
// }
//
// public void setNodes(List<CacheTree> nodes) {
// this.nodes = nodes;
// }
//
// }
| import com.ace.cache.service.ICacheManager;
import com.ace.cache.utils.TreeUtils;
import com.ace.cache.vo.CacheTree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List; | package com.ace.cache.rest;
@RestController
@RequestMapping("cache")
public class CacheRest {
@Autowired | // Path: src/main/java/com/ace/cache/service/ICacheManager.java
// public interface ICacheManager {
// public void removeAll();
//
// public void remove(String key);
//
// public void remove(List<CacheBean> caches);
//
// public void removeByPre(String pre);
//
// public List<CacheTree> getAll();
//
// public List<CacheTree> getByPre(String pre);
//
// public void update(String key, int hour);
//
// public void update(List<CacheBean> caches, int hour);
//
// public String get(String key);
// }
//
// Path: src/main/java/com/ace/cache/utils/TreeUtils.java
// public class TreeUtils {
// public static List<CacheTree> buildTree(List<CacheTree> trees) {
// List<CacheTree> list = new ArrayList<CacheTree>();
// for (CacheTree tree : trees) {
// if (tree.getParentId().equals("-1")) {
// list.add(tree);
// }
// for (CacheTree t : trees) {
// if (t.getParentId().equals(tree.getId())) {
// if (tree.getNodes() == null) {
// List<CacheTree> myChildrens = new ArrayList<CacheTree>();
// myChildrens.add(t);
// tree.setNodes(myChildrens);
// } else {
// tree.getNodes().add(t);
// }
// }
// }
// }
// return list;
// }
//
// }
//
// Path: src/main/java/com/ace/cache/vo/CacheTree.java
// public class CacheTree extends CacheBean {
// private String id;
// private String parentId;
// private String text = null;
// private List<CacheTree> nodes = new ArrayList<CacheTree>();
//
// public CacheTree(CacheBean cache) {
// this.setKey(cache.getKey());
// this.setDesc(cache.getDesc());
// this.setExpireTime(cache.getExpireTime());
// }
//
// public CacheTree() {
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.text = id;
// this.id = id;
// }
//
// public String getParentId() {
// return parentId;
// }
//
// public void setParentId(String parentId) {
// this.parentId = parentId;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((id == null) ? 0 : id.hashCode());
// result = prime * result + ((parentId == null) ? 0 : parentId.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// CacheTree other = (CacheTree) obj;
// if (id == null) {
// if (other.id != null)
// return false;
// } else if (!id.equals(other.id))
// return false;
// if (parentId == null) {
// if (other.parentId != null)
// return false;
// } else if (!parentId.equals(other.parentId))
// return false;
// return true;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// public List<CacheTree> getNodes() {
// return nodes;
// }
//
// public void setNodes(List<CacheTree> nodes) {
// this.nodes = nodes;
// }
//
// }
// Path: src/main/java/com/ace/cache/rest/CacheRest.java
import com.ace.cache.service.ICacheManager;
import com.ace.cache.utils.TreeUtils;
import com.ace.cache.vo.CacheTree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
package com.ace.cache.rest;
@RestController
@RequestMapping("cache")
public class CacheRest {
@Autowired | private ICacheManager cacheManager; |
wxiaoqi/ace-cache | src/main/java/com/ace/cache/rest/CacheRest.java | // Path: src/main/java/com/ace/cache/service/ICacheManager.java
// public interface ICacheManager {
// public void removeAll();
//
// public void remove(String key);
//
// public void remove(List<CacheBean> caches);
//
// public void removeByPre(String pre);
//
// public List<CacheTree> getAll();
//
// public List<CacheTree> getByPre(String pre);
//
// public void update(String key, int hour);
//
// public void update(List<CacheBean> caches, int hour);
//
// public String get(String key);
// }
//
// Path: src/main/java/com/ace/cache/utils/TreeUtils.java
// public class TreeUtils {
// public static List<CacheTree> buildTree(List<CacheTree> trees) {
// List<CacheTree> list = new ArrayList<CacheTree>();
// for (CacheTree tree : trees) {
// if (tree.getParentId().equals("-1")) {
// list.add(tree);
// }
// for (CacheTree t : trees) {
// if (t.getParentId().equals(tree.getId())) {
// if (tree.getNodes() == null) {
// List<CacheTree> myChildrens = new ArrayList<CacheTree>();
// myChildrens.add(t);
// tree.setNodes(myChildrens);
// } else {
// tree.getNodes().add(t);
// }
// }
// }
// }
// return list;
// }
//
// }
//
// Path: src/main/java/com/ace/cache/vo/CacheTree.java
// public class CacheTree extends CacheBean {
// private String id;
// private String parentId;
// private String text = null;
// private List<CacheTree> nodes = new ArrayList<CacheTree>();
//
// public CacheTree(CacheBean cache) {
// this.setKey(cache.getKey());
// this.setDesc(cache.getDesc());
// this.setExpireTime(cache.getExpireTime());
// }
//
// public CacheTree() {
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.text = id;
// this.id = id;
// }
//
// public String getParentId() {
// return parentId;
// }
//
// public void setParentId(String parentId) {
// this.parentId = parentId;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((id == null) ? 0 : id.hashCode());
// result = prime * result + ((parentId == null) ? 0 : parentId.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// CacheTree other = (CacheTree) obj;
// if (id == null) {
// if (other.id != null)
// return false;
// } else if (!id.equals(other.id))
// return false;
// if (parentId == null) {
// if (other.parentId != null)
// return false;
// } else if (!parentId.equals(other.parentId))
// return false;
// return true;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// public List<CacheTree> getNodes() {
// return nodes;
// }
//
// public void setNodes(List<CacheTree> nodes) {
// this.nodes = nodes;
// }
//
// }
| import com.ace.cache.service.ICacheManager;
import com.ace.cache.utils.TreeUtils;
import com.ace.cache.vo.CacheTree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List; | package com.ace.cache.rest;
@RestController
@RequestMapping("cache")
public class CacheRest {
@Autowired
private ICacheManager cacheManager;
@RequestMapping("/list") | // Path: src/main/java/com/ace/cache/service/ICacheManager.java
// public interface ICacheManager {
// public void removeAll();
//
// public void remove(String key);
//
// public void remove(List<CacheBean> caches);
//
// public void removeByPre(String pre);
//
// public List<CacheTree> getAll();
//
// public List<CacheTree> getByPre(String pre);
//
// public void update(String key, int hour);
//
// public void update(List<CacheBean> caches, int hour);
//
// public String get(String key);
// }
//
// Path: src/main/java/com/ace/cache/utils/TreeUtils.java
// public class TreeUtils {
// public static List<CacheTree> buildTree(List<CacheTree> trees) {
// List<CacheTree> list = new ArrayList<CacheTree>();
// for (CacheTree tree : trees) {
// if (tree.getParentId().equals("-1")) {
// list.add(tree);
// }
// for (CacheTree t : trees) {
// if (t.getParentId().equals(tree.getId())) {
// if (tree.getNodes() == null) {
// List<CacheTree> myChildrens = new ArrayList<CacheTree>();
// myChildrens.add(t);
// tree.setNodes(myChildrens);
// } else {
// tree.getNodes().add(t);
// }
// }
// }
// }
// return list;
// }
//
// }
//
// Path: src/main/java/com/ace/cache/vo/CacheTree.java
// public class CacheTree extends CacheBean {
// private String id;
// private String parentId;
// private String text = null;
// private List<CacheTree> nodes = new ArrayList<CacheTree>();
//
// public CacheTree(CacheBean cache) {
// this.setKey(cache.getKey());
// this.setDesc(cache.getDesc());
// this.setExpireTime(cache.getExpireTime());
// }
//
// public CacheTree() {
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.text = id;
// this.id = id;
// }
//
// public String getParentId() {
// return parentId;
// }
//
// public void setParentId(String parentId) {
// this.parentId = parentId;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((id == null) ? 0 : id.hashCode());
// result = prime * result + ((parentId == null) ? 0 : parentId.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// CacheTree other = (CacheTree) obj;
// if (id == null) {
// if (other.id != null)
// return false;
// } else if (!id.equals(other.id))
// return false;
// if (parentId == null) {
// if (other.parentId != null)
// return false;
// } else if (!parentId.equals(other.parentId))
// return false;
// return true;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// public List<CacheTree> getNodes() {
// return nodes;
// }
//
// public void setNodes(List<CacheTree> nodes) {
// this.nodes = nodes;
// }
//
// }
// Path: src/main/java/com/ace/cache/rest/CacheRest.java
import com.ace.cache.service.ICacheManager;
import com.ace.cache.utils.TreeUtils;
import com.ace.cache.vo.CacheTree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
package com.ace.cache.rest;
@RestController
@RequestMapping("cache")
public class CacheRest {
@Autowired
private ICacheManager cacheManager;
@RequestMapping("/list") | public List<CacheTree> listAll() { |
wxiaoqi/ace-cache | src/main/java/com/ace/cache/rest/CacheRest.java | // Path: src/main/java/com/ace/cache/service/ICacheManager.java
// public interface ICacheManager {
// public void removeAll();
//
// public void remove(String key);
//
// public void remove(List<CacheBean> caches);
//
// public void removeByPre(String pre);
//
// public List<CacheTree> getAll();
//
// public List<CacheTree> getByPre(String pre);
//
// public void update(String key, int hour);
//
// public void update(List<CacheBean> caches, int hour);
//
// public String get(String key);
// }
//
// Path: src/main/java/com/ace/cache/utils/TreeUtils.java
// public class TreeUtils {
// public static List<CacheTree> buildTree(List<CacheTree> trees) {
// List<CacheTree> list = new ArrayList<CacheTree>();
// for (CacheTree tree : trees) {
// if (tree.getParentId().equals("-1")) {
// list.add(tree);
// }
// for (CacheTree t : trees) {
// if (t.getParentId().equals(tree.getId())) {
// if (tree.getNodes() == null) {
// List<CacheTree> myChildrens = new ArrayList<CacheTree>();
// myChildrens.add(t);
// tree.setNodes(myChildrens);
// } else {
// tree.getNodes().add(t);
// }
// }
// }
// }
// return list;
// }
//
// }
//
// Path: src/main/java/com/ace/cache/vo/CacheTree.java
// public class CacheTree extends CacheBean {
// private String id;
// private String parentId;
// private String text = null;
// private List<CacheTree> nodes = new ArrayList<CacheTree>();
//
// public CacheTree(CacheBean cache) {
// this.setKey(cache.getKey());
// this.setDesc(cache.getDesc());
// this.setExpireTime(cache.getExpireTime());
// }
//
// public CacheTree() {
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.text = id;
// this.id = id;
// }
//
// public String getParentId() {
// return parentId;
// }
//
// public void setParentId(String parentId) {
// this.parentId = parentId;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((id == null) ? 0 : id.hashCode());
// result = prime * result + ((parentId == null) ? 0 : parentId.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// CacheTree other = (CacheTree) obj;
// if (id == null) {
// if (other.id != null)
// return false;
// } else if (!id.equals(other.id))
// return false;
// if (parentId == null) {
// if (other.parentId != null)
// return false;
// } else if (!parentId.equals(other.parentId))
// return false;
// return true;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// public List<CacheTree> getNodes() {
// return nodes;
// }
//
// public void setNodes(List<CacheTree> nodes) {
// this.nodes = nodes;
// }
//
// }
| import com.ace.cache.service.ICacheManager;
import com.ace.cache.utils.TreeUtils;
import com.ace.cache.vo.CacheTree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List; | package com.ace.cache.rest;
@RestController
@RequestMapping("cache")
public class CacheRest {
@Autowired
private ICacheManager cacheManager;
@RequestMapping("/list")
public List<CacheTree> listAll() { | // Path: src/main/java/com/ace/cache/service/ICacheManager.java
// public interface ICacheManager {
// public void removeAll();
//
// public void remove(String key);
//
// public void remove(List<CacheBean> caches);
//
// public void removeByPre(String pre);
//
// public List<CacheTree> getAll();
//
// public List<CacheTree> getByPre(String pre);
//
// public void update(String key, int hour);
//
// public void update(List<CacheBean> caches, int hour);
//
// public String get(String key);
// }
//
// Path: src/main/java/com/ace/cache/utils/TreeUtils.java
// public class TreeUtils {
// public static List<CacheTree> buildTree(List<CacheTree> trees) {
// List<CacheTree> list = new ArrayList<CacheTree>();
// for (CacheTree tree : trees) {
// if (tree.getParentId().equals("-1")) {
// list.add(tree);
// }
// for (CacheTree t : trees) {
// if (t.getParentId().equals(tree.getId())) {
// if (tree.getNodes() == null) {
// List<CacheTree> myChildrens = new ArrayList<CacheTree>();
// myChildrens.add(t);
// tree.setNodes(myChildrens);
// } else {
// tree.getNodes().add(t);
// }
// }
// }
// }
// return list;
// }
//
// }
//
// Path: src/main/java/com/ace/cache/vo/CacheTree.java
// public class CacheTree extends CacheBean {
// private String id;
// private String parentId;
// private String text = null;
// private List<CacheTree> nodes = new ArrayList<CacheTree>();
//
// public CacheTree(CacheBean cache) {
// this.setKey(cache.getKey());
// this.setDesc(cache.getDesc());
// this.setExpireTime(cache.getExpireTime());
// }
//
// public CacheTree() {
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.text = id;
// this.id = id;
// }
//
// public String getParentId() {
// return parentId;
// }
//
// public void setParentId(String parentId) {
// this.parentId = parentId;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((id == null) ? 0 : id.hashCode());
// result = prime * result + ((parentId == null) ? 0 : parentId.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// CacheTree other = (CacheTree) obj;
// if (id == null) {
// if (other.id != null)
// return false;
// } else if (!id.equals(other.id))
// return false;
// if (parentId == null) {
// if (other.parentId != null)
// return false;
// } else if (!parentId.equals(other.parentId))
// return false;
// return true;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// public List<CacheTree> getNodes() {
// return nodes;
// }
//
// public void setNodes(List<CacheTree> nodes) {
// this.nodes = nodes;
// }
//
// }
// Path: src/main/java/com/ace/cache/rest/CacheRest.java
import com.ace.cache.service.ICacheManager;
import com.ace.cache.utils.TreeUtils;
import com.ace.cache.vo.CacheTree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
package com.ace.cache.rest;
@RestController
@RequestMapping("cache")
public class CacheRest {
@Autowired
private ICacheManager cacheManager;
@RequestMapping("/list")
public List<CacheTree> listAll() { | return TreeUtils.buildTree(cacheManager.getAll()); |
wxiaoqi/ace-cache | src/main/java/com/ace/cache/service/ICacheManager.java | // Path: src/main/java/com/ace/cache/vo/CacheTree.java
// public class CacheTree extends CacheBean {
// private String id;
// private String parentId;
// private String text = null;
// private List<CacheTree> nodes = new ArrayList<CacheTree>();
//
// public CacheTree(CacheBean cache) {
// this.setKey(cache.getKey());
// this.setDesc(cache.getDesc());
// this.setExpireTime(cache.getExpireTime());
// }
//
// public CacheTree() {
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.text = id;
// this.id = id;
// }
//
// public String getParentId() {
// return parentId;
// }
//
// public void setParentId(String parentId) {
// this.parentId = parentId;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((id == null) ? 0 : id.hashCode());
// result = prime * result + ((parentId == null) ? 0 : parentId.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// CacheTree other = (CacheTree) obj;
// if (id == null) {
// if (other.id != null)
// return false;
// } else if (!id.equals(other.id))
// return false;
// if (parentId == null) {
// if (other.parentId != null)
// return false;
// } else if (!parentId.equals(other.parentId))
// return false;
// return true;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// public List<CacheTree> getNodes() {
// return nodes;
// }
//
// public void setNodes(List<CacheTree> nodes) {
// this.nodes = nodes;
// }
//
// }
//
// Path: src/main/java/com/ace/cache/entity/CacheBean.java
// public class CacheBean {
// private String key = "";
// private String desc = "";
// @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
// private Date expireTime;
//
// public CacheBean(String key, String desc, Date expireTime) {
// this.key = key;
// this.desc = desc;
// this.expireTime = expireTime;
// }
//
// public CacheBean(String key, Date expireTime) {
// this.key = key;
// this.expireTime = expireTime;
// }
//
// public CacheBean() {
//
// }
//
// public String getKey() {
// return key;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getDesc() {
// return desc;
// }
//
// public void setDesc(String desc) {
// this.desc = desc;
// }
//
// public Date getExpireTime() {
// return expireTime;
// }
//
// public void setExpireTime(Date expireTime) {
// this.expireTime = expireTime;
// }
//
// }
| import com.ace.cache.entity.CacheBean;
import java.util.List;
import com.ace.cache.vo.CacheTree; | /**
*
*/
package com.ace.cache.service;
/**
* 解决问题:
*
* @author Ace
* @version 1.0
* @date 2017年5月3日
* @since 1.7
*/
public interface ICacheManager {
public void removeAll();
public void remove(String key);
| // Path: src/main/java/com/ace/cache/vo/CacheTree.java
// public class CacheTree extends CacheBean {
// private String id;
// private String parentId;
// private String text = null;
// private List<CacheTree> nodes = new ArrayList<CacheTree>();
//
// public CacheTree(CacheBean cache) {
// this.setKey(cache.getKey());
// this.setDesc(cache.getDesc());
// this.setExpireTime(cache.getExpireTime());
// }
//
// public CacheTree() {
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.text = id;
// this.id = id;
// }
//
// public String getParentId() {
// return parentId;
// }
//
// public void setParentId(String parentId) {
// this.parentId = parentId;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((id == null) ? 0 : id.hashCode());
// result = prime * result + ((parentId == null) ? 0 : parentId.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// CacheTree other = (CacheTree) obj;
// if (id == null) {
// if (other.id != null)
// return false;
// } else if (!id.equals(other.id))
// return false;
// if (parentId == null) {
// if (other.parentId != null)
// return false;
// } else if (!parentId.equals(other.parentId))
// return false;
// return true;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// public List<CacheTree> getNodes() {
// return nodes;
// }
//
// public void setNodes(List<CacheTree> nodes) {
// this.nodes = nodes;
// }
//
// }
//
// Path: src/main/java/com/ace/cache/entity/CacheBean.java
// public class CacheBean {
// private String key = "";
// private String desc = "";
// @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
// private Date expireTime;
//
// public CacheBean(String key, String desc, Date expireTime) {
// this.key = key;
// this.desc = desc;
// this.expireTime = expireTime;
// }
//
// public CacheBean(String key, Date expireTime) {
// this.key = key;
// this.expireTime = expireTime;
// }
//
// public CacheBean() {
//
// }
//
// public String getKey() {
// return key;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getDesc() {
// return desc;
// }
//
// public void setDesc(String desc) {
// this.desc = desc;
// }
//
// public Date getExpireTime() {
// return expireTime;
// }
//
// public void setExpireTime(Date expireTime) {
// this.expireTime = expireTime;
// }
//
// }
// Path: src/main/java/com/ace/cache/service/ICacheManager.java
import com.ace.cache.entity.CacheBean;
import java.util.List;
import com.ace.cache.vo.CacheTree;
/**
*
*/
package com.ace.cache.service;
/**
* 解决问题:
*
* @author Ace
* @version 1.0
* @date 2017年5月3日
* @since 1.7
*/
public interface ICacheManager {
public void removeAll();
public void remove(String key);
| public void remove(List<CacheBean> caches); |
wxiaoqi/ace-cache | src/main/java/com/ace/cache/service/ICacheManager.java | // Path: src/main/java/com/ace/cache/vo/CacheTree.java
// public class CacheTree extends CacheBean {
// private String id;
// private String parentId;
// private String text = null;
// private List<CacheTree> nodes = new ArrayList<CacheTree>();
//
// public CacheTree(CacheBean cache) {
// this.setKey(cache.getKey());
// this.setDesc(cache.getDesc());
// this.setExpireTime(cache.getExpireTime());
// }
//
// public CacheTree() {
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.text = id;
// this.id = id;
// }
//
// public String getParentId() {
// return parentId;
// }
//
// public void setParentId(String parentId) {
// this.parentId = parentId;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((id == null) ? 0 : id.hashCode());
// result = prime * result + ((parentId == null) ? 0 : parentId.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// CacheTree other = (CacheTree) obj;
// if (id == null) {
// if (other.id != null)
// return false;
// } else if (!id.equals(other.id))
// return false;
// if (parentId == null) {
// if (other.parentId != null)
// return false;
// } else if (!parentId.equals(other.parentId))
// return false;
// return true;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// public List<CacheTree> getNodes() {
// return nodes;
// }
//
// public void setNodes(List<CacheTree> nodes) {
// this.nodes = nodes;
// }
//
// }
//
// Path: src/main/java/com/ace/cache/entity/CacheBean.java
// public class CacheBean {
// private String key = "";
// private String desc = "";
// @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
// private Date expireTime;
//
// public CacheBean(String key, String desc, Date expireTime) {
// this.key = key;
// this.desc = desc;
// this.expireTime = expireTime;
// }
//
// public CacheBean(String key, Date expireTime) {
// this.key = key;
// this.expireTime = expireTime;
// }
//
// public CacheBean() {
//
// }
//
// public String getKey() {
// return key;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getDesc() {
// return desc;
// }
//
// public void setDesc(String desc) {
// this.desc = desc;
// }
//
// public Date getExpireTime() {
// return expireTime;
// }
//
// public void setExpireTime(Date expireTime) {
// this.expireTime = expireTime;
// }
//
// }
| import com.ace.cache.entity.CacheBean;
import java.util.List;
import com.ace.cache.vo.CacheTree; | /**
*
*/
package com.ace.cache.service;
/**
* 解决问题:
*
* @author Ace
* @version 1.0
* @date 2017年5月3日
* @since 1.7
*/
public interface ICacheManager {
public void removeAll();
public void remove(String key);
public void remove(List<CacheBean> caches);
public void removeByPre(String pre);
| // Path: src/main/java/com/ace/cache/vo/CacheTree.java
// public class CacheTree extends CacheBean {
// private String id;
// private String parentId;
// private String text = null;
// private List<CacheTree> nodes = new ArrayList<CacheTree>();
//
// public CacheTree(CacheBean cache) {
// this.setKey(cache.getKey());
// this.setDesc(cache.getDesc());
// this.setExpireTime(cache.getExpireTime());
// }
//
// public CacheTree() {
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.text = id;
// this.id = id;
// }
//
// public String getParentId() {
// return parentId;
// }
//
// public void setParentId(String parentId) {
// this.parentId = parentId;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((id == null) ? 0 : id.hashCode());
// result = prime * result + ((parentId == null) ? 0 : parentId.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// CacheTree other = (CacheTree) obj;
// if (id == null) {
// if (other.id != null)
// return false;
// } else if (!id.equals(other.id))
// return false;
// if (parentId == null) {
// if (other.parentId != null)
// return false;
// } else if (!parentId.equals(other.parentId))
// return false;
// return true;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// public List<CacheTree> getNodes() {
// return nodes;
// }
//
// public void setNodes(List<CacheTree> nodes) {
// this.nodes = nodes;
// }
//
// }
//
// Path: src/main/java/com/ace/cache/entity/CacheBean.java
// public class CacheBean {
// private String key = "";
// private String desc = "";
// @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
// private Date expireTime;
//
// public CacheBean(String key, String desc, Date expireTime) {
// this.key = key;
// this.desc = desc;
// this.expireTime = expireTime;
// }
//
// public CacheBean(String key, Date expireTime) {
// this.key = key;
// this.expireTime = expireTime;
// }
//
// public CacheBean() {
//
// }
//
// public String getKey() {
// return key;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getDesc() {
// return desc;
// }
//
// public void setDesc(String desc) {
// this.desc = desc;
// }
//
// public Date getExpireTime() {
// return expireTime;
// }
//
// public void setExpireTime(Date expireTime) {
// this.expireTime = expireTime;
// }
//
// }
// Path: src/main/java/com/ace/cache/service/ICacheManager.java
import com.ace.cache.entity.CacheBean;
import java.util.List;
import com.ace.cache.vo.CacheTree;
/**
*
*/
package com.ace.cache.service;
/**
* 解决问题:
*
* @author Ace
* @version 1.0
* @date 2017年5月3日
* @since 1.7
*/
public interface ICacheManager {
public void removeAll();
public void remove(String key);
public void remove(List<CacheBean> caches);
public void removeByPre(String pre);
| public List<CacheTree> getAll(); |
wxiaoqi/ace-cache | src/main/java/com/ace/cache/api/CacheAPI.java | // Path: src/main/java/com/ace/cache/entity/CacheBean.java
// public class CacheBean {
// private String key = "";
// private String desc = "";
// @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
// private Date expireTime;
//
// public CacheBean(String key, String desc, Date expireTime) {
// this.key = key;
// this.desc = desc;
// this.expireTime = expireTime;
// }
//
// public CacheBean(String key, Date expireTime) {
// this.key = key;
// this.expireTime = expireTime;
// }
//
// public CacheBean() {
//
// }
//
// public String getKey() {
// return key;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getDesc() {
// return desc;
// }
//
// public void setDesc(String desc) {
// this.desc = desc;
// }
//
// public Date getExpireTime() {
// return expireTime;
// }
//
// public void setExpireTime(Date expireTime) {
// this.expireTime = expireTime;
// }
//
// }
| import java.util.List;
import com.ace.cache.entity.CacheBean; | package com.ace.cache.api;
/**
* 缓存API
* <p/>
* 解决问题:
*
* @author Ace
* @version 1.0
* @date 2017年5月4日
* @since 1.7
*/
public interface CacheAPI {
/**
* 传入key获取缓存json,需要用fastjson转换为对象
*
* @param key
* @return
* @author Ace
* @date 2017年5月12日
*/
public String get(String key);
/**
* 保存缓存
*
* @param key
* @param value
* @param expireMin
* @author Ace
* @date 2017年5月12日
*/
public void set(String key, Object value, int expireMin);
/**
* 保存缓存
*
* @param key
* @param value
* @param expireMin
* @param desc
* @author Ace
* @date 2017年5月12日
*/
public void set(String key, Object value, int expireMin, String desc);
/**
* 移除单个缓存
*
* @param key
* @return
* @author Ace
* @date 2017年5月12日
*/
public Long remove(String key);
/**
* 移除多个缓存
*
* @param keys
* @return
* @author Ace
* @date 2017年5月12日
*/
public Long remove(String... keys);
/**
* 按前缀移除缓存
*
* @param pre
* @return
* @author Ace
* @date 2017年5月12日
*/
public Long removeByPre(String pre);
/**
* 通过前缀获取缓存信息
*
* @param pre
* @return
* @author Ace
* @date 2017年5月12日
*/ | // Path: src/main/java/com/ace/cache/entity/CacheBean.java
// public class CacheBean {
// private String key = "";
// private String desc = "";
// @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
// private Date expireTime;
//
// public CacheBean(String key, String desc, Date expireTime) {
// this.key = key;
// this.desc = desc;
// this.expireTime = expireTime;
// }
//
// public CacheBean(String key, Date expireTime) {
// this.key = key;
// this.expireTime = expireTime;
// }
//
// public CacheBean() {
//
// }
//
// public String getKey() {
// return key;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getDesc() {
// return desc;
// }
//
// public void setDesc(String desc) {
// this.desc = desc;
// }
//
// public Date getExpireTime() {
// return expireTime;
// }
//
// public void setExpireTime(Date expireTime) {
// this.expireTime = expireTime;
// }
//
// }
// Path: src/main/java/com/ace/cache/api/CacheAPI.java
import java.util.List;
import com.ace.cache.entity.CacheBean;
package com.ace.cache.api;
/**
* 缓存API
* <p/>
* 解决问题:
*
* @author Ace
* @version 1.0
* @date 2017年5月4日
* @since 1.7
*/
public interface CacheAPI {
/**
* 传入key获取缓存json,需要用fastjson转换为对象
*
* @param key
* @return
* @author Ace
* @date 2017年5月12日
*/
public String get(String key);
/**
* 保存缓存
*
* @param key
* @param value
* @param expireMin
* @author Ace
* @date 2017年5月12日
*/
public void set(String key, Object value, int expireMin);
/**
* 保存缓存
*
* @param key
* @param value
* @param expireMin
* @param desc
* @author Ace
* @date 2017年5月12日
*/
public void set(String key, Object value, int expireMin, String desc);
/**
* 移除单个缓存
*
* @param key
* @return
* @author Ace
* @date 2017年5月12日
*/
public Long remove(String key);
/**
* 移除多个缓存
*
* @param keys
* @return
* @author Ace
* @date 2017年5月12日
*/
public Long remove(String... keys);
/**
* 按前缀移除缓存
*
* @param pre
* @return
* @author Ace
* @date 2017年5月12日
*/
public Long removeByPre(String pre);
/**
* 通过前缀获取缓存信息
*
* @param pre
* @return
* @author Ace
* @date 2017年5月12日
*/ | public List<CacheBean> getCacheBeanByPre(String pre); |
wxiaoqi/ace-cache | src/test/java/com/ace/cache/test/cache/MyKeyGenerator.java | // Path: src/main/java/com/ace/cache/constants/CacheScope.java
// public enum CacheScope {
// user, application
// }
//
// Path: src/main/java/com/ace/cache/parser/IKeyGenerator.java
// public abstract class IKeyGenerator {
// public static final String LINK = "_";
//
// /**
// * 获取动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public String getKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments) {
// StringBuffer sb = new StringBuffer("");
// key = buildKey(key, scope, parameterTypes, arguments);
// sb.append(key);
// if (CacheScope.user.equals(scope)) {
// if (getUserKeyGenerator() != null)
// sb.append(LINK)
// .append(getUserKeyGenerator().getCurrentUserAccount());
// }
// return sb.toString();
// }
//
// /**
// * 当前登陆人key
// *
// * @param userKeyGenerator
// */
// public abstract IUserKeyGenerator getUserKeyGenerator();
//
// /**
// * 生成动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public abstract String buildKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments);
// }
//
// Path: src/main/java/com/ace/cache/parser/IUserKeyGenerator.java
// public interface IUserKeyGenerator {
// public String getCurrentUserAccount();
// }
| import com.ace.cache.constants.CacheScope;
import com.ace.cache.parser.IKeyGenerator;
import com.ace.cache.parser.IUserKeyGenerator;
| package com.ace.cache.test.cache;
/**
* ${DESCRIPTION}
*
* @author 小郎君
* @create 2017-05-22 14:05
*/
public class MyKeyGenerator extends IKeyGenerator {
@Override
| // Path: src/main/java/com/ace/cache/constants/CacheScope.java
// public enum CacheScope {
// user, application
// }
//
// Path: src/main/java/com/ace/cache/parser/IKeyGenerator.java
// public abstract class IKeyGenerator {
// public static final String LINK = "_";
//
// /**
// * 获取动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public String getKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments) {
// StringBuffer sb = new StringBuffer("");
// key = buildKey(key, scope, parameterTypes, arguments);
// sb.append(key);
// if (CacheScope.user.equals(scope)) {
// if (getUserKeyGenerator() != null)
// sb.append(LINK)
// .append(getUserKeyGenerator().getCurrentUserAccount());
// }
// return sb.toString();
// }
//
// /**
// * 当前登陆人key
// *
// * @param userKeyGenerator
// */
// public abstract IUserKeyGenerator getUserKeyGenerator();
//
// /**
// * 生成动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public abstract String buildKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments);
// }
//
// Path: src/main/java/com/ace/cache/parser/IUserKeyGenerator.java
// public interface IUserKeyGenerator {
// public String getCurrentUserAccount();
// }
// Path: src/test/java/com/ace/cache/test/cache/MyKeyGenerator.java
import com.ace.cache.constants.CacheScope;
import com.ace.cache.parser.IKeyGenerator;
import com.ace.cache.parser.IUserKeyGenerator;
package com.ace.cache.test.cache;
/**
* ${DESCRIPTION}
*
* @author 小郎君
* @create 2017-05-22 14:05
*/
public class MyKeyGenerator extends IKeyGenerator {
@Override
| public IUserKeyGenerator getUserKeyGenerator() {
|
wxiaoqi/ace-cache | src/test/java/com/ace/cache/test/cache/MyKeyGenerator.java | // Path: src/main/java/com/ace/cache/constants/CacheScope.java
// public enum CacheScope {
// user, application
// }
//
// Path: src/main/java/com/ace/cache/parser/IKeyGenerator.java
// public abstract class IKeyGenerator {
// public static final String LINK = "_";
//
// /**
// * 获取动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public String getKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments) {
// StringBuffer sb = new StringBuffer("");
// key = buildKey(key, scope, parameterTypes, arguments);
// sb.append(key);
// if (CacheScope.user.equals(scope)) {
// if (getUserKeyGenerator() != null)
// sb.append(LINK)
// .append(getUserKeyGenerator().getCurrentUserAccount());
// }
// return sb.toString();
// }
//
// /**
// * 当前登陆人key
// *
// * @param userKeyGenerator
// */
// public abstract IUserKeyGenerator getUserKeyGenerator();
//
// /**
// * 生成动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public abstract String buildKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments);
// }
//
// Path: src/main/java/com/ace/cache/parser/IUserKeyGenerator.java
// public interface IUserKeyGenerator {
// public String getCurrentUserAccount();
// }
| import com.ace.cache.constants.CacheScope;
import com.ace.cache.parser.IKeyGenerator;
import com.ace.cache.parser.IUserKeyGenerator;
| package com.ace.cache.test.cache;
/**
* ${DESCRIPTION}
*
* @author 小郎君
* @create 2017-05-22 14:05
*/
public class MyKeyGenerator extends IKeyGenerator {
@Override
public IUserKeyGenerator getUserKeyGenerator() {
return null;
}
@Override
| // Path: src/main/java/com/ace/cache/constants/CacheScope.java
// public enum CacheScope {
// user, application
// }
//
// Path: src/main/java/com/ace/cache/parser/IKeyGenerator.java
// public abstract class IKeyGenerator {
// public static final String LINK = "_";
//
// /**
// * 获取动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public String getKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments) {
// StringBuffer sb = new StringBuffer("");
// key = buildKey(key, scope, parameterTypes, arguments);
// sb.append(key);
// if (CacheScope.user.equals(scope)) {
// if (getUserKeyGenerator() != null)
// sb.append(LINK)
// .append(getUserKeyGenerator().getCurrentUserAccount());
// }
// return sb.toString();
// }
//
// /**
// * 当前登陆人key
// *
// * @param userKeyGenerator
// */
// public abstract IUserKeyGenerator getUserKeyGenerator();
//
// /**
// * 生成动态key
// *
// * @param key
// * @param scope
// * @param parameterTypes
// * @param arguments
// * @return
// */
// public abstract String buildKey(String key, CacheScope scope,
// Class<?>[] parameterTypes, Object[] arguments);
// }
//
// Path: src/main/java/com/ace/cache/parser/IUserKeyGenerator.java
// public interface IUserKeyGenerator {
// public String getCurrentUserAccount();
// }
// Path: src/test/java/com/ace/cache/test/cache/MyKeyGenerator.java
import com.ace.cache.constants.CacheScope;
import com.ace.cache.parser.IKeyGenerator;
import com.ace.cache.parser.IUserKeyGenerator;
package com.ace.cache.test.cache;
/**
* ${DESCRIPTION}
*
* @author 小郎君
* @create 2017-05-22 14:05
*/
public class MyKeyGenerator extends IKeyGenerator {
@Override
public IUserKeyGenerator getUserKeyGenerator() {
return null;
}
@Override
| public String buildKey(String key, CacheScope scope, Class<?>[] parameterTypes, Object[] arguments) {
|
wxiaoqi/ace-cache | src/main/java/com/ace/cache/aspect/ResultParseService.java | // Path: src/main/java/com/ace/cache/parser/ICacheResultParser.java
// public interface ICacheResultParser {
// /**
// * 解析结果
// *
// * @param value
// * @param returnType
// * @param origins
// * @return
// */
// public Object parse(String value, Type returnType, Class<?>... origins);
// }
| import com.ace.cache.annotation.Cache;
import com.ace.cache.parser.ICacheResultParser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.lang.reflect.Type;
import java.util.concurrent.ConcurrentHashMap; | package com.ace.cache.aspect;
@Slf4j
@Service
public class ResultParseService { | // Path: src/main/java/com/ace/cache/parser/ICacheResultParser.java
// public interface ICacheResultParser {
// /**
// * 解析结果
// *
// * @param value
// * @param returnType
// * @param origins
// * @return
// */
// public Object parse(String value, Type returnType, Class<?>... origins);
// }
// Path: src/main/java/com/ace/cache/aspect/ResultParseService.java
import com.ace.cache.annotation.Cache;
import com.ace.cache.parser.ICacheResultParser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.lang.reflect.Type;
import java.util.concurrent.ConcurrentHashMap;
package com.ace.cache.aspect;
@Slf4j
@Service
public class ResultParseService { | private ConcurrentHashMap<String, ICacheResultParser> parserMap = new ConcurrentHashMap<String, ICacheResultParser>(); |
notem/Saber-Bot | src/main/java/ws/nmathe/saber/utils/HttpUtilities.java | // Path: src/main/java/ws/nmathe/saber/Main.java
// public class Main
// {
// private static ShardManager shardManager;
// private static BotSettingsManager botSettingsManager = new BotSettingsManager();
// private static EntryManager entryManager = new EntryManager();
// private static ScheduleManager scheduleManager = new ScheduleManager();
// private static CommandHandler commandHandler = new CommandHandler();
// private static CalendarConverter calendarConverter = new CalendarConverter();
// private static GuildSettingsManager guildSettingsManager = new GuildSettingsManager();
// private static Driver mongoDriver = new Driver();
//
// /**
// * initialize the bot
// */
// public static void main(String[] args)
// {
// if(botSettingsManager.hasSettings())
// {
// Logging.info(Main.class, "A 'saber.toml' configuration file has been created. Add your " +
// "bot token to the file and restart the bot.\n");
// System.exit(0);
// }
//
// mongoDriver.init(); // ready database
// calendarConverter.init(); // connect to calendar service
//
// // create the shard manager
// shardManager = new ShardManager(botSettingsManager.getShards(), botSettingsManager.getShardTotal());
// }
//
// /*
// * Getters for manager type objects
// */
//
// public static ShardManager getShardManager()
// {
// return shardManager;
// }
//
// public static BotSettingsManager getBotSettingsManager()
// {
// return botSettingsManager;
// }
//
// public static CommandHandler getCommandHandler()
// {
// return commandHandler;
// }
//
// public static EntryManager getEntryManager()
// {
// return entryManager;
// }
//
// public static ScheduleManager getScheduleManager()
// {
// return scheduleManager;
// }
//
// public static GuildSettingsManager getGuildSettingsManager()
// {
// return guildSettingsManager;
// }
//
// public static CalendarConverter getCalendarConverter()
// {
// return calendarConverter;
// }
//
// public static Driver getDBDriver()
// {
// return mongoDriver;
// }
// }
| import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.json.JSONObject;
import ws.nmathe.saber.Main;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit; | package ws.nmathe.saber.utils;
/**
*/
public class HttpUtilities
{
private static LocalDateTime lastUpdate = LocalDateTime.MIN;
/**
* Updates bot metrics for any connected metric tracking services
*/
public static void updateStats(Integer shardId)
{ | // Path: src/main/java/ws/nmathe/saber/Main.java
// public class Main
// {
// private static ShardManager shardManager;
// private static BotSettingsManager botSettingsManager = new BotSettingsManager();
// private static EntryManager entryManager = new EntryManager();
// private static ScheduleManager scheduleManager = new ScheduleManager();
// private static CommandHandler commandHandler = new CommandHandler();
// private static CalendarConverter calendarConverter = new CalendarConverter();
// private static GuildSettingsManager guildSettingsManager = new GuildSettingsManager();
// private static Driver mongoDriver = new Driver();
//
// /**
// * initialize the bot
// */
// public static void main(String[] args)
// {
// if(botSettingsManager.hasSettings())
// {
// Logging.info(Main.class, "A 'saber.toml' configuration file has been created. Add your " +
// "bot token to the file and restart the bot.\n");
// System.exit(0);
// }
//
// mongoDriver.init(); // ready database
// calendarConverter.init(); // connect to calendar service
//
// // create the shard manager
// shardManager = new ShardManager(botSettingsManager.getShards(), botSettingsManager.getShardTotal());
// }
//
// /*
// * Getters for manager type objects
// */
//
// public static ShardManager getShardManager()
// {
// return shardManager;
// }
//
// public static BotSettingsManager getBotSettingsManager()
// {
// return botSettingsManager;
// }
//
// public static CommandHandler getCommandHandler()
// {
// return commandHandler;
// }
//
// public static EntryManager getEntryManager()
// {
// return entryManager;
// }
//
// public static ScheduleManager getScheduleManager()
// {
// return scheduleManager;
// }
//
// public static GuildSettingsManager getGuildSettingsManager()
// {
// return guildSettingsManager;
// }
//
// public static CalendarConverter getCalendarConverter()
// {
// return calendarConverter;
// }
//
// public static Driver getDBDriver()
// {
// return mongoDriver;
// }
// }
// Path: src/main/java/ws/nmathe/saber/utils/HttpUtilities.java
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.json.JSONObject;
import ws.nmathe.saber.Main;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
package ws.nmathe.saber.utils;
/**
*/
public class HttpUtilities
{
private static LocalDateTime lastUpdate = LocalDateTime.MIN;
/**
* Updates bot metrics for any connected metric tracking services
*/
public static void updateStats(Integer shardId)
{ | String auth = Main.getBotSettingsManager().getWebToken(); |
notem/Saber-Bot | src/main/java/ws/nmathe/saber/core/settings/GuildSettingsManager.java | // Path: src/main/java/ws/nmathe/saber/Main.java
// public class Main
// {
// private static ShardManager shardManager;
// private static BotSettingsManager botSettingsManager = new BotSettingsManager();
// private static EntryManager entryManager = new EntryManager();
// private static ScheduleManager scheduleManager = new ScheduleManager();
// private static CommandHandler commandHandler = new CommandHandler();
// private static CalendarConverter calendarConverter = new CalendarConverter();
// private static GuildSettingsManager guildSettingsManager = new GuildSettingsManager();
// private static Driver mongoDriver = new Driver();
//
// /**
// * initialize the bot
// */
// public static void main(String[] args)
// {
// if(botSettingsManager.hasSettings())
// {
// Logging.info(Main.class, "A 'saber.toml' configuration file has been created. Add your " +
// "bot token to the file and restart the bot.\n");
// System.exit(0);
// }
//
// mongoDriver.init(); // ready database
// calendarConverter.init(); // connect to calendar service
//
// // create the shard manager
// shardManager = new ShardManager(botSettingsManager.getShards(), botSettingsManager.getShardTotal());
// }
//
// /*
// * Getters for manager type objects
// */
//
// public static ShardManager getShardManager()
// {
// return shardManager;
// }
//
// public static BotSettingsManager getBotSettingsManager()
// {
// return botSettingsManager;
// }
//
// public static CommandHandler getCommandHandler()
// {
// return commandHandler;
// }
//
// public static EntryManager getEntryManager()
// {
// return entryManager;
// }
//
// public static ScheduleManager getScheduleManager()
// {
// return scheduleManager;
// }
//
// public static GuildSettingsManager getGuildSettingsManager()
// {
// return guildSettingsManager;
// }
//
// public static CalendarConverter getCalendarConverter()
// {
// return calendarConverter;
// }
//
// public static Driver getDBDriver()
// {
// return mongoDriver;
// }
// }
| import org.bson.Document;
import ws.nmathe.saber.Main;
import ws.nmathe.saber.commands.general.*;
import java.util.ArrayList;
import java.util.Arrays;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Updates.set; | package ws.nmathe.saber.core.settings;
/**
* manager for guild setting options
*/
public class GuildSettingsManager
{
/**
* retrieves the guild settings object for a guild
* @param guildId ID of guild
* @return GuildSettings object (never null)
*/
public GuildSettings getGuildSettings(String guildId)
{ | // Path: src/main/java/ws/nmathe/saber/Main.java
// public class Main
// {
// private static ShardManager shardManager;
// private static BotSettingsManager botSettingsManager = new BotSettingsManager();
// private static EntryManager entryManager = new EntryManager();
// private static ScheduleManager scheduleManager = new ScheduleManager();
// private static CommandHandler commandHandler = new CommandHandler();
// private static CalendarConverter calendarConverter = new CalendarConverter();
// private static GuildSettingsManager guildSettingsManager = new GuildSettingsManager();
// private static Driver mongoDriver = new Driver();
//
// /**
// * initialize the bot
// */
// public static void main(String[] args)
// {
// if(botSettingsManager.hasSettings())
// {
// Logging.info(Main.class, "A 'saber.toml' configuration file has been created. Add your " +
// "bot token to the file and restart the bot.\n");
// System.exit(0);
// }
//
// mongoDriver.init(); // ready database
// calendarConverter.init(); // connect to calendar service
//
// // create the shard manager
// shardManager = new ShardManager(botSettingsManager.getShards(), botSettingsManager.getShardTotal());
// }
//
// /*
// * Getters for manager type objects
// */
//
// public static ShardManager getShardManager()
// {
// return shardManager;
// }
//
// public static BotSettingsManager getBotSettingsManager()
// {
// return botSettingsManager;
// }
//
// public static CommandHandler getCommandHandler()
// {
// return commandHandler;
// }
//
// public static EntryManager getEntryManager()
// {
// return entryManager;
// }
//
// public static ScheduleManager getScheduleManager()
// {
// return scheduleManager;
// }
//
// public static GuildSettingsManager getGuildSettingsManager()
// {
// return guildSettingsManager;
// }
//
// public static CalendarConverter getCalendarConverter()
// {
// return calendarConverter;
// }
//
// public static Driver getDBDriver()
// {
// return mongoDriver;
// }
// }
// Path: src/main/java/ws/nmathe/saber/core/settings/GuildSettingsManager.java
import org.bson.Document;
import ws.nmathe.saber.Main;
import ws.nmathe.saber.commands.general.*;
import java.util.ArrayList;
import java.util.Arrays;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Updates.set;
package ws.nmathe.saber.core.settings;
/**
* manager for guild setting options
*/
public class GuildSettingsManager
{
/**
* retrieves the guild settings object for a guild
* @param guildId ID of guild
* @return GuildSettings object (never null)
*/
public GuildSettings getGuildSettings(String guildId)
{ | Document guildDoc = Main.getDBDriver().getGuildCollection().find(eq("_id", guildId)).first(); |
notem/Saber-Bot | src/main/java/ws/nmathe/saber/utils/Logging.java | // Path: src/main/java/ws/nmathe/saber/Main.java
// public class Main
// {
// private static ShardManager shardManager;
// private static BotSettingsManager botSettingsManager = new BotSettingsManager();
// private static EntryManager entryManager = new EntryManager();
// private static ScheduleManager scheduleManager = new ScheduleManager();
// private static CommandHandler commandHandler = new CommandHandler();
// private static CalendarConverter calendarConverter = new CalendarConverter();
// private static GuildSettingsManager guildSettingsManager = new GuildSettingsManager();
// private static Driver mongoDriver = new Driver();
//
// /**
// * initialize the bot
// */
// public static void main(String[] args)
// {
// if(botSettingsManager.hasSettings())
// {
// Logging.info(Main.class, "A 'saber.toml' configuration file has been created. Add your " +
// "bot token to the file and restart the bot.\n");
// System.exit(0);
// }
//
// mongoDriver.init(); // ready database
// calendarConverter.init(); // connect to calendar service
//
// // create the shard manager
// shardManager = new ShardManager(botSettingsManager.getShards(), botSettingsManager.getShardTotal());
// }
//
// /*
// * Getters for manager type objects
// */
//
// public static ShardManager getShardManager()
// {
// return shardManager;
// }
//
// public static BotSettingsManager getBotSettingsManager()
// {
// return botSettingsManager;
// }
//
// public static CommandHandler getCommandHandler()
// {
// return commandHandler;
// }
//
// public static EntryManager getEntryManager()
// {
// return entryManager;
// }
//
// public static ScheduleManager getScheduleManager()
// {
// return scheduleManager;
// }
//
// public static GuildSettingsManager getGuildSettingsManager()
// {
// return guildSettingsManager;
// }
//
// public static CalendarConverter getCalendarConverter()
// {
// return calendarConverter;
// }
//
// public static Driver getDBDriver()
// {
// return mongoDriver;
// }
// }
| import ws.nmathe.saber.Main;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit; | package ws.nmathe.saber.utils;
/**
* used for logging information to the console
*/
public class Logging
{
public static final String ANSI_RESET = "\u001B[0m";
public static final String ANSI_BLACK = "\u001B[30m";
public static final String ANSI_RED = "\u001B[31m";
public static final String ANSI_GREEN = "\u001B[32m";
public static final String ANSI_YELLOW = "\u001B[33m";
public static final String ANSI_BLUE = "\u001B[34m";
public static final String ANSI_PURPLE = "\u001B[35m";
public static final String ANSI_CYAN = "\u001B[36m";
public static final String ANSI_WHITE = "\u001B[37m";
public static final String ANSI_BLACK_BACKGROUND = "\u001B[40m";
public static final String ANSI_RED_BACKGROUND = "\u001B[41m";
public static final String ANSI_GREEN_BACKGROUND = "\u001B[42m";
public static final String ANSI_YELLOW_BACKGROUND = "\u001B[43m";
public static final String ANSI_BLUE_BACKGROUND = "\u001B[44m";
public static final String ANSI_PURPLE_BACKGROUND = "\u001B[45m";
public static final String ANSI_CYAN_BACKGROUND = "\u001B[46m";
public static final String ANSI_WHITE_BACKGROUND = "\u001B[47m";
/**
* used for most general logging (level 5)
* @param caller the java class from which the command is called
* @param msg the message to log
*/
public static void info(Class caller, String msg)
{ | // Path: src/main/java/ws/nmathe/saber/Main.java
// public class Main
// {
// private static ShardManager shardManager;
// private static BotSettingsManager botSettingsManager = new BotSettingsManager();
// private static EntryManager entryManager = new EntryManager();
// private static ScheduleManager scheduleManager = new ScheduleManager();
// private static CommandHandler commandHandler = new CommandHandler();
// private static CalendarConverter calendarConverter = new CalendarConverter();
// private static GuildSettingsManager guildSettingsManager = new GuildSettingsManager();
// private static Driver mongoDriver = new Driver();
//
// /**
// * initialize the bot
// */
// public static void main(String[] args)
// {
// if(botSettingsManager.hasSettings())
// {
// Logging.info(Main.class, "A 'saber.toml' configuration file has been created. Add your " +
// "bot token to the file and restart the bot.\n");
// System.exit(0);
// }
//
// mongoDriver.init(); // ready database
// calendarConverter.init(); // connect to calendar service
//
// // create the shard manager
// shardManager = new ShardManager(botSettingsManager.getShards(), botSettingsManager.getShardTotal());
// }
//
// /*
// * Getters for manager type objects
// */
//
// public static ShardManager getShardManager()
// {
// return shardManager;
// }
//
// public static BotSettingsManager getBotSettingsManager()
// {
// return botSettingsManager;
// }
//
// public static CommandHandler getCommandHandler()
// {
// return commandHandler;
// }
//
// public static EntryManager getEntryManager()
// {
// return entryManager;
// }
//
// public static ScheduleManager getScheduleManager()
// {
// return scheduleManager;
// }
//
// public static GuildSettingsManager getGuildSettingsManager()
// {
// return guildSettingsManager;
// }
//
// public static CalendarConverter getCalendarConverter()
// {
// return calendarConverter;
// }
//
// public static Driver getDBDriver()
// {
// return mongoDriver;
// }
// }
// Path: src/main/java/ws/nmathe/saber/utils/Logging.java
import ws.nmathe.saber.Main;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
package ws.nmathe.saber.utils;
/**
* used for logging information to the console
*/
public class Logging
{
public static final String ANSI_RESET = "\u001B[0m";
public static final String ANSI_BLACK = "\u001B[30m";
public static final String ANSI_RED = "\u001B[31m";
public static final String ANSI_GREEN = "\u001B[32m";
public static final String ANSI_YELLOW = "\u001B[33m";
public static final String ANSI_BLUE = "\u001B[34m";
public static final String ANSI_PURPLE = "\u001B[35m";
public static final String ANSI_CYAN = "\u001B[36m";
public static final String ANSI_WHITE = "\u001B[37m";
public static final String ANSI_BLACK_BACKGROUND = "\u001B[40m";
public static final String ANSI_RED_BACKGROUND = "\u001B[41m";
public static final String ANSI_GREEN_BACKGROUND = "\u001B[42m";
public static final String ANSI_YELLOW_BACKGROUND = "\u001B[43m";
public static final String ANSI_BLUE_BACKGROUND = "\u001B[44m";
public static final String ANSI_PURPLE_BACKGROUND = "\u001B[45m";
public static final String ANSI_CYAN_BACKGROUND = "\u001B[46m";
public static final String ANSI_WHITE_BACKGROUND = "\u001B[47m";
/**
* used for most general logging (level 5)
* @param caller the java class from which the command is called
* @param msg the message to log
*/
public static void info(Class caller, String msg)
{ | if(Main.getBotSettingsManager().getLogLevel() < 5) return; |
notem/Saber-Bot | src/main/java/ws/nmathe/saber/core/RateLimiter.java | // Path: src/main/java/ws/nmathe/saber/Main.java
// public class Main
// {
// private static ShardManager shardManager;
// private static BotSettingsManager botSettingsManager = new BotSettingsManager();
// private static EntryManager entryManager = new EntryManager();
// private static ScheduleManager scheduleManager = new ScheduleManager();
// private static CommandHandler commandHandler = new CommandHandler();
// private static CalendarConverter calendarConverter = new CalendarConverter();
// private static GuildSettingsManager guildSettingsManager = new GuildSettingsManager();
// private static Driver mongoDriver = new Driver();
//
// /**
// * initialize the bot
// */
// public static void main(String[] args)
// {
// if(botSettingsManager.hasSettings())
// {
// Logging.info(Main.class, "A 'saber.toml' configuration file has been created. Add your " +
// "bot token to the file and restart the bot.\n");
// System.exit(0);
// }
//
// mongoDriver.init(); // ready database
// calendarConverter.init(); // connect to calendar service
//
// // create the shard manager
// shardManager = new ShardManager(botSettingsManager.getShards(), botSettingsManager.getShardTotal());
// }
//
// /*
// * Getters for manager type objects
// */
//
// public static ShardManager getShardManager()
// {
// return shardManager;
// }
//
// public static BotSettingsManager getBotSettingsManager()
// {
// return botSettingsManager;
// }
//
// public static CommandHandler getCommandHandler()
// {
// return commandHandler;
// }
//
// public static EntryManager getEntryManager()
// {
// return entryManager;
// }
//
// public static ScheduleManager getScheduleManager()
// {
// return scheduleManager;
// }
//
// public static GuildSettingsManager getGuildSettingsManager()
// {
// return guildSettingsManager;
// }
//
// public static CalendarConverter getCalendarConverter()
// {
// return calendarConverter;
// }
//
// public static Driver getDBDriver()
// {
// return mongoDriver;
// }
// }
| import ws.nmathe.saber.Main;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; | package ws.nmathe.saber.core;
/**
* Simple class which maintains a list of timestamps of the last command
* message that a user sent (within the bot's current runtime instance)
*/
public class RateLimiter
{
private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); | // Path: src/main/java/ws/nmathe/saber/Main.java
// public class Main
// {
// private static ShardManager shardManager;
// private static BotSettingsManager botSettingsManager = new BotSettingsManager();
// private static EntryManager entryManager = new EntryManager();
// private static ScheduleManager scheduleManager = new ScheduleManager();
// private static CommandHandler commandHandler = new CommandHandler();
// private static CalendarConverter calendarConverter = new CalendarConverter();
// private static GuildSettingsManager guildSettingsManager = new GuildSettingsManager();
// private static Driver mongoDriver = new Driver();
//
// /**
// * initialize the bot
// */
// public static void main(String[] args)
// {
// if(botSettingsManager.hasSettings())
// {
// Logging.info(Main.class, "A 'saber.toml' configuration file has been created. Add your " +
// "bot token to the file and restart the bot.\n");
// System.exit(0);
// }
//
// mongoDriver.init(); // ready database
// calendarConverter.init(); // connect to calendar service
//
// // create the shard manager
// shardManager = new ShardManager(botSettingsManager.getShards(), botSettingsManager.getShardTotal());
// }
//
// /*
// * Getters for manager type objects
// */
//
// public static ShardManager getShardManager()
// {
// return shardManager;
// }
//
// public static BotSettingsManager getBotSettingsManager()
// {
// return botSettingsManager;
// }
//
// public static CommandHandler getCommandHandler()
// {
// return commandHandler;
// }
//
// public static EntryManager getEntryManager()
// {
// return entryManager;
// }
//
// public static ScheduleManager getScheduleManager()
// {
// return scheduleManager;
// }
//
// public static GuildSettingsManager getGuildSettingsManager()
// {
// return guildSettingsManager;
// }
//
// public static CalendarConverter getCalendarConverter()
// {
// return calendarConverter;
// }
//
// public static Driver getDBDriver()
// {
// return mongoDriver;
// }
// }
// Path: src/main/java/ws/nmathe/saber/core/RateLimiter.java
import ws.nmathe.saber.Main;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
package ws.nmathe.saber.core;
/**
* Simple class which maintains a list of timestamps of the last command
* message that a user sent (within the bot's current runtime instance)
*/
public class RateLimiter
{
private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); | private long startThreshold = Main.getBotSettingsManager().getCooldownThreshold(); |
notem/Saber-Bot | src/main/java/ws/nmathe/saber/core/database/Driver.java | // Path: src/main/java/ws/nmathe/saber/Main.java
// public class Main
// {
// private static ShardManager shardManager;
// private static BotSettingsManager botSettingsManager = new BotSettingsManager();
// private static EntryManager entryManager = new EntryManager();
// private static ScheduleManager scheduleManager = new ScheduleManager();
// private static CommandHandler commandHandler = new CommandHandler();
// private static CalendarConverter calendarConverter = new CalendarConverter();
// private static GuildSettingsManager guildSettingsManager = new GuildSettingsManager();
// private static Driver mongoDriver = new Driver();
//
// /**
// * initialize the bot
// */
// public static void main(String[] args)
// {
// if(botSettingsManager.hasSettings())
// {
// Logging.info(Main.class, "A 'saber.toml' configuration file has been created. Add your " +
// "bot token to the file and restart the bot.\n");
// System.exit(0);
// }
//
// mongoDriver.init(); // ready database
// calendarConverter.init(); // connect to calendar service
//
// // create the shard manager
// shardManager = new ShardManager(botSettingsManager.getShards(), botSettingsManager.getShardTotal());
// }
//
// /*
// * Getters for manager type objects
// */
//
// public static ShardManager getShardManager()
// {
// return shardManager;
// }
//
// public static BotSettingsManager getBotSettingsManager()
// {
// return botSettingsManager;
// }
//
// public static CommandHandler getCommandHandler()
// {
// return commandHandler;
// }
//
// public static EntryManager getEntryManager()
// {
// return entryManager;
// }
//
// public static ScheduleManager getScheduleManager()
// {
// return scheduleManager;
// }
//
// public static GuildSettingsManager getGuildSettingsManager()
// {
// return guildSettingsManager;
// }
//
// public static CalendarConverter getCalendarConverter()
// {
// return calendarConverter;
// }
//
// public static Driver getDBDriver()
// {
// return mongoDriver;
// }
// }
| import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import ws.nmathe.saber.Main;
import java.util.concurrent.*; | package ws.nmathe.saber.core.database;
public class Driver
{
private MongoDatabase db;
public void init()
{
// for a connection to the Mongo database
// connection properties should be configured via the URI used in the bot toml file | // Path: src/main/java/ws/nmathe/saber/Main.java
// public class Main
// {
// private static ShardManager shardManager;
// private static BotSettingsManager botSettingsManager = new BotSettingsManager();
// private static EntryManager entryManager = new EntryManager();
// private static ScheduleManager scheduleManager = new ScheduleManager();
// private static CommandHandler commandHandler = new CommandHandler();
// private static CalendarConverter calendarConverter = new CalendarConverter();
// private static GuildSettingsManager guildSettingsManager = new GuildSettingsManager();
// private static Driver mongoDriver = new Driver();
//
// /**
// * initialize the bot
// */
// public static void main(String[] args)
// {
// if(botSettingsManager.hasSettings())
// {
// Logging.info(Main.class, "A 'saber.toml' configuration file has been created. Add your " +
// "bot token to the file and restart the bot.\n");
// System.exit(0);
// }
//
// mongoDriver.init(); // ready database
// calendarConverter.init(); // connect to calendar service
//
// // create the shard manager
// shardManager = new ShardManager(botSettingsManager.getShards(), botSettingsManager.getShardTotal());
// }
//
// /*
// * Getters for manager type objects
// */
//
// public static ShardManager getShardManager()
// {
// return shardManager;
// }
//
// public static BotSettingsManager getBotSettingsManager()
// {
// return botSettingsManager;
// }
//
// public static CommandHandler getCommandHandler()
// {
// return commandHandler;
// }
//
// public static EntryManager getEntryManager()
// {
// return entryManager;
// }
//
// public static ScheduleManager getScheduleManager()
// {
// return scheduleManager;
// }
//
// public static GuildSettingsManager getGuildSettingsManager()
// {
// return guildSettingsManager;
// }
//
// public static CalendarConverter getCalendarConverter()
// {
// return calendarConverter;
// }
//
// public static Driver getDBDriver()
// {
// return mongoDriver;
// }
// }
// Path: src/main/java/ws/nmathe/saber/core/database/Driver.java
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import ws.nmathe.saber.Main;
import java.util.concurrent.*;
package ws.nmathe.saber.core.database;
public class Driver
{
private MongoDatabase db;
public void init()
{
// for a connection to the Mongo database
// connection properties should be configured via the URI used in the bot toml file | MongoClient mongoClient = new MongoClient(new MongoClientURI(Main.getBotSettingsManager().getMongoURI())); |
handstudio/HzGrapher | library/src/com/handstudio/android/hzgrapherlib/vo/linegraph/LineGraphVO.java | // Path: library/src/com/handstudio/android/hzgrapherlib/animation/GraphAnimation.java
// public class GraphAnimation {
// public static final int LINEAR_ANIMATION = 1;
//
// public static final int CURVE_REGION_ANIMATION_1 = 2;
// public static final int CURVE_REGION_ANIMATION_2 = 3;
//
// public static final int DEFAULT_DURATION = 2000;
//
// private int animation = LINEAR_ANIMATION;
// private int duration = DEFAULT_DURATION;
//
// public GraphAnimation() {
//
// }
//
// public GraphAnimation(int animation, int duration) {
// super();
// this.animation = animation;
// this.duration = duration;
// }
// public int getAnimation() {
// return animation;
// }
// public void setAnimation(int animation) {
// this.animation = animation;
// }
// public int getDuration() {
// return duration;
// }
// public void setDuration(int duration) {
// this.duration = duration;
// }
//
// }
//
// Path: library/src/com/handstudio/android/hzgrapherlib/vo/Graph.java
// public class Graph {
// public static final int DEFAULT_PADDING = 100;
// public static final int DEFAULT_MARGIN_TOP = 10;
// public static final int DEFAULT_MARGIN_RIGHT = 100;
// public static final int DEFAULT_MAX_VALUE = 500;
// public static final int DEFAULT_INCREMENT = 100;
//
// //padding
// private int paddingBottom = DEFAULT_PADDING;
// private int paddingTop = DEFAULT_PADDING;
// private int paddingLeft = DEFAULT_PADDING;
// private int paddingRight = DEFAULT_PADDING;
//
// //graph margin
// private int marginTop = DEFAULT_MARGIN_TOP;
// private int marginRight = DEFAULT_MARGIN_RIGHT;
//
// private GraphNameBox graphNameBox = null;
//
// public Graph() {
//
// }
// public Graph(int paddingBottom, int paddingTop, int paddingLeft,
// int paddingRight, int marginTop, int marginRight) {
// super();
// this.paddingBottom = paddingBottom;
// this.paddingTop = paddingTop;
// this.paddingLeft = paddingLeft;
// this.paddingRight = paddingRight;
// this.marginTop = marginTop;
// this.marginRight = marginRight;
// }
// public int getPaddingBottom() {
// return paddingBottom;
// }
// public void setPaddingBottom(int paddingBottom) {
// this.paddingBottom = paddingBottom;
// }
// public int getPaddingTop() {
// return paddingTop;
// }
// public void setPaddingTop(int paddingTop) {
// this.paddingTop = paddingTop;
// }
// public int getPaddingLeft() {
// return paddingLeft;
// }
// public void setPaddingLeft(int paddingLeft) {
// this.paddingLeft = paddingLeft;
// }
// public int getPaddingRight() {
// return paddingRight;
// }
// public void setPaddingRight(int paddingRight) {
// this.paddingRight = paddingRight;
// }
// public int getMarginTop() {
// return marginTop;
// }
// public void setMarginTop(int marginTop) {
// this.marginTop = marginTop;
// }
// public int getMarginRight() {
// return marginRight;
// }
// public void setMarginRight(int marginRight) {
// this.marginRight = marginRight;
// }
// public GraphNameBox getGraphNameBox() {
// return graphNameBox;
// }
// public void setGraphNameBox(GraphNameBox graphNameBox) {
// this.graphNameBox = graphNameBox;
// }
// }
| import java.util.List;
import com.handstudio.android.hzgrapherlib.animation.GraphAnimation;
import com.handstudio.android.hzgrapherlib.vo.Graph; | package com.handstudio.android.hzgrapherlib.vo.linegraph;
public class LineGraphVO extends Graph{
//max value
private int maxValue = DEFAULT_MAX_VALUE;
//increment
private int increment = DEFAULT_INCREMENT;
//animation | // Path: library/src/com/handstudio/android/hzgrapherlib/animation/GraphAnimation.java
// public class GraphAnimation {
// public static final int LINEAR_ANIMATION = 1;
//
// public static final int CURVE_REGION_ANIMATION_1 = 2;
// public static final int CURVE_REGION_ANIMATION_2 = 3;
//
// public static final int DEFAULT_DURATION = 2000;
//
// private int animation = LINEAR_ANIMATION;
// private int duration = DEFAULT_DURATION;
//
// public GraphAnimation() {
//
// }
//
// public GraphAnimation(int animation, int duration) {
// super();
// this.animation = animation;
// this.duration = duration;
// }
// public int getAnimation() {
// return animation;
// }
// public void setAnimation(int animation) {
// this.animation = animation;
// }
// public int getDuration() {
// return duration;
// }
// public void setDuration(int duration) {
// this.duration = duration;
// }
//
// }
//
// Path: library/src/com/handstudio/android/hzgrapherlib/vo/Graph.java
// public class Graph {
// public static final int DEFAULT_PADDING = 100;
// public static final int DEFAULT_MARGIN_TOP = 10;
// public static final int DEFAULT_MARGIN_RIGHT = 100;
// public static final int DEFAULT_MAX_VALUE = 500;
// public static final int DEFAULT_INCREMENT = 100;
//
// //padding
// private int paddingBottom = DEFAULT_PADDING;
// private int paddingTop = DEFAULT_PADDING;
// private int paddingLeft = DEFAULT_PADDING;
// private int paddingRight = DEFAULT_PADDING;
//
// //graph margin
// private int marginTop = DEFAULT_MARGIN_TOP;
// private int marginRight = DEFAULT_MARGIN_RIGHT;
//
// private GraphNameBox graphNameBox = null;
//
// public Graph() {
//
// }
// public Graph(int paddingBottom, int paddingTop, int paddingLeft,
// int paddingRight, int marginTop, int marginRight) {
// super();
// this.paddingBottom = paddingBottom;
// this.paddingTop = paddingTop;
// this.paddingLeft = paddingLeft;
// this.paddingRight = paddingRight;
// this.marginTop = marginTop;
// this.marginRight = marginRight;
// }
// public int getPaddingBottom() {
// return paddingBottom;
// }
// public void setPaddingBottom(int paddingBottom) {
// this.paddingBottom = paddingBottom;
// }
// public int getPaddingTop() {
// return paddingTop;
// }
// public void setPaddingTop(int paddingTop) {
// this.paddingTop = paddingTop;
// }
// public int getPaddingLeft() {
// return paddingLeft;
// }
// public void setPaddingLeft(int paddingLeft) {
// this.paddingLeft = paddingLeft;
// }
// public int getPaddingRight() {
// return paddingRight;
// }
// public void setPaddingRight(int paddingRight) {
// this.paddingRight = paddingRight;
// }
// public int getMarginTop() {
// return marginTop;
// }
// public void setMarginTop(int marginTop) {
// this.marginTop = marginTop;
// }
// public int getMarginRight() {
// return marginRight;
// }
// public void setMarginRight(int marginRight) {
// this.marginRight = marginRight;
// }
// public GraphNameBox getGraphNameBox() {
// return graphNameBox;
// }
// public void setGraphNameBox(GraphNameBox graphNameBox) {
// this.graphNameBox = graphNameBox;
// }
// }
// Path: library/src/com/handstudio/android/hzgrapherlib/vo/linegraph/LineGraphVO.java
import java.util.List;
import com.handstudio.android.hzgrapherlib.animation.GraphAnimation;
import com.handstudio.android.hzgrapherlib.vo.Graph;
package com.handstudio.android.hzgrapherlib.vo.linegraph;
public class LineGraphVO extends Graph{
//max value
private int maxValue = DEFAULT_MAX_VALUE;
//increment
private int increment = DEFAULT_INCREMENT;
//animation | private GraphAnimation animation = null; |
handstudio/HzGrapher | library/src/com/handstudio/android/hzgraphlib/vo/scattergraph/ScatterGraphVO.java | // Path: library/src/com/handstudio/android/hzgrapherlib/animation/GraphAnimation.java
// public class GraphAnimation {
// public static final int LINEAR_ANIMATION = 1;
//
// public static final int CURVE_REGION_ANIMATION_1 = 2;
// public static final int CURVE_REGION_ANIMATION_2 = 3;
//
// public static final int DEFAULT_DURATION = 2000;
//
// private int animation = LINEAR_ANIMATION;
// private int duration = DEFAULT_DURATION;
//
// public GraphAnimation() {
//
// }
//
// public GraphAnimation(int animation, int duration) {
// super();
// this.animation = animation;
// this.duration = duration;
// }
// public int getAnimation() {
// return animation;
// }
// public void setAnimation(int animation) {
// this.animation = animation;
// }
// public int getDuration() {
// return duration;
// }
// public void setDuration(int duration) {
// this.duration = duration;
// }
//
// }
//
// Path: library/src/com/handstudio/android/hzgrapherlib/vo/Graph.java
// public class Graph {
// public static final int DEFAULT_PADDING = 100;
// public static final int DEFAULT_MARGIN_TOP = 10;
// public static final int DEFAULT_MARGIN_RIGHT = 100;
// public static final int DEFAULT_MAX_VALUE = 500;
// public static final int DEFAULT_INCREMENT = 100;
//
// //padding
// private int paddingBottom = DEFAULT_PADDING;
// private int paddingTop = DEFAULT_PADDING;
// private int paddingLeft = DEFAULT_PADDING;
// private int paddingRight = DEFAULT_PADDING;
//
// //graph margin
// private int marginTop = DEFAULT_MARGIN_TOP;
// private int marginRight = DEFAULT_MARGIN_RIGHT;
//
// private GraphNameBox graphNameBox = null;
//
// public Graph() {
//
// }
// public Graph(int paddingBottom, int paddingTop, int paddingLeft,
// int paddingRight, int marginTop, int marginRight) {
// super();
// this.paddingBottom = paddingBottom;
// this.paddingTop = paddingTop;
// this.paddingLeft = paddingLeft;
// this.paddingRight = paddingRight;
// this.marginTop = marginTop;
// this.marginRight = marginRight;
// }
// public int getPaddingBottom() {
// return paddingBottom;
// }
// public void setPaddingBottom(int paddingBottom) {
// this.paddingBottom = paddingBottom;
// }
// public int getPaddingTop() {
// return paddingTop;
// }
// public void setPaddingTop(int paddingTop) {
// this.paddingTop = paddingTop;
// }
// public int getPaddingLeft() {
// return paddingLeft;
// }
// public void setPaddingLeft(int paddingLeft) {
// this.paddingLeft = paddingLeft;
// }
// public int getPaddingRight() {
// return paddingRight;
// }
// public void setPaddingRight(int paddingRight) {
// this.paddingRight = paddingRight;
// }
// public int getMarginTop() {
// return marginTop;
// }
// public void setMarginTop(int marginTop) {
// this.marginTop = marginTop;
// }
// public int getMarginRight() {
// return marginRight;
// }
// public void setMarginRight(int marginRight) {
// this.marginRight = marginRight;
// }
// public GraphNameBox getGraphNameBox() {
// return graphNameBox;
// }
// public void setGraphNameBox(GraphNameBox graphNameBox) {
// this.graphNameBox = graphNameBox;
// }
// }
| import java.util.List;
import com.handstudio.android.hzgrapherlib.animation.GraphAnimation;
import com.handstudio.android.hzgrapherlib.vo.Graph; | package com.handstudio.android.hzgraphlib.vo.scattergraph;
public class ScatterGraphVO extends Graph
{
public static final String TAG = ScatterGraphVO.class.getSimpleName();
private int maxValueX = 100;
private int maxValueY = 100;
private int incrementX = 20;
private int incrementY = 20;
| // Path: library/src/com/handstudio/android/hzgrapherlib/animation/GraphAnimation.java
// public class GraphAnimation {
// public static final int LINEAR_ANIMATION = 1;
//
// public static final int CURVE_REGION_ANIMATION_1 = 2;
// public static final int CURVE_REGION_ANIMATION_2 = 3;
//
// public static final int DEFAULT_DURATION = 2000;
//
// private int animation = LINEAR_ANIMATION;
// private int duration = DEFAULT_DURATION;
//
// public GraphAnimation() {
//
// }
//
// public GraphAnimation(int animation, int duration) {
// super();
// this.animation = animation;
// this.duration = duration;
// }
// public int getAnimation() {
// return animation;
// }
// public void setAnimation(int animation) {
// this.animation = animation;
// }
// public int getDuration() {
// return duration;
// }
// public void setDuration(int duration) {
// this.duration = duration;
// }
//
// }
//
// Path: library/src/com/handstudio/android/hzgrapherlib/vo/Graph.java
// public class Graph {
// public static final int DEFAULT_PADDING = 100;
// public static final int DEFAULT_MARGIN_TOP = 10;
// public static final int DEFAULT_MARGIN_RIGHT = 100;
// public static final int DEFAULT_MAX_VALUE = 500;
// public static final int DEFAULT_INCREMENT = 100;
//
// //padding
// private int paddingBottom = DEFAULT_PADDING;
// private int paddingTop = DEFAULT_PADDING;
// private int paddingLeft = DEFAULT_PADDING;
// private int paddingRight = DEFAULT_PADDING;
//
// //graph margin
// private int marginTop = DEFAULT_MARGIN_TOP;
// private int marginRight = DEFAULT_MARGIN_RIGHT;
//
// private GraphNameBox graphNameBox = null;
//
// public Graph() {
//
// }
// public Graph(int paddingBottom, int paddingTop, int paddingLeft,
// int paddingRight, int marginTop, int marginRight) {
// super();
// this.paddingBottom = paddingBottom;
// this.paddingTop = paddingTop;
// this.paddingLeft = paddingLeft;
// this.paddingRight = paddingRight;
// this.marginTop = marginTop;
// this.marginRight = marginRight;
// }
// public int getPaddingBottom() {
// return paddingBottom;
// }
// public void setPaddingBottom(int paddingBottom) {
// this.paddingBottom = paddingBottom;
// }
// public int getPaddingTop() {
// return paddingTop;
// }
// public void setPaddingTop(int paddingTop) {
// this.paddingTop = paddingTop;
// }
// public int getPaddingLeft() {
// return paddingLeft;
// }
// public void setPaddingLeft(int paddingLeft) {
// this.paddingLeft = paddingLeft;
// }
// public int getPaddingRight() {
// return paddingRight;
// }
// public void setPaddingRight(int paddingRight) {
// this.paddingRight = paddingRight;
// }
// public int getMarginTop() {
// return marginTop;
// }
// public void setMarginTop(int marginTop) {
// this.marginTop = marginTop;
// }
// public int getMarginRight() {
// return marginRight;
// }
// public void setMarginRight(int marginRight) {
// this.marginRight = marginRight;
// }
// public GraphNameBox getGraphNameBox() {
// return graphNameBox;
// }
// public void setGraphNameBox(GraphNameBox graphNameBox) {
// this.graphNameBox = graphNameBox;
// }
// }
// Path: library/src/com/handstudio/android/hzgraphlib/vo/scattergraph/ScatterGraphVO.java
import java.util.List;
import com.handstudio.android.hzgrapherlib.animation.GraphAnimation;
import com.handstudio.android.hzgrapherlib.vo.Graph;
package com.handstudio.android.hzgraphlib.vo.scattergraph;
public class ScatterGraphVO extends Graph
{
public static final String TAG = ScatterGraphVO.class.getSimpleName();
private int maxValueX = 100;
private int maxValueY = 100;
private int incrementX = 20;
private int incrementY = 20;
| private GraphAnimation animation = null; |
handstudio/HzGrapher | library/src/com/handstudio/android/hzgrapherlib/vo/radargraph/RadarGraphVO.java | // Path: library/src/com/handstudio/android/hzgrapherlib/animation/GraphAnimation.java
// public class GraphAnimation {
// public static final int LINEAR_ANIMATION = 1;
//
// public static final int CURVE_REGION_ANIMATION_1 = 2;
// public static final int CURVE_REGION_ANIMATION_2 = 3;
//
// public static final int DEFAULT_DURATION = 2000;
//
// private int animation = LINEAR_ANIMATION;
// private int duration = DEFAULT_DURATION;
//
// public GraphAnimation() {
//
// }
//
// public GraphAnimation(int animation, int duration) {
// super();
// this.animation = animation;
// this.duration = duration;
// }
// public int getAnimation() {
// return animation;
// }
// public void setAnimation(int animation) {
// this.animation = animation;
// }
// public int getDuration() {
// return duration;
// }
// public void setDuration(int duration) {
// this.duration = duration;
// }
//
// }
//
// Path: library/src/com/handstudio/android/hzgrapherlib/vo/Graph.java
// public class Graph {
// public static final int DEFAULT_PADDING = 100;
// public static final int DEFAULT_MARGIN_TOP = 10;
// public static final int DEFAULT_MARGIN_RIGHT = 100;
// public static final int DEFAULT_MAX_VALUE = 500;
// public static final int DEFAULT_INCREMENT = 100;
//
// //padding
// private int paddingBottom = DEFAULT_PADDING;
// private int paddingTop = DEFAULT_PADDING;
// private int paddingLeft = DEFAULT_PADDING;
// private int paddingRight = DEFAULT_PADDING;
//
// //graph margin
// private int marginTop = DEFAULT_MARGIN_TOP;
// private int marginRight = DEFAULT_MARGIN_RIGHT;
//
// private GraphNameBox graphNameBox = null;
//
// public Graph() {
//
// }
// public Graph(int paddingBottom, int paddingTop, int paddingLeft,
// int paddingRight, int marginTop, int marginRight) {
// super();
// this.paddingBottom = paddingBottom;
// this.paddingTop = paddingTop;
// this.paddingLeft = paddingLeft;
// this.paddingRight = paddingRight;
// this.marginTop = marginTop;
// this.marginRight = marginRight;
// }
// public int getPaddingBottom() {
// return paddingBottom;
// }
// public void setPaddingBottom(int paddingBottom) {
// this.paddingBottom = paddingBottom;
// }
// public int getPaddingTop() {
// return paddingTop;
// }
// public void setPaddingTop(int paddingTop) {
// this.paddingTop = paddingTop;
// }
// public int getPaddingLeft() {
// return paddingLeft;
// }
// public void setPaddingLeft(int paddingLeft) {
// this.paddingLeft = paddingLeft;
// }
// public int getPaddingRight() {
// return paddingRight;
// }
// public void setPaddingRight(int paddingRight) {
// this.paddingRight = paddingRight;
// }
// public int getMarginTop() {
// return marginTop;
// }
// public void setMarginTop(int marginTop) {
// this.marginTop = marginTop;
// }
// public int getMarginRight() {
// return marginRight;
// }
// public void setMarginRight(int marginRight) {
// this.marginRight = marginRight;
// }
// public GraphNameBox getGraphNameBox() {
// return graphNameBox;
// }
// public void setGraphNameBox(GraphNameBox graphNameBox) {
// this.graphNameBox = graphNameBox;
// }
// }
//
// Path: library/src/com/handstudio/android/hzgrapherlib/vo/linegraph/LineGraph.java
// public class LineGraph {
// private String name = null;
// private int color = Color.BLUE;
// private float[] coordinateArr = null;
// private int bitmapResource = -1;
//
// public LineGraph(String name, int color, float[] coordinateArr) {
// this.name = name;
// this.color = color;
// this.setCoordinateArr(coordinateArr);
// }
//
// public LineGraph(String name, int color, float[] coordinateArr, int bitmapResource) {
// this.name = name;
// this.color = color;
// this.setCoordinateArr(coordinateArr);
// this.bitmapResource = bitmapResource;
// }
//
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
// public int getColor() {
// return color;
// }
// public void setColor(int color) {
// this.color = color;
// }
// public float[] getCoordinateArr() {
// return coordinateArr;
// }
// public void setCoordinateArr(float[] coordinateArr) {
// this.coordinateArr = coordinateArr;
// }
// public int getBitmapResource() {
// return bitmapResource;
// }
// public void setBitmapResource(int bitmapResource) {
// this.bitmapResource = bitmapResource;
// }
// }
| import java.util.List;
import com.handstudio.android.hzgrapherlib.animation.GraphAnimation;
import com.handstudio.android.hzgrapherlib.vo.Graph;
import com.handstudio.android.hzgrapherlib.vo.linegraph.LineGraph; | package com.handstudio.android.hzgrapherlib.vo.radargraph;
public class RadarGraphVO extends Graph{
public static final int DEFAULT_MAX_VALUE = 100;
public static final int DEFAULT_INCREMENT = 20;
//max value
private int maxValue = DEFAULT_MAX_VALUE;
//increment
private int increment = DEFAULT_INCREMENT;
//animation | // Path: library/src/com/handstudio/android/hzgrapherlib/animation/GraphAnimation.java
// public class GraphAnimation {
// public static final int LINEAR_ANIMATION = 1;
//
// public static final int CURVE_REGION_ANIMATION_1 = 2;
// public static final int CURVE_REGION_ANIMATION_2 = 3;
//
// public static final int DEFAULT_DURATION = 2000;
//
// private int animation = LINEAR_ANIMATION;
// private int duration = DEFAULT_DURATION;
//
// public GraphAnimation() {
//
// }
//
// public GraphAnimation(int animation, int duration) {
// super();
// this.animation = animation;
// this.duration = duration;
// }
// public int getAnimation() {
// return animation;
// }
// public void setAnimation(int animation) {
// this.animation = animation;
// }
// public int getDuration() {
// return duration;
// }
// public void setDuration(int duration) {
// this.duration = duration;
// }
//
// }
//
// Path: library/src/com/handstudio/android/hzgrapherlib/vo/Graph.java
// public class Graph {
// public static final int DEFAULT_PADDING = 100;
// public static final int DEFAULT_MARGIN_TOP = 10;
// public static final int DEFAULT_MARGIN_RIGHT = 100;
// public static final int DEFAULT_MAX_VALUE = 500;
// public static final int DEFAULT_INCREMENT = 100;
//
// //padding
// private int paddingBottom = DEFAULT_PADDING;
// private int paddingTop = DEFAULT_PADDING;
// private int paddingLeft = DEFAULT_PADDING;
// private int paddingRight = DEFAULT_PADDING;
//
// //graph margin
// private int marginTop = DEFAULT_MARGIN_TOP;
// private int marginRight = DEFAULT_MARGIN_RIGHT;
//
// private GraphNameBox graphNameBox = null;
//
// public Graph() {
//
// }
// public Graph(int paddingBottom, int paddingTop, int paddingLeft,
// int paddingRight, int marginTop, int marginRight) {
// super();
// this.paddingBottom = paddingBottom;
// this.paddingTop = paddingTop;
// this.paddingLeft = paddingLeft;
// this.paddingRight = paddingRight;
// this.marginTop = marginTop;
// this.marginRight = marginRight;
// }
// public int getPaddingBottom() {
// return paddingBottom;
// }
// public void setPaddingBottom(int paddingBottom) {
// this.paddingBottom = paddingBottom;
// }
// public int getPaddingTop() {
// return paddingTop;
// }
// public void setPaddingTop(int paddingTop) {
// this.paddingTop = paddingTop;
// }
// public int getPaddingLeft() {
// return paddingLeft;
// }
// public void setPaddingLeft(int paddingLeft) {
// this.paddingLeft = paddingLeft;
// }
// public int getPaddingRight() {
// return paddingRight;
// }
// public void setPaddingRight(int paddingRight) {
// this.paddingRight = paddingRight;
// }
// public int getMarginTop() {
// return marginTop;
// }
// public void setMarginTop(int marginTop) {
// this.marginTop = marginTop;
// }
// public int getMarginRight() {
// return marginRight;
// }
// public void setMarginRight(int marginRight) {
// this.marginRight = marginRight;
// }
// public GraphNameBox getGraphNameBox() {
// return graphNameBox;
// }
// public void setGraphNameBox(GraphNameBox graphNameBox) {
// this.graphNameBox = graphNameBox;
// }
// }
//
// Path: library/src/com/handstudio/android/hzgrapherlib/vo/linegraph/LineGraph.java
// public class LineGraph {
// private String name = null;
// private int color = Color.BLUE;
// private float[] coordinateArr = null;
// private int bitmapResource = -1;
//
// public LineGraph(String name, int color, float[] coordinateArr) {
// this.name = name;
// this.color = color;
// this.setCoordinateArr(coordinateArr);
// }
//
// public LineGraph(String name, int color, float[] coordinateArr, int bitmapResource) {
// this.name = name;
// this.color = color;
// this.setCoordinateArr(coordinateArr);
// this.bitmapResource = bitmapResource;
// }
//
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
// public int getColor() {
// return color;
// }
// public void setColor(int color) {
// this.color = color;
// }
// public float[] getCoordinateArr() {
// return coordinateArr;
// }
// public void setCoordinateArr(float[] coordinateArr) {
// this.coordinateArr = coordinateArr;
// }
// public int getBitmapResource() {
// return bitmapResource;
// }
// public void setBitmapResource(int bitmapResource) {
// this.bitmapResource = bitmapResource;
// }
// }
// Path: library/src/com/handstudio/android/hzgrapherlib/vo/radargraph/RadarGraphVO.java
import java.util.List;
import com.handstudio.android.hzgrapherlib.animation.GraphAnimation;
import com.handstudio.android.hzgrapherlib.vo.Graph;
import com.handstudio.android.hzgrapherlib.vo.linegraph.LineGraph;
package com.handstudio.android.hzgrapherlib.vo.radargraph;
public class RadarGraphVO extends Graph{
public static final int DEFAULT_MAX_VALUE = 100;
public static final int DEFAULT_INCREMENT = 20;
//max value
private int maxValue = DEFAULT_MAX_VALUE;
//increment
private int increment = DEFAULT_INCREMENT;
//animation | private GraphAnimation animation = null; |
handstudio/HzGrapher | library/src/com/handstudio/android/hzgrapherlib/vo/circlegraph/CircleGraphVO.java | // Path: library/src/com/handstudio/android/hzgrapherlib/animation/GraphAnimation.java
// public class GraphAnimation {
// public static final int LINEAR_ANIMATION = 1;
//
// public static final int CURVE_REGION_ANIMATION_1 = 2;
// public static final int CURVE_REGION_ANIMATION_2 = 3;
//
// public static final int DEFAULT_DURATION = 2000;
//
// private int animation = LINEAR_ANIMATION;
// private int duration = DEFAULT_DURATION;
//
// public GraphAnimation() {
//
// }
//
// public GraphAnimation(int animation, int duration) {
// super();
// this.animation = animation;
// this.duration = duration;
// }
// public int getAnimation() {
// return animation;
// }
// public void setAnimation(int animation) {
// this.animation = animation;
// }
// public int getDuration() {
// return duration;
// }
// public void setDuration(int duration) {
// this.duration = duration;
// }
//
// }
//
// Path: library/src/com/handstudio/android/hzgrapherlib/vo/Graph.java
// public class Graph {
// public static final int DEFAULT_PADDING = 100;
// public static final int DEFAULT_MARGIN_TOP = 10;
// public static final int DEFAULT_MARGIN_RIGHT = 100;
// public static final int DEFAULT_MAX_VALUE = 500;
// public static final int DEFAULT_INCREMENT = 100;
//
// //padding
// private int paddingBottom = DEFAULT_PADDING;
// private int paddingTop = DEFAULT_PADDING;
// private int paddingLeft = DEFAULT_PADDING;
// private int paddingRight = DEFAULT_PADDING;
//
// //graph margin
// private int marginTop = DEFAULT_MARGIN_TOP;
// private int marginRight = DEFAULT_MARGIN_RIGHT;
//
// private GraphNameBox graphNameBox = null;
//
// public Graph() {
//
// }
// public Graph(int paddingBottom, int paddingTop, int paddingLeft,
// int paddingRight, int marginTop, int marginRight) {
// super();
// this.paddingBottom = paddingBottom;
// this.paddingTop = paddingTop;
// this.paddingLeft = paddingLeft;
// this.paddingRight = paddingRight;
// this.marginTop = marginTop;
// this.marginRight = marginRight;
// }
// public int getPaddingBottom() {
// return paddingBottom;
// }
// public void setPaddingBottom(int paddingBottom) {
// this.paddingBottom = paddingBottom;
// }
// public int getPaddingTop() {
// return paddingTop;
// }
// public void setPaddingTop(int paddingTop) {
// this.paddingTop = paddingTop;
// }
// public int getPaddingLeft() {
// return paddingLeft;
// }
// public void setPaddingLeft(int paddingLeft) {
// this.paddingLeft = paddingLeft;
// }
// public int getPaddingRight() {
// return paddingRight;
// }
// public void setPaddingRight(int paddingRight) {
// this.paddingRight = paddingRight;
// }
// public int getMarginTop() {
// return marginTop;
// }
// public void setMarginTop(int marginTop) {
// this.marginTop = marginTop;
// }
// public int getMarginRight() {
// return marginRight;
// }
// public void setMarginRight(int marginRight) {
// this.marginRight = marginRight;
// }
// public GraphNameBox getGraphNameBox() {
// return graphNameBox;
// }
// public void setGraphNameBox(GraphNameBox graphNameBox) {
// this.graphNameBox = graphNameBox;
// }
// }
| import java.util.List;
import android.graphics.Color;
import com.handstudio.android.hzgrapherlib.animation.GraphAnimation;
import com.handstudio.android.hzgrapherlib.vo.Graph; | package com.handstudio.android.hzgrapherlib.vo.circlegraph;
public class CircleGraphVO extends Graph{
//animation
private int radius ;
private int lineColor = Color.BLACK;
private int textColor = Color.BLACK;
private int textSize = 20;
private int graphBG = -1;
private int centerX = 0;
private int centerY = 0;
| // Path: library/src/com/handstudio/android/hzgrapherlib/animation/GraphAnimation.java
// public class GraphAnimation {
// public static final int LINEAR_ANIMATION = 1;
//
// public static final int CURVE_REGION_ANIMATION_1 = 2;
// public static final int CURVE_REGION_ANIMATION_2 = 3;
//
// public static final int DEFAULT_DURATION = 2000;
//
// private int animation = LINEAR_ANIMATION;
// private int duration = DEFAULT_DURATION;
//
// public GraphAnimation() {
//
// }
//
// public GraphAnimation(int animation, int duration) {
// super();
// this.animation = animation;
// this.duration = duration;
// }
// public int getAnimation() {
// return animation;
// }
// public void setAnimation(int animation) {
// this.animation = animation;
// }
// public int getDuration() {
// return duration;
// }
// public void setDuration(int duration) {
// this.duration = duration;
// }
//
// }
//
// Path: library/src/com/handstudio/android/hzgrapherlib/vo/Graph.java
// public class Graph {
// public static final int DEFAULT_PADDING = 100;
// public static final int DEFAULT_MARGIN_TOP = 10;
// public static final int DEFAULT_MARGIN_RIGHT = 100;
// public static final int DEFAULT_MAX_VALUE = 500;
// public static final int DEFAULT_INCREMENT = 100;
//
// //padding
// private int paddingBottom = DEFAULT_PADDING;
// private int paddingTop = DEFAULT_PADDING;
// private int paddingLeft = DEFAULT_PADDING;
// private int paddingRight = DEFAULT_PADDING;
//
// //graph margin
// private int marginTop = DEFAULT_MARGIN_TOP;
// private int marginRight = DEFAULT_MARGIN_RIGHT;
//
// private GraphNameBox graphNameBox = null;
//
// public Graph() {
//
// }
// public Graph(int paddingBottom, int paddingTop, int paddingLeft,
// int paddingRight, int marginTop, int marginRight) {
// super();
// this.paddingBottom = paddingBottom;
// this.paddingTop = paddingTop;
// this.paddingLeft = paddingLeft;
// this.paddingRight = paddingRight;
// this.marginTop = marginTop;
// this.marginRight = marginRight;
// }
// public int getPaddingBottom() {
// return paddingBottom;
// }
// public void setPaddingBottom(int paddingBottom) {
// this.paddingBottom = paddingBottom;
// }
// public int getPaddingTop() {
// return paddingTop;
// }
// public void setPaddingTop(int paddingTop) {
// this.paddingTop = paddingTop;
// }
// public int getPaddingLeft() {
// return paddingLeft;
// }
// public void setPaddingLeft(int paddingLeft) {
// this.paddingLeft = paddingLeft;
// }
// public int getPaddingRight() {
// return paddingRight;
// }
// public void setPaddingRight(int paddingRight) {
// this.paddingRight = paddingRight;
// }
// public int getMarginTop() {
// return marginTop;
// }
// public void setMarginTop(int marginTop) {
// this.marginTop = marginTop;
// }
// public int getMarginRight() {
// return marginRight;
// }
// public void setMarginRight(int marginRight) {
// this.marginRight = marginRight;
// }
// public GraphNameBox getGraphNameBox() {
// return graphNameBox;
// }
// public void setGraphNameBox(GraphNameBox graphNameBox) {
// this.graphNameBox = graphNameBox;
// }
// }
// Path: library/src/com/handstudio/android/hzgrapherlib/vo/circlegraph/CircleGraphVO.java
import java.util.List;
import android.graphics.Color;
import com.handstudio.android.hzgrapherlib.animation.GraphAnimation;
import com.handstudio.android.hzgrapherlib.vo.Graph;
package com.handstudio.android.hzgrapherlib.vo.circlegraph;
public class CircleGraphVO extends Graph{
//animation
private int radius ;
private int lineColor = Color.BLACK;
private int textColor = Color.BLACK;
private int textSize = 20;
private int graphBG = -1;
private int centerX = 0;
private int centerY = 0;
| private GraphAnimation animation = null; |
handstudio/HzGrapher | library/src/com/handstudio/android/hzgrapherlib/vo/bargraph/BarGraphVO.java | // Path: library/src/com/handstudio/android/hzgrapherlib/animation/GraphAnimation.java
// public class GraphAnimation {
// public static final int LINEAR_ANIMATION = 1;
//
// public static final int CURVE_REGION_ANIMATION_1 = 2;
// public static final int CURVE_REGION_ANIMATION_2 = 3;
//
// public static final int DEFAULT_DURATION = 2000;
//
// private int animation = LINEAR_ANIMATION;
// private int duration = DEFAULT_DURATION;
//
// public GraphAnimation() {
//
// }
//
// public GraphAnimation(int animation, int duration) {
// super();
// this.animation = animation;
// this.duration = duration;
// }
// public int getAnimation() {
// return animation;
// }
// public void setAnimation(int animation) {
// this.animation = animation;
// }
// public int getDuration() {
// return duration;
// }
// public void setDuration(int duration) {
// this.duration = duration;
// }
//
// }
//
// Path: library/src/com/handstudio/android/hzgrapherlib/vo/Graph.java
// public class Graph {
// public static final int DEFAULT_PADDING = 100;
// public static final int DEFAULT_MARGIN_TOP = 10;
// public static final int DEFAULT_MARGIN_RIGHT = 100;
// public static final int DEFAULT_MAX_VALUE = 500;
// public static final int DEFAULT_INCREMENT = 100;
//
// //padding
// private int paddingBottom = DEFAULT_PADDING;
// private int paddingTop = DEFAULT_PADDING;
// private int paddingLeft = DEFAULT_PADDING;
// private int paddingRight = DEFAULT_PADDING;
//
// //graph margin
// private int marginTop = DEFAULT_MARGIN_TOP;
// private int marginRight = DEFAULT_MARGIN_RIGHT;
//
// private GraphNameBox graphNameBox = null;
//
// public Graph() {
//
// }
// public Graph(int paddingBottom, int paddingTop, int paddingLeft,
// int paddingRight, int marginTop, int marginRight) {
// super();
// this.paddingBottom = paddingBottom;
// this.paddingTop = paddingTop;
// this.paddingLeft = paddingLeft;
// this.paddingRight = paddingRight;
// this.marginTop = marginTop;
// this.marginRight = marginRight;
// }
// public int getPaddingBottom() {
// return paddingBottom;
// }
// public void setPaddingBottom(int paddingBottom) {
// this.paddingBottom = paddingBottom;
// }
// public int getPaddingTop() {
// return paddingTop;
// }
// public void setPaddingTop(int paddingTop) {
// this.paddingTop = paddingTop;
// }
// public int getPaddingLeft() {
// return paddingLeft;
// }
// public void setPaddingLeft(int paddingLeft) {
// this.paddingLeft = paddingLeft;
// }
// public int getPaddingRight() {
// return paddingRight;
// }
// public void setPaddingRight(int paddingRight) {
// this.paddingRight = paddingRight;
// }
// public int getMarginTop() {
// return marginTop;
// }
// public void setMarginTop(int marginTop) {
// this.marginTop = marginTop;
// }
// public int getMarginRight() {
// return marginRight;
// }
// public void setMarginRight(int marginRight) {
// this.marginRight = marginRight;
// }
// public GraphNameBox getGraphNameBox() {
// return graphNameBox;
// }
// public void setGraphNameBox(GraphNameBox graphNameBox) {
// this.graphNameBox = graphNameBox;
// }
// }
| import java.util.List;
import com.handstudio.android.hzgrapherlib.animation.GraphAnimation;
import com.handstudio.android.hzgrapherlib.vo.Graph; | package com.handstudio.android.hzgrapherlib.vo.bargraph;
public class BarGraphVO extends Graph {
private float minValueX;
private float maxValueX;
private float minValueY;
private float maxValueY;
private float incrementX;
private float incrementY;
private float barWidth;
private int graphBG;
private long animationDuration;
private boolean isAnimationShow;
private boolean isDrawRegion = false;
| // Path: library/src/com/handstudio/android/hzgrapherlib/animation/GraphAnimation.java
// public class GraphAnimation {
// public static final int LINEAR_ANIMATION = 1;
//
// public static final int CURVE_REGION_ANIMATION_1 = 2;
// public static final int CURVE_REGION_ANIMATION_2 = 3;
//
// public static final int DEFAULT_DURATION = 2000;
//
// private int animation = LINEAR_ANIMATION;
// private int duration = DEFAULT_DURATION;
//
// public GraphAnimation() {
//
// }
//
// public GraphAnimation(int animation, int duration) {
// super();
// this.animation = animation;
// this.duration = duration;
// }
// public int getAnimation() {
// return animation;
// }
// public void setAnimation(int animation) {
// this.animation = animation;
// }
// public int getDuration() {
// return duration;
// }
// public void setDuration(int duration) {
// this.duration = duration;
// }
//
// }
//
// Path: library/src/com/handstudio/android/hzgrapherlib/vo/Graph.java
// public class Graph {
// public static final int DEFAULT_PADDING = 100;
// public static final int DEFAULT_MARGIN_TOP = 10;
// public static final int DEFAULT_MARGIN_RIGHT = 100;
// public static final int DEFAULT_MAX_VALUE = 500;
// public static final int DEFAULT_INCREMENT = 100;
//
// //padding
// private int paddingBottom = DEFAULT_PADDING;
// private int paddingTop = DEFAULT_PADDING;
// private int paddingLeft = DEFAULT_PADDING;
// private int paddingRight = DEFAULT_PADDING;
//
// //graph margin
// private int marginTop = DEFAULT_MARGIN_TOP;
// private int marginRight = DEFAULT_MARGIN_RIGHT;
//
// private GraphNameBox graphNameBox = null;
//
// public Graph() {
//
// }
// public Graph(int paddingBottom, int paddingTop, int paddingLeft,
// int paddingRight, int marginTop, int marginRight) {
// super();
// this.paddingBottom = paddingBottom;
// this.paddingTop = paddingTop;
// this.paddingLeft = paddingLeft;
// this.paddingRight = paddingRight;
// this.marginTop = marginTop;
// this.marginRight = marginRight;
// }
// public int getPaddingBottom() {
// return paddingBottom;
// }
// public void setPaddingBottom(int paddingBottom) {
// this.paddingBottom = paddingBottom;
// }
// public int getPaddingTop() {
// return paddingTop;
// }
// public void setPaddingTop(int paddingTop) {
// this.paddingTop = paddingTop;
// }
// public int getPaddingLeft() {
// return paddingLeft;
// }
// public void setPaddingLeft(int paddingLeft) {
// this.paddingLeft = paddingLeft;
// }
// public int getPaddingRight() {
// return paddingRight;
// }
// public void setPaddingRight(int paddingRight) {
// this.paddingRight = paddingRight;
// }
// public int getMarginTop() {
// return marginTop;
// }
// public void setMarginTop(int marginTop) {
// this.marginTop = marginTop;
// }
// public int getMarginRight() {
// return marginRight;
// }
// public void setMarginRight(int marginRight) {
// this.marginRight = marginRight;
// }
// public GraphNameBox getGraphNameBox() {
// return graphNameBox;
// }
// public void setGraphNameBox(GraphNameBox graphNameBox) {
// this.graphNameBox = graphNameBox;
// }
// }
// Path: library/src/com/handstudio/android/hzgrapherlib/vo/bargraph/BarGraphVO.java
import java.util.List;
import com.handstudio.android.hzgrapherlib.animation.GraphAnimation;
import com.handstudio.android.hzgrapherlib.vo.Graph;
package com.handstudio.android.hzgrapherlib.vo.bargraph;
public class BarGraphVO extends Graph {
private float minValueX;
private float maxValueX;
private float minValueY;
private float maxValueY;
private float incrementX;
private float incrementY;
private float barWidth;
private int graphBG;
private long animationDuration;
private boolean isAnimationShow;
private boolean isDrawRegion = false;
| private GraphAnimation animation = null; |
handstudio/HzGrapher | library/src/com/handstudio/android/hzgrapherlib/vo/curvegraph/CurveGraphVO.java | // Path: library/src/com/handstudio/android/hzgrapherlib/animation/GraphAnimation.java
// public class GraphAnimation {
// public static final int LINEAR_ANIMATION = 1;
//
// public static final int CURVE_REGION_ANIMATION_1 = 2;
// public static final int CURVE_REGION_ANIMATION_2 = 3;
//
// public static final int DEFAULT_DURATION = 2000;
//
// private int animation = LINEAR_ANIMATION;
// private int duration = DEFAULT_DURATION;
//
// public GraphAnimation() {
//
// }
//
// public GraphAnimation(int animation, int duration) {
// super();
// this.animation = animation;
// this.duration = duration;
// }
// public int getAnimation() {
// return animation;
// }
// public void setAnimation(int animation) {
// this.animation = animation;
// }
// public int getDuration() {
// return duration;
// }
// public void setDuration(int duration) {
// this.duration = duration;
// }
//
// }
//
// Path: library/src/com/handstudio/android/hzgrapherlib/vo/Graph.java
// public class Graph {
// public static final int DEFAULT_PADDING = 100;
// public static final int DEFAULT_MARGIN_TOP = 10;
// public static final int DEFAULT_MARGIN_RIGHT = 100;
// public static final int DEFAULT_MAX_VALUE = 500;
// public static final int DEFAULT_INCREMENT = 100;
//
// //padding
// private int paddingBottom = DEFAULT_PADDING;
// private int paddingTop = DEFAULT_PADDING;
// private int paddingLeft = DEFAULT_PADDING;
// private int paddingRight = DEFAULT_PADDING;
//
// //graph margin
// private int marginTop = DEFAULT_MARGIN_TOP;
// private int marginRight = DEFAULT_MARGIN_RIGHT;
//
// private GraphNameBox graphNameBox = null;
//
// public Graph() {
//
// }
// public Graph(int paddingBottom, int paddingTop, int paddingLeft,
// int paddingRight, int marginTop, int marginRight) {
// super();
// this.paddingBottom = paddingBottom;
// this.paddingTop = paddingTop;
// this.paddingLeft = paddingLeft;
// this.paddingRight = paddingRight;
// this.marginTop = marginTop;
// this.marginRight = marginRight;
// }
// public int getPaddingBottom() {
// return paddingBottom;
// }
// public void setPaddingBottom(int paddingBottom) {
// this.paddingBottom = paddingBottom;
// }
// public int getPaddingTop() {
// return paddingTop;
// }
// public void setPaddingTop(int paddingTop) {
// this.paddingTop = paddingTop;
// }
// public int getPaddingLeft() {
// return paddingLeft;
// }
// public void setPaddingLeft(int paddingLeft) {
// this.paddingLeft = paddingLeft;
// }
// public int getPaddingRight() {
// return paddingRight;
// }
// public void setPaddingRight(int paddingRight) {
// this.paddingRight = paddingRight;
// }
// public int getMarginTop() {
// return marginTop;
// }
// public void setMarginTop(int marginTop) {
// this.marginTop = marginTop;
// }
// public int getMarginRight() {
// return marginRight;
// }
// public void setMarginRight(int marginRight) {
// this.marginRight = marginRight;
// }
// public GraphNameBox getGraphNameBox() {
// return graphNameBox;
// }
// public void setGraphNameBox(GraphNameBox graphNameBox) {
// this.graphNameBox = graphNameBox;
// }
// }
| import java.util.List;
import com.handstudio.android.hzgrapherlib.animation.GraphAnimation;
import com.handstudio.android.hzgrapherlib.vo.Graph; | package com.handstudio.android.hzgrapherlib.vo.curvegraph;
public class CurveGraphVO extends Graph {
// max value
private int maxValue = DEFAULT_MAX_VALUE;
// increment
private int increment = DEFAULT_INCREMENT;
// animation | // Path: library/src/com/handstudio/android/hzgrapherlib/animation/GraphAnimation.java
// public class GraphAnimation {
// public static final int LINEAR_ANIMATION = 1;
//
// public static final int CURVE_REGION_ANIMATION_1 = 2;
// public static final int CURVE_REGION_ANIMATION_2 = 3;
//
// public static final int DEFAULT_DURATION = 2000;
//
// private int animation = LINEAR_ANIMATION;
// private int duration = DEFAULT_DURATION;
//
// public GraphAnimation() {
//
// }
//
// public GraphAnimation(int animation, int duration) {
// super();
// this.animation = animation;
// this.duration = duration;
// }
// public int getAnimation() {
// return animation;
// }
// public void setAnimation(int animation) {
// this.animation = animation;
// }
// public int getDuration() {
// return duration;
// }
// public void setDuration(int duration) {
// this.duration = duration;
// }
//
// }
//
// Path: library/src/com/handstudio/android/hzgrapherlib/vo/Graph.java
// public class Graph {
// public static final int DEFAULT_PADDING = 100;
// public static final int DEFAULT_MARGIN_TOP = 10;
// public static final int DEFAULT_MARGIN_RIGHT = 100;
// public static final int DEFAULT_MAX_VALUE = 500;
// public static final int DEFAULT_INCREMENT = 100;
//
// //padding
// private int paddingBottom = DEFAULT_PADDING;
// private int paddingTop = DEFAULT_PADDING;
// private int paddingLeft = DEFAULT_PADDING;
// private int paddingRight = DEFAULT_PADDING;
//
// //graph margin
// private int marginTop = DEFAULT_MARGIN_TOP;
// private int marginRight = DEFAULT_MARGIN_RIGHT;
//
// private GraphNameBox graphNameBox = null;
//
// public Graph() {
//
// }
// public Graph(int paddingBottom, int paddingTop, int paddingLeft,
// int paddingRight, int marginTop, int marginRight) {
// super();
// this.paddingBottom = paddingBottom;
// this.paddingTop = paddingTop;
// this.paddingLeft = paddingLeft;
// this.paddingRight = paddingRight;
// this.marginTop = marginTop;
// this.marginRight = marginRight;
// }
// public int getPaddingBottom() {
// return paddingBottom;
// }
// public void setPaddingBottom(int paddingBottom) {
// this.paddingBottom = paddingBottom;
// }
// public int getPaddingTop() {
// return paddingTop;
// }
// public void setPaddingTop(int paddingTop) {
// this.paddingTop = paddingTop;
// }
// public int getPaddingLeft() {
// return paddingLeft;
// }
// public void setPaddingLeft(int paddingLeft) {
// this.paddingLeft = paddingLeft;
// }
// public int getPaddingRight() {
// return paddingRight;
// }
// public void setPaddingRight(int paddingRight) {
// this.paddingRight = paddingRight;
// }
// public int getMarginTop() {
// return marginTop;
// }
// public void setMarginTop(int marginTop) {
// this.marginTop = marginTop;
// }
// public int getMarginRight() {
// return marginRight;
// }
// public void setMarginRight(int marginRight) {
// this.marginRight = marginRight;
// }
// public GraphNameBox getGraphNameBox() {
// return graphNameBox;
// }
// public void setGraphNameBox(GraphNameBox graphNameBox) {
// this.graphNameBox = graphNameBox;
// }
// }
// Path: library/src/com/handstudio/android/hzgrapherlib/vo/curvegraph/CurveGraphVO.java
import java.util.List;
import com.handstudio.android.hzgrapherlib.animation.GraphAnimation;
import com.handstudio.android.hzgrapherlib.vo.Graph;
package com.handstudio.android.hzgrapherlib.vo.curvegraph;
public class CurveGraphVO extends Graph {
// max value
private int maxValue = DEFAULT_MAX_VALUE;
// increment
private int increment = DEFAULT_INCREMENT;
// animation | private GraphAnimation animation = null; |
dmytroKarataiev/EarthquakeSurvival | app/src/main/java/com/adkdevelopment/earthquakesurvival/App.java | // Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/data/remote/ApiManager.java
// public class ApiManager {
//
// private final String BASE_URL = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/";
//
// private final Retrofit EARTHQUAKE_ADAPTER = new Retrofit.Builder()
// .baseUrl(BASE_URL)
// .addConverterFactory(new ToStringConverterFactory())
// .client(new OkHttpClient.Builder()
// .sslSocketFactory(getSSLConfig(App.getContext()).getSocketFactory()).build())
// .addConverterFactory(GsonConverterFactory.create())
// .build();
//
// private final EarthquakeService EARTHQUAKE_SERVICE = EARTHQUAKE_ADAPTER.create(EarthquakeService.class);
//
// public ApiManager() throws Exception {
// }
//
// public EarthquakeService getEarthquakeService() {
// return EARTHQUAKE_SERVICE;
// }
//
// private final Retrofit NEWS_ADAPTER = new Retrofit.Builder()
// .baseUrl(BASE_URL)
// .addConverterFactory(SimpleXmlConverterFactory.create())
// .build();
//
// private final EarthquakeService NEWS_SERVICE = NEWS_ADAPTER.create(EarthquakeService.class);
//
// public EarthquakeService getNewsService() {
// return NEWS_SERVICE;
// }
//
// private static SSLContext getSSLConfig(Context context) throws CertificateException, IOException,
// KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
//
// // Loading CAs from an InputStream
// CertificateFactory cf = null;
// cf = CertificateFactory.getInstance("X.509");
//
// Certificate ca;
// // I'm using Java7. If you used Java6 close it manually with finally.
// InputStream cert = context.getResources().openRawResource(R.raw.usgs);
// ca = cf.generateCertificate(cert);
//
// // Creating a KeyStore containing our trusted CAs
// String keyStoreType = KeyStore.getDefaultType();
// KeyStore keyStore = KeyStore.getInstance(keyStoreType);
// keyStore.load(null, null);
// keyStore.setCertificateEntry("ca", ca);
//
// // Creating a TrustManager that trusts the CAs in our KeyStore.
// String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
// TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
// tmf.init(keyStore);
//
// TrustManager[] trustManagers = tmf.getTrustManagers();
// final X509TrustManager origTrustmanager = (X509TrustManager) trustManagers[0];
//
// TrustManager[] wrappedTrustManagers = new TrustManager[]{
// new X509TrustManager() {
// @Override
// public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
// origTrustmanager.checkClientTrusted(x509Certificates, s);
// }
//
// public java.security.cert.X509Certificate[] getAcceptedIssuers() {
// return origTrustmanager.getAcceptedIssuers();
// }
//
// public void checkServerTrusted(X509Certificate[] certs, String authType) {
// try {
// origTrustmanager.checkServerTrusted(certs, authType);
// } catch (CertificateException e) {
// e.printStackTrace();
// }
// }
// }
// };
//
// // Creating an SSLSocketFactory that uses our TrustManager
// SSLContext sslContext = SSLContext.getInstance("TLS");
// sslContext.init(null, wrappedTrustManagers, null);
//
// return sslContext;
// }
// }
//
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/eventbus/RxBus.java
// public class RxBus {
//
// private final Subject<Object, Object> _bus = new SerializedSubject<>(PublishSubject.create());
//
// public void send(Object o) {
// _bus.onNext(o);
// }
//
// public Observable<Object> toObservable() {
// return _bus;
// }
//
// public boolean hasObservers() {
// return _bus.hasObservers();
// }
// }
| import io.fabric.sdk.android.Fabric;
import android.app.Application;
import android.content.Context;
import com.adkdevelopment.earthquakesurvival.data.remote.ApiManager;
import com.adkdevelopment.earthquakesurvival.eventbus.RxBus;
import com.crashlytics.android.Crashlytics; | /*
* MIT License
*
* Copyright (c) 2016. Dmytro Karataiev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.adkdevelopment.earthquakesurvival;
/**
* Main Application class, which keeps singletons for managers
* and for the eventbus.
* Created by karataev on 3/24/16.
*/
public class App extends Application {
private static ApiManager sApiManager, sNewsManager;
private static Context sContext;
// event bus from RxJava | // Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/data/remote/ApiManager.java
// public class ApiManager {
//
// private final String BASE_URL = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/";
//
// private final Retrofit EARTHQUAKE_ADAPTER = new Retrofit.Builder()
// .baseUrl(BASE_URL)
// .addConverterFactory(new ToStringConverterFactory())
// .client(new OkHttpClient.Builder()
// .sslSocketFactory(getSSLConfig(App.getContext()).getSocketFactory()).build())
// .addConverterFactory(GsonConverterFactory.create())
// .build();
//
// private final EarthquakeService EARTHQUAKE_SERVICE = EARTHQUAKE_ADAPTER.create(EarthquakeService.class);
//
// public ApiManager() throws Exception {
// }
//
// public EarthquakeService getEarthquakeService() {
// return EARTHQUAKE_SERVICE;
// }
//
// private final Retrofit NEWS_ADAPTER = new Retrofit.Builder()
// .baseUrl(BASE_URL)
// .addConverterFactory(SimpleXmlConverterFactory.create())
// .build();
//
// private final EarthquakeService NEWS_SERVICE = NEWS_ADAPTER.create(EarthquakeService.class);
//
// public EarthquakeService getNewsService() {
// return NEWS_SERVICE;
// }
//
// private static SSLContext getSSLConfig(Context context) throws CertificateException, IOException,
// KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
//
// // Loading CAs from an InputStream
// CertificateFactory cf = null;
// cf = CertificateFactory.getInstance("X.509");
//
// Certificate ca;
// // I'm using Java7. If you used Java6 close it manually with finally.
// InputStream cert = context.getResources().openRawResource(R.raw.usgs);
// ca = cf.generateCertificate(cert);
//
// // Creating a KeyStore containing our trusted CAs
// String keyStoreType = KeyStore.getDefaultType();
// KeyStore keyStore = KeyStore.getInstance(keyStoreType);
// keyStore.load(null, null);
// keyStore.setCertificateEntry("ca", ca);
//
// // Creating a TrustManager that trusts the CAs in our KeyStore.
// String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
// TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
// tmf.init(keyStore);
//
// TrustManager[] trustManagers = tmf.getTrustManagers();
// final X509TrustManager origTrustmanager = (X509TrustManager) trustManagers[0];
//
// TrustManager[] wrappedTrustManagers = new TrustManager[]{
// new X509TrustManager() {
// @Override
// public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
// origTrustmanager.checkClientTrusted(x509Certificates, s);
// }
//
// public java.security.cert.X509Certificate[] getAcceptedIssuers() {
// return origTrustmanager.getAcceptedIssuers();
// }
//
// public void checkServerTrusted(X509Certificate[] certs, String authType) {
// try {
// origTrustmanager.checkServerTrusted(certs, authType);
// } catch (CertificateException e) {
// e.printStackTrace();
// }
// }
// }
// };
//
// // Creating an SSLSocketFactory that uses our TrustManager
// SSLContext sslContext = SSLContext.getInstance("TLS");
// sslContext.init(null, wrappedTrustManagers, null);
//
// return sslContext;
// }
// }
//
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/eventbus/RxBus.java
// public class RxBus {
//
// private final Subject<Object, Object> _bus = new SerializedSubject<>(PublishSubject.create());
//
// public void send(Object o) {
// _bus.onNext(o);
// }
//
// public Observable<Object> toObservable() {
// return _bus;
// }
//
// public boolean hasObservers() {
// return _bus.hasObservers();
// }
// }
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/App.java
import io.fabric.sdk.android.Fabric;
import android.app.Application;
import android.content.Context;
import com.adkdevelopment.earthquakesurvival.data.remote.ApiManager;
import com.adkdevelopment.earthquakesurvival.eventbus.RxBus;
import com.crashlytics.android.Crashlytics;
/*
* MIT License
*
* Copyright (c) 2016. Dmytro Karataiev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.adkdevelopment.earthquakesurvival;
/**
* Main Application class, which keeps singletons for managers
* and for the eventbus.
* Created by karataev on 3/24/16.
*/
public class App extends Application {
private static ApiManager sApiManager, sNewsManager;
private static Context sContext;
// event bus from RxJava | private static RxBus _rxBus; |
dmytroKarataiev/EarthquakeSurvival | app/src/main/java/com/adkdevelopment/earthquakesurvival/data/remote/EarthquakeService.java | // Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/data/objects/earthquake/EarthquakeObject.java
// public class EarthquakeObject {
//
// @SerializedName("type")
// @Expose
// private String type;
// @SerializedName("metadata")
// @Expose
// private Metadata metadata;
// @SerializedName("features")
// @Expose
// private List<Feature> features = new ArrayList<>();
// @SerializedName("bbox")
// @Expose
// private List<Double> bbox = new ArrayList<>();
//
// public static final int NOTIFICATION_ID_1 = 2001;
// public static final int NOTIFICATION_ID_2 = 2000;
//
// public static final int SORT_TIME = 1;
// public static final int SORT_MAGNITUDE = 2;
// public static final int SORT_DISTANCE = 3;
//
// public static final String NOTIFICATION_GROUP = "earthquake_group";
//
// /**
// *
// * @return
// * The type
// */
// public String getType() {
// return type;
// }
//
// /**
// *
// * @param type
// * The type
// */
// public void setType(String type) {
// this.type = type;
// }
//
// /**
// *
// * @return
// * The metadata
// */
// public Metadata getMetadata() {
// return metadata;
// }
//
// /**
// *
// * @param metadata
// * The metadata
// */
// public void setMetadata(Metadata metadata) {
// this.metadata = metadata;
// }
//
// /**
// *
// * @return
// * The features
// */
// public List<Feature> getFeatures() {
// return features;
// }
//
// /**
// *
// * @param features
// * The features
// */
// public void setFeatures(List<Feature> features) {
// this.features = features;
// }
//
// /**
// *
// * @return
// * The bbox
// */
// public List<Double> getBbox() {
// return bbox;
// }
//
// /**
// *
// * @param bbox
// * The bbox
// */
// public void setBbox(List<Double> bbox) {
// this.bbox = bbox;
// }
//
// }
//
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/data/objects/info/CountEarthquakes.java
// public class CountEarthquakes {
//
// @SerializedName("count")
// @Expose
// private int count;
// @SerializedName("maxAllowed")
// @Expose
// private int maxAllowed;
//
// /**
// * @return The count
// */
// public int getCount() {
// return count;
// }
//
// /**
// * @param count The count
// */
// public void setCount(int count) {
// this.count = count;
// }
//
// /**
// * @return The maxAllowed
// */
// public int getMaxAllowed() {
// return maxAllowed;
// }
//
// /**
// * @param maxAllowed The maxAllowed
// */
// public void setMaxAllowed(int maxAllowed) {
// this.maxAllowed = maxAllowed;
// }
//
// }
//
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/data/objects/news/Rss.java
// public class Rss
// {
// @Element(required = false)
// private Channel channel;
//
// @Attribute
// private String version;
//
// public Channel getChannel ()
// {
// return channel;
// }
//
// public void setChannel (Channel channel)
// {
// this.channel = channel;
// }
//
// public String getVersion ()
// {
// return version;
// }
//
// public void setVersion (String version)
// {
// this.version = version;
// }
//
// @Override
// public String toString()
// {
// return "ClassPojo [channel = "+channel+", version = "+version+"]";
// }
// }
| import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;
import com.adkdevelopment.earthquakesurvival.data.objects.earthquake.EarthquakeObject;
import com.adkdevelopment.earthquakesurvival.data.objects.info.CountEarthquakes;
import com.adkdevelopment.earthquakesurvival.data.objects.news.Rss;
import retrofit2.Call;
import retrofit2.http.Field; | /*
* MIT License
*
* Copyright (c) 2016. Dmytro Karataiev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.adkdevelopment.earthquakesurvival.data.remote;
/**
* Public interface with a link to the Endpoint
*/
public interface EarthquakeService {
String sEarthquakeCount = "http://earthquake.usgs.gov/fdsnws/event/1/count?format=geojson";
@GET("all_day.geojson") | // Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/data/objects/earthquake/EarthquakeObject.java
// public class EarthquakeObject {
//
// @SerializedName("type")
// @Expose
// private String type;
// @SerializedName("metadata")
// @Expose
// private Metadata metadata;
// @SerializedName("features")
// @Expose
// private List<Feature> features = new ArrayList<>();
// @SerializedName("bbox")
// @Expose
// private List<Double> bbox = new ArrayList<>();
//
// public static final int NOTIFICATION_ID_1 = 2001;
// public static final int NOTIFICATION_ID_2 = 2000;
//
// public static final int SORT_TIME = 1;
// public static final int SORT_MAGNITUDE = 2;
// public static final int SORT_DISTANCE = 3;
//
// public static final String NOTIFICATION_GROUP = "earthquake_group";
//
// /**
// *
// * @return
// * The type
// */
// public String getType() {
// return type;
// }
//
// /**
// *
// * @param type
// * The type
// */
// public void setType(String type) {
// this.type = type;
// }
//
// /**
// *
// * @return
// * The metadata
// */
// public Metadata getMetadata() {
// return metadata;
// }
//
// /**
// *
// * @param metadata
// * The metadata
// */
// public void setMetadata(Metadata metadata) {
// this.metadata = metadata;
// }
//
// /**
// *
// * @return
// * The features
// */
// public List<Feature> getFeatures() {
// return features;
// }
//
// /**
// *
// * @param features
// * The features
// */
// public void setFeatures(List<Feature> features) {
// this.features = features;
// }
//
// /**
// *
// * @return
// * The bbox
// */
// public List<Double> getBbox() {
// return bbox;
// }
//
// /**
// *
// * @param bbox
// * The bbox
// */
// public void setBbox(List<Double> bbox) {
// this.bbox = bbox;
// }
//
// }
//
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/data/objects/info/CountEarthquakes.java
// public class CountEarthquakes {
//
// @SerializedName("count")
// @Expose
// private int count;
// @SerializedName("maxAllowed")
// @Expose
// private int maxAllowed;
//
// /**
// * @return The count
// */
// public int getCount() {
// return count;
// }
//
// /**
// * @param count The count
// */
// public void setCount(int count) {
// this.count = count;
// }
//
// /**
// * @return The maxAllowed
// */
// public int getMaxAllowed() {
// return maxAllowed;
// }
//
// /**
// * @param maxAllowed The maxAllowed
// */
// public void setMaxAllowed(int maxAllowed) {
// this.maxAllowed = maxAllowed;
// }
//
// }
//
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/data/objects/news/Rss.java
// public class Rss
// {
// @Element(required = false)
// private Channel channel;
//
// @Attribute
// private String version;
//
// public Channel getChannel ()
// {
// return channel;
// }
//
// public void setChannel (Channel channel)
// {
// this.channel = channel;
// }
//
// public String getVersion ()
// {
// return version;
// }
//
// public void setVersion (String version)
// {
// this.version = version;
// }
//
// @Override
// public String toString()
// {
// return "ClassPojo [channel = "+channel+", version = "+version+"]";
// }
// }
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/data/remote/EarthquakeService.java
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;
import com.adkdevelopment.earthquakesurvival.data.objects.earthquake.EarthquakeObject;
import com.adkdevelopment.earthquakesurvival.data.objects.info.CountEarthquakes;
import com.adkdevelopment.earthquakesurvival.data.objects.news.Rss;
import retrofit2.Call;
import retrofit2.http.Field;
/*
* MIT License
*
* Copyright (c) 2016. Dmytro Karataiev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.adkdevelopment.earthquakesurvival.data.remote;
/**
* Public interface with a link to the Endpoint
*/
public interface EarthquakeService {
String sEarthquakeCount = "http://earthquake.usgs.gov/fdsnws/event/1/count?format=geojson";
@GET("all_day.geojson") | Call<EarthquakeObject> getData(); |
dmytroKarataiev/EarthquakeSurvival | app/src/main/java/com/adkdevelopment/earthquakesurvival/data/remote/EarthquakeService.java | // Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/data/objects/earthquake/EarthquakeObject.java
// public class EarthquakeObject {
//
// @SerializedName("type")
// @Expose
// private String type;
// @SerializedName("metadata")
// @Expose
// private Metadata metadata;
// @SerializedName("features")
// @Expose
// private List<Feature> features = new ArrayList<>();
// @SerializedName("bbox")
// @Expose
// private List<Double> bbox = new ArrayList<>();
//
// public static final int NOTIFICATION_ID_1 = 2001;
// public static final int NOTIFICATION_ID_2 = 2000;
//
// public static final int SORT_TIME = 1;
// public static final int SORT_MAGNITUDE = 2;
// public static final int SORT_DISTANCE = 3;
//
// public static final String NOTIFICATION_GROUP = "earthquake_group";
//
// /**
// *
// * @return
// * The type
// */
// public String getType() {
// return type;
// }
//
// /**
// *
// * @param type
// * The type
// */
// public void setType(String type) {
// this.type = type;
// }
//
// /**
// *
// * @return
// * The metadata
// */
// public Metadata getMetadata() {
// return metadata;
// }
//
// /**
// *
// * @param metadata
// * The metadata
// */
// public void setMetadata(Metadata metadata) {
// this.metadata = metadata;
// }
//
// /**
// *
// * @return
// * The features
// */
// public List<Feature> getFeatures() {
// return features;
// }
//
// /**
// *
// * @param features
// * The features
// */
// public void setFeatures(List<Feature> features) {
// this.features = features;
// }
//
// /**
// *
// * @return
// * The bbox
// */
// public List<Double> getBbox() {
// return bbox;
// }
//
// /**
// *
// * @param bbox
// * The bbox
// */
// public void setBbox(List<Double> bbox) {
// this.bbox = bbox;
// }
//
// }
//
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/data/objects/info/CountEarthquakes.java
// public class CountEarthquakes {
//
// @SerializedName("count")
// @Expose
// private int count;
// @SerializedName("maxAllowed")
// @Expose
// private int maxAllowed;
//
// /**
// * @return The count
// */
// public int getCount() {
// return count;
// }
//
// /**
// * @param count The count
// */
// public void setCount(int count) {
// this.count = count;
// }
//
// /**
// * @return The maxAllowed
// */
// public int getMaxAllowed() {
// return maxAllowed;
// }
//
// /**
// * @param maxAllowed The maxAllowed
// */
// public void setMaxAllowed(int maxAllowed) {
// this.maxAllowed = maxAllowed;
// }
//
// }
//
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/data/objects/news/Rss.java
// public class Rss
// {
// @Element(required = false)
// private Channel channel;
//
// @Attribute
// private String version;
//
// public Channel getChannel ()
// {
// return channel;
// }
//
// public void setChannel (Channel channel)
// {
// this.channel = channel;
// }
//
// public String getVersion ()
// {
// return version;
// }
//
// public void setVersion (String version)
// {
// this.version = version;
// }
//
// @Override
// public String toString()
// {
// return "ClassPojo [channel = "+channel+", version = "+version+"]";
// }
// }
| import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;
import com.adkdevelopment.earthquakesurvival.data.objects.earthquake.EarthquakeObject;
import com.adkdevelopment.earthquakesurvival.data.objects.info.CountEarthquakes;
import com.adkdevelopment.earthquakesurvival.data.objects.news.Rss;
import retrofit2.Call;
import retrofit2.http.Field; | /*
* MIT License
*
* Copyright (c) 2016. Dmytro Karataiev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.adkdevelopment.earthquakesurvival.data.remote;
/**
* Public interface with a link to the Endpoint
*/
public interface EarthquakeService {
String sEarthquakeCount = "http://earthquake.usgs.gov/fdsnws/event/1/count?format=geojson";
@GET("all_day.geojson")
Call<EarthquakeObject> getData();
@GET("https://news.google.com/news?q=earthquake&output=rss") | // Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/data/objects/earthquake/EarthquakeObject.java
// public class EarthquakeObject {
//
// @SerializedName("type")
// @Expose
// private String type;
// @SerializedName("metadata")
// @Expose
// private Metadata metadata;
// @SerializedName("features")
// @Expose
// private List<Feature> features = new ArrayList<>();
// @SerializedName("bbox")
// @Expose
// private List<Double> bbox = new ArrayList<>();
//
// public static final int NOTIFICATION_ID_1 = 2001;
// public static final int NOTIFICATION_ID_2 = 2000;
//
// public static final int SORT_TIME = 1;
// public static final int SORT_MAGNITUDE = 2;
// public static final int SORT_DISTANCE = 3;
//
// public static final String NOTIFICATION_GROUP = "earthquake_group";
//
// /**
// *
// * @return
// * The type
// */
// public String getType() {
// return type;
// }
//
// /**
// *
// * @param type
// * The type
// */
// public void setType(String type) {
// this.type = type;
// }
//
// /**
// *
// * @return
// * The metadata
// */
// public Metadata getMetadata() {
// return metadata;
// }
//
// /**
// *
// * @param metadata
// * The metadata
// */
// public void setMetadata(Metadata metadata) {
// this.metadata = metadata;
// }
//
// /**
// *
// * @return
// * The features
// */
// public List<Feature> getFeatures() {
// return features;
// }
//
// /**
// *
// * @param features
// * The features
// */
// public void setFeatures(List<Feature> features) {
// this.features = features;
// }
//
// /**
// *
// * @return
// * The bbox
// */
// public List<Double> getBbox() {
// return bbox;
// }
//
// /**
// *
// * @param bbox
// * The bbox
// */
// public void setBbox(List<Double> bbox) {
// this.bbox = bbox;
// }
//
// }
//
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/data/objects/info/CountEarthquakes.java
// public class CountEarthquakes {
//
// @SerializedName("count")
// @Expose
// private int count;
// @SerializedName("maxAllowed")
// @Expose
// private int maxAllowed;
//
// /**
// * @return The count
// */
// public int getCount() {
// return count;
// }
//
// /**
// * @param count The count
// */
// public void setCount(int count) {
// this.count = count;
// }
//
// /**
// * @return The maxAllowed
// */
// public int getMaxAllowed() {
// return maxAllowed;
// }
//
// /**
// * @param maxAllowed The maxAllowed
// */
// public void setMaxAllowed(int maxAllowed) {
// this.maxAllowed = maxAllowed;
// }
//
// }
//
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/data/objects/news/Rss.java
// public class Rss
// {
// @Element(required = false)
// private Channel channel;
//
// @Attribute
// private String version;
//
// public Channel getChannel ()
// {
// return channel;
// }
//
// public void setChannel (Channel channel)
// {
// this.channel = channel;
// }
//
// public String getVersion ()
// {
// return version;
// }
//
// public void setVersion (String version)
// {
// this.version = version;
// }
//
// @Override
// public String toString()
// {
// return "ClassPojo [channel = "+channel+", version = "+version+"]";
// }
// }
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/data/remote/EarthquakeService.java
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;
import com.adkdevelopment.earthquakesurvival.data.objects.earthquake.EarthquakeObject;
import com.adkdevelopment.earthquakesurvival.data.objects.info.CountEarthquakes;
import com.adkdevelopment.earthquakesurvival.data.objects.news.Rss;
import retrofit2.Call;
import retrofit2.http.Field;
/*
* MIT License
*
* Copyright (c) 2016. Dmytro Karataiev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.adkdevelopment.earthquakesurvival.data.remote;
/**
* Public interface with a link to the Endpoint
*/
public interface EarthquakeService {
String sEarthquakeCount = "http://earthquake.usgs.gov/fdsnws/event/1/count?format=geojson";
@GET("all_day.geojson")
Call<EarthquakeObject> getData();
@GET("https://news.google.com/news?q=earthquake&output=rss") | Call<Rss> getNews(); |
dmytroKarataiev/EarthquakeSurvival | app/src/main/java/com/adkdevelopment/earthquakesurvival/data/remote/EarthquakeService.java | // Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/data/objects/earthquake/EarthquakeObject.java
// public class EarthquakeObject {
//
// @SerializedName("type")
// @Expose
// private String type;
// @SerializedName("metadata")
// @Expose
// private Metadata metadata;
// @SerializedName("features")
// @Expose
// private List<Feature> features = new ArrayList<>();
// @SerializedName("bbox")
// @Expose
// private List<Double> bbox = new ArrayList<>();
//
// public static final int NOTIFICATION_ID_1 = 2001;
// public static final int NOTIFICATION_ID_2 = 2000;
//
// public static final int SORT_TIME = 1;
// public static final int SORT_MAGNITUDE = 2;
// public static final int SORT_DISTANCE = 3;
//
// public static final String NOTIFICATION_GROUP = "earthquake_group";
//
// /**
// *
// * @return
// * The type
// */
// public String getType() {
// return type;
// }
//
// /**
// *
// * @param type
// * The type
// */
// public void setType(String type) {
// this.type = type;
// }
//
// /**
// *
// * @return
// * The metadata
// */
// public Metadata getMetadata() {
// return metadata;
// }
//
// /**
// *
// * @param metadata
// * The metadata
// */
// public void setMetadata(Metadata metadata) {
// this.metadata = metadata;
// }
//
// /**
// *
// * @return
// * The features
// */
// public List<Feature> getFeatures() {
// return features;
// }
//
// /**
// *
// * @param features
// * The features
// */
// public void setFeatures(List<Feature> features) {
// this.features = features;
// }
//
// /**
// *
// * @return
// * The bbox
// */
// public List<Double> getBbox() {
// return bbox;
// }
//
// /**
// *
// * @param bbox
// * The bbox
// */
// public void setBbox(List<Double> bbox) {
// this.bbox = bbox;
// }
//
// }
//
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/data/objects/info/CountEarthquakes.java
// public class CountEarthquakes {
//
// @SerializedName("count")
// @Expose
// private int count;
// @SerializedName("maxAllowed")
// @Expose
// private int maxAllowed;
//
// /**
// * @return The count
// */
// public int getCount() {
// return count;
// }
//
// /**
// * @param count The count
// */
// public void setCount(int count) {
// this.count = count;
// }
//
// /**
// * @return The maxAllowed
// */
// public int getMaxAllowed() {
// return maxAllowed;
// }
//
// /**
// * @param maxAllowed The maxAllowed
// */
// public void setMaxAllowed(int maxAllowed) {
// this.maxAllowed = maxAllowed;
// }
//
// }
//
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/data/objects/news/Rss.java
// public class Rss
// {
// @Element(required = false)
// private Channel channel;
//
// @Attribute
// private String version;
//
// public Channel getChannel ()
// {
// return channel;
// }
//
// public void setChannel (Channel channel)
// {
// this.channel = channel;
// }
//
// public String getVersion ()
// {
// return version;
// }
//
// public void setVersion (String version)
// {
// this.version = version;
// }
//
// @Override
// public String toString()
// {
// return "ClassPojo [channel = "+channel+", version = "+version+"]";
// }
// }
| import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;
import com.adkdevelopment.earthquakesurvival.data.objects.earthquake.EarthquakeObject;
import com.adkdevelopment.earthquakesurvival.data.objects.info.CountEarthquakes;
import com.adkdevelopment.earthquakesurvival.data.objects.news.Rss;
import retrofit2.Call;
import retrofit2.http.Field; | /*
* MIT License
*
* Copyright (c) 2016. Dmytro Karataiev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.adkdevelopment.earthquakesurvival.data.remote;
/**
* Public interface with a link to the Endpoint
*/
public interface EarthquakeService {
String sEarthquakeCount = "http://earthquake.usgs.gov/fdsnws/event/1/count?format=geojson";
@GET("all_day.geojson")
Call<EarthquakeObject> getData();
@GET("https://news.google.com/news?q=earthquake&output=rss")
Call<Rss> getNews();
@GET(sEarthquakeCount) | // Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/data/objects/earthquake/EarthquakeObject.java
// public class EarthquakeObject {
//
// @SerializedName("type")
// @Expose
// private String type;
// @SerializedName("metadata")
// @Expose
// private Metadata metadata;
// @SerializedName("features")
// @Expose
// private List<Feature> features = new ArrayList<>();
// @SerializedName("bbox")
// @Expose
// private List<Double> bbox = new ArrayList<>();
//
// public static final int NOTIFICATION_ID_1 = 2001;
// public static final int NOTIFICATION_ID_2 = 2000;
//
// public static final int SORT_TIME = 1;
// public static final int SORT_MAGNITUDE = 2;
// public static final int SORT_DISTANCE = 3;
//
// public static final String NOTIFICATION_GROUP = "earthquake_group";
//
// /**
// *
// * @return
// * The type
// */
// public String getType() {
// return type;
// }
//
// /**
// *
// * @param type
// * The type
// */
// public void setType(String type) {
// this.type = type;
// }
//
// /**
// *
// * @return
// * The metadata
// */
// public Metadata getMetadata() {
// return metadata;
// }
//
// /**
// *
// * @param metadata
// * The metadata
// */
// public void setMetadata(Metadata metadata) {
// this.metadata = metadata;
// }
//
// /**
// *
// * @return
// * The features
// */
// public List<Feature> getFeatures() {
// return features;
// }
//
// /**
// *
// * @param features
// * The features
// */
// public void setFeatures(List<Feature> features) {
// this.features = features;
// }
//
// /**
// *
// * @return
// * The bbox
// */
// public List<Double> getBbox() {
// return bbox;
// }
//
// /**
// *
// * @param bbox
// * The bbox
// */
// public void setBbox(List<Double> bbox) {
// this.bbox = bbox;
// }
//
// }
//
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/data/objects/info/CountEarthquakes.java
// public class CountEarthquakes {
//
// @SerializedName("count")
// @Expose
// private int count;
// @SerializedName("maxAllowed")
// @Expose
// private int maxAllowed;
//
// /**
// * @return The count
// */
// public int getCount() {
// return count;
// }
//
// /**
// * @param count The count
// */
// public void setCount(int count) {
// this.count = count;
// }
//
// /**
// * @return The maxAllowed
// */
// public int getMaxAllowed() {
// return maxAllowed;
// }
//
// /**
// * @param maxAllowed The maxAllowed
// */
// public void setMaxAllowed(int maxAllowed) {
// this.maxAllowed = maxAllowed;
// }
//
// }
//
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/data/objects/news/Rss.java
// public class Rss
// {
// @Element(required = false)
// private Channel channel;
//
// @Attribute
// private String version;
//
// public Channel getChannel ()
// {
// return channel;
// }
//
// public void setChannel (Channel channel)
// {
// this.channel = channel;
// }
//
// public String getVersion ()
// {
// return version;
// }
//
// public void setVersion (String version)
// {
// this.version = version;
// }
//
// @Override
// public String toString()
// {
// return "ClassPojo [channel = "+channel+", version = "+version+"]";
// }
// }
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/data/remote/EarthquakeService.java
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;
import com.adkdevelopment.earthquakesurvival.data.objects.earthquake.EarthquakeObject;
import com.adkdevelopment.earthquakesurvival.data.objects.info.CountEarthquakes;
import com.adkdevelopment.earthquakesurvival.data.objects.news.Rss;
import retrofit2.Call;
import retrofit2.http.Field;
/*
* MIT License
*
* Copyright (c) 2016. Dmytro Karataiev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.adkdevelopment.earthquakesurvival.data.remote;
/**
* Public interface with a link to the Endpoint
*/
public interface EarthquakeService {
String sEarthquakeCount = "http://earthquake.usgs.gov/fdsnws/event/1/count?format=geojson";
@GET("all_day.geojson")
Call<EarthquakeObject> getData();
@GET("https://news.google.com/news?q=earthquake&output=rss")
Call<Rss> getNews();
@GET(sEarthquakeCount) | Call<CountEarthquakes> getEarthquakeStats(@Query("starttime") String starttime, |
dmytroKarataiev/EarthquakeSurvival | app/src/main/java/com/adkdevelopment/earthquakesurvival/data/remote/ApiManager.java | // Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/App.java
// public class App extends Application {
//
// private static ApiManager sApiManager, sNewsManager;
// private static Context sContext;
//
// // event bus from RxJava
// private static RxBus _rxBus;
//
// // Singleton Retrofit for Earthquakes
// public static ApiManager getApiManager() {
// if (sApiManager == null) {
// try {
// sApiManager = new ApiManager();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// return sApiManager;
// }
//
// // Singleton Retrofit for News
// public static ApiManager getNewsManager() {
// if (sNewsManager == null) {
// try {
// sNewsManager = new ApiManager();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// return sNewsManager;
// }
//
// // singleton RxBus
// public static RxBus getRxBusSingleton() {
// if (_rxBus == null) {
// _rxBus = new RxBus();
// }
// return _rxBus;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// if (!BuildConfig.DEBUG) {
// Fabric.with(this, new Crashlytics());
// }
//
// sContext = getApplicationContext();
// }
//
// public static Context getContext() {
// return sContext;
// }
// }
| import android.content.Context;
import com.adkdevelopment.earthquakesurvival.App;
import com.adkdevelopment.earthquakesurvival.R;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.simplexml.SimpleXmlConverterFactory; | /*
* MIT License
*
* Copyright (c) 2016. Dmytro Karataiev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.adkdevelopment.earthquakesurvival.data.remote;
/**
* REST Manager using Singleton Pattern
*/
public class ApiManager {
private final String BASE_URL = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/";
private final Retrofit EARTHQUAKE_ADAPTER = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(new ToStringConverterFactory())
.client(new OkHttpClient.Builder() | // Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/App.java
// public class App extends Application {
//
// private static ApiManager sApiManager, sNewsManager;
// private static Context sContext;
//
// // event bus from RxJava
// private static RxBus _rxBus;
//
// // Singleton Retrofit for Earthquakes
// public static ApiManager getApiManager() {
// if (sApiManager == null) {
// try {
// sApiManager = new ApiManager();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// return sApiManager;
// }
//
// // Singleton Retrofit for News
// public static ApiManager getNewsManager() {
// if (sNewsManager == null) {
// try {
// sNewsManager = new ApiManager();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// return sNewsManager;
// }
//
// // singleton RxBus
// public static RxBus getRxBusSingleton() {
// if (_rxBus == null) {
// _rxBus = new RxBus();
// }
// return _rxBus;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// if (!BuildConfig.DEBUG) {
// Fabric.with(this, new Crashlytics());
// }
//
// sContext = getApplicationContext();
// }
//
// public static Context getContext() {
// return sContext;
// }
// }
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/data/remote/ApiManager.java
import android.content.Context;
import com.adkdevelopment.earthquakesurvival.App;
import com.adkdevelopment.earthquakesurvival.R;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.simplexml.SimpleXmlConverterFactory;
/*
* MIT License
*
* Copyright (c) 2016. Dmytro Karataiev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.adkdevelopment.earthquakesurvival.data.remote;
/**
* REST Manager using Singleton Pattern
*/
public class ApiManager {
private final String BASE_URL = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/";
private final Retrofit EARTHQUAKE_ADAPTER = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(new ToStringConverterFactory())
.client(new OkHttpClient.Builder() | .sslSocketFactory(getSSLConfig(App.getContext()).getSocketFactory()).build()) |
dmytroKarataiev/EarthquakeSurvival | app/src/main/java/com/adkdevelopment/earthquakesurvival/utils/Utilities.java | // Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/data/objects/earthquake/EarthquakeObject.java
// public class EarthquakeObject {
//
// @SerializedName("type")
// @Expose
// private String type;
// @SerializedName("metadata")
// @Expose
// private Metadata metadata;
// @SerializedName("features")
// @Expose
// private List<Feature> features = new ArrayList<>();
// @SerializedName("bbox")
// @Expose
// private List<Double> bbox = new ArrayList<>();
//
// public static final int NOTIFICATION_ID_1 = 2001;
// public static final int NOTIFICATION_ID_2 = 2000;
//
// public static final int SORT_TIME = 1;
// public static final int SORT_MAGNITUDE = 2;
// public static final int SORT_DISTANCE = 3;
//
// public static final String NOTIFICATION_GROUP = "earthquake_group";
//
// /**
// *
// * @return
// * The type
// */
// public String getType() {
// return type;
// }
//
// /**
// *
// * @param type
// * The type
// */
// public void setType(String type) {
// this.type = type;
// }
//
// /**
// *
// * @return
// * The metadata
// */
// public Metadata getMetadata() {
// return metadata;
// }
//
// /**
// *
// * @param metadata
// * The metadata
// */
// public void setMetadata(Metadata metadata) {
// this.metadata = metadata;
// }
//
// /**
// *
// * @return
// * The features
// */
// public List<Feature> getFeatures() {
// return features;
// }
//
// /**
// *
// * @param features
// * The features
// */
// public void setFeatures(List<Feature> features) {
// this.features = features;
// }
//
// /**
// *
// * @return
// * The bbox
// */
// public List<Double> getBbox() {
// return bbox;
// }
//
// /**
// *
// * @param bbox
// * The bbox
// */
// public void setBbox(List<Double> bbox) {
// this.bbox = bbox;
// }
//
// }
| import android.animation.Animator;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.Spanned;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.view.animation.Interpolator;
import com.adkdevelopment.earthquakesurvival.R;
import com.adkdevelopment.earthquakesurvival.data.objects.earthquake.EarthquakeObject;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale; | if (result != ConnectionResult.SUCCESS) {
if (GoogleApiAvailability.getInstance().isUserResolvableError(result)) {
GoogleApiAvailability.getInstance().getErrorDialog(activity, result, 0).show();
} else {
Log.e(TAG, "checkPlayServices not available");
}
return false;
}
return true;
}
/**
* Sets sorting preferences in SharedPreferences
* @param context from which call is being made
* @param sort preference according to the database schema
*/
public static void setSortingPreference(Context context, int sort) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(context.getString(R.string.sharedprefs_key_sort), sort);
editor.apply();
}
/**
* Returns sorting preference
* @param context from which call is being made
* @return int preference according to the database schema
*/
public static int getSortingPreference(Context context) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); | // Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/data/objects/earthquake/EarthquakeObject.java
// public class EarthquakeObject {
//
// @SerializedName("type")
// @Expose
// private String type;
// @SerializedName("metadata")
// @Expose
// private Metadata metadata;
// @SerializedName("features")
// @Expose
// private List<Feature> features = new ArrayList<>();
// @SerializedName("bbox")
// @Expose
// private List<Double> bbox = new ArrayList<>();
//
// public static final int NOTIFICATION_ID_1 = 2001;
// public static final int NOTIFICATION_ID_2 = 2000;
//
// public static final int SORT_TIME = 1;
// public static final int SORT_MAGNITUDE = 2;
// public static final int SORT_DISTANCE = 3;
//
// public static final String NOTIFICATION_GROUP = "earthquake_group";
//
// /**
// *
// * @return
// * The type
// */
// public String getType() {
// return type;
// }
//
// /**
// *
// * @param type
// * The type
// */
// public void setType(String type) {
// this.type = type;
// }
//
// /**
// *
// * @return
// * The metadata
// */
// public Metadata getMetadata() {
// return metadata;
// }
//
// /**
// *
// * @param metadata
// * The metadata
// */
// public void setMetadata(Metadata metadata) {
// this.metadata = metadata;
// }
//
// /**
// *
// * @return
// * The features
// */
// public List<Feature> getFeatures() {
// return features;
// }
//
// /**
// *
// * @param features
// * The features
// */
// public void setFeatures(List<Feature> features) {
// this.features = features;
// }
//
// /**
// *
// * @return
// * The bbox
// */
// public List<Double> getBbox() {
// return bbox;
// }
//
// /**
// *
// * @param bbox
// * The bbox
// */
// public void setBbox(List<Double> bbox) {
// this.bbox = bbox;
// }
//
// }
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/utils/Utilities.java
import android.animation.Animator;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.Spanned;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.view.animation.Interpolator;
import com.adkdevelopment.earthquakesurvival.R;
import com.adkdevelopment.earthquakesurvival.data.objects.earthquake.EarthquakeObject;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
if (result != ConnectionResult.SUCCESS) {
if (GoogleApiAvailability.getInstance().isUserResolvableError(result)) {
GoogleApiAvailability.getInstance().getErrorDialog(activity, result, 0).show();
} else {
Log.e(TAG, "checkPlayServices not available");
}
return false;
}
return true;
}
/**
* Sets sorting preferences in SharedPreferences
* @param context from which call is being made
* @param sort preference according to the database schema
*/
public static void setSortingPreference(Context context, int sort) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(context.getString(R.string.sharedprefs_key_sort), sort);
editor.apply();
}
/**
* Returns sorting preference
* @param context from which call is being made
* @return int preference according to the database schema
*/
public static int getSortingPreference(Context context) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); | return sharedPreferences.getInt(context.getString(R.string.sharedprefs_key_sort), EarthquakeObject.SORT_TIME); |
dmytroKarataiev/EarthquakeSurvival | app/src/main/java/com/adkdevelopment/earthquakesurvival/ui/InfoActivity.java | // Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/App.java
// public class App extends Application {
//
// private static ApiManager sApiManager, sNewsManager;
// private static Context sContext;
//
// // event bus from RxJava
// private static RxBus _rxBus;
//
// // Singleton Retrofit for Earthquakes
// public static ApiManager getApiManager() {
// if (sApiManager == null) {
// try {
// sApiManager = new ApiManager();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// return sApiManager;
// }
//
// // Singleton Retrofit for News
// public static ApiManager getNewsManager() {
// if (sNewsManager == null) {
// try {
// sNewsManager = new ApiManager();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// return sNewsManager;
// }
//
// // singleton RxBus
// public static RxBus getRxBusSingleton() {
// if (_rxBus == null) {
// _rxBus = new RxBus();
// }
// return _rxBus;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// if (!BuildConfig.DEBUG) {
// Fabric.with(this, new Crashlytics());
// }
//
// sContext = getApplicationContext();
// }
//
// public static Context getContext() {
// return sContext;
// }
// }
//
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/eventbus/RxBus.java
// public class RxBus {
//
// private final Subject<Object, Object> _bus = new SerializedSubject<>(PublishSubject.create());
//
// public void send(Object o) {
// _bus.onNext(o);
// }
//
// public Observable<Object> toObservable() {
// return _bus;
// }
//
// public boolean hasObservers() {
// return _bus.hasObservers();
// }
// }
| import com.adkdevelopment.earthquakesurvival.App;
import com.adkdevelopment.earthquakesurvival.R;
import com.adkdevelopment.earthquakesurvival.eventbus.RxBus;
import butterknife.BindView;
import butterknife.ButterKnife;
import rx.subscriptions.CompositeSubscription;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem; | /*
* MIT License
*
* Copyright (c) 2016. Dmytro Karataiev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package com.adkdevelopment.earthquakesurvival.ui;
public class InfoActivity extends AppCompatActivity {
@BindView(R.id.toolbar) Toolbar mToolbar;
// RxJava eventbus | // Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/App.java
// public class App extends Application {
//
// private static ApiManager sApiManager, sNewsManager;
// private static Context sContext;
//
// // event bus from RxJava
// private static RxBus _rxBus;
//
// // Singleton Retrofit for Earthquakes
// public static ApiManager getApiManager() {
// if (sApiManager == null) {
// try {
// sApiManager = new ApiManager();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// return sApiManager;
// }
//
// // Singleton Retrofit for News
// public static ApiManager getNewsManager() {
// if (sNewsManager == null) {
// try {
// sNewsManager = new ApiManager();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// return sNewsManager;
// }
//
// // singleton RxBus
// public static RxBus getRxBusSingleton() {
// if (_rxBus == null) {
// _rxBus = new RxBus();
// }
// return _rxBus;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// if (!BuildConfig.DEBUG) {
// Fabric.with(this, new Crashlytics());
// }
//
// sContext = getApplicationContext();
// }
//
// public static Context getContext() {
// return sContext;
// }
// }
//
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/eventbus/RxBus.java
// public class RxBus {
//
// private final Subject<Object, Object> _bus = new SerializedSubject<>(PublishSubject.create());
//
// public void send(Object o) {
// _bus.onNext(o);
// }
//
// public Observable<Object> toObservable() {
// return _bus;
// }
//
// public boolean hasObservers() {
// return _bus.hasObservers();
// }
// }
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/ui/InfoActivity.java
import com.adkdevelopment.earthquakesurvival.App;
import com.adkdevelopment.earthquakesurvival.R;
import com.adkdevelopment.earthquakesurvival.eventbus.RxBus;
import butterknife.BindView;
import butterknife.ButterKnife;
import rx.subscriptions.CompositeSubscription;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
/*
* MIT License
*
* Copyright (c) 2016. Dmytro Karataiev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package com.adkdevelopment.earthquakesurvival.ui;
public class InfoActivity extends AppCompatActivity {
@BindView(R.id.toolbar) Toolbar mToolbar;
// RxJava eventbus | private RxBus _rxBus; |
dmytroKarataiev/EarthquakeSurvival | app/src/main/java/com/adkdevelopment/earthquakesurvival/ui/InfoActivity.java | // Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/App.java
// public class App extends Application {
//
// private static ApiManager sApiManager, sNewsManager;
// private static Context sContext;
//
// // event bus from RxJava
// private static RxBus _rxBus;
//
// // Singleton Retrofit for Earthquakes
// public static ApiManager getApiManager() {
// if (sApiManager == null) {
// try {
// sApiManager = new ApiManager();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// return sApiManager;
// }
//
// // Singleton Retrofit for News
// public static ApiManager getNewsManager() {
// if (sNewsManager == null) {
// try {
// sNewsManager = new ApiManager();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// return sNewsManager;
// }
//
// // singleton RxBus
// public static RxBus getRxBusSingleton() {
// if (_rxBus == null) {
// _rxBus = new RxBus();
// }
// return _rxBus;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// if (!BuildConfig.DEBUG) {
// Fabric.with(this, new Crashlytics());
// }
//
// sContext = getApplicationContext();
// }
//
// public static Context getContext() {
// return sContext;
// }
// }
//
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/eventbus/RxBus.java
// public class RxBus {
//
// private final Subject<Object, Object> _bus = new SerializedSubject<>(PublishSubject.create());
//
// public void send(Object o) {
// _bus.onNext(o);
// }
//
// public Observable<Object> toObservable() {
// return _bus;
// }
//
// public boolean hasObservers() {
// return _bus.hasObservers();
// }
// }
| import com.adkdevelopment.earthquakesurvival.App;
import com.adkdevelopment.earthquakesurvival.R;
import com.adkdevelopment.earthquakesurvival.eventbus.RxBus;
import butterknife.BindView;
import butterknife.ButterKnife;
import rx.subscriptions.CompositeSubscription;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem; | /*
* MIT License
*
* Copyright (c) 2016. Dmytro Karataiev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package com.adkdevelopment.earthquakesurvival.ui;
public class InfoActivity extends AppCompatActivity {
@BindView(R.id.toolbar) Toolbar mToolbar;
// RxJava eventbus
private RxBus _rxBus;
private CompositeSubscription _subscription;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.info_activity);
ButterKnife.bind(this);
| // Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/App.java
// public class App extends Application {
//
// private static ApiManager sApiManager, sNewsManager;
// private static Context sContext;
//
// // event bus from RxJava
// private static RxBus _rxBus;
//
// // Singleton Retrofit for Earthquakes
// public static ApiManager getApiManager() {
// if (sApiManager == null) {
// try {
// sApiManager = new ApiManager();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// return sApiManager;
// }
//
// // Singleton Retrofit for News
// public static ApiManager getNewsManager() {
// if (sNewsManager == null) {
// try {
// sNewsManager = new ApiManager();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// return sNewsManager;
// }
//
// // singleton RxBus
// public static RxBus getRxBusSingleton() {
// if (_rxBus == null) {
// _rxBus = new RxBus();
// }
// return _rxBus;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// if (!BuildConfig.DEBUG) {
// Fabric.with(this, new Crashlytics());
// }
//
// sContext = getApplicationContext();
// }
//
// public static Context getContext() {
// return sContext;
// }
// }
//
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/eventbus/RxBus.java
// public class RxBus {
//
// private final Subject<Object, Object> _bus = new SerializedSubject<>(PublishSubject.create());
//
// public void send(Object o) {
// _bus.onNext(o);
// }
//
// public Observable<Object> toObservable() {
// return _bus;
// }
//
// public boolean hasObservers() {
// return _bus.hasObservers();
// }
// }
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/ui/InfoActivity.java
import com.adkdevelopment.earthquakesurvival.App;
import com.adkdevelopment.earthquakesurvival.R;
import com.adkdevelopment.earthquakesurvival.eventbus.RxBus;
import butterknife.BindView;
import butterknife.ButterKnife;
import rx.subscriptions.CompositeSubscription;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
/*
* MIT License
*
* Copyright (c) 2016. Dmytro Karataiev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package com.adkdevelopment.earthquakesurvival.ui;
public class InfoActivity extends AppCompatActivity {
@BindView(R.id.toolbar) Toolbar mToolbar;
// RxJava eventbus
private RxBus _rxBus;
private CompositeSubscription _subscription;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.info_activity);
ButterKnife.bind(this);
| _rxBus = App.getRxBusSingleton(); |
dmytroKarataiev/EarthquakeSurvival | app/src/main/java/com/adkdevelopment/earthquakesurvival/ui/report_earthquake/ReportFragment.java | // Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/App.java
// public class App extends Application {
//
// private static ApiManager sApiManager, sNewsManager;
// private static Context sContext;
//
// // event bus from RxJava
// private static RxBus _rxBus;
//
// // Singleton Retrofit for Earthquakes
// public static ApiManager getApiManager() {
// if (sApiManager == null) {
// try {
// sApiManager = new ApiManager();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// return sApiManager;
// }
//
// // Singleton Retrofit for News
// public static ApiManager getNewsManager() {
// if (sNewsManager == null) {
// try {
// sNewsManager = new ApiManager();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// return sNewsManager;
// }
//
// // singleton RxBus
// public static RxBus getRxBusSingleton() {
// if (_rxBus == null) {
// _rxBus = new RxBus();
// }
// return _rxBus;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// if (!BuildConfig.DEBUG) {
// Fabric.with(this, new Crashlytics());
// }
//
// sContext = getApplicationContext();
// }
//
// public static Context getContext() {
// return sContext;
// }
// }
| import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.adkdevelopment.earthquakesurvival.App;
import com.adkdevelopment.earthquakesurvival.R;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater; | /*
* MIT License
*
* Copyright (c) 2016. Dmytro Karataiev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package com.adkdevelopment.earthquakesurvival.ui.report_earthquake;
/**
* A fragment reporting an earthquake to the USGS.
*/
public class ReportFragment extends Fragment {
private static final String TAG = ReportFragment.class.getSimpleName();
private Unbinder mUnbinder;
public ReportFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_report, container, false);
mUnbinder = ButterKnife.bind(this, rootView);
// to inflate menu in this fragment
setHasOptionsMenu(true);
return rootView;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_report, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_send:
sendReport();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Sends a report to the USGS about an earthquake.
*/
public void sendReport() { | // Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/App.java
// public class App extends Application {
//
// private static ApiManager sApiManager, sNewsManager;
// private static Context sContext;
//
// // event bus from RxJava
// private static RxBus _rxBus;
//
// // Singleton Retrofit for Earthquakes
// public static ApiManager getApiManager() {
// if (sApiManager == null) {
// try {
// sApiManager = new ApiManager();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// return sApiManager;
// }
//
// // Singleton Retrofit for News
// public static ApiManager getNewsManager() {
// if (sNewsManager == null) {
// try {
// sNewsManager = new ApiManager();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// return sNewsManager;
// }
//
// // singleton RxBus
// public static RxBus getRxBusSingleton() {
// if (_rxBus == null) {
// _rxBus = new RxBus();
// }
// return _rxBus;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// if (!BuildConfig.DEBUG) {
// Fabric.with(this, new Crashlytics());
// }
//
// sContext = getApplicationContext();
// }
//
// public static Context getContext() {
// return sContext;
// }
// }
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/ui/report_earthquake/ReportFragment.java
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.adkdevelopment.earthquakesurvival.App;
import com.adkdevelopment.earthquakesurvival.R;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
/*
* MIT License
*
* Copyright (c) 2016. Dmytro Karataiev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package com.adkdevelopment.earthquakesurvival.ui.report_earthquake;
/**
* A fragment reporting an earthquake to the USGS.
*/
public class ReportFragment extends Fragment {
private static final String TAG = ReportFragment.class.getSimpleName();
private Unbinder mUnbinder;
public ReportFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_report, container, false);
mUnbinder = ButterKnife.bind(this, rootView);
// to inflate menu in this fragment
setHasOptionsMenu(true);
return rootView;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_report, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_send:
sendReport();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Sends a report to the USGS about an earthquake.
*/
public void sendReport() { | App.getApiManager().getEarthquakeService() |
dmytroKarataiev/EarthquakeSurvival | app/src/main/java/com/adkdevelopment/earthquakesurvival/ui/InfoFragment.java | // Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/App.java
// public class App extends Application {
//
// private static ApiManager sApiManager, sNewsManager;
// private static Context sContext;
//
// // event bus from RxJava
// private static RxBus _rxBus;
//
// // Singleton Retrofit for Earthquakes
// public static ApiManager getApiManager() {
// if (sApiManager == null) {
// try {
// sApiManager = new ApiManager();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// return sApiManager;
// }
//
// // Singleton Retrofit for News
// public static ApiManager getNewsManager() {
// if (sNewsManager == null) {
// try {
// sNewsManager = new ApiManager();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// return sNewsManager;
// }
//
// // singleton RxBus
// public static RxBus getRxBusSingleton() {
// if (_rxBus == null) {
// _rxBus = new RxBus();
// }
// return _rxBus;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// if (!BuildConfig.DEBUG) {
// Fabric.with(this, new Crashlytics());
// }
//
// sContext = getApplicationContext();
// }
//
// public static Context getContext() {
// return sContext;
// }
// }
//
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/ui/adapters/InfoAdapter.java
// public class InfoAdapter extends RecyclerView.Adapter<InfoAdapter.ViewHolder> {
//
// private List<String> mTitles;
// private List<String> mTexts;
//
// public InfoAdapter(List<String> title, List<String> text) {
// super();
// mTitles = title;
// mTexts = text;
// }
//
// public static class ViewHolder extends RecyclerView.ViewHolder {
//
// @BindView(R.id.info_title) TextView mTitle;
// @BindView(R.id.info_text) TextView mText;
// @BindView(R.id.info_card) CardView mInfoCard;
//
// public ViewHolder(View v) {
// super(v);
// ButterKnife.bind(this, v);
// }
// }
//
// @Override
// public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//
// View v = LayoutInflater.from(parent.getContext())
// .inflate(R.layout.info_item_card, parent, false);
//
// return new ViewHolder(v);
// }
//
// @Override
// public void onBindViewHolder(ViewHolder holder, int position) {
// holder.mTitle.setText(mTitles.get(position));
// holder.mText.setText(Utilities.getHtmlText(mTexts.get(position)));
// holder.mText.setMovementMethod(LinkMovementMethod.getInstance());
// }
//
// @Override
// public int getItemCount() {
// return mTitles.size();
// }
// }
//
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/eventbus/RxBus.java
// public class RxBus {
//
// private final Subject<Object, Object> _bus = new SerializedSubject<>(PublishSubject.create());
//
// public void send(Object o) {
// _bus.onNext(o);
// }
//
// public Observable<Object> toObservable() {
// return _bus;
// }
//
// public boolean hasObservers() {
// return _bus.hasObservers();
// }
// }
| import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.adkdevelopment.earthquakesurvival.App;
import com.adkdevelopment.earthquakesurvival.R;
import com.adkdevelopment.earthquakesurvival.ui.adapters.InfoAdapter;
import com.adkdevelopment.earthquakesurvival.eventbus.RxBus;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder; | /*
* MIT License
*
* Copyright (c) 2016. Dmytro Karataiev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package com.adkdevelopment.earthquakesurvival.ui;
/**
* A placeholder fragment containing a simple view.
*/
public class InfoFragment extends Fragment {
@BindView(R.id.recyclerview) RecyclerView mRecyclerView;
private Unbinder mUnbinder; | // Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/App.java
// public class App extends Application {
//
// private static ApiManager sApiManager, sNewsManager;
// private static Context sContext;
//
// // event bus from RxJava
// private static RxBus _rxBus;
//
// // Singleton Retrofit for Earthquakes
// public static ApiManager getApiManager() {
// if (sApiManager == null) {
// try {
// sApiManager = new ApiManager();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// return sApiManager;
// }
//
// // Singleton Retrofit for News
// public static ApiManager getNewsManager() {
// if (sNewsManager == null) {
// try {
// sNewsManager = new ApiManager();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// return sNewsManager;
// }
//
// // singleton RxBus
// public static RxBus getRxBusSingleton() {
// if (_rxBus == null) {
// _rxBus = new RxBus();
// }
// return _rxBus;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// if (!BuildConfig.DEBUG) {
// Fabric.with(this, new Crashlytics());
// }
//
// sContext = getApplicationContext();
// }
//
// public static Context getContext() {
// return sContext;
// }
// }
//
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/ui/adapters/InfoAdapter.java
// public class InfoAdapter extends RecyclerView.Adapter<InfoAdapter.ViewHolder> {
//
// private List<String> mTitles;
// private List<String> mTexts;
//
// public InfoAdapter(List<String> title, List<String> text) {
// super();
// mTitles = title;
// mTexts = text;
// }
//
// public static class ViewHolder extends RecyclerView.ViewHolder {
//
// @BindView(R.id.info_title) TextView mTitle;
// @BindView(R.id.info_text) TextView mText;
// @BindView(R.id.info_card) CardView mInfoCard;
//
// public ViewHolder(View v) {
// super(v);
// ButterKnife.bind(this, v);
// }
// }
//
// @Override
// public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//
// View v = LayoutInflater.from(parent.getContext())
// .inflate(R.layout.info_item_card, parent, false);
//
// return new ViewHolder(v);
// }
//
// @Override
// public void onBindViewHolder(ViewHolder holder, int position) {
// holder.mTitle.setText(mTitles.get(position));
// holder.mText.setText(Utilities.getHtmlText(mTexts.get(position)));
// holder.mText.setMovementMethod(LinkMovementMethod.getInstance());
// }
//
// @Override
// public int getItemCount() {
// return mTitles.size();
// }
// }
//
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/eventbus/RxBus.java
// public class RxBus {
//
// private final Subject<Object, Object> _bus = new SerializedSubject<>(PublishSubject.create());
//
// public void send(Object o) {
// _bus.onNext(o);
// }
//
// public Observable<Object> toObservable() {
// return _bus;
// }
//
// public boolean hasObservers() {
// return _bus.hasObservers();
// }
// }
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/ui/InfoFragment.java
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.adkdevelopment.earthquakesurvival.App;
import com.adkdevelopment.earthquakesurvival.R;
import com.adkdevelopment.earthquakesurvival.ui.adapters.InfoAdapter;
import com.adkdevelopment.earthquakesurvival.eventbus.RxBus;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
/*
* MIT License
*
* Copyright (c) 2016. Dmytro Karataiev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package com.adkdevelopment.earthquakesurvival.ui;
/**
* A placeholder fragment containing a simple view.
*/
public class InfoFragment extends Fragment {
@BindView(R.id.recyclerview) RecyclerView mRecyclerView;
private Unbinder mUnbinder; | private RxBus _rxBus; |
dmytroKarataiev/EarthquakeSurvival | app/src/main/java/com/adkdevelopment/earthquakesurvival/ui/InfoFragment.java | // Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/App.java
// public class App extends Application {
//
// private static ApiManager sApiManager, sNewsManager;
// private static Context sContext;
//
// // event bus from RxJava
// private static RxBus _rxBus;
//
// // Singleton Retrofit for Earthquakes
// public static ApiManager getApiManager() {
// if (sApiManager == null) {
// try {
// sApiManager = new ApiManager();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// return sApiManager;
// }
//
// // Singleton Retrofit for News
// public static ApiManager getNewsManager() {
// if (sNewsManager == null) {
// try {
// sNewsManager = new ApiManager();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// return sNewsManager;
// }
//
// // singleton RxBus
// public static RxBus getRxBusSingleton() {
// if (_rxBus == null) {
// _rxBus = new RxBus();
// }
// return _rxBus;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// if (!BuildConfig.DEBUG) {
// Fabric.with(this, new Crashlytics());
// }
//
// sContext = getApplicationContext();
// }
//
// public static Context getContext() {
// return sContext;
// }
// }
//
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/ui/adapters/InfoAdapter.java
// public class InfoAdapter extends RecyclerView.Adapter<InfoAdapter.ViewHolder> {
//
// private List<String> mTitles;
// private List<String> mTexts;
//
// public InfoAdapter(List<String> title, List<String> text) {
// super();
// mTitles = title;
// mTexts = text;
// }
//
// public static class ViewHolder extends RecyclerView.ViewHolder {
//
// @BindView(R.id.info_title) TextView mTitle;
// @BindView(R.id.info_text) TextView mText;
// @BindView(R.id.info_card) CardView mInfoCard;
//
// public ViewHolder(View v) {
// super(v);
// ButterKnife.bind(this, v);
// }
// }
//
// @Override
// public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//
// View v = LayoutInflater.from(parent.getContext())
// .inflate(R.layout.info_item_card, parent, false);
//
// return new ViewHolder(v);
// }
//
// @Override
// public void onBindViewHolder(ViewHolder holder, int position) {
// holder.mTitle.setText(mTitles.get(position));
// holder.mText.setText(Utilities.getHtmlText(mTexts.get(position)));
// holder.mText.setMovementMethod(LinkMovementMethod.getInstance());
// }
//
// @Override
// public int getItemCount() {
// return mTitles.size();
// }
// }
//
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/eventbus/RxBus.java
// public class RxBus {
//
// private final Subject<Object, Object> _bus = new SerializedSubject<>(PublishSubject.create());
//
// public void send(Object o) {
// _bus.onNext(o);
// }
//
// public Observable<Object> toObservable() {
// return _bus;
// }
//
// public boolean hasObservers() {
// return _bus.hasObservers();
// }
// }
| import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.adkdevelopment.earthquakesurvival.App;
import com.adkdevelopment.earthquakesurvival.R;
import com.adkdevelopment.earthquakesurvival.ui.adapters.InfoAdapter;
import com.adkdevelopment.earthquakesurvival.eventbus.RxBus;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder; | /*
* MIT License
*
* Copyright (c) 2016. Dmytro Karataiev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package com.adkdevelopment.earthquakesurvival.ui;
/**
* A placeholder fragment containing a simple view.
*/
public class InfoFragment extends Fragment {
@BindView(R.id.recyclerview) RecyclerView mRecyclerView;
private Unbinder mUnbinder;
private RxBus _rxBus;
public InfoFragment() {
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState); | // Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/App.java
// public class App extends Application {
//
// private static ApiManager sApiManager, sNewsManager;
// private static Context sContext;
//
// // event bus from RxJava
// private static RxBus _rxBus;
//
// // Singleton Retrofit for Earthquakes
// public static ApiManager getApiManager() {
// if (sApiManager == null) {
// try {
// sApiManager = new ApiManager();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// return sApiManager;
// }
//
// // Singleton Retrofit for News
// public static ApiManager getNewsManager() {
// if (sNewsManager == null) {
// try {
// sNewsManager = new ApiManager();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// return sNewsManager;
// }
//
// // singleton RxBus
// public static RxBus getRxBusSingleton() {
// if (_rxBus == null) {
// _rxBus = new RxBus();
// }
// return _rxBus;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// if (!BuildConfig.DEBUG) {
// Fabric.with(this, new Crashlytics());
// }
//
// sContext = getApplicationContext();
// }
//
// public static Context getContext() {
// return sContext;
// }
// }
//
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/ui/adapters/InfoAdapter.java
// public class InfoAdapter extends RecyclerView.Adapter<InfoAdapter.ViewHolder> {
//
// private List<String> mTitles;
// private List<String> mTexts;
//
// public InfoAdapter(List<String> title, List<String> text) {
// super();
// mTitles = title;
// mTexts = text;
// }
//
// public static class ViewHolder extends RecyclerView.ViewHolder {
//
// @BindView(R.id.info_title) TextView mTitle;
// @BindView(R.id.info_text) TextView mText;
// @BindView(R.id.info_card) CardView mInfoCard;
//
// public ViewHolder(View v) {
// super(v);
// ButterKnife.bind(this, v);
// }
// }
//
// @Override
// public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//
// View v = LayoutInflater.from(parent.getContext())
// .inflate(R.layout.info_item_card, parent, false);
//
// return new ViewHolder(v);
// }
//
// @Override
// public void onBindViewHolder(ViewHolder holder, int position) {
// holder.mTitle.setText(mTitles.get(position));
// holder.mText.setText(Utilities.getHtmlText(mTexts.get(position)));
// holder.mText.setMovementMethod(LinkMovementMethod.getInstance());
// }
//
// @Override
// public int getItemCount() {
// return mTitles.size();
// }
// }
//
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/eventbus/RxBus.java
// public class RxBus {
//
// private final Subject<Object, Object> _bus = new SerializedSubject<>(PublishSubject.create());
//
// public void send(Object o) {
// _bus.onNext(o);
// }
//
// public Observable<Object> toObservable() {
// return _bus;
// }
//
// public boolean hasObservers() {
// return _bus.hasObservers();
// }
// }
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/ui/InfoFragment.java
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.adkdevelopment.earthquakesurvival.App;
import com.adkdevelopment.earthquakesurvival.R;
import com.adkdevelopment.earthquakesurvival.ui.adapters.InfoAdapter;
import com.adkdevelopment.earthquakesurvival.eventbus.RxBus;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
/*
* MIT License
*
* Copyright (c) 2016. Dmytro Karataiev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package com.adkdevelopment.earthquakesurvival.ui;
/**
* A placeholder fragment containing a simple view.
*/
public class InfoFragment extends Fragment {
@BindView(R.id.recyclerview) RecyclerView mRecyclerView;
private Unbinder mUnbinder;
private RxBus _rxBus;
public InfoFragment() {
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState); | _rxBus = App.getRxBusSingleton(); |
dmytroKarataiev/EarthquakeSurvival | app/src/main/java/com/adkdevelopment/earthquakesurvival/ui/InfoFragment.java | // Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/App.java
// public class App extends Application {
//
// private static ApiManager sApiManager, sNewsManager;
// private static Context sContext;
//
// // event bus from RxJava
// private static RxBus _rxBus;
//
// // Singleton Retrofit for Earthquakes
// public static ApiManager getApiManager() {
// if (sApiManager == null) {
// try {
// sApiManager = new ApiManager();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// return sApiManager;
// }
//
// // Singleton Retrofit for News
// public static ApiManager getNewsManager() {
// if (sNewsManager == null) {
// try {
// sNewsManager = new ApiManager();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// return sNewsManager;
// }
//
// // singleton RxBus
// public static RxBus getRxBusSingleton() {
// if (_rxBus == null) {
// _rxBus = new RxBus();
// }
// return _rxBus;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// if (!BuildConfig.DEBUG) {
// Fabric.with(this, new Crashlytics());
// }
//
// sContext = getApplicationContext();
// }
//
// public static Context getContext() {
// return sContext;
// }
// }
//
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/ui/adapters/InfoAdapter.java
// public class InfoAdapter extends RecyclerView.Adapter<InfoAdapter.ViewHolder> {
//
// private List<String> mTitles;
// private List<String> mTexts;
//
// public InfoAdapter(List<String> title, List<String> text) {
// super();
// mTitles = title;
// mTexts = text;
// }
//
// public static class ViewHolder extends RecyclerView.ViewHolder {
//
// @BindView(R.id.info_title) TextView mTitle;
// @BindView(R.id.info_text) TextView mText;
// @BindView(R.id.info_card) CardView mInfoCard;
//
// public ViewHolder(View v) {
// super(v);
// ButterKnife.bind(this, v);
// }
// }
//
// @Override
// public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//
// View v = LayoutInflater.from(parent.getContext())
// .inflate(R.layout.info_item_card, parent, false);
//
// return new ViewHolder(v);
// }
//
// @Override
// public void onBindViewHolder(ViewHolder holder, int position) {
// holder.mTitle.setText(mTitles.get(position));
// holder.mText.setText(Utilities.getHtmlText(mTexts.get(position)));
// holder.mText.setMovementMethod(LinkMovementMethod.getInstance());
// }
//
// @Override
// public int getItemCount() {
// return mTitles.size();
// }
// }
//
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/eventbus/RxBus.java
// public class RxBus {
//
// private final Subject<Object, Object> _bus = new SerializedSubject<>(PublishSubject.create());
//
// public void send(Object o) {
// _bus.onNext(o);
// }
//
// public Observable<Object> toObservable() {
// return _bus;
// }
//
// public boolean hasObservers() {
// return _bus.hasObservers();
// }
// }
| import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.adkdevelopment.earthquakesurvival.App;
import com.adkdevelopment.earthquakesurvival.R;
import com.adkdevelopment.earthquakesurvival.ui.adapters.InfoAdapter;
import com.adkdevelopment.earthquakesurvival.eventbus.RxBus;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder; | break;
case 2:
titles.addAll(Arrays.asList(getResources().getStringArray(R.array.survival_during_title)));
text.addAll(Arrays.asList(getResources().getStringArray(R.array.survival_during_text)));
drawable = R.drawable.earth2;
title = getString(R.string.survival_during);
break;
case 3:
titles.addAll(Arrays.asList(getResources().getStringArray(R.array.survival_after_title)));
text.addAll(Arrays.asList(getResources().getStringArray(R.array.survival_after_text)));
drawable = R.drawable.earth3;
title = getString(R.string.survival_after);
break;
case 4:
title = getString(R.string.survival_resources);
titles.addAll(Arrays.asList(getResources().getStringArray(R.array.survival_resources_title)));
text.addAll(Arrays.asList(getResources().getStringArray(R.array.survival_resources_text)));
drawable = R.drawable.earth3;
break;
case 5:
title = getString(R.string.survival_kit);
titles.addAll(Arrays.asList(getResources().getStringArray(R.array.survival_kit_title)));
text.addAll(Arrays.asList(getResources().getStringArray(R.array.survival_kit_text)));
drawable = R.drawable.earth3;
break;
default:
break;
}
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false); | // Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/App.java
// public class App extends Application {
//
// private static ApiManager sApiManager, sNewsManager;
// private static Context sContext;
//
// // event bus from RxJava
// private static RxBus _rxBus;
//
// // Singleton Retrofit for Earthquakes
// public static ApiManager getApiManager() {
// if (sApiManager == null) {
// try {
// sApiManager = new ApiManager();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// return sApiManager;
// }
//
// // Singleton Retrofit for News
// public static ApiManager getNewsManager() {
// if (sNewsManager == null) {
// try {
// sNewsManager = new ApiManager();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// return sNewsManager;
// }
//
// // singleton RxBus
// public static RxBus getRxBusSingleton() {
// if (_rxBus == null) {
// _rxBus = new RxBus();
// }
// return _rxBus;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// if (!BuildConfig.DEBUG) {
// Fabric.with(this, new Crashlytics());
// }
//
// sContext = getApplicationContext();
// }
//
// public static Context getContext() {
// return sContext;
// }
// }
//
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/ui/adapters/InfoAdapter.java
// public class InfoAdapter extends RecyclerView.Adapter<InfoAdapter.ViewHolder> {
//
// private List<String> mTitles;
// private List<String> mTexts;
//
// public InfoAdapter(List<String> title, List<String> text) {
// super();
// mTitles = title;
// mTexts = text;
// }
//
// public static class ViewHolder extends RecyclerView.ViewHolder {
//
// @BindView(R.id.info_title) TextView mTitle;
// @BindView(R.id.info_text) TextView mText;
// @BindView(R.id.info_card) CardView mInfoCard;
//
// public ViewHolder(View v) {
// super(v);
// ButterKnife.bind(this, v);
// }
// }
//
// @Override
// public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//
// View v = LayoutInflater.from(parent.getContext())
// .inflate(R.layout.info_item_card, parent, false);
//
// return new ViewHolder(v);
// }
//
// @Override
// public void onBindViewHolder(ViewHolder holder, int position) {
// holder.mTitle.setText(mTitles.get(position));
// holder.mText.setText(Utilities.getHtmlText(mTexts.get(position)));
// holder.mText.setMovementMethod(LinkMovementMethod.getInstance());
// }
//
// @Override
// public int getItemCount() {
// return mTitles.size();
// }
// }
//
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/eventbus/RxBus.java
// public class RxBus {
//
// private final Subject<Object, Object> _bus = new SerializedSubject<>(PublishSubject.create());
//
// public void send(Object o) {
// _bus.onNext(o);
// }
//
// public Observable<Object> toObservable() {
// return _bus;
// }
//
// public boolean hasObservers() {
// return _bus.hasObservers();
// }
// }
// Path: app/src/main/java/com/adkdevelopment/earthquakesurvival/ui/InfoFragment.java
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.adkdevelopment.earthquakesurvival.App;
import com.adkdevelopment.earthquakesurvival.R;
import com.adkdevelopment.earthquakesurvival.ui.adapters.InfoAdapter;
import com.adkdevelopment.earthquakesurvival.eventbus.RxBus;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
break;
case 2:
titles.addAll(Arrays.asList(getResources().getStringArray(R.array.survival_during_title)));
text.addAll(Arrays.asList(getResources().getStringArray(R.array.survival_during_text)));
drawable = R.drawable.earth2;
title = getString(R.string.survival_during);
break;
case 3:
titles.addAll(Arrays.asList(getResources().getStringArray(R.array.survival_after_title)));
text.addAll(Arrays.asList(getResources().getStringArray(R.array.survival_after_text)));
drawable = R.drawable.earth3;
title = getString(R.string.survival_after);
break;
case 4:
title = getString(R.string.survival_resources);
titles.addAll(Arrays.asList(getResources().getStringArray(R.array.survival_resources_title)));
text.addAll(Arrays.asList(getResources().getStringArray(R.array.survival_resources_text)));
drawable = R.drawable.earth3;
break;
case 5:
title = getString(R.string.survival_kit);
titles.addAll(Arrays.asList(getResources().getStringArray(R.array.survival_kit_title)));
text.addAll(Arrays.asList(getResources().getStringArray(R.array.survival_kit_text)));
drawable = R.drawable.earth3;
break;
default:
break;
}
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false); | InfoAdapter mRecentAdapter = new InfoAdapter(titles, text); |
Comcast/discovery | ha-configurator/src/main/java/com/comcast/tvx/haproxy/MappingsLoaderMain.java | // Path: discovery-client/src/main/java/com/comcast/tvx/cloud/CuratorClient.java
// public class CuratorClient {
//
// private static Logger log = LoggerFactory.getLogger(CuratorClient.class);
//
// public static final int DEFAULT_MAX_SLEEP_MS = 60000;
//
// /**
// * Gets the curator framework.
// *
// * @param zkConnectionString the zoo keeper connection string
// * @return the curator framework
// */
// public static CuratorFramework getCuratorFramework(String zkConnectionString) {
// return getCuratorFramework(getCuratorBuilder(zkConnectionString));
// }
//
// /**
// * Get a framework using a builder argument.
// *
// * @param builder The builder to use.
// * @return the curator framework
// */
// public static CuratorFramework getCuratorFramework(CuratorFrameworkFactory.Builder builder){
// CuratorFramework curatorFramework = builder.build();
// curatorFramework.start();
//
// try {
// curatorFramework.getZookeeperClient().blockUntilConnectedOrTimedOut();
// } catch (InterruptedException e) {
// Throwables.propagate(e);
// }
//
// return curatorFramework;
// }
//
// /**
// * Get a builder object and allow user to override specific parameters.
// *
// * @param zkConnectionString Zookeeper connection string.
// * @return A builder.
// */
// public static CuratorFrameworkFactory.Builder getCuratorBuilder(String zkConnectionString) {
// return CuratorFrameworkFactory.builder()
// .connectionTimeoutMs(10 * 1000)
// .retryPolicy(new ExponentialBackoffRetry(10, 20, DEFAULT_MAX_SLEEP_MS))
// .connectString(zkConnectionString);
// }
//
// public static void registerForChanges(CuratorFramework curatorFramework,
// final RegistrationChangeHandler<MetaData> handler,
// String... basePaths) {
//
// CuratorZookeeperClient client = null;
//
// if (curatorFramework.getState() != CuratorFrameworkState.STARTED) {
// curatorFramework.start();
// }
//
// try {
// client = curatorFramework.getZookeeperClient();
// client.blockUntilConnectedOrTimedOut();
// } catch (InterruptedException e) {
// Throwables.propagate(e);
// }
//
// for (String basePath : basePaths) {
//
// log.debug("Adding watched path: " + basePath);
//
// try {
// new EnsurePath(basePath).ensure(client);
// CuratorEventListener<MetaData> eventBridge = new CuratorEventListener<MetaData>(handler, basePath);
// curatorFramework.getCuratorListenable().addListener(eventBridge);
// } catch (Exception e) {
// Throwables.propagate(e);
// }
// }
//
// log.debug("exiting registerForChanges");
// }
//
// }
| import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import com.comcast.tvx.cloud.CuratorClient;
import com.sampullara.cli.Args;
import com.sampullara.cli.Argument;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.utils.EnsurePath;
import org.apache.zookeeper.KeeperException.NodeExistsException;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | /*
* Copyright 2014 Comcast Corporation
*
* 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.comcast.tvx.haproxy;
/**
* Generate configuration files for HAProxy. Must be executed as the user that owns HAProxy
* configuration files.
*/
public class MappingsLoaderMain {
private static Logger logger = LoggerFactory.getLogger(MappingsLoaderMain.class);
@Argument(alias = "z", description = "ZooKeeper connection string", required = true)
private static String zooKeeperConnectionString = null;
@Argument(alias = "m", description = "Path to file containing port mappings that are to be loaded to ZooKeeper", required = true)
private static String mappingsFile = null;
@Argument(alias = "r", description = "Mappings root to load mappings to.", required = true)
private static String mappingsRoot = null;
/**
* @param args
*/
public static void main(String[] args) {
try {
Args.parse(MappingsLoaderMain.class, args);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
Args.usage(MappingsLoaderMain.class);
System.exit(1);
}
| // Path: discovery-client/src/main/java/com/comcast/tvx/cloud/CuratorClient.java
// public class CuratorClient {
//
// private static Logger log = LoggerFactory.getLogger(CuratorClient.class);
//
// public static final int DEFAULT_MAX_SLEEP_MS = 60000;
//
// /**
// * Gets the curator framework.
// *
// * @param zkConnectionString the zoo keeper connection string
// * @return the curator framework
// */
// public static CuratorFramework getCuratorFramework(String zkConnectionString) {
// return getCuratorFramework(getCuratorBuilder(zkConnectionString));
// }
//
// /**
// * Get a framework using a builder argument.
// *
// * @param builder The builder to use.
// * @return the curator framework
// */
// public static CuratorFramework getCuratorFramework(CuratorFrameworkFactory.Builder builder){
// CuratorFramework curatorFramework = builder.build();
// curatorFramework.start();
//
// try {
// curatorFramework.getZookeeperClient().blockUntilConnectedOrTimedOut();
// } catch (InterruptedException e) {
// Throwables.propagate(e);
// }
//
// return curatorFramework;
// }
//
// /**
// * Get a builder object and allow user to override specific parameters.
// *
// * @param zkConnectionString Zookeeper connection string.
// * @return A builder.
// */
// public static CuratorFrameworkFactory.Builder getCuratorBuilder(String zkConnectionString) {
// return CuratorFrameworkFactory.builder()
// .connectionTimeoutMs(10 * 1000)
// .retryPolicy(new ExponentialBackoffRetry(10, 20, DEFAULT_MAX_SLEEP_MS))
// .connectString(zkConnectionString);
// }
//
// public static void registerForChanges(CuratorFramework curatorFramework,
// final RegistrationChangeHandler<MetaData> handler,
// String... basePaths) {
//
// CuratorZookeeperClient client = null;
//
// if (curatorFramework.getState() != CuratorFrameworkState.STARTED) {
// curatorFramework.start();
// }
//
// try {
// client = curatorFramework.getZookeeperClient();
// client.blockUntilConnectedOrTimedOut();
// } catch (InterruptedException e) {
// Throwables.propagate(e);
// }
//
// for (String basePath : basePaths) {
//
// log.debug("Adding watched path: " + basePath);
//
// try {
// new EnsurePath(basePath).ensure(client);
// CuratorEventListener<MetaData> eventBridge = new CuratorEventListener<MetaData>(handler, basePath);
// curatorFramework.getCuratorListenable().addListener(eventBridge);
// } catch (Exception e) {
// Throwables.propagate(e);
// }
// }
//
// log.debug("exiting registerForChanges");
// }
//
// }
// Path: ha-configurator/src/main/java/com/comcast/tvx/haproxy/MappingsLoaderMain.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import com.comcast.tvx.cloud.CuratorClient;
import com.sampullara.cli.Args;
import com.sampullara.cli.Argument;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.utils.EnsurePath;
import org.apache.zookeeper.KeeperException.NodeExistsException;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
* Copyright 2014 Comcast Corporation
*
* 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.comcast.tvx.haproxy;
/**
* Generate configuration files for HAProxy. Must be executed as the user that owns HAProxy
* configuration files.
*/
public class MappingsLoaderMain {
private static Logger logger = LoggerFactory.getLogger(MappingsLoaderMain.class);
@Argument(alias = "z", description = "ZooKeeper connection string", required = true)
private static String zooKeeperConnectionString = null;
@Argument(alias = "m", description = "Path to file containing port mappings that are to be loaded to ZooKeeper", required = true)
private static String mappingsFile = null;
@Argument(alias = "r", description = "Mappings root to load mappings to.", required = true)
private static String mappingsRoot = null;
/**
* @param args
*/
public static void main(String[] args) {
try {
Args.parse(MappingsLoaderMain.class, args);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
Args.usage(MappingsLoaderMain.class);
System.exit(1);
}
| final CuratorFramework curatorFramework = CuratorClient.getCuratorFramework(zooKeeperConnectionString); |
Comcast/discovery | discovery-client/src/main/java/com/comcast/tvx/cloud/ServiceUtil.java | // Path: discovery-client/src/main/java/com/comcast/tvx/cloud/discovery/EasyDiscoveryBuilder.java
// public class EasyDiscoveryBuilder<T> {
//
// private CuratorFramework client;
// private String basePath;
// private InstanceSerializer<T> serializer;
// private ServiceInstance<T> thisInstance;
//
// /**
// * Return a new builder. The builder will be defaulted with a {@link JsonInstanceSerializer}.
// *
// * @param payloadClass the class of the payload of your service instance (you can use {@link Void}
// * if your instances don't need a payload)
// * @return new builder
// */
// public static<T> EasyDiscoveryBuilder<T> builder(Class<T> payloadClass)
// {
// return new EasyDiscoveryBuilder<T>(payloadClass).serializer(new JsonInstanceSerializer<T>(payloadClass));
// }
//
// /**
// * Build a new service discovery with the currently set values
// *
// * @return new service discovery
// */
// public ServiceDiscovery<T> build() {
// return new EasyDiscoveryImpl<T>(client, basePath, serializer, thisInstance);
// }
//
// /**
// * Required - set the client to use
// *
// * @param client client
// * @return this
// */
// public EasyDiscoveryBuilder<T> client(CuratorFramework client)
// {
// this.client = client;
// return this;
// }
//
// /**
// * Required - set the base path to store in ZK
// *
// * @param basePath base path
// * @return this
// */
// public EasyDiscoveryBuilder<T> basePath(String basePath)
// {
// this.basePath = basePath;
// return this;
// }
//
// /**
// * optional - change the serializer used (the default is {@link JsonInstanceSerializer}
// *
// * @param serializer the serializer
// * @return this
// */
// public EasyDiscoveryBuilder<T> serializer(InstanceSerializer<T> serializer)
// {
// this.serializer = serializer;
// return this;
// }
//
// /**
// * Optional - instance that represents the service that is running. The instance will get auto-registered
// *
// * @param thisInstance initial instance
// * @return this
// */
// public EasyDiscoveryBuilder<T> thisInstance(ServiceInstance<T> thisInstance)
// {
// this.thisInstance = thisInstance;
// return this;
// }
//
// EasyDiscoveryBuilder(Class<T> payloadClass)
// {
// }
//
// }
| import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import com.comcast.tvx.cloud.discovery.EasyDiscoveryBuilder;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.utils.EnsurePath;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.apache.curator.x.discovery.ServiceInstance;
import org.apache.curator.x.discovery.ServiceInstanceBuilder;
import org.apache.curator.x.discovery.ServiceType; |
ServiceInstanceBuilder<MetaData> builder = ServiceInstance.builder();
// Address is optional. The Curator library will automatically use the IP from the first
// ethernet device
String registerAddress = (serviceAddress == null) ? builder.build().getAddress() : serviceAddress;
MetaData metadata = new MetaData(UUID.randomUUID(), registerAddress, servicePort, serviceName);
metadata.setParameters(parameters);
builder.name(serviceName).payload(metadata).id(registerAddress + ":" +
String.valueOf(servicePort)).serviceType(ServiceType.DYNAMIC).address(registerAddress).port(servicePort);
return builder.build();
}
/**
* Gets the discovery.
*
* @param basePath - Registration path
* @param curatorFramework - Curator
* @return the discovery
* @throws Exception the exception
*/
protected static ServiceDiscovery<MetaData> getDiscovery(String basePath, CuratorFramework curatorFramework)
throws Exception {
new EnsurePath(basePath).ensure(curatorFramework.getZookeeperClient());
ServiceDiscovery<MetaData> result = | // Path: discovery-client/src/main/java/com/comcast/tvx/cloud/discovery/EasyDiscoveryBuilder.java
// public class EasyDiscoveryBuilder<T> {
//
// private CuratorFramework client;
// private String basePath;
// private InstanceSerializer<T> serializer;
// private ServiceInstance<T> thisInstance;
//
// /**
// * Return a new builder. The builder will be defaulted with a {@link JsonInstanceSerializer}.
// *
// * @param payloadClass the class of the payload of your service instance (you can use {@link Void}
// * if your instances don't need a payload)
// * @return new builder
// */
// public static<T> EasyDiscoveryBuilder<T> builder(Class<T> payloadClass)
// {
// return new EasyDiscoveryBuilder<T>(payloadClass).serializer(new JsonInstanceSerializer<T>(payloadClass));
// }
//
// /**
// * Build a new service discovery with the currently set values
// *
// * @return new service discovery
// */
// public ServiceDiscovery<T> build() {
// return new EasyDiscoveryImpl<T>(client, basePath, serializer, thisInstance);
// }
//
// /**
// * Required - set the client to use
// *
// * @param client client
// * @return this
// */
// public EasyDiscoveryBuilder<T> client(CuratorFramework client)
// {
// this.client = client;
// return this;
// }
//
// /**
// * Required - set the base path to store in ZK
// *
// * @param basePath base path
// * @return this
// */
// public EasyDiscoveryBuilder<T> basePath(String basePath)
// {
// this.basePath = basePath;
// return this;
// }
//
// /**
// * optional - change the serializer used (the default is {@link JsonInstanceSerializer}
// *
// * @param serializer the serializer
// * @return this
// */
// public EasyDiscoveryBuilder<T> serializer(InstanceSerializer<T> serializer)
// {
// this.serializer = serializer;
// return this;
// }
//
// /**
// * Optional - instance that represents the service that is running. The instance will get auto-registered
// *
// * @param thisInstance initial instance
// * @return this
// */
// public EasyDiscoveryBuilder<T> thisInstance(ServiceInstance<T> thisInstance)
// {
// this.thisInstance = thisInstance;
// return this;
// }
//
// EasyDiscoveryBuilder(Class<T> payloadClass)
// {
// }
//
// }
// Path: discovery-client/src/main/java/com/comcast/tvx/cloud/ServiceUtil.java
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import com.comcast.tvx.cloud.discovery.EasyDiscoveryBuilder;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.utils.EnsurePath;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.apache.curator.x.discovery.ServiceInstance;
import org.apache.curator.x.discovery.ServiceInstanceBuilder;
import org.apache.curator.x.discovery.ServiceType;
ServiceInstanceBuilder<MetaData> builder = ServiceInstance.builder();
// Address is optional. The Curator library will automatically use the IP from the first
// ethernet device
String registerAddress = (serviceAddress == null) ? builder.build().getAddress() : serviceAddress;
MetaData metadata = new MetaData(UUID.randomUUID(), registerAddress, servicePort, serviceName);
metadata.setParameters(parameters);
builder.name(serviceName).payload(metadata).id(registerAddress + ":" +
String.valueOf(servicePort)).serviceType(ServiceType.DYNAMIC).address(registerAddress).port(servicePort);
return builder.build();
}
/**
* Gets the discovery.
*
* @param basePath - Registration path
* @param curatorFramework - Curator
* @return the discovery
* @throws Exception the exception
*/
protected static ServiceDiscovery<MetaData> getDiscovery(String basePath, CuratorFramework curatorFramework)
throws Exception {
new EnsurePath(basePath).ensure(curatorFramework.getZookeeperClient());
ServiceDiscovery<MetaData> result = | EasyDiscoveryBuilder.builder(MetaData.class).basePath(basePath).client(curatorFramework).build(); |
xedin/sasi | test/unit/org/apache/cassandra/db/index/sasi/utils/RangeUnionIteratorTest.java | // Path: src/java/org/apache/cassandra/db/index/sasi/disk/Token.java
// public abstract class Token implements CombinedValue<Long>, Iterable<DecoratedKey>
// {
// protected final long token;
//
// public Token(long token)
// {
// this.token = token;
// }
//
// @Override
// public Long get()
// {
// return token;
// }
//
// @Override
// public int compareTo(CombinedValue<Long> o)
// {
// return Longs.compare(token, ((Token) o).token);
// }
// }
//
// Path: test/unit/org/apache/cassandra/db/index/sasi/utils/LongIterator.java
// public static List<Long> convert(RangeIterator<Long, Token> tokens)
// {
// List<Long> results = new ArrayList<>();
// while (tokens.hasNext())
// results.add(tokens.next().get());
//
// return results;
// }
| import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import org.apache.cassandra.db.index.sasi.disk.Token;
import org.apache.cassandra.io.util.FileUtils;
import org.junit.Assert;
import org.junit.Test;
import static org.apache.cassandra.db.index.sasi.utils.LongIterator.convert; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.db.index.sasi.utils;
public class RangeUnionIteratorTest
{
@Test
public void testNoOverlappingValues()
{ | // Path: src/java/org/apache/cassandra/db/index/sasi/disk/Token.java
// public abstract class Token implements CombinedValue<Long>, Iterable<DecoratedKey>
// {
// protected final long token;
//
// public Token(long token)
// {
// this.token = token;
// }
//
// @Override
// public Long get()
// {
// return token;
// }
//
// @Override
// public int compareTo(CombinedValue<Long> o)
// {
// return Longs.compare(token, ((Token) o).token);
// }
// }
//
// Path: test/unit/org/apache/cassandra/db/index/sasi/utils/LongIterator.java
// public static List<Long> convert(RangeIterator<Long, Token> tokens)
// {
// List<Long> results = new ArrayList<>();
// while (tokens.hasNext())
// results.add(tokens.next().get());
//
// return results;
// }
// Path: test/unit/org/apache/cassandra/db/index/sasi/utils/RangeUnionIteratorTest.java
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import org.apache.cassandra.db.index.sasi.disk.Token;
import org.apache.cassandra.io.util.FileUtils;
import org.junit.Assert;
import org.junit.Test;
import static org.apache.cassandra.db.index.sasi.utils.LongIterator.convert;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.db.index.sasi.utils;
public class RangeUnionIteratorTest
{
@Test
public void testNoOverlappingValues()
{ | RangeUnionIterator.Builder<Long, Token> builder = RangeUnionIterator.builder(); |
xedin/sasi | test/unit/org/apache/cassandra/db/index/sasi/utils/RangeUnionIteratorTest.java | // Path: src/java/org/apache/cassandra/db/index/sasi/disk/Token.java
// public abstract class Token implements CombinedValue<Long>, Iterable<DecoratedKey>
// {
// protected final long token;
//
// public Token(long token)
// {
// this.token = token;
// }
//
// @Override
// public Long get()
// {
// return token;
// }
//
// @Override
// public int compareTo(CombinedValue<Long> o)
// {
// return Longs.compare(token, ((Token) o).token);
// }
// }
//
// Path: test/unit/org/apache/cassandra/db/index/sasi/utils/LongIterator.java
// public static List<Long> convert(RangeIterator<Long, Token> tokens)
// {
// List<Long> results = new ArrayList<>();
// while (tokens.hasNext())
// results.add(tokens.next().get());
//
// return results;
// }
| import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import org.apache.cassandra.db.index.sasi.disk.Token;
import org.apache.cassandra.io.util.FileUtils;
import org.junit.Assert;
import org.junit.Test;
import static org.apache.cassandra.db.index.sasi.utils.LongIterator.convert; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.db.index.sasi.utils;
public class RangeUnionIteratorTest
{
@Test
public void testNoOverlappingValues()
{
RangeUnionIterator.Builder<Long, Token> builder = RangeUnionIterator.builder();
builder.add(new LongIterator(new long[] { 2L, 3L, 5L, 6L }));
builder.add(new LongIterator(new long[] { 1L, 7L }));
builder.add(new LongIterator(new long[] { 4L, 8L, 9L, 10L }));
| // Path: src/java/org/apache/cassandra/db/index/sasi/disk/Token.java
// public abstract class Token implements CombinedValue<Long>, Iterable<DecoratedKey>
// {
// protected final long token;
//
// public Token(long token)
// {
// this.token = token;
// }
//
// @Override
// public Long get()
// {
// return token;
// }
//
// @Override
// public int compareTo(CombinedValue<Long> o)
// {
// return Longs.compare(token, ((Token) o).token);
// }
// }
//
// Path: test/unit/org/apache/cassandra/db/index/sasi/utils/LongIterator.java
// public static List<Long> convert(RangeIterator<Long, Token> tokens)
// {
// List<Long> results = new ArrayList<>();
// while (tokens.hasNext())
// results.add(tokens.next().get());
//
// return results;
// }
// Path: test/unit/org/apache/cassandra/db/index/sasi/utils/RangeUnionIteratorTest.java
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import org.apache.cassandra.db.index.sasi.disk.Token;
import org.apache.cassandra.io.util.FileUtils;
import org.junit.Assert;
import org.junit.Test;
import static org.apache.cassandra.db.index.sasi.utils.LongIterator.convert;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.db.index.sasi.utils;
public class RangeUnionIteratorTest
{
@Test
public void testNoOverlappingValues()
{
RangeUnionIterator.Builder<Long, Token> builder = RangeUnionIterator.builder();
builder.add(new LongIterator(new long[] { 2L, 3L, 5L, 6L }));
builder.add(new LongIterator(new long[] { 1L, 7L }));
builder.add(new LongIterator(new long[] { 4L, 8L, 9L, 10L }));
| Assert.assertEquals(convert(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L), convert(builder.build())); |
xedin/sasi | src/java/org/apache/cassandra/db/index/sasi/conf/ColumnIndex.java | // Path: src/java/org/apache/cassandra/db/index/sasi/analyzer/AbstractAnalyzer.java
// public abstract class AbstractAnalyzer implements Iterator<ByteBuffer>
// {
// protected ByteBuffer next = null;
//
// @Override
// public ByteBuffer next()
// {
// return next;
// }
//
// @Override
// public void remove()
// {
// throw new UnsupportedOperationException();
// }
//
// public abstract void init(Map<String, String> options, AbstractType validator);
//
// public abstract void reset(ByteBuffer input);
//
// public static String normalize(String original)
// {
// return Normalizer.isNormalized(original, Normalizer.Form.NFC)
// ? original
// : Normalizer.normalize(original, Normalizer.Form.NFC);
// }
// }
//
// Path: src/java/org/apache/cassandra/db/index/sasi/conf/view/View.java
// public class View implements Iterable<SSTableIndex>
// {
// private final Map<Descriptor, SSTableIndex> view;
//
// private final TermTree termTree;
// private final IntervalTree<ByteBuffer, SSTableIndex, Interval<ByteBuffer, SSTableIndex>> keyIntervalTree;
//
// public View(ColumnIndex index, AbstractType<?> keyValidator, Set<SSTableIndex> indexes)
// {
// this(index, keyValidator, Collections.<SSTableIndex>emptyList(), Collections.<SSTableReader>emptyList(), indexes);
// }
//
// public View(ColumnIndex index, AbstractType<?> keyValidator,
// Collection<SSTableIndex> currentView,
// Collection<SSTableReader> oldSSTables,
// Set<SSTableIndex> newIndexes)
// {
// Map<Descriptor, SSTableIndex> newView = new HashMap<>();
//
// AbstractType<?> validator = index.getValidator();
// TermTree.Builder termTreeBuilder = (validator instanceof AsciiType || validator instanceof UTF8Type)
// ? new PrefixTermTree.Builder(index.getMode().mode, validator)
// : new RangeTermTree.Builder(index.getMode().mode, validator);
//
// List<Interval<ByteBuffer, SSTableIndex>> keyIntervals = new ArrayList<>();
// for (SSTableIndex sstableIndex : Iterables.concat(currentView, newIndexes))
// {
// SSTableReader sstable = sstableIndex.getSSTable();
// if (oldSSTables.contains(sstable) || sstable.isMarkedCompacted() || newView.containsKey(sstable.descriptor))
// {
// sstableIndex.release();
// continue;
// }
//
// newView.put(sstable.descriptor, sstableIndex);
//
// termTreeBuilder.add(sstableIndex);
// keyIntervals.add(Interval.create(sstableIndex.minKey(), sstableIndex.maxKey(), sstableIndex));
// }
//
// this.view = newView;
// this.termTree = termTreeBuilder.build();
// this.keyIntervalTree = IntervalTree.build(keyIntervals, keyValidator);
//
// if (keyIntervalTree.intervalCount() != termTree.intervalCount())
// throw new IllegalStateException(String.format("mismatched sizes for intervals tree for keys vs terms: %d != %d", keyIntervalTree.intervalCount(), termTree.intervalCount()));
// }
//
// public Set<SSTableIndex> match(final Set<SSTableReader> scope, Expression expression)
// {
// return Sets.filter(termTree.search(expression), new Predicate<SSTableIndex>()
// {
// @Override
// public boolean apply(SSTableIndex index)
// {
// return scope.contains(index.getSSTable());
// }
// });
// }
//
// public List<SSTableIndex> match(ByteBuffer minKey, ByteBuffer maxKey)
// {
// return keyIntervalTree.search(Interval.create(minKey, maxKey, (SSTableIndex) null));
// }
//
// @Override
// public Iterator<SSTableIndex> iterator()
// {
// return view.values().iterator();
// }
//
// public Collection<SSTableIndex> getIndexes()
// {
// return view.values();
// }
// }
| import java.util.*;
import org.apache.cassandra.config.ColumnDefinition;
import org.apache.cassandra.db.index.sasi.analyzer.AbstractAnalyzer;
import org.apache.cassandra.db.index.sasi.conf.view.View;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.db.marshal.AsciiType;
import org.apache.cassandra.db.marshal.UTF8Type;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.io.sstable.Component;
import org.apache.cassandra.io.sstable.Descriptor;
import org.apache.cassandra.io.sstable.SSTableReader; | public ColumnDefinition getDefinition()
{
return column;
}
public AbstractType<?> getValidator()
{
return column.getValidator();
}
public Component getComponent()
{
return component;
}
public IndexMode getMode()
{
return mode;
}
public String getColumnName()
{
return comparator.getString(column.name);
}
public String getIndexName()
{
return column.getIndexName();
}
| // Path: src/java/org/apache/cassandra/db/index/sasi/analyzer/AbstractAnalyzer.java
// public abstract class AbstractAnalyzer implements Iterator<ByteBuffer>
// {
// protected ByteBuffer next = null;
//
// @Override
// public ByteBuffer next()
// {
// return next;
// }
//
// @Override
// public void remove()
// {
// throw new UnsupportedOperationException();
// }
//
// public abstract void init(Map<String, String> options, AbstractType validator);
//
// public abstract void reset(ByteBuffer input);
//
// public static String normalize(String original)
// {
// return Normalizer.isNormalized(original, Normalizer.Form.NFC)
// ? original
// : Normalizer.normalize(original, Normalizer.Form.NFC);
// }
// }
//
// Path: src/java/org/apache/cassandra/db/index/sasi/conf/view/View.java
// public class View implements Iterable<SSTableIndex>
// {
// private final Map<Descriptor, SSTableIndex> view;
//
// private final TermTree termTree;
// private final IntervalTree<ByteBuffer, SSTableIndex, Interval<ByteBuffer, SSTableIndex>> keyIntervalTree;
//
// public View(ColumnIndex index, AbstractType<?> keyValidator, Set<SSTableIndex> indexes)
// {
// this(index, keyValidator, Collections.<SSTableIndex>emptyList(), Collections.<SSTableReader>emptyList(), indexes);
// }
//
// public View(ColumnIndex index, AbstractType<?> keyValidator,
// Collection<SSTableIndex> currentView,
// Collection<SSTableReader> oldSSTables,
// Set<SSTableIndex> newIndexes)
// {
// Map<Descriptor, SSTableIndex> newView = new HashMap<>();
//
// AbstractType<?> validator = index.getValidator();
// TermTree.Builder termTreeBuilder = (validator instanceof AsciiType || validator instanceof UTF8Type)
// ? new PrefixTermTree.Builder(index.getMode().mode, validator)
// : new RangeTermTree.Builder(index.getMode().mode, validator);
//
// List<Interval<ByteBuffer, SSTableIndex>> keyIntervals = new ArrayList<>();
// for (SSTableIndex sstableIndex : Iterables.concat(currentView, newIndexes))
// {
// SSTableReader sstable = sstableIndex.getSSTable();
// if (oldSSTables.contains(sstable) || sstable.isMarkedCompacted() || newView.containsKey(sstable.descriptor))
// {
// sstableIndex.release();
// continue;
// }
//
// newView.put(sstable.descriptor, sstableIndex);
//
// termTreeBuilder.add(sstableIndex);
// keyIntervals.add(Interval.create(sstableIndex.minKey(), sstableIndex.maxKey(), sstableIndex));
// }
//
// this.view = newView;
// this.termTree = termTreeBuilder.build();
// this.keyIntervalTree = IntervalTree.build(keyIntervals, keyValidator);
//
// if (keyIntervalTree.intervalCount() != termTree.intervalCount())
// throw new IllegalStateException(String.format("mismatched sizes for intervals tree for keys vs terms: %d != %d", keyIntervalTree.intervalCount(), termTree.intervalCount()));
// }
//
// public Set<SSTableIndex> match(final Set<SSTableReader> scope, Expression expression)
// {
// return Sets.filter(termTree.search(expression), new Predicate<SSTableIndex>()
// {
// @Override
// public boolean apply(SSTableIndex index)
// {
// return scope.contains(index.getSSTable());
// }
// });
// }
//
// public List<SSTableIndex> match(ByteBuffer minKey, ByteBuffer maxKey)
// {
// return keyIntervalTree.search(Interval.create(minKey, maxKey, (SSTableIndex) null));
// }
//
// @Override
// public Iterator<SSTableIndex> iterator()
// {
// return view.values().iterator();
// }
//
// public Collection<SSTableIndex> getIndexes()
// {
// return view.values();
// }
// }
// Path: src/java/org/apache/cassandra/db/index/sasi/conf/ColumnIndex.java
import java.util.*;
import org.apache.cassandra.config.ColumnDefinition;
import org.apache.cassandra.db.index.sasi.analyzer.AbstractAnalyzer;
import org.apache.cassandra.db.index.sasi.conf.view.View;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.db.marshal.AsciiType;
import org.apache.cassandra.db.marshal.UTF8Type;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.io.sstable.Component;
import org.apache.cassandra.io.sstable.Descriptor;
import org.apache.cassandra.io.sstable.SSTableReader;
public ColumnDefinition getDefinition()
{
return column;
}
public AbstractType<?> getValidator()
{
return column.getValidator();
}
public Component getComponent()
{
return component;
}
public IndexMode getMode()
{
return mode;
}
public String getColumnName()
{
return comparator.getString(column.name);
}
public String getIndexName()
{
return column.getIndexName();
}
| public AbstractAnalyzer getAnalyzer() |
xedin/sasi | src/java/org/apache/cassandra/db/index/sasi/conf/ColumnIndex.java | // Path: src/java/org/apache/cassandra/db/index/sasi/analyzer/AbstractAnalyzer.java
// public abstract class AbstractAnalyzer implements Iterator<ByteBuffer>
// {
// protected ByteBuffer next = null;
//
// @Override
// public ByteBuffer next()
// {
// return next;
// }
//
// @Override
// public void remove()
// {
// throw new UnsupportedOperationException();
// }
//
// public abstract void init(Map<String, String> options, AbstractType validator);
//
// public abstract void reset(ByteBuffer input);
//
// public static String normalize(String original)
// {
// return Normalizer.isNormalized(original, Normalizer.Form.NFC)
// ? original
// : Normalizer.normalize(original, Normalizer.Form.NFC);
// }
// }
//
// Path: src/java/org/apache/cassandra/db/index/sasi/conf/view/View.java
// public class View implements Iterable<SSTableIndex>
// {
// private final Map<Descriptor, SSTableIndex> view;
//
// private final TermTree termTree;
// private final IntervalTree<ByteBuffer, SSTableIndex, Interval<ByteBuffer, SSTableIndex>> keyIntervalTree;
//
// public View(ColumnIndex index, AbstractType<?> keyValidator, Set<SSTableIndex> indexes)
// {
// this(index, keyValidator, Collections.<SSTableIndex>emptyList(), Collections.<SSTableReader>emptyList(), indexes);
// }
//
// public View(ColumnIndex index, AbstractType<?> keyValidator,
// Collection<SSTableIndex> currentView,
// Collection<SSTableReader> oldSSTables,
// Set<SSTableIndex> newIndexes)
// {
// Map<Descriptor, SSTableIndex> newView = new HashMap<>();
//
// AbstractType<?> validator = index.getValidator();
// TermTree.Builder termTreeBuilder = (validator instanceof AsciiType || validator instanceof UTF8Type)
// ? new PrefixTermTree.Builder(index.getMode().mode, validator)
// : new RangeTermTree.Builder(index.getMode().mode, validator);
//
// List<Interval<ByteBuffer, SSTableIndex>> keyIntervals = new ArrayList<>();
// for (SSTableIndex sstableIndex : Iterables.concat(currentView, newIndexes))
// {
// SSTableReader sstable = sstableIndex.getSSTable();
// if (oldSSTables.contains(sstable) || sstable.isMarkedCompacted() || newView.containsKey(sstable.descriptor))
// {
// sstableIndex.release();
// continue;
// }
//
// newView.put(sstable.descriptor, sstableIndex);
//
// termTreeBuilder.add(sstableIndex);
// keyIntervals.add(Interval.create(sstableIndex.minKey(), sstableIndex.maxKey(), sstableIndex));
// }
//
// this.view = newView;
// this.termTree = termTreeBuilder.build();
// this.keyIntervalTree = IntervalTree.build(keyIntervals, keyValidator);
//
// if (keyIntervalTree.intervalCount() != termTree.intervalCount())
// throw new IllegalStateException(String.format("mismatched sizes for intervals tree for keys vs terms: %d != %d", keyIntervalTree.intervalCount(), termTree.intervalCount()));
// }
//
// public Set<SSTableIndex> match(final Set<SSTableReader> scope, Expression expression)
// {
// return Sets.filter(termTree.search(expression), new Predicate<SSTableIndex>()
// {
// @Override
// public boolean apply(SSTableIndex index)
// {
// return scope.contains(index.getSSTable());
// }
// });
// }
//
// public List<SSTableIndex> match(ByteBuffer minKey, ByteBuffer maxKey)
// {
// return keyIntervalTree.search(Interval.create(minKey, maxKey, (SSTableIndex) null));
// }
//
// @Override
// public Iterator<SSTableIndex> iterator()
// {
// return view.values().iterator();
// }
//
// public Collection<SSTableIndex> getIndexes()
// {
// return view.values();
// }
// }
| import java.util.*;
import org.apache.cassandra.config.ColumnDefinition;
import org.apache.cassandra.db.index.sasi.analyzer.AbstractAnalyzer;
import org.apache.cassandra.db.index.sasi.conf.view.View;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.db.marshal.AsciiType;
import org.apache.cassandra.db.marshal.UTF8Type;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.io.sstable.Component;
import org.apache.cassandra.io.sstable.Descriptor;
import org.apache.cassandra.io.sstable.SSTableReader; | return column.getValidator();
}
public Component getComponent()
{
return component;
}
public IndexMode getMode()
{
return mode;
}
public String getColumnName()
{
return comparator.getString(column.name);
}
public String getIndexName()
{
return column.getIndexName();
}
public AbstractAnalyzer getAnalyzer()
{
AbstractAnalyzer analyzer = mode.getAnalyzer(getValidator());
analyzer.init(column.getIndexOptions(), column.getValidator());
return analyzer;
}
| // Path: src/java/org/apache/cassandra/db/index/sasi/analyzer/AbstractAnalyzer.java
// public abstract class AbstractAnalyzer implements Iterator<ByteBuffer>
// {
// protected ByteBuffer next = null;
//
// @Override
// public ByteBuffer next()
// {
// return next;
// }
//
// @Override
// public void remove()
// {
// throw new UnsupportedOperationException();
// }
//
// public abstract void init(Map<String, String> options, AbstractType validator);
//
// public abstract void reset(ByteBuffer input);
//
// public static String normalize(String original)
// {
// return Normalizer.isNormalized(original, Normalizer.Form.NFC)
// ? original
// : Normalizer.normalize(original, Normalizer.Form.NFC);
// }
// }
//
// Path: src/java/org/apache/cassandra/db/index/sasi/conf/view/View.java
// public class View implements Iterable<SSTableIndex>
// {
// private final Map<Descriptor, SSTableIndex> view;
//
// private final TermTree termTree;
// private final IntervalTree<ByteBuffer, SSTableIndex, Interval<ByteBuffer, SSTableIndex>> keyIntervalTree;
//
// public View(ColumnIndex index, AbstractType<?> keyValidator, Set<SSTableIndex> indexes)
// {
// this(index, keyValidator, Collections.<SSTableIndex>emptyList(), Collections.<SSTableReader>emptyList(), indexes);
// }
//
// public View(ColumnIndex index, AbstractType<?> keyValidator,
// Collection<SSTableIndex> currentView,
// Collection<SSTableReader> oldSSTables,
// Set<SSTableIndex> newIndexes)
// {
// Map<Descriptor, SSTableIndex> newView = new HashMap<>();
//
// AbstractType<?> validator = index.getValidator();
// TermTree.Builder termTreeBuilder = (validator instanceof AsciiType || validator instanceof UTF8Type)
// ? new PrefixTermTree.Builder(index.getMode().mode, validator)
// : new RangeTermTree.Builder(index.getMode().mode, validator);
//
// List<Interval<ByteBuffer, SSTableIndex>> keyIntervals = new ArrayList<>();
// for (SSTableIndex sstableIndex : Iterables.concat(currentView, newIndexes))
// {
// SSTableReader sstable = sstableIndex.getSSTable();
// if (oldSSTables.contains(sstable) || sstable.isMarkedCompacted() || newView.containsKey(sstable.descriptor))
// {
// sstableIndex.release();
// continue;
// }
//
// newView.put(sstable.descriptor, sstableIndex);
//
// termTreeBuilder.add(sstableIndex);
// keyIntervals.add(Interval.create(sstableIndex.minKey(), sstableIndex.maxKey(), sstableIndex));
// }
//
// this.view = newView;
// this.termTree = termTreeBuilder.build();
// this.keyIntervalTree = IntervalTree.build(keyIntervals, keyValidator);
//
// if (keyIntervalTree.intervalCount() != termTree.intervalCount())
// throw new IllegalStateException(String.format("mismatched sizes for intervals tree for keys vs terms: %d != %d", keyIntervalTree.intervalCount(), termTree.intervalCount()));
// }
//
// public Set<SSTableIndex> match(final Set<SSTableReader> scope, Expression expression)
// {
// return Sets.filter(termTree.search(expression), new Predicate<SSTableIndex>()
// {
// @Override
// public boolean apply(SSTableIndex index)
// {
// return scope.contains(index.getSSTable());
// }
// });
// }
//
// public List<SSTableIndex> match(ByteBuffer minKey, ByteBuffer maxKey)
// {
// return keyIntervalTree.search(Interval.create(minKey, maxKey, (SSTableIndex) null));
// }
//
// @Override
// public Iterator<SSTableIndex> iterator()
// {
// return view.values().iterator();
// }
//
// public Collection<SSTableIndex> getIndexes()
// {
// return view.values();
// }
// }
// Path: src/java/org/apache/cassandra/db/index/sasi/conf/ColumnIndex.java
import java.util.*;
import org.apache.cassandra.config.ColumnDefinition;
import org.apache.cassandra.db.index.sasi.analyzer.AbstractAnalyzer;
import org.apache.cassandra.db.index.sasi.conf.view.View;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.db.marshal.AsciiType;
import org.apache.cassandra.db.marshal.UTF8Type;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.io.sstable.Component;
import org.apache.cassandra.io.sstable.Descriptor;
import org.apache.cassandra.io.sstable.SSTableReader;
return column.getValidator();
}
public Component getComponent()
{
return component;
}
public IndexMode getMode()
{
return mode;
}
public String getColumnName()
{
return comparator.getString(column.name);
}
public String getIndexName()
{
return column.getIndexName();
}
public AbstractAnalyzer getAnalyzer()
{
AbstractAnalyzer analyzer = mode.getAnalyzer(getValidator());
analyzer.init(column.getIndexOptions(), column.getValidator());
return analyzer;
}
| public View getView() |
xedin/sasi | src/java/org/apache/cassandra/db/index/sasi/analyzer/NonTokenizingAnalyzer.java | // Path: src/java/org/apache/cassandra/db/index/sasi/analyzer/filter/BasicResultFilters.java
// public class BasicResultFilters
// {
// private static final Locale DEFAULT_LOCALE = Locale.getDefault();
//
// public static class LowerCase extends FilterPipelineTask<String, String>
// {
// private Locale locale;
//
// public LowerCase(Locale locale)
// {
// this.locale = locale;
// }
//
// public LowerCase()
// {
// this.locale = DEFAULT_LOCALE;
// }
//
// @Override
// public String process(String input) throws Exception
// {
// return input.toLowerCase(locale);
// }
// }
//
// public static class UpperCase extends FilterPipelineTask<String, String>
// {
// private Locale locale;
//
// public UpperCase(Locale locale)
// {
// this.locale = locale;
// }
//
// public UpperCase()
// {
// this.locale = DEFAULT_LOCALE;
// }
//
// public String process(String input) throws Exception
// {
// return input.toUpperCase(locale);
// }
// }
//
// public static class NoOperation extends FilterPipelineTask<Object, Object>
// {
// public Object process(Object input) throws Exception
// {
// return input;
// }
// }
// }
//
// Path: src/java/org/apache/cassandra/db/index/sasi/analyzer/filter/FilterPipelineBuilder.java
// public class FilterPipelineBuilder
// {
// private final FilterPipelineTask<?,?> parent;
// private FilterPipelineTask<?,?> current;
//
// public FilterPipelineBuilder(FilterPipelineTask<?, ?> first)
// {
// this(first, first);
// }
//
// private FilterPipelineBuilder(FilterPipelineTask<?, ?> first, FilterPipelineTask<?, ?> current)
// {
// this.parent = first;
// this.current = current;
// }
//
// public FilterPipelineBuilder add(String name, FilterPipelineTask<?,?> nextTask)
// {
// this.current.setLast(name, nextTask);
// this.current = nextTask;
// return this;
// }
//
// public FilterPipelineTask<?,?> build()
// {
// return this.parent;
// }
// }
//
// Path: src/java/org/apache/cassandra/db/index/sasi/analyzer/filter/FilterPipelineExecutor.java
// public class FilterPipelineExecutor
// {
// private static final Logger logger = LoggerFactory.getLogger(FilterPipelineExecutor.class);
//
// public static <F,T> T execute(FilterPipelineTask<F, T> task, T initialInput)
// {
// FilterPipelineTask<?, ?> taskPtr = task;
// T result = initialInput;
// try
// {
// while (true)
// {
// FilterPipelineTask<F,T> taskGeneric = (FilterPipelineTask<F,T>) taskPtr;
// result = taskGeneric.process((F) result);
// taskPtr = taskPtr.next;
// if(taskPtr == null)
// return result;
// }
// }
// catch (Exception e)
// {
// logger.info("An unhandled exception to occurred while processing " +
// "pipeline [{}]", task.getName(), e);
// }
// return null;
// }
// }
//
// Path: src/java/org/apache/cassandra/db/index/sasi/analyzer/filter/FilterPipelineTask.java
// public abstract class FilterPipelineTask<F, T>
// {
// private String name;
// public FilterPipelineTask<?, ?> next;
//
// protected <K, V> void setLast(String name, FilterPipelineTask<K, V> last)
// {
// if (last == this)
// throw new IllegalArgumentException("provided last task ["
// + last.name + "] cannot be set to itself");
// if (this.next == null)
// {
// this.next = last;
// this.name = name;
// }
// else
// {
// this.next.setLast(name, last);
// }
// }
//
// public abstract T process(F input) throws Exception;
//
// public String getName()
// {
// return name;
// }
// }
| import org.apache.cassandra.utils.ByteBufferUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.ByteBuffer;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.cassandra.db.index.sasi.analyzer.filter.BasicResultFilters;
import org.apache.cassandra.db.index.sasi.analyzer.filter.FilterPipelineBuilder;
import org.apache.cassandra.db.index.sasi.analyzer.filter.FilterPipelineExecutor;
import org.apache.cassandra.db.index.sasi.analyzer.filter.FilterPipelineTask;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.db.marshal.AsciiType;
import org.apache.cassandra.db.marshal.UTF8Type;
import org.apache.cassandra.serializers.MarshalException; | @Override
public void init(Map<String, String> options, AbstractType validator)
{
init(NonTokenizingOptions.buildFromMap(options), validator);
}
public void init(NonTokenizingOptions tokenizerOptions, AbstractType validator)
{
this.validator = validator;
this.options = tokenizerOptions;
this.filterPipeline = getFilterPipeline();
}
@Override
public boolean hasNext()
{
// check that we know how to handle the input, otherwise bail
if (!VALID_ANALYZABLE_TYPES.contains(validator))
return false;
if (hasNext)
{
String inputStr;
try
{
inputStr = validator.getString(input);
if (inputStr == null)
throw new MarshalException(String.format("'null' deserialized value for %s with %s", ByteBufferUtil.bytesToHex(input), validator));
| // Path: src/java/org/apache/cassandra/db/index/sasi/analyzer/filter/BasicResultFilters.java
// public class BasicResultFilters
// {
// private static final Locale DEFAULT_LOCALE = Locale.getDefault();
//
// public static class LowerCase extends FilterPipelineTask<String, String>
// {
// private Locale locale;
//
// public LowerCase(Locale locale)
// {
// this.locale = locale;
// }
//
// public LowerCase()
// {
// this.locale = DEFAULT_LOCALE;
// }
//
// @Override
// public String process(String input) throws Exception
// {
// return input.toLowerCase(locale);
// }
// }
//
// public static class UpperCase extends FilterPipelineTask<String, String>
// {
// private Locale locale;
//
// public UpperCase(Locale locale)
// {
// this.locale = locale;
// }
//
// public UpperCase()
// {
// this.locale = DEFAULT_LOCALE;
// }
//
// public String process(String input) throws Exception
// {
// return input.toUpperCase(locale);
// }
// }
//
// public static class NoOperation extends FilterPipelineTask<Object, Object>
// {
// public Object process(Object input) throws Exception
// {
// return input;
// }
// }
// }
//
// Path: src/java/org/apache/cassandra/db/index/sasi/analyzer/filter/FilterPipelineBuilder.java
// public class FilterPipelineBuilder
// {
// private final FilterPipelineTask<?,?> parent;
// private FilterPipelineTask<?,?> current;
//
// public FilterPipelineBuilder(FilterPipelineTask<?, ?> first)
// {
// this(first, first);
// }
//
// private FilterPipelineBuilder(FilterPipelineTask<?, ?> first, FilterPipelineTask<?, ?> current)
// {
// this.parent = first;
// this.current = current;
// }
//
// public FilterPipelineBuilder add(String name, FilterPipelineTask<?,?> nextTask)
// {
// this.current.setLast(name, nextTask);
// this.current = nextTask;
// return this;
// }
//
// public FilterPipelineTask<?,?> build()
// {
// return this.parent;
// }
// }
//
// Path: src/java/org/apache/cassandra/db/index/sasi/analyzer/filter/FilterPipelineExecutor.java
// public class FilterPipelineExecutor
// {
// private static final Logger logger = LoggerFactory.getLogger(FilterPipelineExecutor.class);
//
// public static <F,T> T execute(FilterPipelineTask<F, T> task, T initialInput)
// {
// FilterPipelineTask<?, ?> taskPtr = task;
// T result = initialInput;
// try
// {
// while (true)
// {
// FilterPipelineTask<F,T> taskGeneric = (FilterPipelineTask<F,T>) taskPtr;
// result = taskGeneric.process((F) result);
// taskPtr = taskPtr.next;
// if(taskPtr == null)
// return result;
// }
// }
// catch (Exception e)
// {
// logger.info("An unhandled exception to occurred while processing " +
// "pipeline [{}]", task.getName(), e);
// }
// return null;
// }
// }
//
// Path: src/java/org/apache/cassandra/db/index/sasi/analyzer/filter/FilterPipelineTask.java
// public abstract class FilterPipelineTask<F, T>
// {
// private String name;
// public FilterPipelineTask<?, ?> next;
//
// protected <K, V> void setLast(String name, FilterPipelineTask<K, V> last)
// {
// if (last == this)
// throw new IllegalArgumentException("provided last task ["
// + last.name + "] cannot be set to itself");
// if (this.next == null)
// {
// this.next = last;
// this.name = name;
// }
// else
// {
// this.next.setLast(name, last);
// }
// }
//
// public abstract T process(F input) throws Exception;
//
// public String getName()
// {
// return name;
// }
// }
// Path: src/java/org/apache/cassandra/db/index/sasi/analyzer/NonTokenizingAnalyzer.java
import org.apache.cassandra.utils.ByteBufferUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.ByteBuffer;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.cassandra.db.index.sasi.analyzer.filter.BasicResultFilters;
import org.apache.cassandra.db.index.sasi.analyzer.filter.FilterPipelineBuilder;
import org.apache.cassandra.db.index.sasi.analyzer.filter.FilterPipelineExecutor;
import org.apache.cassandra.db.index.sasi.analyzer.filter.FilterPipelineTask;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.db.marshal.AsciiType;
import org.apache.cassandra.db.marshal.UTF8Type;
import org.apache.cassandra.serializers.MarshalException;
@Override
public void init(Map<String, String> options, AbstractType validator)
{
init(NonTokenizingOptions.buildFromMap(options), validator);
}
public void init(NonTokenizingOptions tokenizerOptions, AbstractType validator)
{
this.validator = validator;
this.options = tokenizerOptions;
this.filterPipeline = getFilterPipeline();
}
@Override
public boolean hasNext()
{
// check that we know how to handle the input, otherwise bail
if (!VALID_ANALYZABLE_TYPES.contains(validator))
return false;
if (hasNext)
{
String inputStr;
try
{
inputStr = validator.getString(input);
if (inputStr == null)
throw new MarshalException(String.format("'null' deserialized value for %s with %s", ByteBufferUtil.bytesToHex(input), validator));
| Object pipelineRes = FilterPipelineExecutor.execute(filterPipeline, inputStr); |
xedin/sasi | src/java/org/apache/cassandra/db/index/sasi/analyzer/NonTokenizingAnalyzer.java | // Path: src/java/org/apache/cassandra/db/index/sasi/analyzer/filter/BasicResultFilters.java
// public class BasicResultFilters
// {
// private static final Locale DEFAULT_LOCALE = Locale.getDefault();
//
// public static class LowerCase extends FilterPipelineTask<String, String>
// {
// private Locale locale;
//
// public LowerCase(Locale locale)
// {
// this.locale = locale;
// }
//
// public LowerCase()
// {
// this.locale = DEFAULT_LOCALE;
// }
//
// @Override
// public String process(String input) throws Exception
// {
// return input.toLowerCase(locale);
// }
// }
//
// public static class UpperCase extends FilterPipelineTask<String, String>
// {
// private Locale locale;
//
// public UpperCase(Locale locale)
// {
// this.locale = locale;
// }
//
// public UpperCase()
// {
// this.locale = DEFAULT_LOCALE;
// }
//
// public String process(String input) throws Exception
// {
// return input.toUpperCase(locale);
// }
// }
//
// public static class NoOperation extends FilterPipelineTask<Object, Object>
// {
// public Object process(Object input) throws Exception
// {
// return input;
// }
// }
// }
//
// Path: src/java/org/apache/cassandra/db/index/sasi/analyzer/filter/FilterPipelineBuilder.java
// public class FilterPipelineBuilder
// {
// private final FilterPipelineTask<?,?> parent;
// private FilterPipelineTask<?,?> current;
//
// public FilterPipelineBuilder(FilterPipelineTask<?, ?> first)
// {
// this(first, first);
// }
//
// private FilterPipelineBuilder(FilterPipelineTask<?, ?> first, FilterPipelineTask<?, ?> current)
// {
// this.parent = first;
// this.current = current;
// }
//
// public FilterPipelineBuilder add(String name, FilterPipelineTask<?,?> nextTask)
// {
// this.current.setLast(name, nextTask);
// this.current = nextTask;
// return this;
// }
//
// public FilterPipelineTask<?,?> build()
// {
// return this.parent;
// }
// }
//
// Path: src/java/org/apache/cassandra/db/index/sasi/analyzer/filter/FilterPipelineExecutor.java
// public class FilterPipelineExecutor
// {
// private static final Logger logger = LoggerFactory.getLogger(FilterPipelineExecutor.class);
//
// public static <F,T> T execute(FilterPipelineTask<F, T> task, T initialInput)
// {
// FilterPipelineTask<?, ?> taskPtr = task;
// T result = initialInput;
// try
// {
// while (true)
// {
// FilterPipelineTask<F,T> taskGeneric = (FilterPipelineTask<F,T>) taskPtr;
// result = taskGeneric.process((F) result);
// taskPtr = taskPtr.next;
// if(taskPtr == null)
// return result;
// }
// }
// catch (Exception e)
// {
// logger.info("An unhandled exception to occurred while processing " +
// "pipeline [{}]", task.getName(), e);
// }
// return null;
// }
// }
//
// Path: src/java/org/apache/cassandra/db/index/sasi/analyzer/filter/FilterPipelineTask.java
// public abstract class FilterPipelineTask<F, T>
// {
// private String name;
// public FilterPipelineTask<?, ?> next;
//
// protected <K, V> void setLast(String name, FilterPipelineTask<K, V> last)
// {
// if (last == this)
// throw new IllegalArgumentException("provided last task ["
// + last.name + "] cannot be set to itself");
// if (this.next == null)
// {
// this.next = last;
// this.name = name;
// }
// else
// {
// this.next.setLast(name, last);
// }
// }
//
// public abstract T process(F input) throws Exception;
//
// public String getName()
// {
// return name;
// }
// }
| import org.apache.cassandra.utils.ByteBufferUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.ByteBuffer;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.cassandra.db.index.sasi.analyzer.filter.BasicResultFilters;
import org.apache.cassandra.db.index.sasi.analyzer.filter.FilterPipelineBuilder;
import org.apache.cassandra.db.index.sasi.analyzer.filter.FilterPipelineExecutor;
import org.apache.cassandra.db.index.sasi.analyzer.filter.FilterPipelineTask;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.db.marshal.AsciiType;
import org.apache.cassandra.db.marshal.UTF8Type;
import org.apache.cassandra.serializers.MarshalException; | if (pipelineRes == null || !(pipelineRes instanceof String))
return false;
next = validator.fromString(normalize((String) pipelineRes));
return true;
}
catch (MarshalException e)
{
logger.error("Failed to deserialize value with " + validator, e);
return false;
}
finally
{
hasNext = false;
}
}
return false;
}
@Override
public void reset(ByteBuffer input)
{
this.next = null;
this.input = input;
this.hasNext = true;
}
private FilterPipelineTask getFilterPipeline()
{ | // Path: src/java/org/apache/cassandra/db/index/sasi/analyzer/filter/BasicResultFilters.java
// public class BasicResultFilters
// {
// private static final Locale DEFAULT_LOCALE = Locale.getDefault();
//
// public static class LowerCase extends FilterPipelineTask<String, String>
// {
// private Locale locale;
//
// public LowerCase(Locale locale)
// {
// this.locale = locale;
// }
//
// public LowerCase()
// {
// this.locale = DEFAULT_LOCALE;
// }
//
// @Override
// public String process(String input) throws Exception
// {
// return input.toLowerCase(locale);
// }
// }
//
// public static class UpperCase extends FilterPipelineTask<String, String>
// {
// private Locale locale;
//
// public UpperCase(Locale locale)
// {
// this.locale = locale;
// }
//
// public UpperCase()
// {
// this.locale = DEFAULT_LOCALE;
// }
//
// public String process(String input) throws Exception
// {
// return input.toUpperCase(locale);
// }
// }
//
// public static class NoOperation extends FilterPipelineTask<Object, Object>
// {
// public Object process(Object input) throws Exception
// {
// return input;
// }
// }
// }
//
// Path: src/java/org/apache/cassandra/db/index/sasi/analyzer/filter/FilterPipelineBuilder.java
// public class FilterPipelineBuilder
// {
// private final FilterPipelineTask<?,?> parent;
// private FilterPipelineTask<?,?> current;
//
// public FilterPipelineBuilder(FilterPipelineTask<?, ?> first)
// {
// this(first, first);
// }
//
// private FilterPipelineBuilder(FilterPipelineTask<?, ?> first, FilterPipelineTask<?, ?> current)
// {
// this.parent = first;
// this.current = current;
// }
//
// public FilterPipelineBuilder add(String name, FilterPipelineTask<?,?> nextTask)
// {
// this.current.setLast(name, nextTask);
// this.current = nextTask;
// return this;
// }
//
// public FilterPipelineTask<?,?> build()
// {
// return this.parent;
// }
// }
//
// Path: src/java/org/apache/cassandra/db/index/sasi/analyzer/filter/FilterPipelineExecutor.java
// public class FilterPipelineExecutor
// {
// private static final Logger logger = LoggerFactory.getLogger(FilterPipelineExecutor.class);
//
// public static <F,T> T execute(FilterPipelineTask<F, T> task, T initialInput)
// {
// FilterPipelineTask<?, ?> taskPtr = task;
// T result = initialInput;
// try
// {
// while (true)
// {
// FilterPipelineTask<F,T> taskGeneric = (FilterPipelineTask<F,T>) taskPtr;
// result = taskGeneric.process((F) result);
// taskPtr = taskPtr.next;
// if(taskPtr == null)
// return result;
// }
// }
// catch (Exception e)
// {
// logger.info("An unhandled exception to occurred while processing " +
// "pipeline [{}]", task.getName(), e);
// }
// return null;
// }
// }
//
// Path: src/java/org/apache/cassandra/db/index/sasi/analyzer/filter/FilterPipelineTask.java
// public abstract class FilterPipelineTask<F, T>
// {
// private String name;
// public FilterPipelineTask<?, ?> next;
//
// protected <K, V> void setLast(String name, FilterPipelineTask<K, V> last)
// {
// if (last == this)
// throw new IllegalArgumentException("provided last task ["
// + last.name + "] cannot be set to itself");
// if (this.next == null)
// {
// this.next = last;
// this.name = name;
// }
// else
// {
// this.next.setLast(name, last);
// }
// }
//
// public abstract T process(F input) throws Exception;
//
// public String getName()
// {
// return name;
// }
// }
// Path: src/java/org/apache/cassandra/db/index/sasi/analyzer/NonTokenizingAnalyzer.java
import org.apache.cassandra.utils.ByteBufferUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.ByteBuffer;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.cassandra.db.index.sasi.analyzer.filter.BasicResultFilters;
import org.apache.cassandra.db.index.sasi.analyzer.filter.FilterPipelineBuilder;
import org.apache.cassandra.db.index.sasi.analyzer.filter.FilterPipelineExecutor;
import org.apache.cassandra.db.index.sasi.analyzer.filter.FilterPipelineTask;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.db.marshal.AsciiType;
import org.apache.cassandra.db.marshal.UTF8Type;
import org.apache.cassandra.serializers.MarshalException;
if (pipelineRes == null || !(pipelineRes instanceof String))
return false;
next = validator.fromString(normalize((String) pipelineRes));
return true;
}
catch (MarshalException e)
{
logger.error("Failed to deserialize value with " + validator, e);
return false;
}
finally
{
hasNext = false;
}
}
return false;
}
@Override
public void reset(ByteBuffer input)
{
this.next = null;
this.input = input;
this.hasNext = true;
}
private FilterPipelineTask getFilterPipeline()
{ | FilterPipelineBuilder builder = new FilterPipelineBuilder(new BasicResultFilters.NoOperation()); |
xedin/sasi | src/java/org/apache/cassandra/db/index/sasi/analyzer/NonTokenizingAnalyzer.java | // Path: src/java/org/apache/cassandra/db/index/sasi/analyzer/filter/BasicResultFilters.java
// public class BasicResultFilters
// {
// private static final Locale DEFAULT_LOCALE = Locale.getDefault();
//
// public static class LowerCase extends FilterPipelineTask<String, String>
// {
// private Locale locale;
//
// public LowerCase(Locale locale)
// {
// this.locale = locale;
// }
//
// public LowerCase()
// {
// this.locale = DEFAULT_LOCALE;
// }
//
// @Override
// public String process(String input) throws Exception
// {
// return input.toLowerCase(locale);
// }
// }
//
// public static class UpperCase extends FilterPipelineTask<String, String>
// {
// private Locale locale;
//
// public UpperCase(Locale locale)
// {
// this.locale = locale;
// }
//
// public UpperCase()
// {
// this.locale = DEFAULT_LOCALE;
// }
//
// public String process(String input) throws Exception
// {
// return input.toUpperCase(locale);
// }
// }
//
// public static class NoOperation extends FilterPipelineTask<Object, Object>
// {
// public Object process(Object input) throws Exception
// {
// return input;
// }
// }
// }
//
// Path: src/java/org/apache/cassandra/db/index/sasi/analyzer/filter/FilterPipelineBuilder.java
// public class FilterPipelineBuilder
// {
// private final FilterPipelineTask<?,?> parent;
// private FilterPipelineTask<?,?> current;
//
// public FilterPipelineBuilder(FilterPipelineTask<?, ?> first)
// {
// this(first, first);
// }
//
// private FilterPipelineBuilder(FilterPipelineTask<?, ?> first, FilterPipelineTask<?, ?> current)
// {
// this.parent = first;
// this.current = current;
// }
//
// public FilterPipelineBuilder add(String name, FilterPipelineTask<?,?> nextTask)
// {
// this.current.setLast(name, nextTask);
// this.current = nextTask;
// return this;
// }
//
// public FilterPipelineTask<?,?> build()
// {
// return this.parent;
// }
// }
//
// Path: src/java/org/apache/cassandra/db/index/sasi/analyzer/filter/FilterPipelineExecutor.java
// public class FilterPipelineExecutor
// {
// private static final Logger logger = LoggerFactory.getLogger(FilterPipelineExecutor.class);
//
// public static <F,T> T execute(FilterPipelineTask<F, T> task, T initialInput)
// {
// FilterPipelineTask<?, ?> taskPtr = task;
// T result = initialInput;
// try
// {
// while (true)
// {
// FilterPipelineTask<F,T> taskGeneric = (FilterPipelineTask<F,T>) taskPtr;
// result = taskGeneric.process((F) result);
// taskPtr = taskPtr.next;
// if(taskPtr == null)
// return result;
// }
// }
// catch (Exception e)
// {
// logger.info("An unhandled exception to occurred while processing " +
// "pipeline [{}]", task.getName(), e);
// }
// return null;
// }
// }
//
// Path: src/java/org/apache/cassandra/db/index/sasi/analyzer/filter/FilterPipelineTask.java
// public abstract class FilterPipelineTask<F, T>
// {
// private String name;
// public FilterPipelineTask<?, ?> next;
//
// protected <K, V> void setLast(String name, FilterPipelineTask<K, V> last)
// {
// if (last == this)
// throw new IllegalArgumentException("provided last task ["
// + last.name + "] cannot be set to itself");
// if (this.next == null)
// {
// this.next = last;
// this.name = name;
// }
// else
// {
// this.next.setLast(name, last);
// }
// }
//
// public abstract T process(F input) throws Exception;
//
// public String getName()
// {
// return name;
// }
// }
| import org.apache.cassandra.utils.ByteBufferUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.ByteBuffer;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.cassandra.db.index.sasi.analyzer.filter.BasicResultFilters;
import org.apache.cassandra.db.index.sasi.analyzer.filter.FilterPipelineBuilder;
import org.apache.cassandra.db.index.sasi.analyzer.filter.FilterPipelineExecutor;
import org.apache.cassandra.db.index.sasi.analyzer.filter.FilterPipelineTask;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.db.marshal.AsciiType;
import org.apache.cassandra.db.marshal.UTF8Type;
import org.apache.cassandra.serializers.MarshalException; | if (pipelineRes == null || !(pipelineRes instanceof String))
return false;
next = validator.fromString(normalize((String) pipelineRes));
return true;
}
catch (MarshalException e)
{
logger.error("Failed to deserialize value with " + validator, e);
return false;
}
finally
{
hasNext = false;
}
}
return false;
}
@Override
public void reset(ByteBuffer input)
{
this.next = null;
this.input = input;
this.hasNext = true;
}
private FilterPipelineTask getFilterPipeline()
{ | // Path: src/java/org/apache/cassandra/db/index/sasi/analyzer/filter/BasicResultFilters.java
// public class BasicResultFilters
// {
// private static final Locale DEFAULT_LOCALE = Locale.getDefault();
//
// public static class LowerCase extends FilterPipelineTask<String, String>
// {
// private Locale locale;
//
// public LowerCase(Locale locale)
// {
// this.locale = locale;
// }
//
// public LowerCase()
// {
// this.locale = DEFAULT_LOCALE;
// }
//
// @Override
// public String process(String input) throws Exception
// {
// return input.toLowerCase(locale);
// }
// }
//
// public static class UpperCase extends FilterPipelineTask<String, String>
// {
// private Locale locale;
//
// public UpperCase(Locale locale)
// {
// this.locale = locale;
// }
//
// public UpperCase()
// {
// this.locale = DEFAULT_LOCALE;
// }
//
// public String process(String input) throws Exception
// {
// return input.toUpperCase(locale);
// }
// }
//
// public static class NoOperation extends FilterPipelineTask<Object, Object>
// {
// public Object process(Object input) throws Exception
// {
// return input;
// }
// }
// }
//
// Path: src/java/org/apache/cassandra/db/index/sasi/analyzer/filter/FilterPipelineBuilder.java
// public class FilterPipelineBuilder
// {
// private final FilterPipelineTask<?,?> parent;
// private FilterPipelineTask<?,?> current;
//
// public FilterPipelineBuilder(FilterPipelineTask<?, ?> first)
// {
// this(first, first);
// }
//
// private FilterPipelineBuilder(FilterPipelineTask<?, ?> first, FilterPipelineTask<?, ?> current)
// {
// this.parent = first;
// this.current = current;
// }
//
// public FilterPipelineBuilder add(String name, FilterPipelineTask<?,?> nextTask)
// {
// this.current.setLast(name, nextTask);
// this.current = nextTask;
// return this;
// }
//
// public FilterPipelineTask<?,?> build()
// {
// return this.parent;
// }
// }
//
// Path: src/java/org/apache/cassandra/db/index/sasi/analyzer/filter/FilterPipelineExecutor.java
// public class FilterPipelineExecutor
// {
// private static final Logger logger = LoggerFactory.getLogger(FilterPipelineExecutor.class);
//
// public static <F,T> T execute(FilterPipelineTask<F, T> task, T initialInput)
// {
// FilterPipelineTask<?, ?> taskPtr = task;
// T result = initialInput;
// try
// {
// while (true)
// {
// FilterPipelineTask<F,T> taskGeneric = (FilterPipelineTask<F,T>) taskPtr;
// result = taskGeneric.process((F) result);
// taskPtr = taskPtr.next;
// if(taskPtr == null)
// return result;
// }
// }
// catch (Exception e)
// {
// logger.info("An unhandled exception to occurred while processing " +
// "pipeline [{}]", task.getName(), e);
// }
// return null;
// }
// }
//
// Path: src/java/org/apache/cassandra/db/index/sasi/analyzer/filter/FilterPipelineTask.java
// public abstract class FilterPipelineTask<F, T>
// {
// private String name;
// public FilterPipelineTask<?, ?> next;
//
// protected <K, V> void setLast(String name, FilterPipelineTask<K, V> last)
// {
// if (last == this)
// throw new IllegalArgumentException("provided last task ["
// + last.name + "] cannot be set to itself");
// if (this.next == null)
// {
// this.next = last;
// this.name = name;
// }
// else
// {
// this.next.setLast(name, last);
// }
// }
//
// public abstract T process(F input) throws Exception;
//
// public String getName()
// {
// return name;
// }
// }
// Path: src/java/org/apache/cassandra/db/index/sasi/analyzer/NonTokenizingAnalyzer.java
import org.apache.cassandra.utils.ByteBufferUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.ByteBuffer;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.cassandra.db.index.sasi.analyzer.filter.BasicResultFilters;
import org.apache.cassandra.db.index.sasi.analyzer.filter.FilterPipelineBuilder;
import org.apache.cassandra.db.index.sasi.analyzer.filter.FilterPipelineExecutor;
import org.apache.cassandra.db.index.sasi.analyzer.filter.FilterPipelineTask;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.db.marshal.AsciiType;
import org.apache.cassandra.db.marshal.UTF8Type;
import org.apache.cassandra.serializers.MarshalException;
if (pipelineRes == null || !(pipelineRes instanceof String))
return false;
next = validator.fromString(normalize((String) pipelineRes));
return true;
}
catch (MarshalException e)
{
logger.error("Failed to deserialize value with " + validator, e);
return false;
}
finally
{
hasNext = false;
}
}
return false;
}
@Override
public void reset(ByteBuffer input)
{
this.next = null;
this.input = input;
this.hasNext = true;
}
private FilterPipelineTask getFilterPipeline()
{ | FilterPipelineBuilder builder = new FilterPipelineBuilder(new BasicResultFilters.NoOperation()); |
xedin/sasi | src/java/org/apache/cassandra/db/index/sasi/utils/trie/AbstractPatriciaTrie.java | // Path: src/java/org/apache/cassandra/db/index/sasi/utils/trie/Cursor.java
// enum Decision
// {
//
// /**
// * Exit the traverse operation
// */
// EXIT,
//
// /**
// * Continue with the traverse operation
// */
// CONTINUE,
//
// /**
// * Remove the previously returned element
// * from the {@link Trie} and continue
// */
// REMOVE,
//
// /**
// * Remove the previously returned element
// * from the {@link Trie} and exit from the
// * traverse operation
// */
// REMOVE_AND_EXIT
// }
| import java.util.NoSuchElementException;
import java.util.Set;
import org.apache.cassandra.db.index.sasi.utils.trie.Cursor.Decision;
import java.util.AbstractCollection;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.Map; |
if (!isBitSet(key, h.bitIndex))
{
if (selectR(h.left, h.bitIndex, key, reference))
{
return selectR(h.right, h.bitIndex, key, reference);
}
}
else
{
if (selectR(h.right, h.bitIndex, key, reference))
{
return selectR(h.left, h.bitIndex, key, reference);
}
}
return false;
}
/**
*
*/
private boolean selectR(TrieEntry<K,V> h, int bitIndex,
final K key, final Cursor<? super K, ? super V> cursor,
final Reference<Map.Entry<K, V>> reference)
{
if (h.bitIndex <= bitIndex)
{
if (!h.isEmpty())
{ | // Path: src/java/org/apache/cassandra/db/index/sasi/utils/trie/Cursor.java
// enum Decision
// {
//
// /**
// * Exit the traverse operation
// */
// EXIT,
//
// /**
// * Continue with the traverse operation
// */
// CONTINUE,
//
// /**
// * Remove the previously returned element
// * from the {@link Trie} and continue
// */
// REMOVE,
//
// /**
// * Remove the previously returned element
// * from the {@link Trie} and exit from the
// * traverse operation
// */
// REMOVE_AND_EXIT
// }
// Path: src/java/org/apache/cassandra/db/index/sasi/utils/trie/AbstractPatriciaTrie.java
import java.util.NoSuchElementException;
import java.util.Set;
import org.apache.cassandra.db.index.sasi.utils.trie.Cursor.Decision;
import java.util.AbstractCollection;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.Map;
if (!isBitSet(key, h.bitIndex))
{
if (selectR(h.left, h.bitIndex, key, reference))
{
return selectR(h.right, h.bitIndex, key, reference);
}
}
else
{
if (selectR(h.right, h.bitIndex, key, reference))
{
return selectR(h.left, h.bitIndex, key, reference);
}
}
return false;
}
/**
*
*/
private boolean selectR(TrieEntry<K,V> h, int bitIndex,
final K key, final Cursor<? super K, ? super V> cursor,
final Reference<Map.Entry<K, V>> reference)
{
if (h.bitIndex <= bitIndex)
{
if (!h.isEmpty())
{ | Decision decision = cursor.select(h); |
cscotta/deschutes | src/main/java/com/cscotta/deschutes/json/LoggedRollupListener.java | // Path: src/main/java/com/cscotta/deschutes/example/requests/RequestEvent.java
// public class RequestEvent implements Event {
//
// private final Request request;
//
// public RequestEvent(Request request) {
// this.request = request;
// }
//
// @Override
// public long getTimestamp() {
// return request.getTimestamp();
// }
//
// public int getUserId() {
// return request.getUserId();
// }
//
// public int getClientIp() {
// return request.getClientIp();
// }
//
// public int getServerIp() {
// return request.getServerIp();
// }
//
// public OperationType getOperationType() {
// return request.getOperationType();
// }
//
// public Protocol getProtocol() {
// return request.getProtocol();
// }
//
// public int getResponseCode() {
// return request.getResponseCode();
// }
//
// public String getUri() {
// return request.getUri();
// }
//
// public int getRequestBytes() {
// return request.getRequestBytes();
// }
//
// public int getResponseBytes() {
// return request.getResponseBytes();
// }
//
// public long getHandshakeUsec() {
// return request.getHandshakeUsec();
// }
//
// public long getUsecToFirstByte() {
// return request.getUsecToFirstByte();
// }
//
// public long getUsecTotal() {
// return request.getUsecTotal();
// }
//
// public String getUserAgent() {
// return request.getUserAgent();
// }
//
// public String getLocale() {
// return request.getLocale();
// }
//
// public String getReferrer() {
// return request.getReferrer();
// }
//
// @Override
// public String toString() {
// return request.toString();
// }
//
// }
//
// Path: src/main/java/com/cscotta/deschutes/api/ConcurrentRollup.java
// public interface ConcurrentRollup<Input> extends Event {
//
// /**
// * <p>Rollup method called as events are received by a stream for
// * aggregation.</p>
// *
// * <p>Implementations of ConcurrentRollup should accept {@link Event}s, maintain
// * the aggregations desired (sums, averages, histograms, and so on), and expose
// * them for downstream {@link OutputListener}s to access as output. See the
// * {@link ConcurrentRollup} documentation above for a sample implementation.</p>
// *
// * @param input An event received by a stream to be rolled up.
// */
// public abstract void rollup(Input input);
//
// public long getTimestamp();
// }
//
// Path: src/main/java/com/cscotta/deschutes/api/OutputListener.java
// public interface OutputListener<Input> {
//
// public void update(List<Long> remove,
// Map<Long, Map<String, ConcurrentRollup<Input>>> insert);
//
// }
//
// Path: src/main/java/com/cscotta/deschutes/json/Json.java
// public class Json {
// public final ObjectMapper objectMapper = new ObjectMapper();
//
// public Json() {
// SimpleModule olapMods = new SimpleModule("olapMods", new Version(1,0,0,null));
// olapMods.addSerializer(new HistogramSnapshotSerializer());
// objectMapper.registerModule(olapMods);
// }
//
// }
| import java.util.List;
import java.util.Map;
import com.cscotta.deschutes.example.requests.RequestEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.cscotta.deschutes.api.ConcurrentRollup;
import com.cscotta.deschutes.api.OutputListener;
import com.cscotta.deschutes.json.Json;
import org.codehaus.jackson.map.ObjectMapper; | package com.cscotta.deschutes.json;
public class LoggedRollupListener implements OutputListener<RequestEvent> {
private final ObjectMapper jackson = new Json().objectMapper;
private static final Logger log = LoggerFactory.getLogger(LoggedRollupListener.class);
@Override | // Path: src/main/java/com/cscotta/deschutes/example/requests/RequestEvent.java
// public class RequestEvent implements Event {
//
// private final Request request;
//
// public RequestEvent(Request request) {
// this.request = request;
// }
//
// @Override
// public long getTimestamp() {
// return request.getTimestamp();
// }
//
// public int getUserId() {
// return request.getUserId();
// }
//
// public int getClientIp() {
// return request.getClientIp();
// }
//
// public int getServerIp() {
// return request.getServerIp();
// }
//
// public OperationType getOperationType() {
// return request.getOperationType();
// }
//
// public Protocol getProtocol() {
// return request.getProtocol();
// }
//
// public int getResponseCode() {
// return request.getResponseCode();
// }
//
// public String getUri() {
// return request.getUri();
// }
//
// public int getRequestBytes() {
// return request.getRequestBytes();
// }
//
// public int getResponseBytes() {
// return request.getResponseBytes();
// }
//
// public long getHandshakeUsec() {
// return request.getHandshakeUsec();
// }
//
// public long getUsecToFirstByte() {
// return request.getUsecToFirstByte();
// }
//
// public long getUsecTotal() {
// return request.getUsecTotal();
// }
//
// public String getUserAgent() {
// return request.getUserAgent();
// }
//
// public String getLocale() {
// return request.getLocale();
// }
//
// public String getReferrer() {
// return request.getReferrer();
// }
//
// @Override
// public String toString() {
// return request.toString();
// }
//
// }
//
// Path: src/main/java/com/cscotta/deschutes/api/ConcurrentRollup.java
// public interface ConcurrentRollup<Input> extends Event {
//
// /**
// * <p>Rollup method called as events are received by a stream for
// * aggregation.</p>
// *
// * <p>Implementations of ConcurrentRollup should accept {@link Event}s, maintain
// * the aggregations desired (sums, averages, histograms, and so on), and expose
// * them for downstream {@link OutputListener}s to access as output. See the
// * {@link ConcurrentRollup} documentation above for a sample implementation.</p>
// *
// * @param input An event received by a stream to be rolled up.
// */
// public abstract void rollup(Input input);
//
// public long getTimestamp();
// }
//
// Path: src/main/java/com/cscotta/deschutes/api/OutputListener.java
// public interface OutputListener<Input> {
//
// public void update(List<Long> remove,
// Map<Long, Map<String, ConcurrentRollup<Input>>> insert);
//
// }
//
// Path: src/main/java/com/cscotta/deschutes/json/Json.java
// public class Json {
// public final ObjectMapper objectMapper = new ObjectMapper();
//
// public Json() {
// SimpleModule olapMods = new SimpleModule("olapMods", new Version(1,0,0,null));
// olapMods.addSerializer(new HistogramSnapshotSerializer());
// objectMapper.registerModule(olapMods);
// }
//
// }
// Path: src/main/java/com/cscotta/deschutes/json/LoggedRollupListener.java
import java.util.List;
import java.util.Map;
import com.cscotta.deschutes.example.requests.RequestEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.cscotta.deschutes.api.ConcurrentRollup;
import com.cscotta.deschutes.api.OutputListener;
import com.cscotta.deschutes.json.Json;
import org.codehaus.jackson.map.ObjectMapper;
package com.cscotta.deschutes.json;
public class LoggedRollupListener implements OutputListener<RequestEvent> {
private final ObjectMapper jackson = new Json().objectMapper;
private static final Logger log = LoggerFactory.getLogger(LoggedRollupListener.class);
@Override | public void update(List<Long> remove, Map<Long, Map<String, ConcurrentRollup<RequestEvent>>> insert) { |
cscotta/deschutes | src/main/java/com/cscotta/deschutes/example/requests/WebsocketRollupListener.java | // Path: src/main/java/com/cscotta/deschutes/api/ConcurrentRollup.java
// public interface ConcurrentRollup<Input> extends Event {
//
// /**
// * <p>Rollup method called as events are received by a stream for
// * aggregation.</p>
// *
// * <p>Implementations of ConcurrentRollup should accept {@link Event}s, maintain
// * the aggregations desired (sums, averages, histograms, and so on), and expose
// * them for downstream {@link OutputListener}s to access as output. See the
// * {@link ConcurrentRollup} documentation above for a sample implementation.</p>
// *
// * @param input An event received by a stream to be rolled up.
// */
// public abstract void rollup(Input input);
//
// public long getTimestamp();
// }
//
// Path: src/main/java/com/cscotta/deschutes/api/OutputListener.java
// public interface OutputListener<Input> {
//
// public void update(List<Long> remove,
// Map<Long, Map<String, ConcurrentRollup<Input>>> insert);
//
// }
//
// Path: src/main/java/com/cscotta/deschutes/example/app/websockets/OLAPWebSocket.java
// public class OLAPWebSocket implements WebSocket, WebSocket.OnTextMessage {
//
// private static final Logger log = LoggerFactory.getLogger(OLAPWebSocket.class);
//
// public Connection connection;
// private Set<OLAPWebSocket> users;
//
// public OLAPWebSocket(Set<OLAPWebSocket> users) {
// this.users = users;
// }
//
// @Override
// public void onOpen(Connection connection) {
// log.info("Connection opened: " + connection.toString());
// this.connection = connection;
// users.add(this);
// }
//
// @Override
// public void onClose(int closeCode, String message) {
// log.info("Connection closed: " + connection.toString());
// users.remove(this);
// }
//
// @Override
// public void onMessage(String data) {
// log.info("Message received from : " + connection.toString() + ": " + data);
// }
// }
//
// Path: src/main/java/com/cscotta/deschutes/json/Json.java
// public class Json {
// public final ObjectMapper objectMapper = new ObjectMapper();
//
// public Json() {
// SimpleModule olapMods = new SimpleModule("olapMods", new Version(1,0,0,null));
// olapMods.addSerializer(new HistogramSnapshotSerializer());
// objectMapper.registerModule(olapMods);
// }
//
// }
| import com.cscotta.deschutes.api.ConcurrentRollup;
import com.cscotta.deschutes.api.OutputListener;
import com.cscotta.deschutes.example.app.websockets.OLAPWebSocket;
import com.cscotta.deschutes.json.Json;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set; | package com.cscotta.deschutes.example.requests;
public class WebsocketRollupListener implements OutputListener<RequestEvent> {
private final Set<OLAPWebSocket> users; | // Path: src/main/java/com/cscotta/deschutes/api/ConcurrentRollup.java
// public interface ConcurrentRollup<Input> extends Event {
//
// /**
// * <p>Rollup method called as events are received by a stream for
// * aggregation.</p>
// *
// * <p>Implementations of ConcurrentRollup should accept {@link Event}s, maintain
// * the aggregations desired (sums, averages, histograms, and so on), and expose
// * them for downstream {@link OutputListener}s to access as output. See the
// * {@link ConcurrentRollup} documentation above for a sample implementation.</p>
// *
// * @param input An event received by a stream to be rolled up.
// */
// public abstract void rollup(Input input);
//
// public long getTimestamp();
// }
//
// Path: src/main/java/com/cscotta/deschutes/api/OutputListener.java
// public interface OutputListener<Input> {
//
// public void update(List<Long> remove,
// Map<Long, Map<String, ConcurrentRollup<Input>>> insert);
//
// }
//
// Path: src/main/java/com/cscotta/deschutes/example/app/websockets/OLAPWebSocket.java
// public class OLAPWebSocket implements WebSocket, WebSocket.OnTextMessage {
//
// private static final Logger log = LoggerFactory.getLogger(OLAPWebSocket.class);
//
// public Connection connection;
// private Set<OLAPWebSocket> users;
//
// public OLAPWebSocket(Set<OLAPWebSocket> users) {
// this.users = users;
// }
//
// @Override
// public void onOpen(Connection connection) {
// log.info("Connection opened: " + connection.toString());
// this.connection = connection;
// users.add(this);
// }
//
// @Override
// public void onClose(int closeCode, String message) {
// log.info("Connection closed: " + connection.toString());
// users.remove(this);
// }
//
// @Override
// public void onMessage(String data) {
// log.info("Message received from : " + connection.toString() + ": " + data);
// }
// }
//
// Path: src/main/java/com/cscotta/deschutes/json/Json.java
// public class Json {
// public final ObjectMapper objectMapper = new ObjectMapper();
//
// public Json() {
// SimpleModule olapMods = new SimpleModule("olapMods", new Version(1,0,0,null));
// olapMods.addSerializer(new HistogramSnapshotSerializer());
// objectMapper.registerModule(olapMods);
// }
//
// }
// Path: src/main/java/com/cscotta/deschutes/example/requests/WebsocketRollupListener.java
import com.cscotta.deschutes.api.ConcurrentRollup;
import com.cscotta.deschutes.api.OutputListener;
import com.cscotta.deschutes.example.app.websockets.OLAPWebSocket;
import com.cscotta.deschutes.json.Json;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
package com.cscotta.deschutes.example.requests;
public class WebsocketRollupListener implements OutputListener<RequestEvent> {
private final Set<OLAPWebSocket> users; | private final ObjectMapper jackson = new Json().objectMapper; |
cscotta/deschutes | src/main/java/com/cscotta/deschutes/example/requests/WebsocketRollupListener.java | // Path: src/main/java/com/cscotta/deschutes/api/ConcurrentRollup.java
// public interface ConcurrentRollup<Input> extends Event {
//
// /**
// * <p>Rollup method called as events are received by a stream for
// * aggregation.</p>
// *
// * <p>Implementations of ConcurrentRollup should accept {@link Event}s, maintain
// * the aggregations desired (sums, averages, histograms, and so on), and expose
// * them for downstream {@link OutputListener}s to access as output. See the
// * {@link ConcurrentRollup} documentation above for a sample implementation.</p>
// *
// * @param input An event received by a stream to be rolled up.
// */
// public abstract void rollup(Input input);
//
// public long getTimestamp();
// }
//
// Path: src/main/java/com/cscotta/deschutes/api/OutputListener.java
// public interface OutputListener<Input> {
//
// public void update(List<Long> remove,
// Map<Long, Map<String, ConcurrentRollup<Input>>> insert);
//
// }
//
// Path: src/main/java/com/cscotta/deschutes/example/app/websockets/OLAPWebSocket.java
// public class OLAPWebSocket implements WebSocket, WebSocket.OnTextMessage {
//
// private static final Logger log = LoggerFactory.getLogger(OLAPWebSocket.class);
//
// public Connection connection;
// private Set<OLAPWebSocket> users;
//
// public OLAPWebSocket(Set<OLAPWebSocket> users) {
// this.users = users;
// }
//
// @Override
// public void onOpen(Connection connection) {
// log.info("Connection opened: " + connection.toString());
// this.connection = connection;
// users.add(this);
// }
//
// @Override
// public void onClose(int closeCode, String message) {
// log.info("Connection closed: " + connection.toString());
// users.remove(this);
// }
//
// @Override
// public void onMessage(String data) {
// log.info("Message received from : " + connection.toString() + ": " + data);
// }
// }
//
// Path: src/main/java/com/cscotta/deschutes/json/Json.java
// public class Json {
// public final ObjectMapper objectMapper = new ObjectMapper();
//
// public Json() {
// SimpleModule olapMods = new SimpleModule("olapMods", new Version(1,0,0,null));
// olapMods.addSerializer(new HistogramSnapshotSerializer());
// objectMapper.registerModule(olapMods);
// }
//
// }
| import com.cscotta.deschutes.api.ConcurrentRollup;
import com.cscotta.deschutes.api.OutputListener;
import com.cscotta.deschutes.example.app.websockets.OLAPWebSocket;
import com.cscotta.deschutes.json.Json;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set; | package com.cscotta.deschutes.example.requests;
public class WebsocketRollupListener implements OutputListener<RequestEvent> {
private final Set<OLAPWebSocket> users;
private final ObjectMapper jackson = new Json().objectMapper;
private static final Logger log = LoggerFactory.getLogger(WebsocketRollupListener.class);
public WebsocketRollupListener(Set<OLAPWebSocket> users) {
this.users = users;
}
@Override | // Path: src/main/java/com/cscotta/deschutes/api/ConcurrentRollup.java
// public interface ConcurrentRollup<Input> extends Event {
//
// /**
// * <p>Rollup method called as events are received by a stream for
// * aggregation.</p>
// *
// * <p>Implementations of ConcurrentRollup should accept {@link Event}s, maintain
// * the aggregations desired (sums, averages, histograms, and so on), and expose
// * them for downstream {@link OutputListener}s to access as output. See the
// * {@link ConcurrentRollup} documentation above for a sample implementation.</p>
// *
// * @param input An event received by a stream to be rolled up.
// */
// public abstract void rollup(Input input);
//
// public long getTimestamp();
// }
//
// Path: src/main/java/com/cscotta/deschutes/api/OutputListener.java
// public interface OutputListener<Input> {
//
// public void update(List<Long> remove,
// Map<Long, Map<String, ConcurrentRollup<Input>>> insert);
//
// }
//
// Path: src/main/java/com/cscotta/deschutes/example/app/websockets/OLAPWebSocket.java
// public class OLAPWebSocket implements WebSocket, WebSocket.OnTextMessage {
//
// private static final Logger log = LoggerFactory.getLogger(OLAPWebSocket.class);
//
// public Connection connection;
// private Set<OLAPWebSocket> users;
//
// public OLAPWebSocket(Set<OLAPWebSocket> users) {
// this.users = users;
// }
//
// @Override
// public void onOpen(Connection connection) {
// log.info("Connection opened: " + connection.toString());
// this.connection = connection;
// users.add(this);
// }
//
// @Override
// public void onClose(int closeCode, String message) {
// log.info("Connection closed: " + connection.toString());
// users.remove(this);
// }
//
// @Override
// public void onMessage(String data) {
// log.info("Message received from : " + connection.toString() + ": " + data);
// }
// }
//
// Path: src/main/java/com/cscotta/deschutes/json/Json.java
// public class Json {
// public final ObjectMapper objectMapper = new ObjectMapper();
//
// public Json() {
// SimpleModule olapMods = new SimpleModule("olapMods", new Version(1,0,0,null));
// olapMods.addSerializer(new HistogramSnapshotSerializer());
// objectMapper.registerModule(olapMods);
// }
//
// }
// Path: src/main/java/com/cscotta/deschutes/example/requests/WebsocketRollupListener.java
import com.cscotta.deschutes.api.ConcurrentRollup;
import com.cscotta.deschutes.api.OutputListener;
import com.cscotta.deschutes.example.app.websockets.OLAPWebSocket;
import com.cscotta.deschutes.json.Json;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
package com.cscotta.deschutes.example.requests;
public class WebsocketRollupListener implements OutputListener<RequestEvent> {
private final Set<OLAPWebSocket> users;
private final ObjectMapper jackson = new Json().objectMapper;
private static final Logger log = LoggerFactory.getLogger(WebsocketRollupListener.class);
public WebsocketRollupListener(Set<OLAPWebSocket> users) {
this.users = users;
}
@Override | public void update(List<Long> remove, Map<Long, Map<String, ConcurrentRollup<RequestEvent>>> insert) { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.