hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
725b75a6b7abb4c925a0cae5b52495580ccea2eb | 125 | package momo.com.day58_xutils;
/**
* Created by Administrator on 2016/12/28 0028.
*/
public @interface MyAnnotation {
}
| 12.5 | 47 | 0.712 |
d8ff4a0d0b08df455a7107b390d6e07dd92bf4ed | 176 | package org.apache.avro.perf.test.reflect.jmh_generated;
public class ReflectLongArrayTest_TestStateDecode_jmhType extends ReflectLongArrayTest_TestStateDecode_jmhType_B3 {
}
| 35.2 | 115 | 0.892045 |
9b4f2b47ae264e2d383ed10f13994129b191e826 | 182 | package com.example.util;
/**
* Created by DELL on 2017/3/30.
*/
public interface OnNetRequestCallback {
void onFailed(String reason);
void onSuccess(String response);
}
| 16.545455 | 39 | 0.708791 |
2c188b02cf66f0beb25c41a83a35b86ea64c193d | 807 | package club.cser.leetcode;
import java.util.HashMap;
import java.util.Map;
class FourSumII {
public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
Map<Integer, Integer> AB = new HashMap<>();
Map<Integer, Integer> CD = new HashMap<>();
for (int i = 0; i < A.length; ++ i) {
for (int j = 0; j < A.length; ++ j) {
AB.computeIfPresent(A[i] + B[j], (key, val) -> ++ val);
AB.computeIfAbsent(A[i] + B[j], key -> 1);
CD.computeIfPresent(C[i] + D[j], (key, val) -> ++ val);
CD.computeIfAbsent(C[i] + D[j], key -> 1);
}
}
int res = 0;
for (Integer k : AB.keySet()) {
res += AB.get(k) * CD.getOrDefault(-k, 0);
}
return res;
}
} | 28.821429 | 72 | 0.465923 |
fc10e10c9b0ff01c8447370f6a2d7e0b731760d3 | 1,238 | package com.example.haushaltsapp.slideshow;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.RecyclerView;
import com.example.haushaltsapp.R;
public class HistoryListFragment extends Fragment {
private FinanceViewModel financeViewModel;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
financeViewModel = new ViewModelProvider(requireParentFragment()).get(FinanceViewModel.class);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_history_list, container, false);
RecyclerView recyclerView = view.findViewById(R.id.HistoryListRec);
final HistoryRecyclerViewAdapter adapter = new HistoryRecyclerViewAdapter(financeViewModel.createEntriesAdapter(getViewLifecycleOwner()));
recyclerView.setAdapter(adapter);
// Inflate the layout for this fragment
return view;
}
} | 33.459459 | 146 | 0.758481 |
75fdaf2c15cd26c874040c7661f3ba1a9f607bdf | 13,201 | package com.ejlchina.okhttps;
import com.ejlchina.data.Array;
import com.ejlchina.data.Mapper;
import com.ejlchina.data.TypeRef;
import com.ejlchina.okhttps.HttpResult.State;
import com.ejlchina.okhttps.internal.*;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.List;
import java.util.concurrent.CountDownLatch;
/**
* 异步 Http 请求任务
*
* @author Troy.Zhou
*
*/
public class AHttpTask extends HttpTask<AHttpTask> {
private OnCallback<HttpResult> onResponse;
private OnCallback<IOException> onException;
private OnCallback<State> onComplete;
private boolean responseOnIO;
private boolean exceptionOnIO;
private boolean completeOnIO;
private OnCallback<HttpResult.Body> onResBody;
private OnCallback<Mapper> onResMapper;
private OnCallback<Array> onResArray;
private OnCallback<String> onResString;
private OnCallback<?> onResBean;
private OnCallback<?> onResList;
private boolean resBodyOnIO;
private boolean resMapperOnIO;
private boolean resArrayOnIO;
private boolean resStringOnIO;
private boolean resBeanOnIO;
private boolean resListOnIO;
private Type beanType;
private Class<?> listType;
public AHttpTask(AbstractHttpClient client, String url) {
super(client, url);
}
@Override
public boolean isAsyncHttp() {
return true;
}
/**
* 设置请求执行异常后的回调函数,设置后,相关异常将不再向上抛出
* @param onException 请求异常回调
* @return HttpTask 实例
*/
public AHttpTask setOnException(OnCallback<IOException> onException) {
this.onException = onException;
exceptionOnIO = nextOnIO;
nextOnIO = false;
return this;
}
/**
* 设置请求执行完成后的回调函数,无论成功|失败|异常 都会被执行
* @param onComplete 请求完成回调
* @return HttpTask 实例
*/
public AHttpTask setOnComplete(OnCallback<State> onComplete) {
this.onComplete = onComplete;
completeOnIO = nextOnIO;
nextOnIO = false;
return this;
}
/**
* 设置请求得到响应后的回调函数
* @param onResponse 请求响应回调
* @return HttpTask 实例
*/
public synchronized AHttpTask setOnResponse(OnCallback<HttpResult> onResponse) {
this.onResponse = onResponse;
responseOnIO = nextOnIO;
nextOnIO = false;
return this;
}
/**
* 设置请求得到响应后的回调函数
* @param onResBody 响应报文体回调
* @return HttpTask 实例
*/
public synchronized AHttpTask setOnResBody(OnCallback<HttpResult.Body> onResBody) {
this.onResBody = onResBody;
resBodyOnIO = nextOnIO;
nextOnIO = false;
return this;
}
/**
* 设置请求得到响应后的回调函数
* @param <T> 泛型
* @param type 期望的转换类型
* @param onResBean 响应 Bean 回调
* @return HttpTask 实例
*/
public synchronized <T> AHttpTask setOnResBean(Class<T> type, OnCallback<T> onResBean) {
initBeanType(type);
this.onResBean = onResBean;
resBeanOnIO = nextOnIO;
nextOnIO = false;
return this;
}
/**
* 设置请求得到响应后的回调函数
* @param <T> 泛型
* @param type 期望的转换类型
* @param onResBean 响应 Bean 回调
* @return HttpTask 实例
*/
public synchronized <T> AHttpTask setOnResBean(TypeRef<T> type, OnCallback<T> onResBean) {
initBeanType(type.getType());
this.onResBean = onResBean;
resBeanOnIO = nextOnIO;
nextOnIO = false;
return this;
}
/**
* 设置请求得到响应后的回调函数
* @param <T> 泛型
* @param type 期望的转换类型
* @param onResList 请求响应回调
* @return HttpTask 实例
*/
public synchronized <T> AHttpTask setOnResList(Class<T> type, OnCallback<List<T>> onResList) {
if (type == null) {
throw new IllegalArgumentException(" list type can not be null!");
}
listType = type;
this.onResList = onResList;
resListOnIO = nextOnIO;
nextOnIO = false;
return this;
}
/**
* 设置请求得到响应后的回调函数
* @param onResMapper 请求响应回调
* @return HttpTask 实例
*/
public synchronized AHttpTask setOnResMapper(OnCallback<Mapper> onResMapper) {
this.onResMapper = onResMapper;
resMapperOnIO = nextOnIO;
nextOnIO = false;
return this;
}
/**
* 设置请求得到响应后的回调函数
* @param onResArray 请求响应回调
* @return HttpTask 实例
*/
public synchronized AHttpTask setOnResArray(OnCallback<Array> onResArray) {
this.onResArray = onResArray;
resArrayOnIO = nextOnIO;
nextOnIO = false;
return this;
}
/**
* 设置请求得到响应后的回调函数
* @param onResString 请求响应回调
* @return HttpTask 实例
*/
public synchronized AHttpTask setOnResString(OnCallback<String> onResString) {
this.onResString = onResString;
resStringOnIO = nextOnIO;
nextOnIO = false;
return this;
}
/**
* 发起 GET 请求(Rest:读取资源,幂等)
* @return HttpCall
*/
public HttpCall get() {
return request(HTTP.GET);
}
/**
* 发起 HEAD 请求(Rest:读取资源头信息,幂等)
* @return HttpCall
*/
public HttpCall head() {
return request(HTTP.HEAD);
}
/**
* 发起 POST 请求(Rest:创建资源,非幂等)
* @return HttpCall
*/
public HttpCall post() {
return request(HTTP.POST);
}
/**
* 发起 PUT 请求(Rest:更新资源,幂等)
* @return HttpCall
*/
public HttpCall put() {
return request(HTTP.PUT);
}
/**
* 发起 PATCH 请求(Rest:更新资源,部分更新,幂等)
* @return HttpCall
*/
public HttpCall patch() {
return request(HTTP.PATCH);
}
/**
* 发起 DELETE 请求(Rest:删除资源,幂等)
* @return HttpCall
*/
public HttpCall delete() {
return request(HTTP.DELETE);
}
/**
* 发起 HTTP 请求
* @param method 请求方法
* @return HttpCall
*/
public HttpCall request(String method) {
if (method == null || method.isEmpty()) {
throw new IllegalArgumentException("HTTP 请求方法 method 不可为空!");
}
PreHttpCall call = new PreHttpCall();
registeTagTask(call);
httpClient.preprocess(this, () -> {
synchronized (call) {
if (call.canceled) {
removeTagTask();
} else {
if (onResponse != null || onResBody != null) {
tag(CopyInterceptor.TAG);
}
call.setCall(executeCall(prepareCall(method)));
}
}
}, skipPreproc, skipSerialPreproc);
return call;
}
class PreHttpCall implements HttpCall {
HttpCall call;
boolean canceled = false;
CountDownLatch latch = new CountDownLatch(1);
@Override
public synchronized boolean cancel() {
canceled = call == null || call.cancel();
latch.countDown();
return canceled;
}
@Override
public boolean isDone() {
if (call != null) {
return call.isDone();
}
return canceled;
}
@Override
public boolean isCanceled() {
return canceled;
}
void setCall(HttpCall call) {
this.call = call;
latch.countDown();
}
@Override
public HttpResult getResult() {
if (!timeoutAwait(latch)) {
cancel();
return timeoutResult();
}
if (canceled || call == null) {
return new RealHttpResult(AHttpTask.this, State.CANCELED);
}
return call.getResult();
}
@Override
public AHttpTask getTask() {
return AHttpTask.this;
}
}
public class OkHttpCall implements HttpCall {
final Call call;
HttpResult result;
CountDownLatch latch = new CountDownLatch(1);
boolean finished = false;
OkHttpCall(Call call) {
this.call = call;
}
@Override
public synchronized boolean cancel() {
if (result == null || !finished) {
call.cancel();
return true;
}
return false;
}
@Override
public boolean isDone() {
return result != null && finished || call.isCanceled();
}
@Override
public boolean isCanceled() {
return call.isCanceled() || (result != null && result.getState() == State.CANCELED);
}
@Override
public HttpResult getResult() {
if (result == null) {
if (!timeoutAwait(latch)) {
cancel();
return timeoutResult();
}
}
return result;
}
@Override
public AHttpTask getTask() {
return AHttpTask.this;
}
void setResult(HttpResult result) {
this.result = result;
latch.countDown();
}
public void finish() {
this.finished = true;
}
}
private HttpCall executeCall(Call call) {
OkHttpCall httpCall = new OkHttpCall(call);
call.enqueue(new Callback() {
@Override
@SuppressWarnings("NullableProblems")
public void onFailure(Call call, IOException error) {
State state = toState(error);
HttpResult result = new RealHttpResult(AHttpTask.this, state, error);
onCallback(httpCall, result, () -> {
TaskExecutor executor = httpClient.executor();
executor.executeOnComplete(AHttpTask.this, onComplete, state, completeOnIO);
if (!httpCall.isCanceled() && !executor.executeOnException(AHttpTask.this, httpCall, onException, error, exceptionOnIO)
&& !nothrow) {
throw new OkHttpsException(state, "异步请求异常:" + getUrl(), error);
}
});
}
@Override
@SuppressWarnings("NullableProblems")
public void onResponse(Call call, Response response) {
TaskExecutor executor = httpClient.executor();
HttpResult result = new RealHttpResult(AHttpTask.this, response, executor);
onCallback(httpCall, result, () -> {
executor.executeOnComplete(AHttpTask.this, onComplete, State.RESPONSED, completeOnIO);
if (!httpCall.isCanceled()) {
executor.executeOnResponse(AHttpTask.this, httpCall, complexOnResponse(httpCall), result, true);
}
});
}
});
return httpCall;
}
@SuppressWarnings("all")
private void onCallback(OkHttpCall httpCall, HttpResult result, Runnable runnable) {
synchronized (httpCall) {
removeTagTask();
if (httpCall.isCanceled() || result.getState() == State.CANCELED) {
httpCall.setResult(new RealHttpResult(AHttpTask.this, State.CANCELED));
} else {
httpCall.setResult(result);
}
runnable.run();
}
}
interface ResponseCallback {
void on(Runnable runnable, boolean onIo);
}
private synchronized OnCallback<HttpResult> complexOnResponse(OkHttpCall call) {
return res -> {
OnCallback<HttpResult> onResp = onResponse;
OnCallback<HttpResult.Body> onBody = onResBody;
OnCallback<Mapper> onMapper = onResMapper;
OnCallback<Array> onArray = onResArray;
OnCallback<?> onBean = onResBean;
OnCallback<?> onList = onResList;
OnCallback<String> onString = onResString;
int count = 0;
if (onResp != null)
count++;
if (onBody != null)
count++;
if (onMapper != null)
count++;
if (onArray != null)
count++;
if (onBean != null)
count++;
if (onList != null)
count++;
if (onString != null)
count++;
int callbackCount = count;
HttpResult.Body body = res.getBody();
if (callbackCount > 1) {
// 如果回调数量多于 1 个,则为报文体自动开启缓存
body.cache();
}
ResponseCallback callback = (runnable, onIo) -> execute(new Runnable() {
// 记录已经回调的次数
int count = 0;
@Override
public void run() {
if (!call.isCanceled()) {
runnable.run();
}
if (++count >= callbackCount) {
call.finish();
}
}
}, onIo);
if (onResp != null) {
callback.on(() -> onResp.on(res), responseOnIO);
}
if (onBody != null) {
callback.on(() -> onBody.on(body), resBodyOnIO);
}
if (onMapper != null) {
Mapper mapper = body.toMapper();
callback.on(() -> onMapper.on(mapper), resMapperOnIO);
}
if (onArray != null) {
Array array = body.toArray();
callback.on(() -> onArray.on(array), resArrayOnIO);
}
if (onBean != null) {
Object bean = body.toBean(beanType);
callback.on(() -> {
try {
callbackMethod(onBean.getClass(), bean.getClass()).invoke(onBean, bean);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new OkHttpsException("回调方法调用失败!", e);
}
}, resBeanOnIO);
}
if (onList != null) {
List<?> list = body.toList(listType);
callback.on(() -> {
try {
callbackMethod(onList.getClass(), list.getClass()).invoke(onList, list);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new OkHttpsException("回调方法调用失败!", e);
}
}, resListOnIO);
}
if (onString != null) {
String string = body.toString();
callback.on(() -> onString.on(string), resStringOnIO);
}
};
}
static final String OnCallbackMethod = OnCallback.class.getDeclaredMethods()[0].getName();
private Method callbackMethod(Class<?> clazz, Class<?> paraType) {
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
Class<?>[] paraTypes = method.getParameterTypes();
if (method.getName().equals(OnCallbackMethod) && paraTypes.length == 1
&& paraTypes[0].isAssignableFrom(paraType)) {
method.setAccessible(true);
return method;
}
}
throw new IllegalStateException("没有可调用的方法");
}
private void initBeanType(Type type) {
if (type == null) {
throw new IllegalArgumentException(" bean type can not be null!");
}
if (beanType != null) {
throw new IllegalStateException("已经添加了 OnResBean 回调!");
}
beanType = type;
}
}
| 24.133455 | 124 | 0.641164 |
527257da72084fce60124c39195e57321230d847 | 35,809 | /*
Copyright 2009 Wallace Wadge
This file is part of BoneCP.
BoneCP is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
BoneCP is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with BoneCP. If not, see <http://www.gnu.org/licenses/>.
*/
package org.itas.core.dbpool;
import java.lang.reflect.Proxy;
// #ifdef JDK6
import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
// #endif JDK6
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicInteger;
import org.itas.core.dbpool.hooks.AcquireFailConfig;
import org.itas.core.dbpool.hooks.ConnectionHook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableSet;
/**
* Connection handle wrapper around a JDBC connection.
*
* @author wwadge
*
*/
public class ConnectionHandle implements Connection{
/** Exception message. */
private static final String STATEMENT_NOT_CLOSED = "Stack trace of location where statement was opened follows:\n%s";
/** Exception message. */
private static final String LOG_ERROR_MESSAGE = "Connection closed twice exception detected.\n%s\n%s\n";
/** Exception message. */
private static final String CLOSED_TWICE_EXCEPTION_MESSAGE = "Connection closed from thread [%s] was closed again.\nStack trace of location where connection was first closed follows:\n";
/** Connection handle. */
private Connection connection = null;
/** Last time this connection was used by an application. */
private long connectionLastUsed = System.currentTimeMillis();
/** Last time we sent a reset to this connection. */
private long connectionLastReset = System.currentTimeMillis();
/** Pool handle. */
private BoneCP pool;
/**
* If true, this connection might have failed communicating with the
* database. We assume that exceptions should be rare here i.e. the normal
* case is assumed to succeed.
*/
protected boolean possiblyBroken;
/** If true, we've called close() on this connection. */
protected boolean logicallyClosed = false;
/** Original partition. */
private ConnectionPartition originatingPartition = null;
/** Prepared Statement Cache. */
private IStatementCache preparedStatementCache = null;
/** Prepared Statement Cache. */
private IStatementCache callableStatementCache = null;
/** Logger handle. */
private static Logger logger = LoggerFactory.getLogger(ConnectionHandle.class);
/** An opaque handle for an application to use in any way it deems fit. */
private Object debugHandle;
/** Handle to the connection hook as defined in the config. */
private ConnectionHook connectionHook;
/** If true, give warnings if application tried to issue a close twice (for debugging only). */
private boolean doubleCloseCheck;
/** exception trace if doubleCloseCheck is enabled. */
private volatile String doubleCloseException = null;
/** If true, log sql statements. */
private boolean logStatementsEnabled;
/** Set to true if we have statement caching enabled. */
protected boolean statementCachingEnabled;
/** The recorded actions list used to replay the transaction. */
private List<ReplayLog> replayLog;
/** If true, connection is currently playing back a saved transaction. */
private boolean inReplayMode;
/** Connection url. */
protected String url;
/** Keep track of the thread that's using this connection for connection watch. */
protected Thread threadUsingConnection;
/** If true, we have release helper threads. */
private boolean releaseHelperThreadsEnabled;
/*
* From: http://publib.boulder.ibm.com/infocenter/db2luw/v8/index.jsp?topic=/com.ibm.db2.udb.doc/core/r0sttmsg.htm
* Table 7. Class Code 08: Connection Exception
SQLSTATE Value
Value Meaning
08001 The application requester is unable to establish the connection.
08002 The connection already exists.
08003 The connection does not exist.
08004 The application server rejected establishment of the connection.
08007 Transaction resolution unknown.
08502 The CONNECT statement issued by an application process running with a SYNCPOINT of TWOPHASE has failed, because no transaction manager is available.
08504 An error was encountered while processing the specified path rename configuration file.
*/
/** SQL Failure codes indicating the database is broken/died (and thus kill off remaining connections).
Anything else will be taken as the *connection* (not the db) being broken.
*/
private static final ImmutableSet<String> sqlStateDBFailureCodes = ImmutableSet.of("08001", "08007");
/**
* Connection wrapper constructor
*
* @param url
* JDBC connection string
* @param username
* user to use
* @param password
* password for db
* @param pool
* pool handle.
* @throws SQLException
* on error
*/
public ConnectionHandle(String url, String username, String password,
BoneCP pool) throws SQLException {
this.pool = pool;
this.url = url;
this.connection = obtainInternalConnection();
this.doubleCloseCheck = pool.getConfig().isCloseConnectionWatch();
this.logStatementsEnabled = pool.getConfig().isLogStatementsEnabled();
int cacheSize = pool.getConfig().getStatementsCacheSize();
if (cacheSize > 0) {
this.preparedStatementCache = new StatementCache(cacheSize);
this.callableStatementCache = new StatementCache(cacheSize);
this.statementCachingEnabled = true;
}
if (pool.getConfig().getReleaseHelperThreads() > 0){
this.releaseHelperThreadsEnabled = true;
}
}
/** Obtains a database connection, retrying if necessary.
* @return A DB connection.
* @throws SQLException
*/
protected Connection obtainInternalConnection() throws SQLException {
boolean tryAgain = false;
Connection result = null;
int acquireRetryAttempts = this.pool.getConfig().getAcquireRetryAttempts();
int acquireRetryDelay = this.pool.getConfig().getAcquireRetryDelay();
AcquireFailConfig acquireConfig = new AcquireFailConfig();
acquireConfig.setAcquireRetryAttempts(new AtomicInteger(acquireRetryAttempts));
acquireConfig.setAcquireRetryDelay(acquireRetryDelay);
acquireConfig.setLogMessage("Failed to acquire connection");
this.connectionHook = this.pool.getConfig().getConnectionHook();
do{
try {
// keep track of this hook.
this.connection = this.pool.obtainRawInternalConnection();
tryAgain = false;
if (acquireRetryAttempts != this.pool.getConfig().getAcquireRetryAttempts()){
logger.info("Successfully re-established connection to DB");
}
// call the hook, if available.
if (this.connectionHook != null){
this.connectionHook.onAcquire(this);
}
sendInitSQL();
result = this.connection;
} catch (Throwable t) {
// call the hook, if available.
if (this.connectionHook != null){
tryAgain = this.connectionHook.onAcquireFail(t, acquireConfig);
} else {
logger.error("Failed to acquire connection. Sleeping for "+acquireRetryDelay+"ms. Attempts left: "+acquireRetryAttempts);
try {
Thread.sleep(acquireRetryDelay);
if (acquireRetryAttempts > 0){
tryAgain = (--acquireRetryAttempts) != 0;
}
} catch (InterruptedException e) {
tryAgain=false;
}
}
if (!tryAgain){
throw markPossiblyBroken(t);
}
}
} while (tryAgain);
return result;
}
/** Private constructor used solely for unit testing.
* @param connection
* @param preparedStatementCache
* @param callableStatementCache
* @param pool */
public ConnectionHandle(Connection connection, IStatementCache preparedStatementCache, IStatementCache callableStatementCache, BoneCP pool){
this.connection = connection;
this.preparedStatementCache = preparedStatementCache;
this.callableStatementCache = callableStatementCache;
this.pool = pool;
this.url=null;
int cacheSize = pool.getConfig().getStatementsCacheSize();
if (cacheSize > 0) {
this.statementCachingEnabled = true;
}
}
/** Sends any configured SQL init statement.
* @throws SQLException on error
*/
public void sendInitSQL() throws SQLException {
// fetch any configured setup sql.
String initSQL = this.pool.getConfig().getInitSQL();
if (initSQL != null){
Statement stmt = this.connection.createStatement();
ResultSet rs = stmt.executeQuery(initSQL);
// free up resources
if (rs != null){
rs.close();
}
stmt.close();
}
}
/**
* Given an exception, flag the connection (or database) as being potentially broken. If the exception is a data-specific exception,
* do nothing except throw it back to the application.
*
* @param t Throwable exception to process
* @return SQLException for further processing
*/
protected SQLException markPossiblyBroken(Throwable t) {
SQLException e;
if (t instanceof SQLException){
e=(SQLException) t;
} else {
e = new SQLException(t == null ? "Unknown error" : t.getMessage(), "08999");
e.initCause( t );
}
String state = e.getSQLState();
if (state == null){ // safety;
state = "Z";
}
if (sqlStateDBFailureCodes.contains(state) && this.pool != null){
logger.error("Database access problem. Killing off all remaining connections in the connection pool. SQL State = " + state);
this.pool.terminateAllConnections();
}
// SQL-92 says:
// Class values that begin with one of the <digit>s '5', '6', '7',
// '8', or '9' or one of the <simple Latin upper case letter>s 'I',
// 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
// 'W', 'X', 'Y', or 'Z' are reserved for implementation-specified
// conditions.
// char firstChar = state.charAt(0);
// if it's a communication exception, a mysql deadlock or an implementation-specific error code, flag this connection as being potentially broken.
// state == 40001 is mysql specific triggered when a deadlock is detected
char firstChar = state.charAt(0);
if (state.equals("40001") || state.startsWith("08") || (firstChar >= '5' && firstChar <='9') || (firstChar >='I' && firstChar <= 'Z')){
this.possiblyBroken = true;
}
// Notify anyone who's interested
if (this.possiblyBroken && (this.getConnectionHook() != null)){
this.possiblyBroken = this.getConnectionHook().onConnectionException(this, state, t);
}
return e;
}
public void clearWarnings() throws SQLException {
checkClosed();
try {
this.connection.clearWarnings();
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
}
/**
* Checks if the connection is (logically) closed and throws an exception if it is.
*
* @throws SQLException
* on error
*
*
*/
private void checkClosed() throws SQLException {
if (this.logicallyClosed) {
throw new SQLException("Connection is closed!");
}
}
/**
* Release the connection if called.
*
* @throws SQLException Never really thrown
*/
public void close() throws SQLException {
try {
if (!this.logicallyClosed) {
this.logicallyClosed = true;
this.threadUsingConnection = null;
this.pool.releaseConnection(this);
if (this.doubleCloseCheck){
this.doubleCloseException = this.pool.captureStackTrace(CLOSED_TWICE_EXCEPTION_MESSAGE);
}
} else {
if (this.doubleCloseCheck && this.doubleCloseException != null){
String currentLocation = this.pool.captureStackTrace("Last closed trace from thread ["+Thread.currentThread().getName()+"]:\n");
logger.error(String.format(LOG_ERROR_MESSAGE, this.doubleCloseException, currentLocation));
}
}
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
}
/**
* Close off the connection.
*
* @throws SQLException
*/
protected void internalClose() throws SQLException {
try {
clearStatementCaches(true);
if (this.connection != null){ // safety!
this.connection.close();
if (this.releaseHelperThreadsEnabled){
this.pool.getFinalizableRefs().remove(this.connection);
}
}
this.logicallyClosed = true;
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
}
public void commit() throws SQLException {
checkClosed();
try {
this.connection.commit();
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
}
// #ifdef JDK6
public Properties getClientInfo() throws SQLException {
Properties result = null;
checkClosed();
try {
result = this.connection.getClientInfo();
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
return result;
}
public String getClientInfo(String name) throws SQLException {
String result = null;
checkClosed();
try {
result = this.connection.getClientInfo(name);
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
return result;
}
public boolean isValid(int timeout) throws SQLException {
boolean result = false;
checkClosed();
try {
result = this.connection.isValid(timeout);
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
return result;
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return this.connection.isWrapperFor(iface);
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return this.connection.unwrap(iface);
}
@Override
public void setClientInfo(Properties properties) throws SQLClientInfoException {
this.connection.setClientInfo(properties);
}
@Override
public void setClientInfo(String name, String value) throws SQLClientInfoException {
this.connection.setClientInfo(name, value);
}
@Override
public Struct createStruct(String typeName, Object[] attributes)
throws SQLException {
Struct result = null;
checkClosed();
try {
result = this.connection.createStruct(typeName, attributes);
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
return result;
}
@Override
public Array createArrayOf(String typeName, Object[] elements)
throws SQLException {
Array result = null;
checkClosed();
try {
result = this.connection.createArrayOf(typeName, elements);
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
return result;
}
@Override
public Blob createBlob() throws SQLException {
Blob result = null;
checkClosed();
try {
result = this.connection.createBlob();
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
return result;
}
@Override
public Clob createClob() throws SQLException {
Clob result = null;
checkClosed();
try {
result = this.connection.createClob();
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
return result;
}
public NClob createNClob() throws SQLException {
NClob result = null;
checkClosed();
try {
result = this.connection.createNClob();
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
return result;
}
public SQLXML createSQLXML() throws SQLException {
SQLXML result = null;
checkClosed();
try {
result = this.connection.createSQLXML();
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
return result;
}
// #endif JDK6
public Statement createStatement() throws SQLException {
Statement result = null;
checkClosed();
try {
result =new StatementHandle(this.connection.createStatement(), this, this.logStatementsEnabled);
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
return result;
}
public Statement createStatement(int resultSetType, int resultSetConcurrency)
throws SQLException {
Statement result = null;
checkClosed();
try {
result = new StatementHandle(this.connection.createStatement(resultSetType, resultSetConcurrency), this, this.logStatementsEnabled);
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
return result;
}
public Statement createStatement(int resultSetType,
int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
Statement result = null;
checkClosed();
try {
result = new StatementHandle(this.connection.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability), this, this.logStatementsEnabled);
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
return result;
}
public boolean getAutoCommit() throws SQLException {
boolean result = false;
checkClosed();
try {
result = this.connection.getAutoCommit();
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
return result;
}
public String getCatalog() throws SQLException {
String result = null;
checkClosed();
try {
result = this.connection.getCatalog();
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
return result;
}
public int getHoldability() throws SQLException {
int result = 0;
checkClosed();
try {
result = this.connection.getHoldability();
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
return result;
}
public DatabaseMetaData getMetaData() throws SQLException {
DatabaseMetaData result = null;
checkClosed();
try {
result = this.connection.getMetaData();
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
return result;
}
public int getTransactionIsolation() throws SQLException {
int result = 0;
checkClosed();
try {
result = this.connection.getTransactionIsolation();
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
return result;
}
public Map<String, Class<?>> getTypeMap() throws SQLException {
Map<String, Class<?>> result = null;
checkClosed();
try {
result = this.connection.getTypeMap();
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
return result;
}
public SQLWarning getWarnings() throws SQLException {
SQLWarning result = null;
checkClosed();
try {
result = this.connection.getWarnings();
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
return result;
}
/** Returns true if this connection has been (logically) closed.
* @return the logicallyClosed setting.
*/
// @Override
public boolean isClosed() {
return this.logicallyClosed;
}
public boolean isReadOnly() throws SQLException {
boolean result = false;
checkClosed();
try {
result = this.connection.isReadOnly();
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
return result;
}
public String nativeSQL(String sql) throws SQLException {
String result = null;
checkClosed();
try {
result = this.connection.nativeSQL(sql);
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
return result;
}
public CallableStatement prepareCall(String sql) throws SQLException {
StatementHandle result = null;
String cacheKey = null;
checkClosed();
try {
if (this.statementCachingEnabled) {
cacheKey = sql;
result = this.callableStatementCache.get(cacheKey);
}
if (result == null){
result = new CallableStatementHandle(this.connection.prepareCall(sql),
sql, this, cacheKey, this.callableStatementCache);
}
result.setLogicallyOpen();
if (this.pool.closeConnectionWatch && this.statementCachingEnabled){ // debugging mode enabled?
result.setOpenStackTrace(this.pool.captureStackTrace(STATEMENT_NOT_CLOSED));
}
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
return (CallableStatement) result;
}
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
StatementHandle result = null;
String cacheKey = null;
checkClosed();
try {
if (this.statementCachingEnabled) {
cacheKey = this.callableStatementCache.calculateCacheKey(sql, resultSetType, resultSetConcurrency);
result = this.callableStatementCache.get(cacheKey);
}
if (result == null){
result = new CallableStatementHandle(this.connection.prepareCall(sql, resultSetType, resultSetConcurrency),
sql, this, cacheKey, this.callableStatementCache);
}
result.setLogicallyOpen();
if (this.pool.closeConnectionWatch && this.statementCachingEnabled){ // debugging mode enabled?
result.setOpenStackTrace(this.pool.captureStackTrace(STATEMENT_NOT_CLOSED));
}
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
return (CallableStatement) result;
}
public CallableStatement prepareCall(String sql, int resultSetType,
int resultSetConcurrency, int resultSetHoldability) throws SQLException {
StatementHandle result = null;
String cacheKey = null;
checkClosed();
try {
if (this.statementCachingEnabled) {
cacheKey = this.callableStatementCache.calculateCacheKey(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
result = this.callableStatementCache.get(cacheKey);
}
if (result == null){
result = new CallableStatementHandle(this.connection.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability),
sql, this, cacheKey, this.callableStatementCache);
}
result.setLogicallyOpen();
if (this.pool.closeConnectionWatch && this.statementCachingEnabled){ // debugging mode enabled?
result.setOpenStackTrace(this.pool.captureStackTrace(STATEMENT_NOT_CLOSED));
}
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
return (CallableStatement) result;
}
public PreparedStatement prepareStatement(String sql) throws SQLException {
StatementHandle result = null;
String cacheKey = null;
checkClosed();
try {
if (this.statementCachingEnabled) {
cacheKey = sql;
result = this.preparedStatementCache.get(cacheKey);
}
if (result == null){
result = new PreparedStatementHandle(this.connection.prepareStatement(sql), sql, this, cacheKey, this.preparedStatementCache);
}
result.setLogicallyOpen();
if (this.pool.closeConnectionWatch && this.statementCachingEnabled){ // debugging mode enabled?
result.setOpenStackTrace(this.pool.captureStackTrace(STATEMENT_NOT_CLOSED));
}
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
return (PreparedStatement) result;
}
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
StatementHandle result = null;
String cacheKey = null;
checkClosed();
try {
if (this.statementCachingEnabled) {
cacheKey = this.preparedStatementCache.calculateCacheKey(sql, autoGeneratedKeys);
result = this.preparedStatementCache.get(cacheKey);
}
if (result == null){
result = new PreparedStatementHandle(this.connection.prepareStatement(sql, autoGeneratedKeys), sql, this, cacheKey, this.preparedStatementCache);
}
result.setLogicallyOpen();
if (this.pool.closeConnectionWatch && this.statementCachingEnabled){ // debugging mode enabled?
result.setOpenStackTrace(this.pool.captureStackTrace(STATEMENT_NOT_CLOSED));
}
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
return (PreparedStatement) result;
}
public PreparedStatement prepareStatement(String sql, int[] columnIndexes)
throws SQLException {
StatementHandle result = null;
String cacheKey = null;
checkClosed();
try {
if (this.statementCachingEnabled) {
cacheKey = this.preparedStatementCache.calculateCacheKey(sql, columnIndexes);
result = this.preparedStatementCache.get(cacheKey);
}
if (result == null){
result = new PreparedStatementHandle(this.connection.prepareStatement(sql, columnIndexes),
sql, this, cacheKey, this.preparedStatementCache);
}
result.setLogicallyOpen();
if (this.pool.closeConnectionWatch && this.statementCachingEnabled){ // debugging mode enabled?
result.setOpenStackTrace(this.pool.captureStackTrace(STATEMENT_NOT_CLOSED));
}
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
return (PreparedStatement) result;
}
public PreparedStatement prepareStatement(String sql, String[] columnNames)
throws SQLException {
StatementHandle result = null;
String cacheKey = null;
checkClosed();
try {
if (this.statementCachingEnabled) {
cacheKey = this.preparedStatementCache.calculateCacheKey(sql, columnNames);
result = this.preparedStatementCache.get(cacheKey);
}
if (result == null){
result = new PreparedStatementHandle(this.connection.prepareStatement(sql, columnNames),
sql, this, cacheKey, this.preparedStatementCache);
}
result.setLogicallyOpen();
if (this.pool.closeConnectionWatch && this.statementCachingEnabled){ // debugging mode enabled?
result.setOpenStackTrace(this.pool.captureStackTrace(STATEMENT_NOT_CLOSED));
}
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
return (PreparedStatement) result;
}
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
StatementHandle result = null;
String cacheKey = null;
checkClosed();
try {
if (this.statementCachingEnabled) {
cacheKey = this.preparedStatementCache.calculateCacheKey(sql, resultSetType, resultSetConcurrency);
result = this.preparedStatementCache.get(cacheKey);
}
if (result == null){
result = new PreparedStatementHandle(this.connection.prepareStatement(sql, resultSetType, resultSetConcurrency),
sql, this, cacheKey, this.preparedStatementCache);
}
result.setLogicallyOpen();
if (this.pool.closeConnectionWatch && this.statementCachingEnabled){ // debugging mode enabled?
result.setOpenStackTrace(this.pool.captureStackTrace(STATEMENT_NOT_CLOSED));
}
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
return (PreparedStatement) result;
}
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
StatementHandle result = null;
String cacheKey = null;
checkClosed();
try {
if (this.statementCachingEnabled) {
cacheKey = this.preparedStatementCache.calculateCacheKey(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
result = this.preparedStatementCache.get(cacheKey);
}
if (result == null){
result = new PreparedStatementHandle(this.connection.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability),
sql, this, cacheKey, this.preparedStatementCache);
}
result.setLogicallyOpen();
if (this.pool.closeConnectionWatch && this.statementCachingEnabled){ // debugging mode enabled?
result.setOpenStackTrace(this.pool.captureStackTrace(STATEMENT_NOT_CLOSED));
}
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
return (PreparedStatement) result;
}
public void releaseSavepoint(Savepoint savepoint) throws SQLException {
checkClosed();
try {
this.connection.releaseSavepoint(savepoint);
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
}
public void rollback() throws SQLException {
checkClosed();
try {
this.connection.rollback();
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
}
public void rollback(Savepoint savepoint) throws SQLException {
checkClosed();
try {
this.connection.rollback(savepoint);
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
}
public void setAutoCommit(boolean autoCommit) throws SQLException {
checkClosed();
try {
this.connection.setAutoCommit(autoCommit);
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
}
public void setCatalog(String catalog) throws SQLException {
checkClosed();
try {
this.connection.setCatalog(catalog);
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
}
public void setHoldability(int holdability) throws SQLException {
checkClosed();
try {
this.connection.setHoldability(holdability);
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
}
public void setReadOnly(boolean readOnly) throws SQLException {
checkClosed();
try {
this.connection.setReadOnly(readOnly);
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
}
public Savepoint setSavepoint() throws SQLException {
checkClosed();
Savepoint result = null;
try {
result = this.connection.setSavepoint();
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
return result;
}
public Savepoint setSavepoint(String name) throws SQLException {
checkClosed();
Savepoint result = null;
try {
result = this.connection.setSavepoint(name);
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
return result;
}
public void setTransactionIsolation(int level) throws SQLException {
checkClosed();
try {
this.connection.setTransactionIsolation(level);
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
}
public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
checkClosed();
try {
this.connection.setTypeMap(map);
} catch (Throwable t) {
throw markPossiblyBroken(t);
}
}
/**
* @return the connectionLastUsed
*/
public long getConnectionLastUsed() {
return this.connectionLastUsed;
}
/**
* @param connectionLastUsed
* the connectionLastUsed to set
*/
protected void setConnectionLastUsed(long connectionLastUsed) {
this.connectionLastUsed = connectionLastUsed;
}
/**
* @return the connectionLastReset
*/
public long getConnectionLastReset() {
return this.connectionLastReset;
}
/**
* @param connectionLastReset
* the connectionLastReset to set
*/
protected void setConnectionLastReset(long connectionLastReset) {
this.connectionLastReset = connectionLastReset;
}
/**
* Gets true if connection has triggered an exception at some point.
*
* @return true if the connection has triggered an error
*/
public boolean isPossiblyBroken() {
return this.possiblyBroken;
}
/**
* Gets the partition this came from.
*
* @return the partition this came from
*/
public ConnectionPartition getOriginatingPartition() {
return this.originatingPartition;
}
/**
* Sets Originating partition
*
* @param originatingPartition
* to set
*/
protected void setOriginatingPartition(ConnectionPartition originatingPartition) {
this.originatingPartition = originatingPartition;
}
/**
* Renews this connection, i.e. Sets this connection to be logically open
* (although it was never really physically closed)
*/
protected void renewConnection() {
this.logicallyClosed = false;
this.threadUsingConnection = Thread.currentThread();
if (this.doubleCloseCheck){
this.doubleCloseException = null;
}
}
/** Clears out the statement handles.
* @param internalClose if true, close the inner statement handle too.
*/
protected void clearStatementCaches(boolean internalClose) {
if (this.statementCachingEnabled){ // safety
if (internalClose){
this.callableStatementCache.clear();
this.preparedStatementCache.clear();
} else {
if (this.pool.closeConnectionWatch){ // debugging enabled?
this.callableStatementCache.checkForProperClosure();
this.preparedStatementCache.checkForProperClosure();
}
}
}
}
/** Returns a debug handle as previously set by an application
* @return DebugHandle
*/
public Object getDebugHandle() {
return this.debugHandle;
}
/** Sets a debugHandle, an object that is not used by the connection pool at all but may be set by an application to track
* this particular connection handle for any purpose it deems fit.
* @param debugHandle any object.
*/
public void setDebugHandle(Object debugHandle) {
this.debugHandle = debugHandle;
}
/** Deprecated. Please use getInternalConnection() instead.
*
* @return the raw connection
*/
@Deprecated
public Connection getRawConnection() {
return getInternalConnection();
}
/** Returns the internal connection as obtained via the JDBC driver.
* @return the raw connection
*/
public Connection getInternalConnection() {
return this.connection;
}
/** Returns the configured connection hook object.
* @return the connectionHook that was set in the config
*/
public ConnectionHook getConnectionHook() {
return this.connectionHook;
}
/** Returns true if logging of statements is enabled
* @return logStatementsEnabled status
*/
public boolean isLogStatementsEnabled() {
return this.logStatementsEnabled;
}
/** Enable or disable logging of this connection.
* @param logStatementsEnabled true to enable logging, false to disable.
*/
public void setLogStatementsEnabled(boolean logStatementsEnabled) {
this.logStatementsEnabled = logStatementsEnabled;
}
/**
* @return the inReplayMode
*/
protected boolean isInReplayMode() {
return this.inReplayMode;
}
/**
* @param inReplayMode the inReplayMode to set
*/
protected void setInReplayMode(boolean inReplayMode) {
this.inReplayMode = inReplayMode;
}
/** Sends a test query to the underlying connection and return true if connection is alive.
* @return True if connection is valid, false otherwise.
*/
public boolean isConnectionAlive(){
return this.pool.isConnectionHandleAlive(this);
}
/** Sets the internal connection to use. Be careful how to use this method, normally you should never need it! This is here
* for odd use cases only!
* @param rawConnection to set
*/
public void setInternalConnection(Connection rawConnection) {
this.connection = rawConnection;
}
/** Returns a handle to the global pool from where this connection was obtained.
* @return BoneCP handle
*/
public BoneCP getPool() {
return this.pool;
}
/** Returns transaction history log
* @return replay list
*/
public List<ReplayLog> getReplayLog() {
return this.replayLog;
}
/** Sets the transaction history log
* @param replayLog to set.
*/
protected void setReplayLog(List<ReplayLog> replayLog) {
this.replayLog = replayLog;
}
/** This method will be intercepted by the proxy if it is enabled to return the internal target.
* @return the target.
*/
public Object getProxyTarget(){
try {
return Proxy.getInvocationHandler(this.connection).invoke(null, this.getClass().getMethod("getProxyTarget"), null);
} catch (Throwable t) {
throw new RuntimeException("BoneCP: Internal error - transaction replay log is not turned on?", t);
}
}
/** Returns the thread that is currently utilizing this connection.
* @return the threadUsingConnection
*/
public Thread getThreadUsingConnection() {
return this.threadUsingConnection;
}
@Override
public void setSchema(String schema) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public String getSchema() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public void abort(Executor executor) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setNetworkTimeout(Executor executor, int milliseconds)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public int getNetworkTimeout() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
} | 27.953942 | 187 | 0.722723 |
feea87f9baab5cbc19eeb1e80a3503b1ab630e1e | 2,791 | /*
* Copyright (c) 2012 Maciej Walkowiak
*
* 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 pl.maciejwalkowiak.plist.handler;
import pl.maciejwalkowiak.plist.PlistSerializerImpl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Wraps all defined handlers and provides simple interface to get handlers for objects.
* By default contains handlers for all basic types and {@link java.util.Map} and {@link java.util.Collection}
*
* @author Maciej Walkowiak
*/
public class HandlerWrapper {
private List<Handler> handlers = new ArrayList<Handler>();
public HandlerWrapper(PlistSerializerImpl plistSerializer) {
this.handlers.addAll(Arrays.asList(
new MapHandler(plistSerializer),
new BooleanHandler(),
new StringHandler(),
new IntegerHandler(),
new DoubleHandler(),
new DateHandler(),
new DataHandler(),
new CollectionHandler(plistSerializer)));
}
/**
* Adds handlers for object types not supported by default
*
* @param additionalHandlers collection of additional handlers
*/
public void addAdditionalHandlers(List<Handler> additionalHandlers) {
this.handlers.addAll(additionalHandlers);
}
public Handler getHandlerForObject(Object object) throws HandlerNotFoundException {
Handler result = null;
for (Handler handler : handlers) {
if (handler.supports(object)) {
result = handler;
break;
}
}
if (result == null) {
throw new HandlerNotFoundException("handler for object = " + object + " not found");
}
return result;
}
public boolean isSupported(Object object) {
boolean result = false;
for (Handler handler : handlers) {
if (handler.supports(object)) {
result = true;
break;
}
}
return result;
}
}
| 30.010753 | 110 | 0.736295 |
f2a8ce8f9f0e1a90665b094782af15d582e03ee7 | 1,425 | package src.SudokuSolver;
/**
* @author mingqiao
* @Date 2019/8/18
*/
public class SudokuSolver {
public void solveSudoku(char[][] board) {
if (board == null || board.length == 0) { return; }
dfs(board);
}
/**
* 类似八皇后问题,枚举每个节的值看下全图填充方案是否合理,注意回溯时需要根据回溯结果将节点值进行更改
* @param board
* @return
*/
public boolean dfs(char[][] board) {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] == '.') {
for (char c = '1'; c <= '9'; c++) {
if (valid(board, i, j, c)) {
board[i][j] = c;
if (dfs(board)) {
board[i][j] = c;
return true;
} else {
board[i][j] = '.';
}
}
}
return false;
}
}
}
return true;
}
//判定该情况下棋盘是否合理
public boolean valid(char[][] board, int row, int col, char c) {
for (int i = 0; i < 9; i++) {
if (board[row][i] == c || board[i][col] == c || board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c) {
return false;
}
}
return true;
}
}
| 27.941176 | 119 | 0.352281 |
74c6653682dbca766cd5df170d6174eca93d35f8 | 1,693 | package org.utn.edu.ar.model.domain;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.utn.edu.ar.model.MatchService;
import org.utn.edu.ar.model.SportService;
import org.utn.edu.ar.model.exceptions.match.PlayerAlreadyConfirmedException;
import org.utn.edu.ar.model.exceptions.player.PlayerNotFoundException;
import org.utn.edu.ar.model.exceptions.sport.SportNameAlreadyExistException;
import org.utn.edu.ar.model.exceptions.sport.SportNotFoundException;
import org.utn.edu.ar.model.request.MatchRequest;
import org.utn.edu.ar.util.Coordinates;
import java.util.Date;
public class MatchTest {
// private Match testMatch = null;
//
// private Player p1 = new Player(1, "Leo");
// private Player p2 = new Player(2, "Tom");
// private Player p3 = new Player(3, "Nico");
//
// @Before
// public void setUp() throws SportNameAlreadyExistException, SportNotFoundException, PlayerNotFoundException {
// Sport created = SportService.getInstance().createSport("sototo");
// testMatch = new Match(1, 1, 2, new Date(), null, new Coordinates(1.0D, 1.0D)) ;
// }
//
// @Test
// public void addTest() throws PlayerAlreadyConfirmedException {
// testMatch.addPlayer(p1);
// testMatch.addPlayer(p2);
// testMatch.addPlayer(p3);
// Assert.assertEquals(2, testMatch.getStarters().size());
// Assert.assertEquals(1, testMatch.getAlternates().size());
// }
// @Test(expected=PlayerAlreadyConfirmedException.class)
// public void failToAddTest() throws PlayerAlreadyConfirmedException {
// testMatch.addPlayer(p1);
// testMatch.addPlayer(p1);
// }
}
| 36.021277 | 114 | 0.714708 |
1ce1fde399949d1d6a6755ecef5d8241415c1a16 | 2,983 | /*
* Copyright (C) 2014 The Android Open Source Project
*
* 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.android.deskclock.timer;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.SharedPreferences;
import android.support.v4.view.PagerAdapter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class TimerFragmentAdapter extends FragmentStatePagerAdapter2 {
private final ArrayList<TimerObj> mTimerList = new ArrayList<TimerObj>();
private final SharedPreferences mSharedPrefs;
public TimerFragmentAdapter(FragmentManager fm, SharedPreferences sharedPreferences) {
super(fm);
mSharedPrefs = sharedPreferences;
}
@Override
public int getItemPosition(Object object) {
// Force return NONE so that the adapter always assumes the item position has changed
return PagerAdapter.POSITION_NONE;
}
@Override
public int getCount() {
return mTimerList.size();
}
@Override
public Fragment getItem(int position) {
return TimerItemFragment.newInstance(mTimerList.get(position));
}
public void addTimer(TimerObj timer) {
// Newly created timer should always show on the top of the list
mTimerList.add(0, timer);
notifyDataSetChanged();
}
public TimerObj getTimerAt(int position) {
return mTimerList.get(position);
}
public void saveTimersToSharedPrefs() {
TimerObj.putTimersInSharedPrefs(mSharedPrefs, mTimerList);
}
public void populateTimersFromPref() {
mTimerList.clear();
TimerObj.getTimersFromSharedPrefs(mSharedPrefs, mTimerList);
Collections.sort(mTimerList, new Comparator<TimerObj>() {
@Override
public int compare(TimerObj o1, TimerObj o2) {
return (o2.mTimerId < o1.mTimerId) ? -1 : 1;
}
});
notifyDataSetChanged();
}
public void deleteTimer(int id) {
for (int i = 0; i < mTimerList.size(); i++) {
TimerObj timer = mTimerList.get(i);
if (timer.mTimerId == id) {
if (timer.mView != null) {
timer.mView.stop();
}
timer.deleteFromSharedPref(mSharedPrefs);
mTimerList.remove(i);
break;
}
}
notifyDataSetChanged();
return;
}
}
| 30.438776 | 93 | 0.659068 |
1420fa3379f2f2c18998c7543b4777dd40c756df | 45,275 | /*
* 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.netbeans.modules.debugger.jpda.ui.models;
import com.sun.jdi.AbsentInformationException;
import java.awt.Color;
import java.awt.datatransfer.Transferable;
import java.beans.Customizer;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.prefs.PreferenceChangeEvent;
import java.util.prefs.PreferenceChangeListener;
import java.util.prefs.Preferences;
import org.netbeans.api.debugger.Breakpoint;
import org.netbeans.api.debugger.Session;
import org.netbeans.api.debugger.jpda.CallStackFrame;
import org.netbeans.api.debugger.jpda.ClassLoadUnloadBreakpoint;
import org.netbeans.api.debugger.jpda.DeadlockDetector;
import org.netbeans.api.debugger.jpda.DeadlockDetector.Deadlock;
import org.netbeans.api.debugger.jpda.ExceptionBreakpoint;
import org.netbeans.api.debugger.jpda.FieldBreakpoint;
import org.netbeans.api.debugger.jpda.InvalidExpressionException;
import org.netbeans.api.debugger.jpda.JPDABreakpoint;
import org.netbeans.api.debugger.jpda.JPDADebugger;
import org.netbeans.api.debugger.jpda.JPDAThread;
import org.netbeans.api.debugger.jpda.JPDAThreadGroup;
import org.netbeans.api.debugger.jpda.LineBreakpoint;
import org.netbeans.api.debugger.jpda.MethodBreakpoint;
import org.netbeans.api.debugger.jpda.ObjectVariable;
import org.netbeans.api.debugger.jpda.ThreadBreakpoint;
import org.netbeans.modules.debugger.jpda.models.JPDAThreadImpl;
import org.netbeans.modules.debugger.jpda.ui.SourcePath;
import org.netbeans.modules.debugger.jpda.ui.debugging.DebuggingViewSupportImpl;
import org.netbeans.modules.debugger.jpda.ui.debugging.JPDADVThread;
import org.netbeans.modules.debugger.jpda.ui.debugging.JPDADVThreadGroup;
import org.netbeans.spi.debugger.ContextProvider;
import org.netbeans.spi.debugger.DebuggerServiceRegistration;
import org.netbeans.spi.debugger.ui.DebuggingView;
import org.netbeans.spi.viewmodel.ExtendedNodeModel;
import org.netbeans.spi.viewmodel.ModelEvent;
import org.netbeans.spi.viewmodel.ModelListener;
import org.netbeans.spi.viewmodel.TreeModel;
import org.netbeans.spi.viewmodel.UnknownTypeException;
import org.openide.ErrorManager;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.URLMapper;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle;
import org.openide.util.NbPreferences;
import org.openide.util.RequestProcessor;
import org.openide.util.WeakListeners;
import org.openide.util.datatransfer.PasteType;
/**
*
* @author martin
*/
@DebuggerServiceRegistration(path="netbeans-JPDASession/DebuggingView",
types=ExtendedNodeModel.class,
position=400)
public class DebuggingNodeModel implements ExtendedNodeModel {
public static final String CURRENT_THREAD =
"org/netbeans/modules/debugger/resources/threadsView/CurrentThread"; // NOI18N
public static final String RUNNING_THREAD =
"org/netbeans/modules/debugger/resources/threadsView/RunningThread"; // NOI18N
public static final String SUSPENDED_THREAD =
"org/netbeans/modules/debugger/resources/threadsView/SuspendedThread"; // NOI18N
public static final String CALL_STACK =
"org/netbeans/modules/debugger/resources/callStackView/NonCurrentFrame";
public static final String CURRENT_CALL_STACK =
"org/netbeans/modules/debugger/resources/callStackView/CurrentFrame";
public static final String THREAD_AT_BRKT_LINE =
"org/netbeans/modules/debugger/resources/threadsView/thread_at_line_bpkt_16.png";
public static final String THREAD_AT_BRKT_NONLINE =
"org/netbeans/modules/debugger/resources/threadsView/thread_at_non_line_bpkt_16.png";
public static final String THREAD_AT_BRKT_CONDITIONAL =
"org/netbeans/modules/debugger/resources/threadsView/thread_at_conditional_bpkt_16.png";
public static final String THREAD_SUSPENDED =
"org/netbeans/modules/debugger/resources/threadsView/thread_suspended_16.png";
public static final String THREAD_RUNNING =
"org/netbeans/modules/debugger/resources/threadsView/thread_running_16.png";
public static final String THREAD_ZOMBIE =
"org/netbeans/modules/debugger/resources/threadsView/thread_zombie_16.png";
public static final String CALL_STACK2 =
"org/netbeans/modules/debugger/resources/threadsView/call_stack_16.png";
public static final String THREAD_GROUP_MIXED =
"org/netbeans/modules/debugger/resources/debuggingView/thread_group_mixed_16.png";
public static final String THREAD_GROUP_SUSPENDED =
"org/netbeans/modules/debugger/resources/debuggingView/thread_group_suspended_16.png";
public static final String THREAD_GROUP_RESUMED =
"org/netbeans/modules/debugger/resources/debuggingView/thread_group_running_16.png";
public static final String SHOW_PACKAGE_NAMES = "show.packageNames";
private final JPDADebugger debugger;
private final DebuggingViewSupportImpl dvSupport;
private final List<ModelListener> listeners = new ArrayList<ModelListener>();
private final Map<JPDAThread, ThreadStateUpdater> threadStateUpdaters = new WeakHashMap<JPDAThread, ThreadStateUpdater>();
private final CurrentThreadListener currentThreadListener;
private final DeadlockDetector deadlockDetector;
private final Set nodesInDeadlock = new HashSet();
private static final Map<JPDADebugger, Set> nodesInDeadlockByDebugger = new WeakHashMap<JPDADebugger, Set>();
private final Preferences preferences = DebuggingViewSupportImpl.getFilterPreferences();
private final PreferenceChangeListener prefListener;
private final RequestProcessor rp;
private final SourcePath sourcePath;
private final Session session;
private final PropertyChangeListener sessionLanguageListener;
public DebuggingNodeModel(ContextProvider lookupProvider) {
debugger = lookupProvider.lookupFirst(null, JPDADebugger.class);
dvSupport = (DebuggingViewSupportImpl) lookupProvider.lookupFirst(null, DebuggingView.DVSupport.class);
currentThreadListener = new CurrentThreadListener();
debugger.addPropertyChangeListener(WeakListeners.propertyChange(currentThreadListener, debugger));
deadlockDetector = debugger.getThreadsCollector().getDeadlockDetector();
deadlockDetector.addPropertyChangeListener(new DeadlockListener());
rp = lookupProvider.lookupFirst(null, RequestProcessor.class);
sourcePath = lookupProvider.lookupFirst(null, SourcePath.class);
session = lookupProvider.lookupFirst(null, Session.class);
sessionLanguageListener = new SessionLanguageListener();
session.addPropertyChangeListener(Session.PROP_CURRENT_LANGUAGE,
WeakListeners.propertyChange(sessionLanguageListener,
new ListenerDetaching(Session.PROP_CURRENT_LANGUAGE, session)));
prefListener = new DebuggingPreferenceChangeListener();
preferences.addPreferenceChangeListener(WeakListeners.create(PreferenceChangeListener.class, prefListener, preferences));
}
public static Set getNodesInDeadlock(JPDADebugger debugger) {
synchronized (nodesInDeadlockByDebugger) {
return nodesInDeadlockByDebugger.get(debugger);
}
}
public String getDisplayName(Object node) throws UnknownTypeException {
if (TreeModel.ROOT.equals(node)) {
return ""; // NOI18N
}
boolean showPackageNames = preferences.getBoolean(SHOW_PACKAGE_NAMES, false);
Color c = null;
synchronized (nodesInDeadlock) {
if (nodesInDeadlock.contains(node)) {
c = Color.RED;
}
}
if (node instanceof JPDADVThread) {
JPDAThread t = ((JPDADVThread) node).getKey();
watch(t);
JPDAThread currentThread = debugger.getCurrentThread();
if (t == currentThread && (!DebuggingTreeExpansionModelFilter.isExpanded(debugger, node) ||
!t.isSuspended())) {
return BoldVariablesTableModelFilter.toHTML(
getDisplayName(t, showPackageNames, this),
true, false, c);
} else {
if (c != null) {
return BoldVariablesTableModelFilter.toHTML(
getDisplayName(t, showPackageNames, this),
false, false, c);
} else {
return getDisplayName(t, showPackageNames, this);
}
}
}
if (node instanceof JPDADVThreadGroup) {
JPDAThreadGroup group = ((JPDADVThreadGroup) node).getKey();
if (isCurrent(group) && !DebuggingTreeExpansionModelFilter.isExpanded(debugger, node)) {
return BoldVariablesTableModelFilter.toHTML (
group.getName (),
true,
false,
null
);
} else {
return group.getName ();
}
}
if (node instanceof CallStackFrame) {
CallStackFrame f = (CallStackFrame) node;
boolean isCurrent;
try {
isCurrent = (Boolean) f.getClass().getMethod("isCurrent").invoke(f);
} catch (Exception ex) {
Exceptions.printStackTrace(ex);
isCurrent = false;
}
// Do not call JDI in AWT
//CallStackFrame currentFrame = debugger.getCurrentCallStackFrame();
//if (f.equals(currentFrame)) {
String frameDescr;
synchronized (frameDescriptionsByFrame) {
frameDescr = frameDescriptionsByFrame.get(f);
if (frameDescr == null) {
loadFrameDescription(f, showPackageNames);
return BoldVariablesTableModelFilter.toHTML(
NbBundle.getMessage(DebuggingNodeModel.class, "CTL_Frame_Loading"),
false,
false,
Color.LIGHT_GRAY);
}
}
if (isCurrent) {
return BoldVariablesTableModelFilter.toHTML(
frameDescr,
true, false, c);
} else {
if (c != null) {
return BoldVariablesTableModelFilter.toHTML(
frameDescr,
false, false, c);
} else {
return frameDescr;
}
}
}
throw new UnknownTypeException(node.toString());
}
/**
* Map of threads and their frame descriptions.
* These are loaded lazily, since we must not load call stack frames in AWT EQ.
*/
private static final Map<JPDAThread, String> frameDescriptionsByThread = new WeakHashMap<JPDAThread, String>();
private final Map<CallStackFrame, String> frameDescriptionsByFrame = new WeakHashMap<CallStackFrame, String>();
private static final Map<CallStackFrame, FrameUIInfo> framePathClassURL = new WeakHashMap<CallStackFrame, FrameUIInfo>();
public static String getDisplayName(JPDAThread t, boolean showPackageNames) throws UnknownTypeException {
return getDisplayName(t, showPackageNames, null);
}
private static String getDisplayName(JPDAThread t, boolean showPackageNames, DebuggingNodeModel model) throws UnknownTypeException {
String name = t.getName();
JPDABreakpoint breakpoint = t.getCurrentBreakpoint();
if (((JPDAThreadImpl) t).isMethodInvoking()) {
return NbBundle.getMessage(DebuggingNodeModel.class, "CTL_Thread_Invoking_Method", name);
}
if (breakpoint != null) {
return getThreadAtBreakpointDisplayName(name, breakpoint);
}
if (t.isSuspended()) {
String frame;
synchronized (frameDescriptionsByThread) {
frame = frameDescriptionsByThread.get(t);
if (t.isSuspended()) {
// Load it in any case to assure refreshes
loadFrameDescription(frame, t, showPackageNames, model);
}
}
if (frame != null) {
return NbBundle.getMessage(DebuggingNodeModel.class, "CTL_Thread_State_Suspended_At", name, frame);
} else {
return NbBundle.getMessage(DebuggingNodeModel.class, "CTL_Thread_State_Suspended", name);
}
} else if (JPDAThread.STATE_ZOMBIE == t.getState()) {
// Died, but is still around
return NbBundle.getMessage(DebuggingNodeModel.class, "CTL_Thread_State_Zombie", name);
} else {
return NbBundle.getMessage(DebuggingNodeModel.class, "CTL_Thread_State_Running", name);
}
/*
int i = t.getState ();
switch (i) {
case JPDAThread.STATE_UNKNOWN:
return NbBundle.getMessage(DebuggingNodeModel.class, "CTL_Thread_State_Unknown", name);
case JPDAThread.STATE_MONITOR:
if (frame != null) {
return NbBundle.getMessage(DebuggingNodeModel.class, "CTL_Thread_State_Monitor_At", name, frame);
} else {
return NbBundle.getMessage(DebuggingNodeModel.class, "CTL_Thread_State_Monitor", name);
}
case JPDAThread.STATE_NOT_STARTED:
return NbBundle.getMessage(DebuggingNodeModel.class, "CTL_Thread_State_NotStarted", name);
case JPDAThread.STATE_RUNNING:
if (frame != null) {
return NbBundle.getMessage(DebuggingNodeModel.class, "CTL_Thread_State_Running_At", name, frame);
} else {
return NbBundle.getMessage(DebuggingNodeModel.class, "CTL_Thread_State_Running", name);
}
case JPDAThread.STATE_SLEEPING:
if (frame != null) {
return NbBundle.getMessage(DebuggingNodeModel.class, "CTL_Thread_State_Sleeping_At", name, frame);
} else {
return NbBundle.getMessage(DebuggingNodeModel.class, "CTL_Thread_State_Sleeping", name);
}
case JPDAThread.STATE_WAIT:
if (frame != null) {
return NbBundle.getMessage(DebuggingNodeModel.class, "CTL_Thread_State_Waiting_At", name, frame);
} else {
return NbBundle.getMessage(DebuggingNodeModel.class, "CTL_Thread_State_Waiting", name);
}
case JPDAThread.STATE_ZOMBIE:
return NbBundle.getMessage(DebuggingNodeModel.class, "CTL_Thread_State_Zombie", name);
default:
Exceptions.printStackTrace(new IllegalStateException("Unexpected thread state: "+i+" of "+t));
return NbBundle.getMessage(DebuggingNodeModel.class, "CTL_Thread_State_Unknown", name);
}
*/
}
private static String getThreadAtBreakpointDisplayName(String threadName, JPDABreakpoint breakpoint) {
if (breakpoint instanceof LineBreakpoint) {
LineBreakpoint lb = (LineBreakpoint) breakpoint;
String fileName = null;
String urlStr = lb.getURL();
if (urlStr.isEmpty()) {
fileName = lb.getPreferredClassName();
if (fileName != null) {
int i = fileName.lastIndexOf('.');
if (i > 0) {
fileName = fileName.substring(i+1);
}
}
} else {
try {
FileObject fo = URLMapper.findFileObject(new URL(urlStr));
if (fo != null) {
fileName = fo.getNameExt();
}
} catch (MalformedURLException ex) {
ErrorManager.getDefault().notify(ex);
}
}
if (fileName == null) fileName = lb.getURL();
return NbBundle.getMessage(DebuggingNodeModel.class, "CTL_Thread_At_LineBreakpoint",
threadName, fileName, lb.getLineNumber());
}
if (breakpoint instanceof MethodBreakpoint) {
MethodBreakpoint mb = (MethodBreakpoint) breakpoint;
String classFilters = java.util.Arrays.asList(mb.getClassFilters()).toString();
if (mb.getMethodSignature() == null) {
return NbBundle.getMessage(DebuggingNodeModel.class, "CTL_Thread_At_MethodBreakpoint",
threadName, classFilters, mb.getMethodName());
} else {
return NbBundle.getMessage(DebuggingNodeModel.class, "CTL_Thread_At_MethodBreakpointSig",
new Object[] { threadName, classFilters, mb.getMethodName(), mb.getMethodSignature() });
}
}
if (breakpoint instanceof ExceptionBreakpoint) {
ExceptionBreakpoint eb = (ExceptionBreakpoint) breakpoint;
return NbBundle.getMessage(DebuggingNodeModel.class, "CTL_Thread_At_ExceptionBreakpoint",
threadName, eb.getExceptionClassName());
}
if (breakpoint instanceof FieldBreakpoint) {
FieldBreakpoint fb = (FieldBreakpoint) breakpoint;
return NbBundle.getMessage(DebuggingNodeModel.class, "CTL_Thread_At_FieldBreakpoint",
threadName, fb.getClassName(), fb.getFieldName());
}
if (breakpoint instanceof ThreadBreakpoint) {
//ThreadBreakpoint tb = (ThreadBreakpoint) breakpoint;
return NbBundle.getMessage(DebuggingNodeModel.class, "CTL_Thread_At_ThreadBreakpoint",
threadName);
}
if (breakpoint instanceof ClassLoadUnloadBreakpoint) {
ClassLoadUnloadBreakpoint cb = (ClassLoadUnloadBreakpoint) breakpoint;
String classFilters = java.util.Arrays.asList(cb.getClassFilters()).toString();
return NbBundle.getMessage(DebuggingNodeModel.class, "CTL_Thread_At_ClassBreakpoint",
threadName, classFilters);
}
return NbBundle.getMessage(DebuggingNodeModel.class, "CTL_Thread_At_Breakpoint", threadName, breakpoint.toString());
}
private static void loadFrameDescription(final String oldFrame,
final JPDAThread t,
final boolean showPackageNames,
final DebuggingNodeModel model) {
final Session s;
try {
JPDADebugger debugger = (JPDADebugger) t.getClass().getMethod("getDebugger").invoke(t);
s = (Session) debugger.getClass().getMethod("getSession").invoke(debugger);
} catch (Exception e) {
Exceptions.printStackTrace(e);
return ;
}
RequestProcessor rp;
if (model != null && model.rp != null) {
rp = model.rp;
} else {
rp = s.lookupFirst(null, RequestProcessor.class);
}
if (rp == null) {
// Debugger is finishing
return ;
}
rp.post(new Runnable() {
public void run() {
String frame = null;
t.getReadAccessLock().lock();
try {
if (t.isSuspended () && (t.getStackDepth () > 0)) {
try {
CallStackFrame[] sf = t.getCallStack (0, 1);
if (sf.length > 0) {
frame = CallStackNodeModel.getCSFName (s, sf[0], showPackageNames);
}
} catch (AbsentInformationException e) {
}
}
} finally {
t.getReadAccessLock().unlock();
}
if (oldFrame == null && frame != null || oldFrame != null && !oldFrame.equals(frame)) {
synchronized (frameDescriptionsByThread) {
frameDescriptionsByThread.put(t, frame);
}
if (model != null) {
model.fireDisplayNameChanged(t);
}
}
}
});
}
private void loadFrameDescription(final CallStackFrame f, final boolean showPackageNames) {
rp.post(new Runnable() {
@Override
public void run() {
String frameDescr = CallStackNodeModel.getCSFName(session, f, showPackageNames);
synchronized (frameDescriptionsByFrame) {
frameDescriptionsByFrame.put(f, frameDescr);
}
FrameUIInfo frameInfo = new FrameUIInfo();
String language = session.getCurrentLanguage();
try {
frameInfo.sourcePath = f.getSourcePath(language);
} catch (AbsentInformationException ex) {
}
frameInfo.className = f.getClassName();
frameInfo.url = sourcePath.getURL(f, language);
frameInfo.language = language;
if (frameInfo.url == null) {
// URL is not known for this language. Try other languages...
List<String> supportedLanguages = f.getAvailableStrata();
String otherLanguage = null;
String otherURL = null;
for (String ol : supportedLanguages) {
if (ol.equals(language)) {
continue;
}
otherURL = sourcePath.getURL(f, ol);
if (otherURL != null) {
otherLanguage = ol;
break;
}
}
if (otherURL != null) {
frameInfo.url = otherURL;
frameInfo.language = otherLanguage;
}
}
synchronized (framePathClassURL) {
framePathClassURL.put(f, frameInfo);
}
fireDisplayNameChanged(f);
}
});
}
static String getCachedFramePath(CallStackFrame f) {
synchronized (framePathClassURL) {
FrameUIInfo frameInfo = framePathClassURL.get(f);
if (frameInfo != null) {
return frameInfo.sourcePath;
}
}
return null;
}
static String getCachedFrameClass(CallStackFrame f) {
synchronized (framePathClassURL) {
FrameUIInfo frameInfo = framePathClassURL.get(f);
if (frameInfo != null) {
return frameInfo.className;
}
}
return null;
}
static String getCachedFrameURL(CallStackFrame f) {
synchronized (framePathClassURL) {
FrameUIInfo frameInfo = framePathClassURL.get(f);
if (frameInfo != null) {
return frameInfo.url;
}
}
return null;
}
static String getCachedFrameURLLanguage(CallStackFrame f) {
synchronized (framePathClassURL) {
FrameUIInfo frameInfo = framePathClassURL.get(f);
if (frameInfo != null) {
return frameInfo.language;
}
}
return null;
}
public static String getIconBase(JPDAThread thread) {
Breakpoint b = thread.getCurrentBreakpoint();
if (b != null) {
if (b instanceof LineBreakpoint) {
String condition = ((LineBreakpoint) b).getCondition();
if (condition != null && condition.length() > 0) {
return THREAD_AT_BRKT_CONDITIONAL;
} else {
return THREAD_AT_BRKT_LINE;
}
} else {
return THREAD_AT_BRKT_NONLINE;
}
}
if (thread.isSuspended()) {
return THREAD_SUSPENDED;
} else if (JPDAThread.STATE_ZOMBIE == thread.getState()) {
return THREAD_ZOMBIE;
} else {
return THREAD_RUNNING;
}
}
@Override
public String getIconBase(Object node) throws UnknownTypeException {
if (node instanceof CallStackFrame) {
CallStackFrame ccsf = debugger.getCurrentCallStackFrame ();
if ((ccsf != null) && (ccsf.equals (node))) {
return CURRENT_CALL_STACK;
}
return CALL_STACK;
}
if (node instanceof JPDADVThread) {
JPDADVThread dvt = (JPDADVThread) node;
if (dvt.getKey() == debugger.getCurrentThread ()) {
return CURRENT_THREAD;
}
return dvt.isSuspended () ? SUSPENDED_THREAD : RUNNING_THREAD;
}
if (node == TreeModel.ROOT) {
return CALL_STACK; // will not be displayed
}
throw new UnknownTypeException (node);
}
@Override
public String getIconBaseWithExtension(Object node) throws UnknownTypeException {
if (node instanceof JPDADVThread) {
return getIconBase(((JPDADVThread)node).getKey());
}
if (node instanceof CallStackFrame) {
return CALL_STACK2;
}
if (node instanceof JPDADVThreadGroup) {
boolean[] flags = new boolean[] {false, false};
computeGroupStatus(((JPDADVThreadGroup) node).getKey(), flags);
if (flags[0]) {
// at least one thread suspended
if (flags[1]) {
// mixed thread group
return THREAD_GROUP_MIXED;
} else {
// only suspended threads
return THREAD_GROUP_SUSPENDED;
}
} else {
return THREAD_GROUP_RESUMED;
}
}
return getIconBase(node) + ".gif"; // NOI18N
}
@Override
public String getShortDescription(Object node) throws UnknownTypeException {
if (node instanceof JPDADVThread) {
JPDAThread t = ((JPDADVThread) node).getKey();
int i = t.getState ();
String s = "";
switch (i) {
case JPDAThread.STATE_UNKNOWN:
s = NbBundle.getBundle (DebuggingNodeModel.class).getString
("CTL_ThreadsModel_State_Unknown");
break;
case JPDAThread.STATE_MONITOR:
s = "";
ObjectVariable ov = t.getContendedMonitor ();
if (ov == null)
s = NbBundle.getBundle (ThreadsNodeModel.class).
getString ("CTL_ThreadsModel_State_Monitor");
else
try {
s = java.text.MessageFormat.
format (
NbBundle.getBundle (ThreadsNodeModel.class).
getString (
"CTL_ThreadsModel_State_ConcreteMonitor"),
new Object [] { ov.getToStringValue () });
} catch (InvalidExpressionException ex) {
s = ex.getLocalizedMessage ();
}
break;
case JPDAThread.STATE_NOT_STARTED:
s = NbBundle.getBundle (DebuggingNodeModel.class).getString
("CTL_ThreadsModel_State_NotStarted");
break;
case JPDAThread.STATE_RUNNING:
s = NbBundle.getBundle (DebuggingNodeModel.class).getString
("CTL_ThreadsModel_State_Running");
break;
case JPDAThread.STATE_SLEEPING:
s = NbBundle.getBundle (DebuggingNodeModel.class).getString
("CTL_ThreadsModel_State_Sleeping");
break;
case JPDAThread.STATE_WAIT:
ov = t.getContendedMonitor ();
if (ov == null)
s = NbBundle.getBundle (DebuggingNodeModel.class).
getString ("CTL_ThreadsModel_State_Waiting");
else
try {
s = java.text.MessageFormat.format
(NbBundle.getBundle (DebuggingNodeModel.class).
getString ("CTL_ThreadsModel_State_WaitingOn"),
new Object [] { ov.getToStringValue () });
} catch (InvalidExpressionException ex) {
s = ex.getLocalizedMessage ();
}
break;
case JPDAThread.STATE_ZOMBIE:
s = NbBundle.getBundle (DebuggingNodeModel.class).getString
("CTL_ThreadsModel_State_Zombie");
break;
}
String msg;
if (t.isSuspended()) {
msg = NbBundle.getMessage(DebuggingNodeModel.class,
"CTL_ThreadsModel_Suspended_Thread_Desc");
} else {
msg = NbBundle.getMessage(DebuggingNodeModel.class,
"CTL_ThreadsModel_Resumed_Thread_Desc");
}
if (s != null && s.length() > 0) {
msg = "<html>" + msg + "<br>" + NbBundle.getMessage(DebuggingNodeModel.class,
"CTL_ThreadsModel_Thread_State_Desc", s) + "</html>";
}
return msg;
}
if (node instanceof CallStackFrame) {
CallStackFrame sf = (CallStackFrame) node;
if (((JPDAThreadImpl) sf.getThread()).isMethodInvoking()) {
return "";
}
return CallStackNodeModel.getCSFToolTipText(session, sf);
}
if (node instanceof JPDAThreadGroup) {
return ((JPDAThreadGroup) node).getName ();
}
if (node == TreeModel.ROOT) {
return ""; // NOI18N
}
throw new UnknownTypeException(node.toString());
}
public void addModelListener(ModelListener l) {
synchronized (listeners) {
listeners.add(l);
}
}
public void removeModelListener(ModelListener l) {
synchronized (listeners) {
listeners.remove(l);
}
}
public boolean canCopy(Object node) throws UnknownTypeException {
return false;
}
public boolean canCut(Object node) throws UnknownTypeException {
return false;
}
public boolean canRename(Object node) throws UnknownTypeException {
return false;
}
public void setName(Object node, String name) throws UnknownTypeException {
throw new UnsupportedOperationException("Not supported yet.");
}
public Transferable clipboardCopy(Object node) throws IOException, UnknownTypeException {
throw new UnsupportedOperationException("Not supported yet.");
}
public Transferable clipboardCut(Object node) throws IOException, UnknownTypeException {
throw new UnsupportedOperationException("Not supported yet.");
}
public PasteType[] getPasteTypes(Object node, Transferable t) throws UnknownTypeException {
return null;
}
private void fireNodeChanged (Object node) {
if (node instanceof JPDAThread) {
node = dvSupport.get((JPDAThread) node);
} else if (node instanceof JPDAThreadGroup) {
node = dvSupport.get((JPDAThreadGroup) node);
}
List<ModelListener> ls;
synchronized (listeners) {
ls = new ArrayList<ModelListener>(listeners);
}
ModelEvent event;
if (node instanceof JPDAThread/* && DebuggingTreeModel.isMethodInvoking((JPDAThread) node)*/) {
event = new ModelEvent.NodeChanged(this, node,
ModelEvent.NodeChanged.DISPLAY_NAME_MASK |
ModelEvent.NodeChanged.ICON_MASK |
ModelEvent.NodeChanged.SHORT_DESCRIPTION_MASK);
} else {
event = new ModelEvent.NodeChanged(this, node,
ModelEvent.NodeChanged.DISPLAY_NAME_MASK |
ModelEvent.NodeChanged.ICON_MASK |
ModelEvent.NodeChanged.SHORT_DESCRIPTION_MASK |
ModelEvent.NodeChanged.CHILDREN_MASK |
ModelEvent.NodeChanged.EXPANSION_MASK);
}
for (ModelListener ml : ls) {
ml.modelChanged (event);
}
}
private void fireDisplayNameChanged (Object node) {
if (node instanceof JPDAThread) {
node = dvSupport.get((JPDAThread) node);
} else if (node instanceof JPDAThreadGroup) {
node = dvSupport.get((JPDAThreadGroup) node);
}
List<ModelListener> ls;
synchronized (listeners) {
ls = new ArrayList<ModelListener>(listeners);
}
ModelEvent event = new ModelEvent.NodeChanged(this, node,
ModelEvent.NodeChanged.DISPLAY_NAME_MASK);
for (ModelListener ml : ls) {
ml.modelChanged (event);
}
}
private void fireTreeChanged() {
List<ModelListener> ls;
synchronized (listeners) {
ls = new ArrayList<ModelListener>(listeners);
}
ModelEvent event = new ModelEvent.TreeChanged(this);
for (ModelListener ml : ls) {
ml.modelChanged (event);
}
}
private void watch(JPDAThread t) {
synchronized (threadStateUpdaters) {
if (!threadStateUpdaters.containsKey(t)) {
threadStateUpdaters.put(t, new ThreadStateUpdater(t));
}
}
}
private boolean isCurrent(JPDAThreadGroup tg) {
JPDAThread t = debugger.getCurrentThread ();
if (t == null)
return false;
JPDAThreadGroup ctg = t.getParentThreadGroup ();
while (ctg != null) {
if (ctg == tg) return true;
ctg = ctg.getParentThreadGroup ();
}
return false;
}
/**
* @param tg thread group to inspect
* @param flags flags[0] true if there is at least one suspended thread,
* flags[1] true if there is at least one resumed thread
*/
private void computeGroupStatus(JPDAThreadGroup tg, boolean[] flags) {
JPDAThread[] threads = tg.getThreads();
for (int x = 0; x < threads.length; x++) {
if (threads[x].isSuspended()) {
flags[0] = true; // set 'suspended' flag
} else {
flags[1] = true; // set 'resumed' flag
}
if (flags[0] && flags[1]) {
return; // mixed group detected
}
}
JPDAThreadGroup[] groups = tg.getThreadGroups();
for (int x = 0; x < groups.length; x++) {
computeGroupStatus(groups[x], flags);
if (flags[0] && flags[1]) {
return; // mixed group detected
}
}
}
private class ThreadStateUpdater implements PropertyChangeListener {
private Reference<JPDAThread> tr;
// currently waiting / running refresh task
// there is at most one
private RequestProcessor.Task task;
private boolean shouldExpand = false;
public ThreadStateUpdater(JPDAThread t) {
this.tr = new WeakReference(t);
((Customizer) t).addPropertyChangeListener(WeakListeners.propertyChange(this, t));
}
public void propertyChange(PropertyChangeEvent evt) {
JPDAThread t = tr.get();
if (t != null) {
//if (DebuggingTreeModel.isMethodInvoking(t)) return ;
if (JPDAThread.PROP_BREAKPOINT.equals(evt.getPropertyName()) &&
t.isSuspended() && t.getCurrentBreakpoint() != null) {
synchronized (this) {
shouldExpand = true;
}
}
synchronized (this) {
if (task == null) {
task = rp.create(new Refresher());
}
task.schedule(100);
}
}
}
private class Refresher extends Object implements Runnable {
public void run() {
JPDAThread thread = tr.get();
if (thread != null) {
if (preferences.getBoolean(DebuggingTreeModel.SHOW_SUSPENDED_THREADS_ONLY, false)) {
fireNodeChanged(TreeModel.ROOT);
} else {
fireNodeChanged(thread);
}
boolean shouldExpand;
synchronized (this) {
shouldExpand = ThreadStateUpdater.this.shouldExpand;
ThreadStateUpdater.this.shouldExpand = false;
}
if (shouldExpand) {
DebuggingTreeExpansionModelFilter.expand(debugger, dvSupport.get(thread));
}
if (preferences.getBoolean(DebuggingTreeModel.SHOW_THREAD_GROUPS, false)) {
JPDAThreadGroup group = thread.getParentThreadGroup();
while (group != null) {
fireNodeChanged(group);
group = group.getParentThreadGroup();
} // while
} // if
} // if
} // run
}
}
private class CurrentThreadListener implements PropertyChangeListener {
private Reference<JPDAThread> lastCurrentThreadRef = new WeakReference<JPDAThread>(null);
//private Reference<CallStackFrame> lastCurrentFrameRef = new WeakReference<CallStackFrame>(null);
//private CallStackFrame lastCurrentFrame = null;
private Reference<JPDAThread> lastCurrentFrameThreadRef = new WeakReference<JPDAThread>(null);
private int lastCurrentFrameDepth;
public void propertyChange(PropertyChangeEvent evt) {
if (JPDADebugger.PROP_CURRENT_THREAD.equals(evt.getPropertyName())) {
JPDAThread currentThread = debugger.getCurrentThread();
JPDAThread lastCurrentThread;
synchronized (this) {
lastCurrentThread = lastCurrentThreadRef.get();
lastCurrentThreadRef = new WeakReference(currentThread);
}
if (lastCurrentThread != null) {
fireNodeChanged(lastCurrentThread);
}
if (currentThread != null) {
fireNodeChanged(currentThread);
}
if (preferences.getBoolean(DebuggingTreeModel.SHOW_SUSPENDED_THREADS_ONLY, false)) {
fireNodeChanged(TreeModel.ROOT);
}
}
if (JPDADebugger.PROP_CURRENT_CALL_STACK_FRAME.equals(evt.getPropertyName())) {
CallStackFrame currentFrame = debugger.getCurrentCallStackFrame();
CallStackFrame lastcurrentFrame = null;
JPDAThread lastCurrentFrameThread;
synchronized (this) {
lastCurrentFrameThread = lastCurrentFrameThreadRef.get();
}
if (lastCurrentFrameThread != null) {
try {
CallStackFrame[] frames = lastCurrentFrameThread.getCallStack(lastCurrentFrameDepth, lastCurrentFrameDepth + 1);
if (frames.length > 0) {
lastcurrentFrame = frames[0];
}
} catch (AbsentInformationException aiex) {}
}
synchronized (this) {
//lastcurrentFrame = lastCurrentFrame;//Ref.get();
//lastCurrentFrameRef = new WeakReference(currentFrame);
//lastCurrentFrame = currentFrame;
if (currentFrame != null) {
lastCurrentFrameThreadRef = new WeakReference(currentFrame.getThread());
lastCurrentFrameDepth = currentFrame.getFrameDepth();
} else {
lastCurrentFrameThreadRef = new WeakReference(null);
lastCurrentFrameDepth = 0;
}
}
if (lastcurrentFrame != null) {
fireNodeChanged(lastcurrentFrame);
}
if (currentFrame != null) {
fireNodeChanged(currentFrame);
}
}
}
}
private class DeadlockListener implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent evt) {
Set<Deadlock> deadlocks = deadlockDetector.getDeadlocks();
Set deadlockedElements = new HashSet();
for (Deadlock deadlock : deadlocks) {
for (JPDAThread t : deadlock.getThreads()) {
deadlockedElements.add(dvSupport.get(t));
deadlockedElements.add(t.getContendedMonitor());
}
}
if (deadlockedElements.isEmpty()) {
return ;
}
synchronized (nodesInDeadlock) {
nodesInDeadlock.addAll(deadlockedElements);
}
synchronized (nodesInDeadlockByDebugger) {
nodesInDeadlockByDebugger.put(debugger, nodesInDeadlock);
}
for (Object node : deadlockedElements) {
fireDisplayNameChanged(node);
DebuggingTreeExpansionModelFilter.expand(debugger, node);
}
//fireNodeChanged(TreeModel.ROOT);
}
}
private final class DebuggingPreferenceChangeListener implements PreferenceChangeListener {
@Override
public void preferenceChange(PreferenceChangeEvent evt) {
String key = evt.getKey();
if (DebuggingNodeModel.SHOW_PACKAGE_NAMES.equals(key)) {
synchronized (frameDescriptionsByFrame) {
frameDescriptionsByFrame.clear();
}
}
}
}
private final class SessionLanguageListener implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent evt) {
synchronized (frameDescriptionsByFrame) {
frameDescriptionsByFrame.clear();
}
synchronized (framePathClassURL) {
framePathClassURL.clear();
}
fireTreeChanged();
}
}
private static final class ListenerDetaching {
private String propertyName;
private Session session;
ListenerDetaching(String propertyName, Session session) {
this.propertyName = propertyName;
this.session = session;
}
public void removePropertyChangeListener(PropertyChangeListener l) {
session.removePropertyChangeListener(propertyName, l);
}
}
private static final class FrameUIInfo {
String sourcePath;
String className;
String url;
String language;
}
}
| 43.450096 | 136 | 0.581093 |
78f3e070703e51a03cf36b9fe9d35e7bdb495221 | 345 | package com.my.learning.service;
import com.my.learning.entity.User;
import java.util.List;
import java.util.Optional;
public interface IEntityService<T> {
T add(T entity);
List get();
long count();
Optional<T> get(Long id);
void delete(Long id);
Optional<T> findByProperty(String propertyName, String value);
}
| 15.681818 | 66 | 0.692754 |
7704c46bf4f13471c3e70e5e18f7e66eda2cbf4a | 4,845 | import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MainClass {
static int type = 0;
static GUI view;
static JFrame frame;
static ChangeBoard list = new ChangeBoard();
static App inst;
static int size;
public static final Color OPEN_CELL_BGCOLOR = Color.WHITE;
public static final Color CLOSED_CELL_BGCOLOR = Color.GRAY;
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame = new JFrame("Sudoku");
type = 0;
if (type == 0) {
inst = new App(type, frame);
view = new GUI(type, inst.sudokuCells, 9, frame);
view.button1.addActionListener(list);
view.button2.addActionListener(list);
view.button3.addActionListener(list);
view.reset.addActionListener(list);
} else if (type == 1) {
inst = new App(type, frame);
view = new GUI(type, inst.sudokuCells, 6, frame);
view.button1.addActionListener(list);
view.button2.addActionListener(list);
view.button3.addActionListener(list);
view.reset.addActionListener(list);
} else {
inst = new App(type, frame);
view = new GUI(type, inst.sudokuCells, 16, frame);
view.button1.addActionListener(list);
view.button2.addActionListener(list);
view.button3.addActionListener(list);
view.reset.addActionListener(list);
}
}
});
}
static class ChangeBoard implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JButton butt = (JButton) e.getSource();
String text = butt.getText();
if (text.equals("9x9")) {
type = 0;
view.frame.getContentPane().removeAll();
inst = new App(type, frame);
view = new GUI(type, inst.sudokuCells, 9, frame);
view.button1.addActionListener(list);
view.button2.addActionListener(list);
view.button3.addActionListener(list);
view.reset.addActionListener(list);
} else if (text.equals("6x6")) {
type = 1;
frame.getContentPane().removeAll();
inst = new App(type, frame);
view = new GUI(type, inst.sudokuCells, 6, frame);
view.button1.addActionListener(list);
view.button2.addActionListener(list);
view.button3.addActionListener(list);
view.reset.addActionListener(list);
} else if (text.equals("16x16")){
type = 2;
view.frame.getContentPane().removeAll();
inst = new App(type, frame);
view = new GUI(type, inst.sudokuCells, 16, frame);
view.button1.addActionListener(list);
view.button2.addActionListener(list);
view.button3.addActionListener(list);
view.reset.addActionListener(list);
} else{
if(type==0) size = 9;
else if(type == 1) size = 6;
else size = 16;
for(int i=0; i<size; i++){
for(int j=0; j<size; j++){
if(inst.masks[i][j]){
inst.sudokuCells[i][j].bean.setEditable(true);
inst.sudokuCells[i][j].bean.setBackground(CLOSED_CELL_BGCOLOR);
inst.sudokuCells[i][j].bean.setText(String.valueOf(inst.sudoku[i][j]));
inst.sudokuCells[i][j].oldColor = CLOSED_CELL_BGCOLOR;
inst.sudokuCells[i][j].bean.setEditable(false);
inst.sudokuCells[i][j].conflicts = 0;
inst.sudokuCells[i][j].oldValue = "";
} else{
inst.sudokuCells[i][j].bean.setBackground(OPEN_CELL_BGCOLOR);
inst.sudokuCells[i][j].bean.setText("");
inst.sudokuCells[i][j].oldColor = OPEN_CELL_BGCOLOR;
inst.sudokuCells[i][j].conflicts = 0;
inst.sudokuCells[i][j].oldValue = "";
//inst.sudokuCells[i][j].oldValue = String.valueOf(inst.sudoku[i][j]);
}
}
}
}
}
}
} | 45.707547 | 99 | 0.499278 |
840aa9f9452744ef6e6f14d84c87ebbf2b9d7b60 | 477 | package future;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
/**
* zbj: created on 2021/4/11 21:08.
*/
public class CompletableFutureDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
System.out.println("111111111123");
});
completableFuture.get();
}
}
| 25.105263 | 92 | 0.704403 |
16f5fbb422c482240afec91db9831b74b1748bb4 | 6,483 | /*
* Copyright (c) 2011-2017, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* 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 boofcv.gui.feature;
import boofcv.abst.feature.associate.ScoreAssociation;
import georegression.struct.point.Point2D_F64;
import java.awt.*;
import java.awt.event.MouseListener;
import java.util.List;
/**
* Displays relative association scores for different features. When a feature is clicked on in
* an image the best fit scores are show in the other image.
*
* @author Peter Abeles
*/
public class AssociationScorePanel<D>
extends CompareTwoImagePanel implements MouseListener {
// adjusts how close to the optimal answer a point needs to be before it is plotted
double containmentFraction;
// how big circles are drawn in association window
int maxCircleRadius = 15;
// left and right window information
List<D> leftDesc,rightDesc;
double associationScore[];
// computes association score
ScoreAssociation<D> scorer;
// statistical information on score distribution
int indexBest;
double worst;
double best;
public AssociationScorePanel( double containmentFraction ) {
super(20,false);
if( containmentFraction <= 0 )
throw new IllegalArgumentException("containmentFraction must be more than zero");
this.containmentFraction = containmentFraction;
}
public void setScorer(ScoreAssociation<D> scorer) {
this.scorer = scorer;
}
public void setLocation(List<Point2D_F64> leftPts , List<Point2D_F64> rightPts ,
List<D> leftDesc, List<D> rightDesc ) {
setLocation(leftPts,rightPts);
this.leftDesc = leftDesc;
this.rightDesc = rightDesc;
}
protected void computeScore( boolean isTargetLeft , int targetIndex ) {
int N = Math.max(leftPts.size(),rightPts.size());
if( associationScore == null || associationScore.length < N ) {
associationScore = new double[ N ];
}
if( isTargetLeft ) {
D t = leftDesc.get(targetIndex);
for( int i = 0; i < rightDesc.size(); i++ ) {
D d = rightDesc.get(i);
associationScore[i] = scorer.score(t,d);
}
} else {
D t = rightDesc.get(targetIndex);
for( int i = 0; i < leftDesc.size(); i++ ) {
D d = leftDesc.get(i);
associationScore[i] = scorer.score(t,d);
}
}
}
@Override
protected void drawFeatures(Graphics2D g2,
double scaleLeft, int leftX, int leftY,
double scaleRight, int rightX, int rightY)
{
if( leftPts == null || rightPts == null ) {
System.out.println("is null");
return;
}
// draw all the found features in both images since nothing has been selected yet
if( selected.isEmpty() ) {
drawPoints(g2,leftPts,leftX,leftY,scaleLeft);
drawPoints(g2,rightPts,rightX,rightY,scaleRight);
return;
} else if( selected.size() != 1 ) {
System.err.println("Selected more than one feature!");
return;
}
int selectedIndex = selected.get(0);
// compute association score
computeScore(selectedIsLeft,selectedIndex);
// a feature has been selected. In the image it was selected draw an X
if( selectedIsLeft ) {
drawCrossHair(g2,leftPts.get(selectedIndex),leftX,leftY,scaleLeft);
} else {
drawCrossHair(g2,rightPts.get(selectedIndex),rightX,rightY,scaleRight);
}
// draw circles of based on how similar a feature is to the selected one
if( selectedIsLeft ) {
drawDistribution(g2,rightPts,rightX,rightY,scaleRight);
} else {
drawDistribution(g2,leftPts,leftX,leftY,scaleLeft);
}
}
/**
* Visualizes score distribution. Larger circles mean its closer to the best
* fit score.
*/
private void drawDistribution( Graphics2D g2 , List<Point2D_F64> candidates ,
int offX, int offY , double scale) {
findStatistics();
// draw all the features, adjusting their size based on the first score
g2.setColor(Color.RED);
g2.setStroke(new BasicStroke(3));
double normalizer;
if( scorer.getScoreType().isZeroBest() )
normalizer = best*containmentFraction;
else
normalizer = Math.abs(best)*(Math.exp(-1.0/containmentFraction));
for( int i = 0; i < candidates.size(); i++ ) {
Point2D_F64 p = candidates.get(i);
double s = associationScore[i];
// scale the circle based on how bad it is
double ratio = 1-Math.abs(s-best)/normalizer;
if( ratio < 0 )
continue;
int r = maxCircleRadius - (int)(maxCircleRadius*ratio);
if( r > 0 ) {
int x = (int)(p.x*scale+offX);
int y = (int)(p.y*scale+offY);
g2.drawOval(x-r,y-r,r*2+1,r*2+1);
}
}
// draw the best feature
g2.setColor(Color.GREEN);
g2.setStroke(new BasicStroke(10));
int w = maxCircleRadius*2+1;
Point2D_F64 p = candidates.get(indexBest);
int x = (int)(p.x*scale+offX);
int y = (int)(p.y*scale+offY);
g2.drawOval(x-maxCircleRadius,y-maxCircleRadius,w,w);
}
private void drawPoints( Graphics2D g2 , List<Point2D_F64> points ,
int startX , int startY , double scale ) {
for( Point2D_F64 p : points ) {
int x1 = (int)(scale*p.x)+startX;
int y1 = (int)(scale*p.y)+startY;
VisualizeFeatures.drawPoint(g2,x1,y1,Color.BLUE);
}
}
private void drawCrossHair( Graphics2D g2 , Point2D_F64 target ,
int startX , int startY , double scale) {
int x = startX + (int)(target.x*scale);
int y = startY + (int)(target.y*scale);
int r = 10;
g2.setColor(Color.BLACK);
g2.setStroke(new BasicStroke(11));
g2.drawLine(x-r,y,x+r,y);
g2.drawLine(x,y-r,x,y+r);
g2.setColor(Color.RED);
g2.setStroke(new BasicStroke(5));
g2.drawLine(x-r,y,x+r,y);
g2.drawLine(x,y-r,x,y+r);
}
@Override
protected boolean isValidPoint(int index) {
return true;
}
private void findStatistics( ) {
final int N = selectedIsLeft ? rightPts.size() : leftPts.size();
indexBest = -1;
worst = -Double.MAX_VALUE;
best = Double.MAX_VALUE;
for( int i = 0; i < N; i++ ) {
double s = associationScore[i];
if( s > worst )
worst = s;
if( s < best ) {
best = s;
indexBest = i;
}
}
}
}
| 28.310044 | 96 | 0.686719 |
f2f93f732439b787041c432e228eaf7318e76508 | 1,445 | package com.usst.app.good.ware.service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import com.usst.app.good.ware.model.WareSpecificationVal;
import com.usst.code.ibatis.impl.PublicDAO;
import com.usst.code.service.BaseService;
public class WareSpecificationValService extends BaseService<WareSpecificationVal> {
public List<WareSpecificationVal> getByWareId(String wareId) {
if (StringUtils.isBlank(wareId)) {
return null;
}
Map<String, String> param = new HashMap();
param.put("wareId", wareId);
List<WareSpecificationVal> list = this.publicDAO.select("WareSpecificationVal.WareSpecificationVal", param);
return list;
}
public WareSpecificationVal getSpecificationVal(String wareId, String goodSpecificationValId) {
Map<String, String> param = new HashMap();
param.put("wareId", wareId);
param.put("goodSpecificationValId", goodSpecificationValId);
WareSpecificationVal wareSpecificationVal = (WareSpecificationVal) this.publicDAO
.selectOne("WareSpecificationVal.WareSpecificationVal_ware", param);
return wareSpecificationVal;
}
public void deleteByWareId(String wareId) throws Exception {
if (StringUtils.isBlank(wareId)) {
throw new Exception("wareid is null");
}
Map<String, String> param = new HashMap();
param.put("wareId", wareId);
this.publicDAO.delete("WareSpecificationVal.WareSpecificationVal", param);
}
}
| 35.243902 | 110 | 0.779931 |
90039e6df37698fd986691f502fcf2abcaa3a791 | 338 | package com.koi.ring.widgets.dialog.product.view;
/**
* Created by wuhenzhizao on 2017/8/2.
*/
public class SkuViewDelegate {
private OnSkuListener listener;
public OnSkuListener getListener() {
return listener;
}
public void setListener(OnSkuListener listener) {
this.listener = listener;
}
}
| 16.9 | 53 | 0.677515 |
5f770b799b8a073462c676f2188fd2bd77565c92 | 4,170 | /*
* Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
*
* Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
*
* BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
*
* License for BK-BASE 蓝鲸基础平台:
* --------------------------------------------------------------------
* 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.tencent.bk.base.datalab.queryengine.server.filter;
import static com.tencent.bk.base.datalab.queryengine.server.constant.RequestConstants.REQUEST_TIME;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.google.common.collect.Lists;
import com.tencent.bk.base.datalab.queryengine.server.wrapper.RequestWrapper;
import java.io.IOException;
import java.util.List;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingResponseWrapper;
@Slf4j
public class DownloadResponseFilter extends OncePerRequestFilter {
private static final String DOWNLOAD_PATH = "download_path";
private static final String COST_TIME = "cost_time";
private static final String STATUS_CODE = "status_code";
private static final List<String> EXCLUDE_URIS = Lists.newArrayList();
private static final ObjectMapper JSON_MAPPER = new ObjectMapper();
static {
JSON_MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
JSON_MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
EXCLUDE_URIS.add("/v3/queryengine/dataset/download/generate_secret_key");
}
@Override
protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
String path = request.getRequestURI();
return EXCLUDE_URIS.stream().anyMatch(uri -> uri.equals(path));
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
RequestWrapper requestWrapper = new RequestWrapper(request);
filterChain.doFilter(requestWrapper, response);
ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);
buildMdcLog(requestWrapper, responseWrapper);
responseWrapper.copyBodyToResponse();
}
private void buildMdcLog(RequestWrapper requestWrapper,
ContentCachingResponseWrapper responseWrapper) throws IOException {
long costTime =
System.currentTimeMillis() - (long) requestWrapper.getAttribute(REQUEST_TIME);
MDC.put(COST_TIME, Long.toString(costTime));
MDC.put(DOWNLOAD_PATH, requestWrapper.getRequestURI());
MDC.put(STATUS_CODE, Integer.toString(responseWrapper.getStatus()));
log.info(ResponseFilter.OK);
}
}
| 48.488372 | 114 | 0.759472 |
f8f6f40563b38db14962e6ee642eec69f26d3998 | 5,600 | /*
* 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.stanbol.cmsadapter.servicesapi.helper;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.apache.stanbol.cmsadapter.servicesapi.model.mapping.BridgeDefinitions;
import org.apache.stanbol.cmsadapter.servicesapi.model.mapping.ConceptBridge;
import org.apache.stanbol.cmsadapter.servicesapi.model.mapping.InstanceBridge;
import org.apache.stanbol.cmsadapter.servicesapi.model.mapping.ObjectFactory;
import org.apache.stanbol.cmsadapter.servicesapi.model.mapping.SubsumptionBridge;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Helper class for serializing and deserializing bridge definitions
*
*/
public class MappingModelParser {
private static final Logger logger = LoggerFactory.getLogger(MappingModelParser.class);
/**
* Parses an XML document and returns corresponding {@link BridgeDefinitions} instance.
* @param xmlContent String representation of XML Document.
* @return {@link BridgeDefinitions} instance or null if unsuccessful.
*/
public static BridgeDefinitions deserializeObject(String xmlContent) {
BridgeDefinitions bridgeDefinitions = null;
try {
ClassLoader cl = ObjectFactory.class.getClassLoader();
JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class.getPackage().getName(), cl);
Unmarshaller um = jc.createUnmarshaller();
StringReader stringReader = new StringReader(xmlContent);
bridgeDefinitions = (BridgeDefinitions) um.unmarshal(stringReader);
} catch (JAXBException e) {
logger.error("JAXB Exception when parsing serialized BridgeDefinitions");
}
return bridgeDefinitions;
}
/**
* Converts an object to its XML form.
* @param object Any object that can be created by {@link ObjectFactory}
* @return XML Document as a string.
*/
public static String serializeObject(Object object) {
String bridgeDefinitions = null;
try {
ClassLoader cl = ObjectFactory.class.getClassLoader();
JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class.getPackage().getName(), cl);
Marshaller m = jc.createMarshaller();
StringWriter stringWriter = new StringWriter();
m.marshal(object, stringWriter);
bridgeDefinitions = stringWriter.toString();
} catch (JAXBException e) {
logger.error("JAXB Exception when parsing serialized BridgeDefinitions");
}
return bridgeDefinitions;
}
/**
* Gets {@link ConceptBridge}s from inside the given {@link BridgeDefinitions} object.
*
* @param bridgeDefinitions
* @return
*/
public static List<ConceptBridge> getConceptBridges(BridgeDefinitions bridgeDefinitions) {
List<ConceptBridge> cList = new ArrayList<ConceptBridge>();
List<Object> aList = bridgeDefinitions.getConceptBridgeOrSubsumptionBridgeOrInstanceBridge();
for (Object bridge : aList) {
if (bridge instanceof ConceptBridge) {
cList.add((ConceptBridge) bridge);
}
}
return cList;
}
/**
* Gets {@link SubsumptionBridge}s from inside the given {@link BridgeDefinitions} object.
*
* @param bridgeDefinitions
* @return
*/
public static List<SubsumptionBridge> getSubsumptionBridges(BridgeDefinitions bridgeDefinitions) {
List<SubsumptionBridge> sList = new ArrayList<SubsumptionBridge>();
List<Object> aList = bridgeDefinitions.getConceptBridgeOrSubsumptionBridgeOrInstanceBridge();
for (Object bridge : aList) {
if (bridge instanceof SubsumptionBridge) {
sList.add((SubsumptionBridge) bridge);
}
}
return sList;
}
/**
* Gets {@link InstanceBridge}s from inside the given {@link BridgeDefinitions} object.
*
* @param bridgeDefinitions
* @return
*/
public static List<InstanceBridge> getInstanceBridges(BridgeDefinitions bridgeDefinitions) {
List<InstanceBridge> sList = new ArrayList<InstanceBridge>();
List<Object> aList = bridgeDefinitions.getConceptBridgeOrSubsumptionBridgeOrInstanceBridge();
for (Object bridge : aList) {
if (bridge instanceof InstanceBridge) {
sList.add((InstanceBridge) bridge);
}
}
return sList;
}
}
| 40 | 103 | 0.680893 |
7496637c41492c9cff4cb08636256825402c4b26 | 94 | package ast;
//Class SingleCommandAST
public abstract class SingleCommandAST extends AST {
}
| 15.666667 | 52 | 0.808511 |
12aa371d771c9efea6735496f187e24efcfca76a | 199 | package _003HighQualityMistakes;
/**
* Created by IntelliJ IDEA.
* User: LAPD
* Date: 24.7.2018 г.
* Time: 10:51 ч.
*/
public class Main {
public static void main(String[] args) {
}
} | 14.214286 | 44 | 0.628141 |
17059dd6f428bf353d917584d5a10fafe83d9cdc | 3,788 | package io.github.salemlockwood.flyther.utils;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
public class Colors {
public static Paint getScoreColor(Context context) {
Paint white = new Paint();
white.setTextSize(80);
white.setColor(Color.WHITE);
white.setTypeface(Typeface.DEFAULT_BOLD);
Typeface tf = Typeface.createFromAsset(context.getAssets(),"fonts/kenvector_future.ttf");
white.setTypeface(tf);
white.setShadowLayer(3, 5, 5, Color.BLACK);
return white;
}
public static Paint getGuiColor(Context context){
Paint guipaint = new Paint();
guipaint.setTextSize(100);
guipaint.setColor(Color.BLACK);
guipaint.setStyle(Paint.Style.STROKE);
guipaint.setStrokeWidth(5);
Typeface tf = Typeface.createFromAsset(context.getAssets(),"fonts/kenvector_future.ttf");
guipaint.setTypeface(tf);
return guipaint;
}
public static Paint getGuiDisabledColor(Context context){
Paint guipaint = new Paint();
guipaint.setTextSize(100);
guipaint.setColor(Color.GRAY);
guipaint.setStyle(Paint.Style.STROKE);
guipaint.setStrokeWidth(5);
Typeface tf = Typeface.createFromAsset(context.getAssets(),"fonts/kenvector_future.ttf");
guipaint.setTypeface(tf);
return guipaint;
}
public static Paint getLogoColor(Context context){
Paint paint = new Paint();
paint.setTextSize(260);
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.FILL);
paint.setStrokeWidth(5);
Typeface tf = Typeface.createFromAsset(context.getAssets(),"fonts/kenvector_future.ttf");
paint.setTypeface(tf);
paint.setShadowLayer(3, 5, 5, Color.BLACK);
return paint;
}
public static Paint getBetaColor(Context context) {
Paint betaColor = new Paint();
betaColor.setTextSize(80);
betaColor.setColor(Color.RED);
betaColor.setTypeface(Typeface.DEFAULT_BOLD);
Typeface tf = Typeface.createFromAsset(context.getAssets(),"fonts/kenvector_future.ttf");
betaColor.setTypeface(tf);
betaColor.setShadowLayer(3, 5, 5, Color.BLACK);
return betaColor;
}
public static Paint getFPSColor(Context context) {
Paint betaColor = new Paint();
betaColor.setTextSize(60);
betaColor.setColor(Color.RED);
betaColor.setTypeface(Typeface.DEFAULT_BOLD);
Typeface tf = Typeface.createFromAsset(context.getAssets(),"fonts/kenvector_future.ttf");
betaColor.setTypeface(tf);
betaColor.setShadowLayer(3, 5, 5, Color.BLACK);
return betaColor;
}
public static Paint getGreenPoint() {
Paint greenPoint = new Paint();
greenPoint.setColor(Color.GREEN);
greenPoint.setStyle(Paint.Style.FILL_AND_STROKE);
greenPoint.setStrokeWidth(5);
return greenPoint;
}
public static Paint getRedPoint() {
Paint redPoint = new Paint();
redPoint.setColor(Color.RED);
redPoint.setStyle(Paint.Style.FILL_AND_STROKE);
redPoint.setStrokeWidth(5);
return redPoint;
}
public static Paint getFuelBarPaint() {
Paint fuelBarPaint = new Paint();
fuelBarPaint.setColor(0xFF8A2BE2);
fuelBarPaint.setStyle(Paint.Style.FILL_AND_STROKE);
return fuelBarPaint;
}
public static Paint getFuelBarStrokePaint() {
Paint fuelBarPaint = new Paint();
fuelBarPaint.setColor(Color.BLACK);
fuelBarPaint.setStyle(Paint.Style.STROKE);
fuelBarPaint.setShadowLayer(3, 5, 5, Color.BLACK);
return fuelBarPaint;
}
}
| 35.074074 | 97 | 0.665787 |
627a3d9ff125a5a6f053edbc7c0e723ef1bcfb97 | 311 | package com.n26.challenge.service;
import com.n26.challenge.domain.Transaction;
import org.springframework.stereotype.Service;
/**
* Created by ychahbi on 14/07/2018.
*/
public interface TransactionService {
void handleTransaction(final Transaction transaction, final long latestAcceptedTimestamp);
}
| 22.214286 | 94 | 0.794212 |
b5d16e0b75ed84e9959561f907faade9359d2fb1 | 9,661 | package me.calebjones.spacelaunchnow.ui.orbiter;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatButton;
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.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import at.blogc.android.views.ExpandableTextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.realm.RealmList;
import me.calebjones.spacelaunchnow.R;
import me.calebjones.spacelaunchnow.data.models.main.Orbiter;
import me.calebjones.spacelaunchnow.utils.GlideApp;
import me.calebjones.spacelaunchnow.utils.Utils;
public class OrbiterDetailAdapter extends RecyclerView.Adapter<OrbiterDetailAdapter.ViewHolder> {
public int position;
private Context context;
private Activity activity;
private List<Orbiter> items;
private RequestOptions requestOptions;
private int backgroundColor = 0;
private SimpleDateFormat sdf;
public OrbiterDetailAdapter(Context context, Activity activity) {
items = new ArrayList<>();
requestOptions = new RequestOptions()
.placeholder(R.drawable.placeholder)
.centerCrop();
this.context = context;
this.activity = activity;
sdf = Utils.getSimpleDateFormatForUI("MMMM yyyy");
sdf.toLocalizedPattern();
}
public void addItems(List<Orbiter> items) {
if (this.items != null) {
this.items.addAll(items);
} else {
this.items = new RealmList<>();
this.items.addAll(items);
}
notifyDataSetChanged();
}
public void clear() {
items.clear();
notifyDataSetChanged();
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.orbiter_list_item, viewGroup, false);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int i) {
Orbiter orbiter = items.get(holder.getAdapterPosition());
//Set up vehicle card Information
holder.orbiterTitle.setText(orbiter.getName());
holder.orbiterSubtitle.setText(orbiter.getCapability());
holder.orbiterName.setText(String.format(context.getString(R.string.spacecraft_details), orbiter.getName()));
holder.orbiterDescription.setText(orbiter.getDetails());
holder.orbiterHistory.setText(String.format(context.getString(R.string.spacecraft_history), orbiter.getName()));
holder.orbiterHistoryDescription.setText(orbiter.getHistory());
if (backgroundColor != 0) {
holder.orbiterTitle.setBackgroundColor(backgroundColor);
holder.orbiterSubtitle.setBackgroundColor(backgroundColor);
}
if (orbiter.getDiameter() != null) {
holder.diameter.setText(String.format(context.getString(R.string.diameter_full), orbiter.getDiameter()));
}
if (orbiter.getHeight() != null) {
holder.height.setText(String.format(context.getString(R.string.height_full), orbiter.getHeight()));
}
if (orbiter.getPayloadCapacity() != null) {
holder.payload.setText(String.format(context.getString(R.string.payload), orbiter.getPayloadCapacity()));
}
if (orbiter.getFlightLife() != null) {
holder.flightLife.setVisibility(View.VISIBLE);
holder.flightLife.setText(orbiter.getFlightLife());
} else {
holder.flightLife.setVisibility(View.GONE);
}
if (orbiter.getInUse()){
GlideApp.with(context)
.load(R.drawable.ic_checkmark)
.into(holder.activeIcon);
} else {
GlideApp.with(context)
.load(R.drawable.ic_failed)
.into(holder.activeIcon);
}
if (orbiter.getHumanRated() == null ){
GlideApp.with(context)
.load(R.drawable.ic_question_mark)
.into(holder.crewIcon);
holder.crewCapacity.setVisibility(View.GONE);
} else if (orbiter.getHumanRated()){
GlideApp.with(context)
.load(R.drawable.ic_checkmark)
.into(holder.crewIcon);
holder.crewCapacity.setVisibility(View.VISIBLE);
holder.crewCapacity.setText(String.format(context.getString(R.string.crew_capacity), orbiter.getCrewCapacity()));
} else {
holder.crewCapacity.setVisibility(View.GONE);
GlideApp.with(context)
.load(R.drawable.ic_failed)
.into(holder.crewIcon);
}
if (orbiter.getMaidenFlight() != null) {
holder.firstFlight.setText(sdf.format(orbiter.getMaidenFlight()));
} else {
holder.firstFlight.setText(R.string.unknown);
}
GlideApp.with(context)
.load(orbiter.getImageURL())
.placeholder(R.drawable.placeholder)
.centerCrop()
.listener(new RequestListener<Drawable>() {
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
holder.orbiterImage.setVisibility(View.GONE);
return false;
}
@Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
holder.orbiterImage.setVisibility(View.VISIBLE);
return false;
}
})
.into(holder.orbiterImage);
if (orbiter.getWikiLink() != null && orbiter.getWikiLink().length() > 0) {
holder.wikiButton.setVisibility(View.VISIBLE);
holder.wikiButton.setOnClickListener(v -> Utils.openCustomTab(activity, context, orbiter.getWikiLink()));
} else {
holder.wikiButton.setVisibility(View.GONE);
}
if (orbiter.getInfoLink() != null && orbiter.getInfoLink().length() > 0) {
holder.infoButton.setVisibility(View.VISIBLE);
holder.infoButton.setOnClickListener(v -> Utils.openCustomTab(activity, context, orbiter.getInfoLink()));
} else {
holder.infoButton.setVisibility(View.GONE);
}
}
@Override
public int getItemCount() {
return items.size();
}
public void updateColor(int color) {
backgroundColor = color;
backgroundColor = color;
}
public class ViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.orbiter_image)
ImageView orbiterImage;
@BindView(R.id.in_use_icon)
ImageView activeIcon;
@BindView(R.id.human_rated_icon)
ImageView crewIcon;
@BindView(R.id.orbiter_title)
TextView orbiterTitle;
@BindView(R.id.orbiter_subtitle)
TextView orbiterSubtitle;
@BindView(R.id.orbiter_name)
TextView orbiterName;
@BindView(R.id.orbiter_description_expand)
View orbiterDescriptionExpand;
@BindView(R.id.orbiter_description)
ExpandableTextView orbiterDescription;
@BindView(R.id.orbiter_history)
TextView orbiterHistory;
@BindView(R.id.orbiter_history_description)
ExpandableTextView orbiterHistoryDescription;
@BindView(R.id.orbiter_history_expand)
View orbiterHistoryExpand;
@BindView(R.id.wikiButton)
AppCompatButton wikiButton;
@BindView(R.id.infoButton)
AppCompatButton infoButton;
@BindView(R.id.diameter)
TextView diameter;
@BindView(R.id.height)
TextView height;
@BindView(R.id.payload)
TextView payload;
@BindView(R.id.crew_capacity)
TextView crewCapacity;
@BindView(R.id.flight_life)
TextView flightLife;
@BindView(R.id.first_flight_text)
TextView firstFlight;
//Add content to the card
public ViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
@OnClick(R.id.orbiter_history_expand)
public void onHistoryViewClicked() {
orbiterHistoryDescription.toggle();
if (orbiterHistoryDescription.isExpanded()) {
orbiterHistoryExpand.animate().rotation(0).start();
} else {
orbiterHistoryExpand.animate().rotation(180).start();
}
}
@OnClick(R.id.orbiter_description_expand)
public void onDescriptionViewClicked() {
orbiterDescription.toggle();
if (orbiterDescription.isExpanded()) {
orbiterDescriptionExpand.animate().rotation(0).start();
} else {
orbiterDescriptionExpand.animate().rotation(180).start();
}
}
}
}
| 36.319549 | 158 | 0.637719 |
6c499d04b1ae50be3ee01f41c6af09e459ac13c1 | 2,047 | /*
* Copyright (C) 1999-2008 Jive Software. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.openfire.stats;
import org.jivesoftware.util.LocaleUtils;
/**
* A convience class to build statistic parameters out of a resource bundle.
*
* @author Alexander Wenckus
*/
public abstract class i18nStatistic implements Statistic {
private String resourceKey;
private String pluginName;
private Type statisticType;
public i18nStatistic(String resourceKey, Statistic.Type statisticType) {
this(resourceKey, null, statisticType);
}
public i18nStatistic(String resourceKey, String pluginName, Statistic.Type statisticType) {
this.resourceKey = resourceKey;
this.pluginName = pluginName;
this.statisticType = statisticType;
}
@Override
public final String getName() {
return retrieveValue("name");
}
@Override
public final Type getStatType() {
return statisticType;
}
@Override
public final String getDescription() {
return retrieveValue("desc");
}
@Override
public final String getUnits() {
return retrieveValue("units");
}
private String retrieveValue(String key) {
String wholeKey = "stat." + resourceKey + "." + key;
if (pluginName != null) {
return LocaleUtils.getLocalizedString(wholeKey, pluginName);
}
else {
return LocaleUtils.getLocalizedString(wholeKey);
}
}
}
| 28.430556 | 95 | 0.684416 |
bdfa0af249ec812de1cd9439ac6b5f4c3e0bc880 | 293 | package net.pl3x.map.fabric.configuration.options;
import net.minecraft.text.Text;
import net.pl3x.map.fabric.gui.screen.widget.Button;
public interface Option<T> {
T getValue();
void setValue(T value);
Button.PressAction onPress();
Text getName();
Text tooltip();
}
| 17.235294 | 52 | 0.706485 |
0d38122323893fa2aeedfbc961d9afb3c58eb1c3 | 2,772 | package com.yunussen.artbook;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayList<String >nameArray;
ArrayList<Integer>idArray;
ArrayAdapter arrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=findViewById(R.id.listView);
nameArray=new ArrayList<>();
idArray=new ArrayList<>();
arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,nameArray);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent =new Intent(MainActivity.this,MainActivity2.class);
intent.putExtra("id",idArray.get(i));
intent.putExtra("info","old");
startActivity(intent);
}
});
getData();
}
public void getData(){
try {
SQLiteDatabase db=this.openOrCreateDatabase("Arts",MODE_PRIVATE,null);
Cursor cursor=db.rawQuery("SELECT * FROM arts",null);
int idIndex=cursor.getColumnIndex("id");
int artNameIndex=cursor.getColumnIndex("artName");
while (cursor.moveToNext()){
nameArray.add(cursor.getString(artNameIndex));
idArray.add(cursor.getInt(idIndex));
}
arrayAdapter.notifyDataSetChanged();
cursor.close();
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater=getMenuInflater();
menuInflater.inflate(R.menu.menu_add,menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if(item.getItemId()==R.id.add_art_item){
Intent intent=new Intent(MainActivity.this,MainActivity2.class);
intent.putExtra("info","new");
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
} | 33.804878 | 91 | 0.664502 |
2397ab187b5abd79d2337676b8a1389a5ff07eea | 675 | package br.com.lutztechnology.appveterinario.api.mappers;
import br.com.lutztechnology.appveterinario.api.dto.CustomerDTO;
import br.com.lutztechnology.appveterinario.model.Customer;
import org.springframework.stereotype.Component;
@Component
public class CustomerMapper {
public Customer convertToEntity(CustomerDTO customerDTO) {
Customer customer = new Customer();
customer.setEmail(customerDTO.getEmail());
customer.setName(customerDTO.getName());
customer.setCpf(customerDTO.getCpf());
customer.setPhone(customerDTO.getPhone());
customer.setBirthDate(customerDTO.getBirthDate());
return customer;
}
}
| 30.681818 | 64 | 0.746667 |
f7df8361ff75d6a04cbc8470a4944e6106618291 | 1,239 | package com.sensiblemetrics.api.streamer.analyzer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* Class to process streams
*
* @author alexander.rogalskiy
* @version 1.0
*/
@Slf4j
public class StreamAnalyzer {
/**
* Returns {@link Map} collection of grouped {@link List} strings by input {@link List} collection of strings
*
* @param lines - initial input {@link List} collection of strings to operate by
* @return {@link Map} collection of grouped {@link List} strings
*/
public ConcurrentMap<Integer, List<String>> process(final List<String> lines, final Function<? super String, ? extends Integer> processor) {
return Optional.ofNullable(lines)
.filter(CollectionUtils::isNotEmpty)
.<ConcurrentMap<Integer, List<String>>>map(data -> data.stream().parallel().collect(Collectors.groupingByConcurrent(processor)))
.orElseGet(ConcurrentHashMap::new);
}
}
| 34.416667 | 144 | 0.717514 |
60ccb700355465d5746e04314694c71eb01cf87b | 764 | /**
* Copyright (c) 2005-2012 https://github.com/zhuruiboqq
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.sishuok.es.common.utils;
import org.springframework.context.MessageSource;
/**
* <p>User: Zhang Kaitao
* <p>Date: 13-2-9 下午8:49
* <p>Version: 1.0
*/
public class MessageUtils {
private static MessageSource messageSource;
/**
* 根据消息键和参数 获取消息
* 委托给spring messageSource
*
* @param code 消息键
* @param args 参数
* @return
*/
public static String message(String code, Object... args) {
if (messageSource == null) {
messageSource = SpringUtils.getBean(MessageSource.class);
}
return messageSource.getMessage(code, args, null);
}
}
| 21.828571 | 69 | 0.632199 |
5220cb1e5f19cc1555dc52dd83e9ef8761d4fed6 | 796 | package ch.difty.scipamato.core.persistence.paper.searchorder;
import static ch.difty.scipamato.common.persistence.TranslationUtilsKt.deCamelCase;
import org.jetbrains.annotations.NotNull;
import org.jooq.Condition;
import org.jooq.impl.DSL;
import ch.difty.scipamato.core.entity.search.BooleanSearchTerm;
/**
* {@link SearchTermEvaluator} implementation evaluating boolean searchTerms.
*
* @author u.joss
*/
public class BooleanSearchTermEvaluator implements SearchTermEvaluator<BooleanSearchTerm> {
@NotNull
@Override
public Condition evaluate(@NotNull final BooleanSearchTerm searchTerm) {
final String fieldName = deCamelCase(searchTerm.getFieldName());
return DSL
.field(fieldName)
.equal(DSL.val(searchTerm.getValue()));
}
}
| 29.481481 | 91 | 0.756281 |
9c1dc392c36837456c78aaa3331386547404bba6 | 2,664 | package cz.romario.opensudoku.game.command;
import java.util.Stack;
import cz.romario.opensudoku.game.CellCollection;
import android.os.Bundle;
public class CommandStack {
private Stack<AbstractCommand> mCommandStack = new Stack<AbstractCommand>();
// TODO: I need cells collection, because I have to call validate on it after some
// commands. CellCollection should be able to validate itself on change.
private CellCollection mCells;
public CommandStack(CellCollection cells) {
mCells = cells;
}
public void saveState(Bundle outState) {
outState.putInt("cmdStack.size", mCommandStack.size());
for (int i = 0; i < mCommandStack.size(); i++) {
AbstractCommand command = mCommandStack.get(i);
Bundle commandState = new Bundle();
commandState.putString("commandClass", command.getCommandClass());
command.saveState(commandState);
outState.putBundle("cmdStack." + i, commandState);
}
}
public void restoreState(Bundle inState) {
int stackSize = inState.getInt("cmdStack.size");
for (int i = 0; i < stackSize; i++) {
Bundle commandState = inState.getBundle("cmdStack." + i);
AbstractCommand command = AbstractCommand.newInstance(commandState.getString("commandClass"));
command.restoreState(commandState);
push(command);
}
}
public boolean empty() {
return mCommandStack.empty();
}
public void execute(AbstractCommand command) {
push(command);
command.execute();
}
public void undo() {
if (!mCommandStack.empty()) {
AbstractCommand c = pop();
c.undo();
validateCells();
}
}
public void setCheckpoint() {
if (!mCommandStack.empty()) {
AbstractCommand c = mCommandStack.peek();
c.setCheckpoint(true);
}
}
public boolean hasCheckpoint() {
for (AbstractCommand c : mCommandStack) {
if (c.isCheckpoint())
return true;
}
return false;
}
public void undoToCheckpoint() {
/*
* I originally planned to just call undo but this way it doesn't need to
* validateCells() until the run is complete
*/
AbstractCommand c;
while (!mCommandStack.empty()) {
c = mCommandStack.pop();
c.undo();
if (mCommandStack.empty() || mCommandStack.peek().isCheckpoint()) {
break;
}
}
validateCells();
}
public boolean hasSomethingToUndo() {
return mCommandStack.size() != 0;
}
private void push(AbstractCommand command) {
if (command instanceof AbstractCellCommand) {
((AbstractCellCommand)command).setCells(mCells);
}
mCommandStack.push(command);
}
private AbstractCommand pop() {
return mCommandStack.pop();
}
private void validateCells() {
mCells.validate();
}
}
| 23.785714 | 97 | 0.689565 |
a274ec982cfd327c9121153ae6578c5a42ccf050 | 7,561 | /*
* Copyright (c) 2020 Dzikoysk
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.panda_lang.panda.language.resource.syntax.expressions.subparsers;
import org.jetbrains.annotations.Nullable;
import org.panda_lang.language.architecture.expression.Expression;
import org.panda_lang.language.architecture.type.Adjustment;
import org.panda_lang.language.architecture.type.TypeMethod;
import org.panda_lang.language.interpreter.parser.Context;
import org.panda_lang.language.interpreter.parser.PandaParserFailure;
import org.panda_lang.language.interpreter.parser.expression.ExpressionCategory;
import org.panda_lang.language.interpreter.parser.expression.ExpressionContext;
import org.panda_lang.language.interpreter.parser.expression.ExpressionResult;
import org.panda_lang.language.interpreter.parser.expression.ExpressionSubparser;
import org.panda_lang.language.interpreter.parser.expression.ExpressionSubparserWorker;
import org.panda_lang.language.interpreter.token.Snippet;
import org.panda_lang.language.interpreter.token.TokenInfo;
import org.panda_lang.language.architecture.expression.StaticExpression;
import org.panda_lang.language.architecture.expression.ThisExpression;
import org.panda_lang.language.architecture.type.TypeExecutableExpression;
import org.panda_lang.language.architecture.type.utils.TypedUtils;
import org.panda_lang.language.architecture.type.utils.VisibilityComparator;
import org.panda_lang.language.interpreter.token.SynchronizedSource;
import org.panda_lang.language.interpreter.token.TokenUtils;
import org.panda_lang.language.resource.syntax.TokenTypes;
import org.panda_lang.language.resource.syntax.auxiliary.Section;
import org.panda_lang.language.resource.syntax.separator.Separators;
import org.panda_lang.utilities.commons.ObjectUtils;
import org.panda_lang.utilities.commons.console.Effect;
import org.panda_lang.utilities.commons.function.Option;
import org.panda_lang.utilities.commons.text.ContentJoiner;
import java.util.List;
public final class MethodExpressionSubparser implements ExpressionSubparser {
@Override
public ExpressionSubparserWorker createWorker(Context context) {
return new MethodWorker().withSubparser(this);
}
@Override
public int getMinimalRequiredLengthOfSource() {
return 2;
}
@Override
public ExpressionCategory getCategory() {
return ExpressionCategory.STANDALONE;
}
@Override
public String getSubparserName() {
return "method";
}
private static final class MethodWorker extends AbstractExpressionSubparserWorker {
private static final ArgumentsParser ARGUMENT_PARSER = new ArgumentsParser();
@Override
public @Nullable ExpressionResult next(ExpressionContext context, TokenInfo nameToken) {
SynchronizedSource source = context.getSynchronizedSource();
// name has to be declared by unknown or sequence token
if ((nameToken.getType() != TokenTypes.UNKNOWN) && (nameToken.getType() != TokenTypes.SEQUENCE) || !source.hasNext()) {
return null;
}
// section of arguments
@Nullable Section section = ObjectUtils.cast(Section.class, source.next().getToken());
// section type required
if (section == null || !section.getSeparator().equals(Separators.PARENTHESIS_LEFT)) {
return null;
}
// fetch method instance
Expression instance;
boolean autofilled = false;
// fetch instance from stack if token before name was period
if (context.hasResults() && TokenUtils.contentEquals(source.getPrevious(1), Separators.PERIOD)) {
instance = context.peekExpression();
}
// use current instance (this) if source contains only name and section
else /* if (source.getIndex() == 2) ^ not really */ {
instance = ThisExpression.of(context.toContext());
autofilled = true;
}
// instance required
if (instance == null) {
return null;
}
// check if type of instance contains required method
if (!instance.getType().getMethods().hasPropertyLike(nameToken.getValue())) {
return ExpressionResult.error("Cannot find method called '" + nameToken.getValue() + "' in type " + instance.getType(), nameToken);
}
// parse method
Expression expression = parseMethod(context, instance, nameToken, section.getContent());
// drop used instance
if (context.hasResults() && !autofilled) {
context.popExpression();
}
return ExpressionResult.of(expression);
}
private Expression parseMethod(ExpressionContext context, Expression instance, TokenInfo methodName, Snippet argumentsSource) {
Expression[] arguments = ARGUMENT_PARSER.parse(context, argumentsSource);
Option<Adjustment<TypeMethod>> adjustedArguments = instance.getType().getMethods().getAdjustedArguments(methodName.getValue(), arguments);
if (!adjustedArguments.isDefined()) {
String types = TypedUtils.toString(arguments);
List<? extends TypeMethod> propertiesLike = instance.getType().getMethods().getPropertiesLike(methodName.getValue());
String similar = "";
if (!propertiesLike.isEmpty()) {
similar = "Similar methods:" + Effect.LINE_SEPARATOR;
similar += ContentJoiner.on(Effect.LINE_SEPARATOR.toString()).join(propertiesLike, method -> {
return " • &7" + method.getName() + "&r";
});
}
throw new PandaParserFailure(context, argumentsSource,
"Class " + instance.getType().getSimpleName() + " does not have method &1" + methodName + "&r with parameters &1" + types + "&r",
"Change arguments or add a new method with the provided types of parameters. " + similar
);
}
TypeMethod method = adjustedArguments.get().getExecutable();
if (!method.isStatic() && instance instanceof StaticExpression) {
throw new PandaParserFailure(context, methodName,
"Cannot invoke non-static method on static context",
"Call method using class instance or add missing 'static' keyword to the '" + methodName.getValue() + "'method signature"
);
}
Option<String> issue = VisibilityComparator.canAccess(method, context.toContext());
if (issue.isDefined()) {
throw new PandaParserFailure(context, methodName, issue.get(), VisibilityComparator.NOTE_MESSAGE);
}
return new TypeExecutableExpression(instance, adjustedArguments.get());
}
}
}
| 44.216374 | 153 | 0.680201 |
34862d21dff3423844ae31d4b19ca85ba183b5a7 | 3,109 | package org.glob3.mobile.generated;
//
// Vector2D.cpp
// G3MiOSSDK
//
// Created by Diego Gomez Deck on 31/05/12.
//
//
// Vector2D.hpp
// G3MiOSSDK
//
// Created by Diego Gomez Deck on 31/05/12.
//
//class Angle;
//class MutableVector2D;
public class Vector2D
{
//C++ TO JAVA CONVERTER TODO TASK: The implementation of the following method could not be found:
// Vector2D operator =(Vector2D v);
public final double _x;
public final double _y;
public static Vector2D zero()
{
return new Vector2D(0, 0);
}
public Vector2D(double x, double y)
{
_x = x;
_y = y;
}
public Vector2D(Vector2D v)
{
_x = v._x;
_y = v._y;
}
public final double length()
{
return IMathUtils.instance().sqrt(squaredLength());
}
public final Angle orientation()
{
return Angle.fromRadians(IMathUtils.instance().atan2(_y, _x));
}
public final double squaredLength()
{
return _x * _x + _y * _y;
}
public final Vector2D add(Vector2D v)
{
return new Vector2D(_x + v._x, _y + v._y);
}
public final Vector2D sub(Vector2D v)
{
return new Vector2D(_x - v._x, _y - v._y);
}
public final Vector2D times(Vector2D v)
{
return new Vector2D(_x * v._x, _y * v._y);
}
public final Vector2D times(double magnitude)
{
return new Vector2D(_x * magnitude, _y * magnitude);
}
public final Vector2D div(Vector2D v)
{
return new Vector2D(_x / v._x, _y / v._y);
}
public final Vector2D div(double v)
{
return new Vector2D(_x / v, _y / v);
}
public final Angle angle()
{
double a = IMathUtils.instance().atan2(_y, _x);
return Angle.fromRadians(a);
}
public static Vector2D nan()
{
return new Vector2D(Double.NaN, Double.NaN);
}
public final double maxAxis()
{
return (_x >= _y) ? _x : _y;
}
public final double minAxis()
{
return (_x <= _y) ? _x : _y;
}
public final MutableVector2D asMutableVector2D()
{
return new MutableVector2D(_x, _y);
}
public final boolean isNan()
{
if (_x != _x)
{
return true;
}
if (_y != _y)
{
return true;
}
return false;
}
public final String description()
{
IStringBuilder isb = IStringBuilder.newStringBuilder();
isb.addString("(V2D ");
isb.addDouble(_x);
isb.addString(", ");
isb.addDouble(_y);
isb.addString(")");
final String s = isb.getString();
if (isb != null)
isb.dispose();
return s;
}
@Override
public String toString() {
return description();
}
public static Vector2D intersectionOfTwoLines(Vector2D p1, Vector2D r1, Vector2D p2, Vector2D r2)
{
//u = (p2 - p1) × r1 / (r1 × r2)
//out = p2 + u x r2
final double u = ((p2.sub(p1)).dot(r1)) / r1.dot(r2);
Vector2D out = p2.add(r2.times(u));
return out;
}
public final double dot(Vector2D v)
{
return _x * v._x + _y * v._y;
}
}
| 18.288235 | 100 | 0.570923 |
1a646d6cd0cd4fbbaef2eb8c66baa8d47c539ad0 | 1,554 | package com.vikashkothary.life.ui.about;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.vikashkothary.life.R;
import com.vikashkothary.life.ui.base.BaseFragment;
import butterknife.ButterKnife;
/**
* Created by vikash on 14/09/17.
*/
public class AboutFragment extends BaseFragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public AboutFragment() {
}
public static AboutFragment newInstance(int sectionNumber) {
AboutFragment fragment = new AboutFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ((BaseActivity) getActivity()).activityComponent().inject(this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View fragmentView = inflater.inflate(R.layout.fragment_about, container, false);
ButterKnife.bind(this, fragmentView);
TextView textView = (TextView) fragmentView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return fragmentView;
}
} | 30.470588 | 104 | 0.719434 |
e3a32af262fdc9bf339787682c20689b784ff33a | 80,083 | /*
* Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved.
*
* 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.hazelcast.internal.nearcache;
import com.hazelcast.cache.HazelcastExpiryPolicy;
import com.hazelcast.config.InMemoryFormat;
import com.hazelcast.config.NearCacheConfig;
import com.hazelcast.core.ICompletableFuture;
import com.hazelcast.internal.adapter.DataStructureAdapter;
import com.hazelcast.internal.adapter.DataStructureAdapter.DataStructureMethods;
import com.hazelcast.internal.adapter.DataStructureAdapterMethod;
import com.hazelcast.internal.adapter.ICacheCompletionListener;
import com.hazelcast.internal.adapter.ICacheReplaceEntryProcessor;
import com.hazelcast.internal.adapter.IMapReplaceEntryProcessor;
import com.hazelcast.internal.adapter.ReplicatedMapDataStructureAdapter;
import com.hazelcast.monitor.NearCacheStats;
import com.hazelcast.monitor.impl.NearCacheStatsImpl;
import com.hazelcast.query.TruePredicate;
import com.hazelcast.test.AssertTask;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.annotation.ConfigureParallelRunnerWith;
import com.hazelcast.test.annotation.HeavilyMultiThreadedTestLimiter;
import org.junit.Test;
import javax.cache.expiry.ExpiryPolicy;
import javax.cache.processor.EntryProcessorResult;
import java.util.ArrayList;
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.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static com.hazelcast.config.EvictionConfig.MaxSizePolicy.ENTRY_COUNT;
import static com.hazelcast.config.EvictionPolicy.LRU;
import static com.hazelcast.config.EvictionPolicy.NONE;
import static com.hazelcast.internal.nearcache.NearCacheTestUtils.assertNearCacheContent;
import static com.hazelcast.internal.nearcache.NearCacheTestUtils.assertNearCacheEvictionsEventually;
import static com.hazelcast.internal.nearcache.NearCacheTestUtils.assertNearCacheInvalidationRequests;
import static com.hazelcast.internal.nearcache.NearCacheTestUtils.assertNearCacheInvalidations;
import static com.hazelcast.internal.nearcache.NearCacheTestUtils.assertNearCacheInvalidationsBetween;
import static com.hazelcast.internal.nearcache.NearCacheTestUtils.assertNearCacheReference;
import static com.hazelcast.internal.nearcache.NearCacheTestUtils.assertNearCacheSize;
import static com.hazelcast.internal.nearcache.NearCacheTestUtils.assertNearCacheSizeEventually;
import static com.hazelcast.internal.nearcache.NearCacheTestUtils.assertNearCacheStats;
import static com.hazelcast.internal.nearcache.NearCacheTestUtils.assertThatMemoryCostsAreGreaterThanZero;
import static com.hazelcast.internal.nearcache.NearCacheTestUtils.assertThatMemoryCostsAreZero;
import static com.hazelcast.internal.nearcache.NearCacheTestUtils.assumeThatLocalUpdatePolicyIsCacheOnUpdate;
import static com.hazelcast.internal.nearcache.NearCacheTestUtils.assumeThatLocalUpdatePolicyIsInvalidate;
import static com.hazelcast.internal.nearcache.NearCacheTestUtils.getFuture;
import static com.hazelcast.internal.nearcache.NearCacheTestUtils.getNearCacheKey;
import static com.hazelcast.internal.nearcache.NearCacheTestUtils.getValueFromNearCache;
import static com.hazelcast.internal.nearcache.NearCacheTestUtils.isCacheOnUpdate;
import static com.hazelcast.internal.nearcache.NearCacheTestUtils.setEvictionConfig;
import static com.hazelcast.internal.nearcache.NearCacheTestUtils.waitUntilLoaded;
import static java.lang.String.format;
import static java.util.Arrays.asList;
import static java.util.concurrent.Executors.newFixedThreadPool;
import static java.util.concurrent.TimeUnit.HOURS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* Contains the logic code for unified Near Cache tests.
*
* @param <NK> key type of the tested Near Cache
* @param <NV> value type of the tested Near Cache
*/
@ConfigureParallelRunnerWith(HeavilyMultiThreadedTestLimiter.class)
@SuppressWarnings("WeakerAccess")
public abstract class AbstractNearCacheBasicTest<NK, NV> extends HazelcastTestSupport {
/**
* The default count to be inserted into the Near Caches.
*/
protected static final int DEFAULT_RECORD_COUNT = 1000;
/**
* Number of seconds to expire Near Cache entries via TTL.
*/
protected static final int MAX_TTL_SECONDS = 2;
/**
* Number of seconds to expire idle Near Cache entries.
*/
protected static final int MAX_IDLE_SECONDS = 1;
/**
* The default name used for the data structures which have a Near Cache.
*/
protected static final String DEFAULT_NEAR_CACHE_NAME = "defaultNearCache";
/**
* Defines all {@link DataStructureMethods} which are using EntryProcessors.
*/
private static final List<DataStructureMethods> ENTRY_PROCESSOR_METHODS = asList(
DataStructureMethods.INVOKE,
DataStructureMethods.EXECUTE_ON_KEY,
DataStructureMethods.EXECUTE_ON_KEYS,
DataStructureMethods.EXECUTE_ON_ENTRIES,
DataStructureMethods.EXECUTE_ON_ENTRIES_WITH_PREDICATE,
DataStructureMethods.INVOKE_ALL
);
/**
* The {@link NearCacheConfig} used by the Near Cache tests.
* <p>
* Needs to be set by the implementations of this class in their {@link org.junit.Before} methods.
*/
protected NearCacheConfig nearCacheConfig;
/**
* Assumes that the {@link DataStructureAdapter} created by the Near Cache test supports a given
* {@link DataStructureAdapterMethod}.
*
* @param method the {@link DataStructureAdapterMethod} to test for
*/
protected abstract void assumeThatMethodIsAvailable(DataStructureAdapterMethod method);
/**
* Creates the {@link NearCacheTestContext} used by the Near Cache tests.
* <p>
* The backing {@link DataStructureAdapter} will be populated with {@value DEFAULT_RECORD_COUNT} entries.
*
* @param <K> key type of the created {@link DataStructureAdapter}
* @param <V> value type of the created {@link DataStructureAdapter}
* @return a {@link NearCacheTestContext} used by the Near Cache tests
*/
protected final <K, V> NearCacheTestContext<K, V, NK, NV> createContext() {
return createContext(false);
}
/**
* Creates the {@link NearCacheTestContext} used by the Near Cache tests.
*
* @param <K> key type of the created {@link DataStructureAdapter}
* @param <V> value type of the created {@link DataStructureAdapter}
* @param loaderEnabled determines if a loader should be configured
* @return a {@link NearCacheTestContext} used by the Near Cache tests
*/
protected abstract <K, V> NearCacheTestContext<K, V, NK, NV> createContext(boolean loaderEnabled);
/**
* Creates the {@link NearCacheTestContext} with only a Near Cache instance used by the Near Cache tests.
*
* @param <K> key type of the created {@link com.hazelcast.internal.adapter.DataStructureAdapter}
* @param <V> value type of the created {@link com.hazelcast.internal.adapter.DataStructureAdapter}
* @return a {@link NearCacheTestContext} with only a client used by the Near Cache tests
*/
protected abstract <K, V> NearCacheTestContext<K, V, NK, NV> createNearCacheContext();
/**
* Checks that the Near Cache is populated when {@link DataStructureMethods#GET} is used
* and that the {@link com.hazelcast.monitor.NearCacheStats} are calculated correctly.
*/
@Test
public void whenGetIsUsed_thenNearCacheShouldBePopulated() {
whenGetIsUsed_thenNearCacheShouldBePopulated(DataStructureMethods.GET);
}
/**
* Checks that the Near Cache is populated when {@link DataStructureMethods#GET_ASYNC} is used
* and that the {@link com.hazelcast.monitor.NearCacheStats} are calculated correctly.
*/
@Test
public void whenGetAsyncIsUsed_thenNearCacheShouldBePopulated() {
whenGetIsUsed_thenNearCacheShouldBePopulated(DataStructureMethods.GET_ASYNC);
}
/**
* Checks that the Near Cache is populated when {@link DataStructureMethods#GET_ALL} is used
* and that the {@link com.hazelcast.monitor.NearCacheStats} are calculated correctly.
*/
@Test
public void whenGetAllIsUsed_thenNearCacheShouldBePopulated() {
whenGetIsUsed_thenNearCacheShouldBePopulated(DataStructureMethods.GET_ALL);
}
protected void whenGetIsUsed_thenNearCacheShouldBePopulated(DataStructureMethods method) {
assumeThatMethodIsAvailable(method);
NearCacheTestContext<Integer, String, NK, NV> context = createContext();
// assert that the Near Cache is empty
populateDataAdapter(context, DEFAULT_RECORD_COUNT);
assertNearCacheSize(context, 0);
assertNearCacheStats(context, 0, 0, 0);
// populate the Near Cache
populateNearCache(context, method);
assertNearCacheSizeEventually(context, DEFAULT_RECORD_COUNT);
assertNearCacheStats(context, DEFAULT_RECORD_COUNT, 0, DEFAULT_RECORD_COUNT);
// generate Near Cache hits
populateNearCache(context, method);
assertNearCacheSize(context, DEFAULT_RECORD_COUNT);
assertNearCacheStats(context, DEFAULT_RECORD_COUNT, DEFAULT_RECORD_COUNT, DEFAULT_RECORD_COUNT);
assertNearCacheContent(context, DEFAULT_RECORD_COUNT);
assertNearCacheReferences(context, DEFAULT_RECORD_COUNT, method);
}
/**
* Checks that the Near Cache is populated when {@link DataStructureMethods#GET_ALL} is used on a half
* filled Near Cache and that the {@link com.hazelcast.monitor.NearCacheStats} are calculated correctly.
*/
@Test
public void whenGetAllWithHalfFilledNearCacheIsUsed_thenNearCacheShouldBePopulated() {
assumeThatMethodIsAvailable(DataStructureMethods.GET_ALL);
NearCacheTestContext<Integer, String, NK, NV> context = createContext();
// assert that the Near Cache is empty
populateDataAdapter(context, DEFAULT_RECORD_COUNT);
assertNearCacheSize(context, 0);
assertNearCacheStats(context, 0, 0, 0);
// populate the Near Cache with half of the entries
int size = DEFAULT_RECORD_COUNT / 2;
populateNearCache(context, DataStructureMethods.GET_ALL, size);
assertNearCacheSizeEventually(context, size);
assertNearCacheStats(context, size, 0, size);
// generate Near Cache hits and populate the missing entries
int expectedHits = size;
populateNearCache(context, DataStructureMethods.GET_ALL);
assertNearCacheSize(context, DEFAULT_RECORD_COUNT);
assertNearCacheStats(context, DEFAULT_RECORD_COUNT, expectedHits, DEFAULT_RECORD_COUNT);
// generate Near Cache hits
expectedHits += DEFAULT_RECORD_COUNT;
populateNearCache(context, DataStructureMethods.GET_ALL);
assertNearCacheSize(context, DEFAULT_RECORD_COUNT);
assertNearCacheStats(context, DEFAULT_RECORD_COUNT, expectedHits, DEFAULT_RECORD_COUNT);
assertNearCacheContent(context, DEFAULT_RECORD_COUNT);
}
/**
* Checks that the Near Cache is not populated when {@link DataStructureMethods#GET_ALL} is used with an empty key set.
*/
@Test
public void whenGetAllWithEmptySetIsUsed_thenNearCacheShouldNotBePopulated() {
assumeThatMethodIsAvailable(DataStructureMethods.GET_ALL);
NearCacheTestContext<Integer, String, NK, NV> context = createContext();
// assert that the Near Cache is empty
populateDataAdapter(context, DEFAULT_RECORD_COUNT);
assertNearCacheSize(context, 0);
assertNearCacheStats(context, 0, 0, 0);
// use getAll() with an empty set, which should not populate the Near Cache
context.nearCacheAdapter.getAll(Collections.<Integer>emptySet());
assertNearCacheSize(context, 0);
assertNearCacheStats(context, 0, 0, 0);
}
/**
* Checks that the Near Cache is populated when {@link DataStructureMethods#SET} with
* {@link com.hazelcast.config.NearCacheConfig.LocalUpdatePolicy#CACHE_ON_UPDATE} is used.
*/
@Test
public void whenSetIsUsedWithCacheOnUpdate_thenNearCacheShouldBePopulated() {
whenEntryIsAddedWithCacheOnUpdate_thenNearCacheShouldBePopulated(DataStructureMethods.SET);
}
/**
* Checks that the Near Cache is populated when {@link DataStructureMethods#SET_ASYNC} with
* {@link com.hazelcast.config.NearCacheConfig.LocalUpdatePolicy#CACHE_ON_UPDATE} is used.
*/
@Test
public void whenSetAsyncIsUsedWithCacheOnUpdate_thenNearCacheShouldBePopulated() {
whenEntryIsAddedWithCacheOnUpdate_thenNearCacheShouldBePopulated(DataStructureMethods.SET_ASYNC);
}
/**
* Checks that the Near Cache is populated when {@link DataStructureMethods#SET_ASYNC_WITH_TTL} with
* {@link com.hazelcast.config.NearCacheConfig.LocalUpdatePolicy#CACHE_ON_UPDATE} is used.
*/
@Test
public void whenSetAsyncWithTtlIsUsedWithCacheOnUpdate_thenNearCacheShouldBePopulated() {
whenEntryIsAddedWithCacheOnUpdate_thenNearCacheShouldBePopulated(DataStructureMethods.SET_ASYNC_WITH_TTL);
}
/**
* Checks that the Near Cache is populated when {@link DataStructureMethods#SET_ASYNC_WITH_EXPIRY_POLICY} with
* {@link com.hazelcast.config.NearCacheConfig.LocalUpdatePolicy#CACHE_ON_UPDATE} is used.
*/
@Test
public void whenSetAsyncWithExpiryPolicyIsUsedWithCacheOnUpdate_thenNearCacheShouldBePopulated() {
whenEntryIsAddedWithCacheOnUpdate_thenNearCacheShouldBePopulated(DataStructureMethods.SET_ASYNC_WITH_EXPIRY_POLICY);
}
/**
* Checks that the Near Cache is populated when {@link DataStructureMethods#PUT} with
* {@link com.hazelcast.config.NearCacheConfig.LocalUpdatePolicy#CACHE_ON_UPDATE} is used.
*/
@Test
public void whenPutIsUsedWithCacheOnUpdate_thenNearCacheShouldBePopulated() {
whenEntryIsAddedWithCacheOnUpdate_thenNearCacheShouldBePopulated(DataStructureMethods.PUT);
}
/**
* Checks that the Near Cache is populated when {@link DataStructureMethods#PUT_ASYNC} with
* {@link com.hazelcast.config.NearCacheConfig.LocalUpdatePolicy#CACHE_ON_UPDATE} is used.
*/
@Test
public void whenPutAsyncIsUsedWithCacheOnUpdate_thenNearCacheShouldBePopulated() {
whenEntryIsAddedWithCacheOnUpdate_thenNearCacheShouldBePopulated(DataStructureMethods.PUT_ASYNC);
}
/**
* Checks that the Near Cache is populated when {@link DataStructureMethods#PUT_ASYNC_WITH_TTL} with
* {@link com.hazelcast.config.NearCacheConfig.LocalUpdatePolicy#CACHE_ON_UPDATE} is used.
*/
@Test
public void whenPutAsyncWithTtlIsUsedWithCacheOnUpdate_thenNearCacheShouldBePopulated() {
whenEntryIsAddedWithCacheOnUpdate_thenNearCacheShouldBePopulated(DataStructureMethods.PUT_ASYNC_WITH_TTL);
}
/**
* Checks that the Near Cache is populated when {@link DataStructureMethods#PUT_ASYNC_WITH_EXPIRY_POLICY} with
* {@link com.hazelcast.config.NearCacheConfig.LocalUpdatePolicy#CACHE_ON_UPDATE} is used.
*/
@Test
public void whenPutAsyncWithExpiryPolicyIsUsedWithCacheOnUpdate_thenNearCacheShouldBePopulated() {
whenEntryIsAddedWithCacheOnUpdate_thenNearCacheShouldBePopulated(DataStructureMethods.PUT_ASYNC_WITH_EXPIRY_POLICY);
}
/**
* Checks that the Near Cache is populated when {@link DataStructureMethods#PUT_TRANSIENT} with
* {@link com.hazelcast.config.NearCacheConfig.LocalUpdatePolicy#CACHE_ON_UPDATE} is used.
*/
@Test
public void whenPutTransientIsUsedWithCacheOnUpdate_thenNearCacheShouldBePopulated() {
whenEntryIsAddedWithCacheOnUpdate_thenNearCacheShouldBePopulated(DataStructureMethods.PUT_TRANSIENT);
}
/**
* Checks that the Near Cache is populated when {@link DataStructureMethods#PUT_IF_ABSENT} with
* {@link com.hazelcast.config.NearCacheConfig.LocalUpdatePolicy#CACHE_ON_UPDATE} is used.
*/
@Test
public void whenPutIfAbsentIsUsedWithCacheOnUpdate_thenNearCacheShouldBePopulated() {
whenEntryIsAddedWithCacheOnUpdate_thenNearCacheShouldBePopulated(DataStructureMethods.PUT_IF_ABSENT);
}
/**
* Checks that the Near Cache is populated when {@link DataStructureMethods#PUT_IF_ABSENT_ASYNC} with
* {@link com.hazelcast.config.NearCacheConfig.LocalUpdatePolicy#CACHE_ON_UPDATE} is used.
*/
@Test
public void whenPutIfAbsentAsyncIsUsedWithCacheOnUpdate_thenNearCacheShouldBePopulated() {
whenEntryIsAddedWithCacheOnUpdate_thenNearCacheShouldBePopulated(DataStructureMethods.PUT_IF_ABSENT_ASYNC);
}
/**
* Checks that the Near Cache is populated when {@link DataStructureMethods#REPLACE} with
* {@link com.hazelcast.config.NearCacheConfig.LocalUpdatePolicy#CACHE_ON_UPDATE} is used.
*/
@Test
public void whenReplaceIsUsedWithCacheOnUpdate_thenNearCacheShouldBePopulated() {
whenEntryIsAddedWithCacheOnUpdate_thenNearCacheShouldBePopulated(DataStructureMethods.REPLACE);
}
/**
* Checks that the Near Cache is populated when {@link DataStructureMethods#REPLACE_WITH_OLD_VALUE} with
* {@link com.hazelcast.config.NearCacheConfig.LocalUpdatePolicy#CACHE_ON_UPDATE} is used.
*/
@Test
public void whenReplaceWithOldValueIsUsedWithCacheOnUpdate_thenNearCacheShouldBePopulated() {
whenEntryIsAddedWithCacheOnUpdate_thenNearCacheShouldBePopulated(DataStructureMethods.REPLACE_WITH_OLD_VALUE);
}
/**
* Checks that the Near Cache is populated when {@link DataStructureMethods#PUT_ALL} with
* {@link com.hazelcast.config.NearCacheConfig.LocalUpdatePolicy#CACHE_ON_UPDATE} is used.
*/
@Test
public void whenPutAllIsUsedWithCacheOnUpdate_thenNearCacheShouldBePopulated() {
whenEntryIsAddedWithCacheOnUpdate_thenNearCacheShouldBePopulated(DataStructureMethods.PUT_ALL);
}
private void whenEntryIsAddedWithCacheOnUpdate_thenNearCacheShouldBePopulated(DataStructureMethods method) {
assumeThatMethodIsAvailable(method);
assumeThatLocalUpdatePolicyIsCacheOnUpdate(nearCacheConfig);
NearCacheTestContext<Integer, String, NK, NV> context = createContext();
DataStructureAdapter<Integer, String> adapter = context.nearCacheAdapter;
ExpiryPolicy expiryPolicy = new HazelcastExpiryPolicy(1, 1, 1, HOURS);
Map<Integer, String> putAllMap = new HashMap<Integer, String>(DEFAULT_RECORD_COUNT);
for (int i = 0; i < DEFAULT_RECORD_COUNT; i++) {
String value = "value-" + i;
switch (method) {
case SET:
adapter.set(i, value);
break;
case SET_ASYNC:
getFuture(adapter.setAsync(i, value), "Could not set value via setAsync()");
break;
case SET_ASYNC_WITH_TTL:
getFuture(adapter.setAsync(i, value, 1, HOURS), "Could not set value via setAsync() with TTL");
break;
case SET_ASYNC_WITH_EXPIRY_POLICY:
getFuture(adapter.setAsync(i, value, expiryPolicy), "Could not set value via setAsync() with ExpiryPolicy");
break;
case PUT:
assertNull(adapter.put(i, value));
break;
case PUT_ASYNC:
assertNull(getFuture(adapter.putAsync(i, value), "Could not put value via putAsync()"));
break;
case PUT_ASYNC_WITH_TTL:
assertNull(getFuture(adapter.putAsync(i, value, 1, HOURS), "Could not put value via putAsync() with TTL"));
break;
case PUT_ASYNC_WITH_EXPIRY_POLICY:
ICompletableFuture<String> future = adapter.putAsync(i, value, expiryPolicy);
assertNull(getFuture(future, "Could not put value via putAsync() with ExpiryPolicy"));
break;
case PUT_TRANSIENT:
adapter.putTransient(i, value, 1, HOURS);
break;
case PUT_IF_ABSENT:
assertTrue(adapter.putIfAbsent(i, value));
break;
case PUT_IF_ABSENT_ASYNC:
assertTrue(getFuture(adapter.putIfAbsentAsync(i, value), "Could not put value via putIfAbsentAsync()"));
break;
case REPLACE:
assertNull(adapter.replace(i, value));
break;
case REPLACE_WITH_OLD_VALUE:
String oldValue = "oldValue-" + i;
context.dataAdapter.put(i, oldValue);
assertTrue(adapter.replace(i, oldValue, value));
break;
case PUT_ALL:
putAllMap.put(i, value);
break;
default:
throw new IllegalArgumentException("Unexpected method: " + method);
}
}
if (method == DataStructureMethods.PUT_ALL) {
adapter.putAll(putAllMap);
}
String message = format("Population is not working on %s()", method.getMethodName());
assertNearCacheSizeEventually(context, DEFAULT_RECORD_COUNT, message);
assertNearCacheContent(context, DEFAULT_RECORD_COUNT);
}
@Test
public void whenSetExpiryPolicyIsUsed_thenNearCacheShouldBeInvalidated_onDataAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.SET_EXPIRY_POLICY_MULTI_KEY);
}
@Test
public void whenSetExpiryPolicyIsUsed_thenNearCacheShouldBeInvalidated_onNearCacheAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.SET_EXPIRY_POLICY_MULTI_KEY);
}
@Test
public void whenSetExpiryPolicyOnSingleKeyIsUsed_thenNearCacheShouldBeInvalidated_onDataAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.SET_EXPIRY_POLICY);
}
@Test
public void whenSetExpiryPolicyOnSingleKeyIsUsed_thenNearCacheShouldBeInvalidated_onNearCacheAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.SET_EXPIRY_POLICY);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#SET} is used.
*/
@Test
public void whenSetIsUsed_thenNearCacheShouldBeInvalidated_onNearCacheAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.SET);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#SET} is used.
*/
@Test
public void whenSetIsUsed_thenNearCacheShouldBeInvalidated_onDataAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.SET);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#SET_ASYNC} is used.
*/
@Test
public void whenSetAsyncIsUsed_thenNearCacheShouldBeInvalidated_onNearCacheAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.SET_ASYNC);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#SET_ASYNC} is used.
*/
@Test
public void whenSetAsyncIsUsed_thenNearCacheShouldBeInvalidated_onDataAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.SET_ASYNC);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#SET_ASYNC_WITH_TTL} is used.
*/
@Test
public void whenSetAsyncWithTtlIsUsed_thenNearCacheShouldBeInvalidated_onNearCacheAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.SET_ASYNC_WITH_TTL);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#SET_ASYNC_WITH_TTL} is used.
*/
@Test
public void whenSetAsyncWithTtlIsUsed_thenNearCacheShouldBeInvalidated_onDataAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.SET_ASYNC_WITH_TTL);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#SET_ASYNC_WITH_EXPIRY_POLICY}
* is used.
*/
@Test
public void whenSetAsyncWithExpiryPolicyIsUsed_thenNearCacheShouldBeInvalidated_onNearCacheAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.SET_ASYNC_WITH_EXPIRY_POLICY);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#SET_ASYNC_WITH_EXPIRY_POLICY}
* is used.
*/
@Test
public void whenSetAsyncWithExpiryPolicyIsUsed_thenNearCacheShouldBeInvalidated_onDataAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.SET_ASYNC_WITH_EXPIRY_POLICY);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#PUT} is used.
*/
@Test
public void whenPutIsUsed_thenNearCacheShouldBeInvalidated_onNearCacheAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.PUT);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#PUT} is used.
*/
@Test
public void whenPutIsUsed_thenNearCacheShouldBeInvalidated_onDataAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.PUT);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#PUT_ASYNC} is used.
*/
@Test
public void whenPutAsyncIsUsed_thenNearCacheShouldBeInvalidated_onNearCacheAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.PUT_ASYNC);
}
@Test
public void whenSetTTLIsUsed_thenNearCacheShouldBeInvalidated_onDataAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.SET_TTL);
}
@Test
public void whenSetTTLIsUsed_thenNearCacheShouldBeInvalidated_onNearCacheAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.SET_TTL);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#PUT_ASYNC} is used.
*/
@Test
public void whenPutAsyncIsUsed_thenNearCacheShouldBeInvalidated_onDataAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.PUT_ASYNC);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#PUT_ASYNC_WITH_TTL} is used.
*/
@Test
public void whenPutAsyncWithTtlIsUsed_thenNearCacheShouldBeInvalidated_onNearCacheAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.PUT_ASYNC_WITH_TTL);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#PUT_ASYNC_WITH_TTL} is used.
*/
@Test
public void whenPutAsyncWithTtlIsUsed_thenNearCacheShouldBeInvalidated_onDataAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.PUT_ASYNC_WITH_TTL);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#PUT_ASYNC_WITH_EXPIRY_POLICY}
* is used.
*/
@Test
public void whenPutAsyncWithExpiryPolicyIsUsed_thenNearCacheShouldBeInvalidated_onNearCacheAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.PUT_ASYNC_WITH_EXPIRY_POLICY);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#PUT_ASYNC_WITH_EXPIRY_POLICY}
* is used.
*/
@Test
public void whenPutAsyncWithExpiryPolicyIsUsed_thenNearCacheShouldBeInvalidated_onDataAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.PUT_ASYNC_WITH_EXPIRY_POLICY);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#PUT_TRANSIENT}
* is used.
*/
@Test
public void whenPutTransientIsUsed_thenNearCacheShouldBeInvalidated_onNearCacheAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.PUT_TRANSIENT);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#PUT_TRANSIENT}
* is used.
*/
@Test
public void whenPutTransientIsUsed_thenNearCacheShouldBeInvalidated_onDataAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.PUT_TRANSIENT);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#REPLACE} is used.
*/
@Test
public void whenReplaceIsUsed_thenNearCacheShouldBeInvalidated_onNearCacheAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.REPLACE);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#REPLACE} is used.
*/
@Test
public void whenReplaceIsUsed_thenNearCacheShouldBeInvalidated_onDataAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.REPLACE);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#REPLACE_WITH_OLD_VALUE} is used.
*/
@Test
public void whenReplaceWithOldValueIsUsed_thenNearCacheShouldBeInvalidated_onNearCacheAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.REPLACE_WITH_OLD_VALUE);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#REPLACE_WITH_OLD_VALUE} is used.
*/
@Test
public void whenReplaceWithOldValueIsUsed_thenNearCacheShouldBeInvalidated_onDataAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.REPLACE_WITH_OLD_VALUE);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#INVOKE} is used.
*/
@Test
public void whenInvokeIsUsed_thenNearCacheIsInvalidated_onNearCacheAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.INVOKE);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#INVOKE} is used.
*/
@Test
public void whenInvokeIsUsed_thenNearCacheIsInvalidated_onDataAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.INVOKE);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#EXECUTE_ON_KEY} is used.
*/
@Test
public void whenExecuteOnKeyIsUsed_thenNearCacheIsInvalidated_onNearCacheAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.EXECUTE_ON_KEY);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#EXECUTE_ON_KEY} is used.
*/
@Test
public void whenExecuteOnKeyIsUsed_thenNearCacheIsInvalidated_onDataAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.EXECUTE_ON_KEY);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#EXECUTE_ON_KEYS} is used.
*/
@Test
public void whenExecuteOnKeysIsUsed_thenNearCacheIsInvalidated_onNearCacheAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.EXECUTE_ON_KEYS);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#EXECUTE_ON_KEYS} is used.
*/
@Test
public void whenExecuteOnKeysIsUsed_thenNearCacheIsInvalidated_onDataAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.EXECUTE_ON_KEYS);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#EXECUTE_ON_ENTRIES} is used.
*/
@Test
public void whenExecuteOnEntriesIsUsed_thenNearCacheIsInvalidated_onNearCacheAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.EXECUTE_ON_ENTRIES);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#EXECUTE_ON_ENTRIES} is used.
*/
@Test
public void whenExecuteOnEntriesIsUsed_thenNearCacheIsInvalidated_onDataAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.EXECUTE_ON_ENTRIES);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#EXECUTE_ON_ENTRIES_WITH_PREDICATE}
* is used.
*/
@Test
public void whenExecuteOnEntriesWithPredicateIsUsed_thenNearCacheIsInvalidated_onNearCacheAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.EXECUTE_ON_ENTRIES_WITH_PREDICATE);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#EXECUTE_ON_ENTRIES_WITH_PREDICATE}
* is used.
*/
@Test
public void whenExecuteOnEntriesWithPredicateIsUsed_thenNearCacheIsInvalidated_onDataAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.EXECUTE_ON_ENTRIES_WITH_PREDICATE);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#PUT_ALL} is used.
*/
@Test
public void whenPutAllIsUsed_thenNearCacheShouldBeInvalidated_onNearCacheAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.PUT_ALL);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#PUT_ALL} is used.
*/
@Test
public void whenPutAllIsUsed_thenNearCacheShouldBeInvalidated_onDataAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.PUT_ALL);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#INVOKE_ALL} is used.
*/
@Test
public void whenInvokeAllIsUsed_thenNearCacheIsInvalidated_onNearCacheAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.INVOKE_ALL);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#INVOKE_ALL} is used.
*/
@Test
public void whenInvokeAllIsUsed_thenNearCacheIsInvalidated_onDataAdapter() {
whenEntryIsChanged_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.INVOKE_ALL);
}
/**
* With the {@link NearCacheTestContext#dataAdapter} we have to set {@link NearCacheConfig#setInvalidateOnChange(boolean)}.
* With the {@link NearCacheTestContext#nearCacheAdapter} Near Cache invalidations are not needed.
*/
private void whenEntryIsChanged_thenNearCacheShouldBeInvalidated(boolean useDataAdapter, DataStructureMethods method) {
assumeThatMethodIsAvailable(method);
if (!ENTRY_PROCESSOR_METHODS.contains(method)) {
// since EntryProcessors return a user-defined result we cannot directly put this into the Near Cache,
// so we execute this test also for CACHE_ON_UPDATE configurations
assumeThatLocalUpdatePolicyIsInvalidate(nearCacheConfig);
}
nearCacheConfig.setInvalidateOnChange(useDataAdapter);
NearCacheTestContext<Integer, String, NK, NV> context = createContext();
DataStructureAdapter<Integer, String> adapter = useDataAdapter ? context.dataAdapter : context.nearCacheAdapter;
populateDataAdapter(context, DEFAULT_RECORD_COUNT);
populateNearCache(context);
// this should invalidate the Near Cache
IMapReplaceEntryProcessor mapEntryProcessor = new IMapReplaceEntryProcessor("value", "newValue");
ExpiryPolicy expiryPolicy = new HazelcastExpiryPolicy(1, 1, 1, HOURS);
Map<Integer, String> invalidationMap = new HashMap<Integer, String>(DEFAULT_RECORD_COUNT);
for (int i = 0; i < DEFAULT_RECORD_COUNT; i++) {
String value = "value-" + i;
String newValue = "newValue-" + i;
switch (method) {
case SET:
adapter.set(i, newValue);
break;
case SET_ASYNC:
getFuture(adapter.setAsync(i, newValue), "Could not set value via setAsync()");
break;
case SET_ASYNC_WITH_TTL:
getFuture(adapter.setAsync(i, newValue, 1, HOURS), "Could not set value via setAsync() with TTL");
break;
case SET_ASYNC_WITH_EXPIRY_POLICY:
ICompletableFuture<Void> voidFuture = adapter.setAsync(i, newValue, expiryPolicy);
getFuture(voidFuture, "Could not set value via setAsync() with ExpiryPolicy");
break;
case PUT:
assertEquals(value, adapter.put(i, newValue));
break;
case PUT_ASYNC:
assertEquals(value, getFuture(adapter.putAsync(i, newValue), "Could not put value via putAsync()"));
break;
case PUT_ASYNC_WITH_TTL:
ICompletableFuture<String> ttlFuture = adapter.putAsync(i, newValue, 1, HOURS);
assertEquals(value, getFuture(ttlFuture, "Could not put value via putAsync() with TTL"));
break;
case PUT_ASYNC_WITH_EXPIRY_POLICY:
ICompletableFuture<String> expiryFuture = adapter.putAsync(i, newValue, expiryPolicy);
assertEquals(value, getFuture(expiryFuture, "Could not put value via putAsync() with ExpiryPolicy"));
break;
case PUT_TRANSIENT:
adapter.putTransient(i, newValue, 1, HOURS);
break;
case REPLACE:
assertEquals(value, adapter.replace(i, newValue));
break;
case REPLACE_WITH_OLD_VALUE:
assertTrue(adapter.replace(i, value, newValue));
break;
case INVOKE:
assertEquals(newValue, adapter.invoke(i, new ICacheReplaceEntryProcessor(), "value", "newValue"));
break;
case EXECUTE_ON_KEY:
assertEquals(newValue, adapter.executeOnKey(i, mapEntryProcessor));
break;
case SET_EXPIRY_POLICY:
assertTrue(adapter.setExpiryPolicy(i, expiryPolicy));
break;
case EXECUTE_ON_KEYS:
case PUT_ALL:
case INVOKE_ALL:
case SET_EXPIRY_POLICY_MULTI_KEY:
invalidationMap.put(i, newValue);
break;
case EXECUTE_ON_ENTRIES:
case EXECUTE_ON_ENTRIES_WITH_PREDICATE:
break;
case SET_TTL:
adapter.setTtl(i, 1, TimeUnit.DAYS);
break;
default:
throw new IllegalArgumentException("Unexpected method: " + method);
}
}
String newValuePrefix = "newValue-";
if (method == DataStructureMethods.EXECUTE_ON_KEYS) {
Map<Integer, Object> resultMap = adapter.executeOnKeys(invalidationMap.keySet(), mapEntryProcessor);
assertResultMap(resultMap);
} else if (method == DataStructureMethods.EXECUTE_ON_ENTRIES) {
Map<Integer, Object> resultMap = adapter.executeOnEntries(mapEntryProcessor);
assertResultMap(resultMap);
} else if (method == DataStructureMethods.EXECUTE_ON_ENTRIES_WITH_PREDICATE) {
Map<Integer, Object> resultMap = adapter.executeOnEntries(mapEntryProcessor, TruePredicate.INSTANCE);
assertResultMap(resultMap);
} else if (method == DataStructureMethods.PUT_ALL) {
adapter.putAll(invalidationMap);
} else if (method == DataStructureMethods.INVOKE_ALL) {
Map<Integer, EntryProcessorResult<String>> resultMap = adapter.invokeAll(invalidationMap.keySet(),
new ICacheReplaceEntryProcessor(), "value", "newValue");
assertEquals(DEFAULT_RECORD_COUNT, resultMap.size());
for (int i = 0; i < DEFAULT_RECORD_COUNT; i++) {
assertEquals("newValue-" + i, resultMap.get(i).get());
}
} else if (method == DataStructureMethods.SET_EXPIRY_POLICY_MULTI_KEY) {
adapter.setExpiryPolicy(invalidationMap.keySet(), expiryPolicy);
newValuePrefix = "value-";
}
assertNearCacheInvalidations(context, DEFAULT_RECORD_COUNT);
String message = format("Invalidation is not working on %s()", method.getMethodName());
assertNearCacheSizeEventually(context, 0, message);
if (method == DataStructureMethods.SET_TTL || method == DataStructureMethods.SET_EXPIRY_POLICY) {
newValuePrefix = "value-";
}
for (int i = 0; i < DEFAULT_RECORD_COUNT; i++) {
assertEquals(newValuePrefix + i, context.dataAdapter.get(i));
}
}
private void assertResultMap(Map<Integer, Object> resultMap) {
assertEquals(DEFAULT_RECORD_COUNT, resultMap.size());
for (int i = 0; i < DEFAULT_RECORD_COUNT; i++) {
assertEquals("newValue-" + i, resultMap.get(i));
}
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#LOAD_ALL} is used.
*/
@Test
public void whenLoadAllIsUsed_thenNearCacheIsInvalidated_onNearCacheAdapter() {
whenEntryIsLoaded_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.LOAD_ALL);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#LOAD_ALL} is used.
*/
@Test
public void whenLoadAllIsUsed_thenNearCacheIsInvalidated_onDataAdapter() {
whenEntryIsLoaded_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.LOAD_ALL);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#LOAD_ALL_WITH_KEYS} is used.
*/
@Test
public void whenLoadAllWithKeysIsUsed_thenNearCacheIsInvalidated_onNearCacheAdapter() {
whenEntryIsLoaded_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.LOAD_ALL_WITH_KEYS);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#LOAD_ALL_WITH_KEYS} is used.
*/
@Test
public void whenLoadAllWithKeysIsUsed_thenNearCacheIsInvalidated_onDataAdapter() {
whenEntryIsLoaded_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.LOAD_ALL_WITH_KEYS);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#LOAD_ALL_WITH_LISTENER} is used.
*/
@Test
public void whenLoadAllWithListenerIsUsed_thenNearCacheIsInvalidated_onNearCacheAdapter() {
whenEntryIsLoaded_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.LOAD_ALL_WITH_LISTENER);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#LOAD_ALL_WITH_LISTENER} is used.
*/
@Test
public void whenLoadAllWithListenerIsUsed_thenNearCacheIsInvalidated_onDataAdapter() {
whenEntryIsLoaded_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.LOAD_ALL_WITH_LISTENER);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#EVICT} is used.
*/
@Test
public void whenEvictIsUsed_thenNearCacheIsInvalidated_onNearCacheAdapter() {
whenEntryIsLoaded_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.EVICT);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#EVICT} is used.
*/
@Test
public void whenEvictIsUsed_thenNearCacheIsInvalidated_onDataAdapter() {
whenEntryIsLoaded_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.EVICT);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#EVICT_ALL} is used.
*/
@Test
public void whenEvictAllIsUsed_thenNearCacheIsInvalidated_onNearCacheAdapter() {
whenEntryIsLoaded_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.EVICT_ALL);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#EVICT_ALL} is used.
*/
@Test
public void whenEvictAllIsUsed_thenNearCacheIsInvalidated_onDataAdapter() {
whenEntryIsLoaded_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.EVICT_ALL);
}
/**
* With the {@link NearCacheTestContext#dataAdapter} we have to set {@link NearCacheConfig#setInvalidateOnChange(boolean)}.
* With the {@link NearCacheTestContext#nearCacheAdapter} Near Cache invalidations are not needed.
*/
private void whenEntryIsLoaded_thenNearCacheShouldBeInvalidated(boolean useDataAdapter, DataStructureMethods method) {
assumeThatMethodIsAvailable(method);
nearCacheConfig.setInvalidateOnChange(useDataAdapter);
NearCacheTestContext<Integer, String, NK, NV> context = createContext(true);
DataStructureAdapter<Integer, String> adapter = useDataAdapter ? context.dataAdapter : context.nearCacheAdapter;
populateDataAdapter(context, DEFAULT_RECORD_COUNT);
populateNearCache(context);
// this should invalidate the Near Cache
Set<Integer> keys = new HashSet<Integer>(DEFAULT_RECORD_COUNT);
for (int i = 0; i < DEFAULT_RECORD_COUNT; i++) {
keys.add(i);
}
switch (method) {
case LOAD_ALL:
context.loader.setKeys(keys);
adapter.loadAll(true);
break;
case LOAD_ALL_WITH_KEYS:
adapter.loadAll(keys, true);
break;
case LOAD_ALL_WITH_LISTENER:
ICacheCompletionListener listener = new ICacheCompletionListener();
adapter.loadAll(keys, true, listener);
listener.await();
break;
case EVICT:
for (int i = 0; i < DEFAULT_RECORD_COUNT; i++) {
adapter.evict(i);
}
break;
case EVICT_ALL:
adapter.evictAll();
break;
default:
throw new IllegalArgumentException("Unexpected method: " + method);
}
// wait until the loader is finished and validate the updated or evicted values
waitUntilLoaded(context);
for (int i = 0; i < DEFAULT_RECORD_COUNT; i++) {
if (method == DataStructureMethods.EVICT || method == DataStructureMethods.EVICT_ALL) {
assertNull(context.dataAdapter.get(i));
} else {
assertEquals("newValue-" + i, context.dataAdapter.get(i));
}
}
assertNearCacheInvalidationsBetween(context, DEFAULT_RECORD_COUNT, DEFAULT_RECORD_COUNT * 2);
String message = format("Invalidation is not working on %s()", method.getMethodName());
assertNearCacheSizeEventually(context, 0, message);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#REMOVE} is used.
*/
@Test
public void whenRemoveIsUsed_thenNearCacheShouldBeInvalidated_onNearCacheAdapter() {
whenEntryIsRemoved_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.REMOVE);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#REMOVE} is used.
*/
@Test
public void whenRemoveIsUsed_thenNearCacheShouldBeInvalidated_onDataAdapter() {
whenEntryIsRemoved_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.REMOVE);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#REMOVE_ASYNC} is used.
*/
@Test
public void whenRemoveAsyncIsUsed_thenNearCacheShouldBeInvalidated_onNearCacheAdapter() {
whenEntryIsRemoved_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.REMOVE_ASYNC);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#REMOVE_ASYNC} is used.
*/
@Test
public void whenRemoveAsyncIsUsed_thenNearCacheShouldBeInvalidated_onDataAdapter() {
whenEntryIsRemoved_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.REMOVE_ASYNC);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#REMOVE_WITH_OLD_VALUE)} is used.
*/
@Test
public void whenRemoveWithOldValueIsUsed_thenNearCacheShouldBeInvalidated_onNearCacheAdapter() {
whenEntryIsRemoved_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.REMOVE_WITH_OLD_VALUE);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#REMOVE_WITH_OLD_VALUE)} is used.
*/
@Test
public void whenRemoveWithOldValueIsUsed_thenNearCacheShouldBeInvalidated_onDataAdapter() {
whenEntryIsRemoved_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.REMOVE_WITH_OLD_VALUE);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#DELETE} is used.
*/
@Test
public void whenDeleteIsUsed_thenNearCacheShouldBeInvalidated_onNearCacheAdapter() {
whenEntryIsRemoved_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.DELETE);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#DELETE} is used.
*/
@Test
public void whenDeleteIsUsed_thenNearCacheShouldBeInvalidated_onDataAdapter() {
whenEntryIsRemoved_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.DELETE);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#DELETE_ASYNC} is used.
*/
@Test
public void whenDeleteAsyncIsUsed_thenNearCacheShouldBeInvalidated_onNearCacheAdapter() {
whenEntryIsRemoved_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.DELETE_ASYNC);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#DELETE_ASYNC} is used.
*/
@Test
public void whenDeleteAsyncIsUsed_thenNearCacheShouldBeInvalidated_onDataAdapter() {
whenEntryIsRemoved_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.DELETE_ASYNC);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#REMOVE_ALL)} is used.
*/
@Test
public void whenRemoveAllIsUsed_thenNearCacheShouldBeInvalidated_onNearCacheAdapter() {
whenEntryIsRemoved_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.REMOVE_ALL);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#REMOVE_ALL)} is used.
*/
@Test
public void whenRemoveAllIsUsed_thenNearCacheShouldBeInvalidated_onDataAdapter() {
whenEntryIsRemoved_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.REMOVE_ALL);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#REMOVE_ALL_WITH_KEYS)} is used.
*/
@Test
public void whenRemoveAllWithKeysIsUsed_thenNearCacheShouldBeInvalidated_onNearCacheAdapter() {
whenEntryIsRemoved_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.REMOVE_ALL_WITH_KEYS);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#REMOVE_ALL_WITH_KEYS)} is used.
*/
@Test
public void whenRemoveAllWithKeysIsUsed_thenNearCacheShouldBeInvalidated_onDataAdapter() {
whenEntryIsRemoved_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.REMOVE_ALL_WITH_KEYS);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#CLEAR)} is used.
*/
@Test
public void whenClearIsUsed_thenNearCacheShouldBeInvalidated_onNearCacheAdapter() {
whenEntryIsRemoved_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.CLEAR);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#CLEAR)} is used.
*/
@Test
public void whenClearIsUsed_thenNearCacheShouldBeInvalidated_onDataAdapter() {
whenEntryIsRemoved_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.CLEAR);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#DESTROY)} is used.
*/
@Test
public void whenDestroyIsUsed_thenNearCacheShouldBeInvalidated_onNearCacheAdapter() {
whenEntryIsRemoved_thenNearCacheShouldBeInvalidated(false, DataStructureMethods.DESTROY);
}
/**
* Checks that the Near Cache is eventually invalidated when {@link DataStructureMethods#DESTROY)} is used.
*/
@Test
public void whenDestroyIsUsed_thenNearCacheShouldBeInvalidated_onDataAdapter() {
whenEntryIsRemoved_thenNearCacheShouldBeInvalidated(true, DataStructureMethods.DESTROY);
}
/**
* With the {@link NearCacheTestContext#dataAdapter} we have to set {@link NearCacheConfig#setInvalidateOnChange(boolean)}.
* With the {@link NearCacheTestContext#nearCacheAdapter} Near Cache invalidations are not needed.
*/
private void whenEntryIsRemoved_thenNearCacheShouldBeInvalidated(boolean useDataAdapter, DataStructureMethods method) {
assumeThatMethodIsAvailable(method);
nearCacheConfig.setInvalidateOnChange(useDataAdapter);
NearCacheTestContext<Integer, String, NK, NV> context = createContext();
DataStructureAdapter<Integer, String> adapter = useDataAdapter ? context.dataAdapter : context.nearCacheAdapter;
populateDataAdapter(context, DEFAULT_RECORD_COUNT);
populateNearCache(context);
// this should invalidate the Near Cache
Set<Integer> removeKeys = new HashSet<Integer>();
if (method == DataStructureMethods.REMOVE_ALL) {
adapter.removeAll();
} else {
for (int i = 0; i < DEFAULT_RECORD_COUNT; i++) {
String value = "value-" + i;
switch (method) {
case REMOVE:
assertEquals(value, adapter.remove(i));
break;
case REMOVE_WITH_OLD_VALUE:
assertTrue(adapter.remove(i, value));
break;
case REMOVE_ASYNC:
assertEquals(value, getFuture(adapter.removeAsync(i), "Could not remove entry via removeAsync()"));
break;
case DELETE:
adapter.delete(i);
break;
case DELETE_ASYNC:
assertTrue(value, getFuture(adapter.deleteAsync(i), "Could not remove entry via deleteAsync()"));
break;
case REMOVE_ALL_WITH_KEYS:
removeKeys.add(i);
break;
case CLEAR:
case DESTROY:
break;
default:
throw new IllegalArgumentException("Unexpected method: " + method);
}
}
}
if (method == DataStructureMethods.REMOVE_ALL_WITH_KEYS) {
adapter.removeAll(removeKeys);
} else if (method == DataStructureMethods.CLEAR) {
adapter.clear();
} else if (method == DataStructureMethods.DESTROY) {
adapter.destroy();
}
if (method == DataStructureMethods.DESTROY) {
// FIXME: there can be more invalidations in a lite member setup
assertNearCacheInvalidationsBetween(context, DEFAULT_RECORD_COUNT, DEFAULT_RECORD_COUNT * 2);
} else {
// there should be an invalidation for each key
assertNearCacheInvalidations(context, DEFAULT_RECORD_COUNT);
}
String message = format("Invalidation is not working on %s()", method.getMethodName());
assertNearCacheSizeEventually(context, 0, message);
}
/**
* Checks that the Near Cache works correctly when {@link DataStructureMethods#CONTAINS_KEY} is used.
*/
@Test
public void testContainsKey_onNearCacheAdapter() {
testContainsKey(false);
}
/**
* Checks that the Near Cache works correctly when {@link DataStructureMethods#CONTAINS_KEY} is used.
*/
@Test
public void testContainsKey_onDataAdapter() {
testContainsKey(true);
}
/**
* With the {@link NearCacheTestContext#dataAdapter} we have to set {@link NearCacheConfig#setInvalidateOnChange(boolean)}.
* With the {@link NearCacheTestContext#nearCacheAdapter} Near Cache invalidations are not needed.
*/
private void testContainsKey(boolean useDataAdapter) {
assumeThatMethodIsAvailable(DataStructureMethods.CONTAINS_KEY);
nearCacheConfig.setInvalidateOnChange(useDataAdapter);
final NearCacheTestContext<Integer, String, NK, NV> context = createContext();
populateDataAdapter(context, 3);
populateNearCache(context, DataStructureMethods.GET, 3);
assertTrue(context.nearCacheAdapter.containsKey(0));
assertTrue(context.nearCacheAdapter.containsKey(1));
assertTrue(context.nearCacheAdapter.containsKey(2));
assertFalse(context.nearCacheAdapter.containsKey(3));
assertFalse(context.nearCacheAdapter.containsKey(4));
// remove a key which is in the Near Cache
DataStructureAdapter<Integer, String> adapter = useDataAdapter ? context.dataAdapter : context.nearCacheAdapter;
adapter.remove(0);
adapter.remove(2);
assertTrueEventually(new AssertTask() {
@Override
public void run() {
assertFalse(context.nearCacheAdapter.containsKey(0));
assertTrue(context.nearCacheAdapter.containsKey(1));
assertFalse(context.nearCacheAdapter.containsKey(2));
assertFalse(context.nearCacheAdapter.containsKey(3));
assertFalse(context.nearCacheAdapter.containsKey(4));
}
});
}
@Test
public void whenNullKeyIsCached_thenContainsKeyShouldReturnFalse() {
NearCacheTestContext<Integer, Integer, NK, NV> context = createContext();
int absentKey = 1;
assertNull("Returned value should be null", context.nearCacheAdapter.get(absentKey));
assertFalse("containsKey() should return false", context.nearCacheAdapter.containsKey(absentKey));
}
/**
* Checks that the Near Cache eviction works as expected if the Near Cache is full.
*/
@Test
public void testNearCacheEviction() {
setEvictionConfig(nearCacheConfig, LRU, ENTRY_COUNT, DEFAULT_RECORD_COUNT);
NearCacheTestContext<Integer, String, NK, NV> context = createContext();
// populate the backing data structure with an extra entry
populateDataAdapter(context, DEFAULT_RECORD_COUNT + 1);
populateNearCache(context);
// all Near Cache implementations use the same eviction algorithm, which evicts a single entry
int expectedEvictions = 1;
// we expect (size + the extra entry - the expectedEvictions) entries in the Near Cache
long expectedOwnedEntryCount = DEFAULT_RECORD_COUNT + 1 - expectedEvictions;
long expectedHits = context.stats.getHits();
long expectedMisses = context.stats.getMisses() + 1;
// trigger eviction via fetching the extra entry
context.nearCacheAdapter.get(DEFAULT_RECORD_COUNT);
assertNearCacheEvictionsEventually(context, expectedEvictions);
assertNearCacheStats(context, expectedOwnedEntryCount, expectedHits, expectedMisses, expectedEvictions, 0);
}
@Test
public void testNearCacheExpiration_withTTL() {
nearCacheConfig.setTimeToLiveSeconds(MAX_TTL_SECONDS);
testNearCacheExpiration(MAX_TTL_SECONDS);
}
@Test
public void testNearCacheExpiration_withMaxIdle() {
nearCacheConfig.setMaxIdleSeconds(MAX_IDLE_SECONDS);
testNearCacheExpiration(MAX_IDLE_SECONDS);
}
@SuppressWarnings("UnnecessaryLocalVariable")
private void testNearCacheExpiration(int expireSeconds) {
final NearCacheTestContext<Integer, String, NK, NV> context = createContext();
populateDataAdapter(context, DEFAULT_RECORD_COUNT);
populateNearCache(context);
// we allow a difference of -1 here, since the NearCacheStats are not updated atomically,
// so one entry could already be removed from the owned entry count, but not added to the
// expirations yet (we also copy the stats, so there are no on-fly changes during the assert)
NearCacheStats stats = new NearCacheStatsImpl(context.stats);
assertTrue(format("All entries (beside one) should be in the Near Cache or expired from the Near Cache (%s)", stats),
stats.getOwnedEntryCount() + stats.getExpirations() >= DEFAULT_RECORD_COUNT - 1
&& stats.getOwnedEntryCount() + stats.getExpirations() <= DEFAULT_RECORD_COUNT);
sleepSeconds(expireSeconds + 1);
assertTrueEventually(new AssertTask() {
public void run() {
// the get() call triggers the Near Cache eviction/expiration process,
// but we need to call this on every assert, since the Near Cache has a cooldown for TTL cleanups
context.nearCacheAdapter.get(0);
assertNearCacheSize(context, 1, "Expected the Near Cache to contain just the trigger entry");
assertEquals("Expected no Near Cache evictions", 0, context.stats.getEvictions());
assertTrue(format("Expected at least %d entries to be expired from the Near Cache", DEFAULT_RECORD_COUNT),
context.stats.getExpirations() >= DEFAULT_RECORD_COUNT);
}
});
}
/**
* Checks that the memory costs are calculated correctly.
* <p>
* This variant uses a single-threaded approach to fill the Near Cache with data.
*/
@Test
public void testNearCacheMemoryCostCalculation() {
testNearCacheMemoryCostCalculation(1);
}
/**
* Checks that the memory costs are calculated correctly.
* <p>
* This variant uses a multi-threaded approach to fill the Near Cache with data.
*/
@Test
public void testNearCacheMemoryCostCalculation_withConcurrentCacheMisses() {
testNearCacheMemoryCostCalculation(10);
}
private void testNearCacheMemoryCostCalculation(int threadCount) {
final NearCacheTestContext<Integer, String, NK, NV> context = createContext();
populateDataAdapter(context, DEFAULT_RECORD_COUNT);
final CountDownLatch countDownLatch = new CountDownLatch(threadCount);
Runnable task = new Runnable() {
@Override
public void run() {
populateNearCache(context);
countDownLatch.countDown();
}
};
ExecutorService executorService = newFixedThreadPool(threadCount);
for (int i = 0; i < threadCount; i++) {
executorService.execute(task);
}
assertOpenEventually(countDownLatch);
// the Near Cache is filled, we should see some memory costs now
assertNearCacheSizeEventually(context, DEFAULT_RECORD_COUNT);
assertThatMemoryCostsAreGreaterThanZero(context, nearCacheConfig.getInMemoryFormat());
for (int i = 0; i < DEFAULT_RECORD_COUNT; i++) {
context.nearCacheAdapter.remove(i);
}
// the Near Cache is empty, we shouldn't see memory costs anymore
assertNearCacheSizeEventually(context, 0);
assertThatMemoryCostsAreZero(context);
}
/**
* Checks that the Near Cache never returns its internal {@link NearCache#CACHED_AS_NULL} to the user
* when {@link DataStructureMethods#GET} is used.
*/
@Test
public void whenGetIsUsedOnEmptyDataStructure_thenAlwaysReturnNullFromNearCache() {
whenGetIsUsedOnEmptyDataStructure_thenAlwaysReturnNullFromNearCache(DataStructureMethods.GET);
}
/**
* Checks that the Near Cache never returns its internal {@link NearCache#CACHED_AS_NULL} to the user
* when {@link DataStructureMethods#GET_ASYNC} is used.
*/
@Test
public void whenGetAsyncIsUsedOnEmptyDataStructure_thenAlwaysReturnNullFromNearCache() {
whenGetIsUsedOnEmptyDataStructure_thenAlwaysReturnNullFromNearCache(DataStructureMethods.GET_ASYNC);
}
/**
* Checks that the Near Cache never returns its internal {@link NearCache#CACHED_AS_NULL} to the user
* when {@link DataStructureMethods#GET_ALL} is used.
*/
@Test
public void whenGetAllIsUsedOnEmptyDataStructure_thenAlwaysReturnNullFromNearCache() {
whenGetIsUsedOnEmptyDataStructure_thenAlwaysReturnNullFromNearCache(DataStructureMethods.GET_ALL);
}
/**
* Checks that the Near Cache never returns its internal {@link NearCache#CACHED_AS_NULL} to the user.
*/
private void whenGetIsUsedOnEmptyDataStructure_thenAlwaysReturnNullFromNearCache(DataStructureMethods method) {
assumeThatMethodIsAvailable(method);
NearCacheTestContext<Integer, String, NK, NV> context = createContext();
// populate Near Cache and check for null values
populateNearCache(context, method, DEFAULT_RECORD_COUNT, null);
// fetch value from Near Cache and check for null values
populateNearCache(context, method, DEFAULT_RECORD_COUNT, null);
// fetch internal value directly from Near Cache
for (int i = 0; i < DEFAULT_RECORD_COUNT; i++) {
NV value = getValueFromNearCache(context, getNearCacheKey(context, i));
if (value != null) {
// the internal value should either be `null` or `CACHED_AS_NULL`
assertEquals("Expected CACHED_AS_NULL in Near Cache for key " + i, NearCache.CACHED_AS_NULL, value);
}
}
}
/**
* Checks that the Near Cache updates value for keys which are already in the Near Cache,
* even if the Near Cache is full an the eviction is disabled (via {@link com.hazelcast.config.EvictionPolicy#NONE}.
*/
@Test
public void whenNearCacheIsFull_thenPutOnSameKeyShouldUpdateValue_onNearCacheAdapter() {
whenNearCacheIsFull_thenPutOnSameKeyShouldUpdateValue(false);
}
/**
* Checks that the Near Cache updates value for keys which are already in the Near Cache,
* even if the Near Cache is full an the eviction is disabled (via {@link com.hazelcast.config.EvictionPolicy#NONE}.
*/
@Test
public void whenNearCacheIsFull_thenPutOnSameKeyShouldUpdateValue_onDataAdapter() {
whenNearCacheIsFull_thenPutOnSameKeyShouldUpdateValue(true);
}
/**
* With the {@link NearCacheTestContext#dataAdapter} we have to set {@link NearCacheConfig#setInvalidateOnChange(boolean)}.
* With the {@link NearCacheTestContext#nearCacheAdapter} Near Cache invalidations are not needed.
*/
private void whenNearCacheIsFull_thenPutOnSameKeyShouldUpdateValue(boolean useDataAdapter) {
int size = DEFAULT_RECORD_COUNT / 2;
setEvictionConfig(nearCacheConfig, NONE, ENTRY_COUNT, size);
nearCacheConfig.setInvalidateOnChange(useDataAdapter);
NearCacheTestContext<Integer, String, NK, NV> context = createContext();
DataStructureAdapter<Integer, String> adapter = useDataAdapter ? context.dataAdapter : context.nearCacheAdapter;
boolean isNearCacheDirectlyUpdated = isCacheOnUpdate(nearCacheConfig) && !useDataAdapter;
populateDataAdapter(context, DEFAULT_RECORD_COUNT);
populateNearCache(context);
// assert that the old value is present
assertNearCacheSize(context, size);
assertEquals("value-1", context.nearCacheAdapter.get(1));
// update the entry
adapter.put(1, "newValue");
// wait for the invalidation to be processed
int expectedSize = isNearCacheDirectlyUpdated ? size : size - 1;
assertNearCacheSizeEventually(context, expectedSize);
assertNearCacheInvalidations(context, 1);
long expectedHits = context.stats.getHits() + (isNearCacheDirectlyUpdated ? 2 : 1);
long expectedMisses = context.stats.getMisses() + (isNearCacheDirectlyUpdated ? 0 : 1);
// assert that the new entry is updated
assertEquals("newValue", context.nearCacheAdapter.get(1));
assertEquals("newValue", context.nearCacheAdapter.get(1));
assertNearCacheStats(context, size, expectedHits, expectedMisses);
}
@Test
public void whenSetTTLIsCalled_thenAnotherNearCacheContextShouldBeInvalidated() {
assumeThatMethodIsAvailable(DataStructureMethods.SET_TTL);
nearCacheConfig.setInvalidateOnChange(true);
NearCacheTestContext<Integer, String, NK, NV> firstContext = createContext();
NearCacheTestContext<Integer, String, NK, NV> secondContext = createNearCacheContext();
populateDataAdapter(firstContext, DEFAULT_RECORD_COUNT);
populateNearCache(secondContext);
for (int i = 0; i < DEFAULT_RECORD_COUNT; i++) {
firstContext.nearCacheAdapter.setTtl(i, 0, TimeUnit.DAYS);
}
assertNearCacheSizeEventually(secondContext, 0);
}
@Test
public void whenValueIsUpdated_thenAnotherNearCacheContextShouldBeInvalidated() {
nearCacheConfig.setInvalidateOnChange(true);
NearCacheTestContext<Integer, String, NK, NV> firstContext = createContext();
NearCacheTestContext<Integer, String, NK, NV> secondContext = createNearCacheContext();
// populate the data adapter in the first context
populateDataAdapter(firstContext, DEFAULT_RECORD_COUNT);
// populate Near Cache in the second context
populateNearCache(secondContext);
// update values in the first context
for (int i = 0; i < DEFAULT_RECORD_COUNT; i++) {
firstContext.nearCacheAdapter.put(i, "newValue-" + i);
}
// wait until the second context is invalidated
assertNearCacheSizeEventually(secondContext, 0);
// populate the second context again with the updated values
populateNearCache(secondContext, DataStructureMethods.GET, DEFAULT_RECORD_COUNT, "newValue-");
}
@Test
public void whenValueIsRemoved_thenAnotherNearCacheContextCannotGetValueAgain() {
nearCacheConfig.setInvalidateOnChange(true);
NearCacheTestContext<Integer, String, NK, NV> firstContext = createContext();
NearCacheTestContext<Integer, String, NK, NV> secondContext = createNearCacheContext();
// populate the data adapter in the first context
populateDataAdapter(firstContext, DEFAULT_RECORD_COUNT);
// populate Near Cache in the second context
populateNearCache(secondContext);
// remove values from the first context
for (int i = 0; i < DEFAULT_RECORD_COUNT; i++) {
firstContext.nearCacheAdapter.remove(i);
}
// wait until the second context is invalidated
assertNearCacheSizeEventually(secondContext, 0);
// populate the second context again with the updated values
populateNearCache(secondContext, DataStructureMethods.GET, DEFAULT_RECORD_COUNT, null);
}
@Test
public void whenDataStructureIsCleared_thenAnotherNearCacheContextCannotGetValuesAgain() {
assumeThatMethodIsAvailable(DataStructureMethods.CLEAR);
nearCacheConfig.setInvalidateOnChange(true);
NearCacheTestContext<Integer, String, NK, NV> firstContext = createContext();
NearCacheTestContext<Integer, String, NK, NV> secondContext = createNearCacheContext();
// populate the data adapter in the first context
populateDataAdapter(firstContext, DEFAULT_RECORD_COUNT);
// populate Near Cache in the second context
populateNearCache(secondContext);
// call clear() from the first context
firstContext.nearCacheAdapter.clear();
// wait until the second context is invalidated
assertNearCacheSizeEventually(secondContext, 0);
// populate the second context again with the updated values
populateNearCache(secondContext, DataStructureMethods.GET, DEFAULT_RECORD_COUNT, null);
}
protected void populateDataAdapter(NearCacheTestContext<Integer, String, ?, ?> context, int size) {
if (size < 1) {
return;
}
for (int i = 0; i < size; i++) {
context.dataAdapter.put(i, "value-" + i);
}
if (context.dataAdapter instanceof ReplicatedMapDataStructureAdapter) {
// FIXME: there are two extra invalidations in the ReplicatedMap
assertNearCacheInvalidationRequests(context, size + 2);
} else {
assertNearCacheInvalidationRequests(context, size);
}
}
protected void populateNearCache(NearCacheTestContext<Integer, String, ?, ?> context) {
populateNearCache(context, DataStructureMethods.GET);
}
protected void populateNearCache(NearCacheTestContext<Integer, String, ?, ?> context, DataStructureMethods method) {
populateNearCache(context, method, DEFAULT_RECORD_COUNT, "value-");
}
protected void populateNearCache(NearCacheTestContext<Integer, String, ?, ?> context, DataStructureMethods method,
int size) {
populateNearCache(context, method, size, "value-");
}
protected void populateNearCache(NearCacheTestContext<Integer, String, ?, ?> context, DataStructureMethods method,
int size, String valuePrefix) {
switch (method) {
case GET:
for (int i = 0; i < size; i++) {
Object value = context.nearCacheAdapter.get(i);
if (valuePrefix == null) {
assertNull(value);
} else {
assertEquals(valuePrefix + i, value);
}
}
break;
case GET_ASYNC:
List<Future<String>> futures = new ArrayList<Future<String>>(size);
for (int i = 0; i < size; i++) {
futures.add(context.nearCacheAdapter.getAsync(i));
}
for (int i = 0; i < size; i++) {
Object value = getFuture(futures.get(i), "Could not get value for index " + i + " via getAsync()");
if (valuePrefix == null) {
assertNull(value);
} else {
assertEquals(valuePrefix + i, value);
}
}
break;
case GET_ALL:
Set<Integer> getAllSet = new HashSet<Integer>(size);
for (int i = 0; i < size; i++) {
getAllSet.add(i);
}
Map<Integer, String> resultMap = context.nearCacheAdapter.getAll(getAllSet);
int resultSize = resultMap.size();
if (valuePrefix == null) {
if (context.nearCacheAdapter instanceof ReplicatedMapDataStructureAdapter) {
assertEquals(size, resultSize);
for (int i = 0; i < size; i++) {
assertNull(resultMap.get(i));
}
} else {
assertTrue("result map from getAll() should be empty, but was " + resultSize, resultMap.isEmpty());
}
} else {
assertEquals(size, resultSize);
for (int i = 0; i < size; i++) {
Object value = resultMap.get(i);
assertEquals(valuePrefix + i, value);
}
}
break;
default:
throw new IllegalArgumentException("Unexpected method: " + method);
}
}
private static void assertNearCacheReferences(NearCacheTestContext<Integer, String, ?, ?> context, int size,
DataStructureMethods method) {
if (context.nearCacheConfig.getInMemoryFormat() != InMemoryFormat.OBJECT) {
return;
}
switch (method) {
case GET:
for (int i = 0; i < size; i++) {
Object value = context.nearCacheAdapter.get(i);
assertNearCacheReference(context, i, value);
}
break;
case GET_ASYNC:
for (int i = 0; i < size; i++) {
Object value = getFuture(context.nearCacheAdapter.getAsync(i), "");
assertNearCacheReference(context, i, value);
}
break;
case GET_ALL:
Set<Integer> getAllSet = new HashSet<Integer>(size);
for (int i = 0; i < size; i++) {
getAllSet.add(i);
}
Map<Integer, String> resultMap = context.nearCacheAdapter.getAll(getAllSet);
for (Map.Entry<Integer, String> entry : resultMap.entrySet()) {
assertNearCacheReference(context, entry.getKey(), entry.getValue());
}
break;
default:
throw new IllegalArgumentException("Unexpected method: " + method);
}
}
}
| 45.142616 | 128 | 0.699462 |
304a3e7d4fa84c29eed22529844776c40637d43b | 2,917 | package com.learning.lesson13binarysorttree;
/**
* 二叉排序树结点
*
* @author Zongheng Ma
* @date 2020/8/5
*/
public class Node {
/**
* 数据域
*/
private Integer val;
/**
* 左子结点
*/
private Node left;
/**
* 右子结点
*/
private Node right;
public Node(int val) {
this.val = val;
}
public Integer getVal() {
return val;
}
public void setVal(Integer val) {
this.val = val;
}
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
@Override
public String toString() {
return "Node[" +
"val = " + val +
']';
}
/**
* 二叉排序树的添加结点
*
* @param node 树结点
*/
public void add(Node node) {
if (node.val < this.val) {
// 待添加结点的data小于当前结点,应添加至左子树
if (this.left == null) {
// 左子结点空,赋给左子节点
this.left = node;
} else {
// 向左子树递归
this.left.add(node);
}
} else {
// 待添加节点的data大于等于当前节点
if (this.right == null) {
// 右子节点空,赋给右子节点
this.right = node;
} else {
// 向右子树递归
this.right.add(node);
}
}
}
/**
* 中序遍历
*/
public void inOrder() {
if (this.left != null) {
this.left.inOrder();
}
System.out.println(this.toString());
if (this.right != null) {
this.right.inOrder();
}
}
/**
* 找到待删除的目标结点
*
* @param val 目标结点的值
* @return
*/
public Node findTarget(int val) {
if (this.val == val) {
return this;
}
if (val < this.val) {
// 目标值较小,向左子树递归
return this.left == null ? null : this.left.findTarget(val);
} else {
// 目标值较大,向右子树递归
return this.right == null ? null : this.right.findTarget(val);
}
}
/**
* 查找目标结点的父节点
*
* @param val 待删除结点的关键字
* @return 待删除结点的父节点
*/
public Node findParent(int val) {
// 判断是否为左子结点或者右子节点
boolean leftChild = this.left != null && this.left.val == val;
boolean rightChild = this.right != null && this.right.val == val;
if (leftChild || rightChild) {
return this;
} else {
if (val < this.val) {
// 目标值较小,向左子树递归
return this.left == null ? null : this.left.findParent(val);
} else {
// 目标值较大,向右子树递归
return this.right == null ? null : this.right.findParent(val);
}
}
}
}
| 19.843537 | 78 | 0.442235 |
bd332ec3e9e075b27e20583940ecb79a40967d2a | 700 | package com.active4j.hr.hr.service.impl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.active4j.hr.hr.dao.OaHrUserPactDao;
import com.active4j.hr.hr.entity.OaHrUserPactEntity;
import com.active4j.hr.hr.service.OaHrUserPactService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
/**
*
* @title OaHrUserPactServiceImpl.java
* @description
人力资源-人事合同
* @time 2020年4月15日 下午5:02:36
* @author guyp
* @version 1.0
*/
@Service("oaHrUserPactService")
@Transactional
public class OaHrUserPactServiceImpl extends ServiceImpl<OaHrUserPactDao, OaHrUserPactEntity> implements OaHrUserPactService {
}
| 26.923077 | 126 | 0.808571 |
bd44dd7913d48d365a1ed9fabd00b202ad605390 | 1,807 | /*
* This file is part of yosql. It is subject to the license terms in the LICENSE file found in the top-level
* directory of this distribution and at http://creativecommons.org/publicdomain/zero/1.0/. No part of yosql,
* including this file, may be copied, modified, propagated, or distributed except according to the terms contained
* in the LICENSE file.
*/
package wtf.metio.yosql.dao.jdbc;
import wtf.metio.yosql.internals.jdk.Strings;
import wtf.metio.yosql.models.immutables.JdbcConfiguration;
import wtf.metio.yosql.models.immutables.SqlConfiguration;
public final class DefaultJdbcFields implements JdbcFields {
private static final String NAME_REGEX = "([a-z])([A-Z])";
private static final String NAME_REPLACEMENT = "$1_$2";
private final JdbcConfiguration jdbc;
public DefaultJdbcFields(final JdbcConfiguration jdbc) {
this.jdbc = jdbc;
}
@Override
public String constantSqlStatementFieldName(final SqlConfiguration configuration) {
return configuration.name()
.replaceAll(NAME_REGEX, NAME_REPLACEMENT)
.toUpperCase()
+ getVendor(configuration);
}
@Override
public String constantRawSqlStatementFieldName(final SqlConfiguration configuration) {
return constantSqlStatementFieldName(configuration) + jdbc.rawSuffix();
}
@Override
public String constantSqlStatementParameterIndexFieldName(final SqlConfiguration configuration) {
return constantSqlStatementFieldName(configuration) + jdbc.indexSuffix();
}
private static String getVendor(final SqlConfiguration configuration) {
return Strings.isBlank(configuration.vendor())
? ""
: "_" + configuration.vendor().replace(" ", "_").toUpperCase();
}
}
| 36.14 | 115 | 0.716657 |
6ae094fe0fde4c3388baf9d512a1367ee9568f33 | 2,843 | package com.szczepix.quitsmoker.views;
import com.szczepix.quitsmoker.managers.IStageManager;
import javafx.embed.swing.JFXPanel;
import javafx.event.ActionEvent;
import javafx.scene.control.Button;
import javafx.scene.control.Control;
import javafx.scene.layout.AnchorPane;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = FXMLViewTest.FXMLViewTestConfiguration.class)
public abstract class FXMLViewTest<T extends FXMLView> {
@Autowired
private IStageManager stageManager;
private FXMLView view;
private JFXPanel fxPanel;
public abstract Class<T> getTClass();
public T getView() {
return (T) view;
}
@Before
public void setUp() throws Exception {
fxPanel = new JFXPanel();
view = getTClass().newInstance();
view.stageManager = stageManager;
}
@Test
public void creation() {
assertThat(view).isNotNull();
assertThat(view.getClass()).isEqualTo(getTClass());
assertThat(view.stageManager).isNotNull();
}
@Test
public void enableCompononetWithoutButton() {
view.enableCompononet(null);
}
@Test
public void enableCompononetWithButton() {
Control component = mock(Control.class);
view.enableCompononet(component);
}
@Test
public void enableWithButton() {
Button button = new Button();
view.enableButton(button, this::handleButton);
}
@Test
public void enableWithoutButton() {
view.enableButton(null, this::handleButton);
}
public void handleButton(ActionEvent actionEvent) {
}
@Configuration
static class FXMLViewTestConfiguration {
@Bean
public AnnotationConfigApplicationContext context() {
return mock(AnnotationConfigApplicationContext.class);
}
@Bean
public IStageManager stageManager() {
IStageManager stageManager = mock(IStageManager.class);
MainView mainView = mock(MainView.class);
mainView.contentPane = mock(AnchorPane.class);
mainView.menuPane = mock(AnchorPane.class);
doReturn(mainView).when(stageManager).getView();
return stageManager;
}
}
} | 29.309278 | 81 | 0.710517 |
ff96f280fc5925f301911bbf2eaa10f01e2f5603 | 3,157 | /*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Server
* Copyright (C) 2011, 2012, 2013, 2014, 2016 Synacor, Inc.
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software Foundation,
* version 2 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with this program.
* If not, see <https://www.gnu.org/licenses/>.
* ***** END LICENSE BLOCK *****
*/
package com.zimbra.soap.mail.message;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import com.zimbra.common.soap.MailConstants;
import com.zimbra.soap.mail.type.GetCalendarItemRequestBase;
/**
* @zm-api-command-auth-required true
* @zm-api-command-admin-auth-required false
* @zm-api-command-description Get Appointment. Returns the metadata info for each Invite that makes up this appointment.
* <br />
* The content (original email) for each invite is stored within the Appointment itself in a big multipart/digest
* containing each invite in the appointment as a sub-mimepart it can be retreived from the content servlet:
* <pre>
* http://servername/service/content/get?id=<calItemId>
* </pre>
* The content for a single Invite can be requested from the content servlet (or from <b><GetMsg></b>)
* Individual. The client can ALSO request just the content for each individual invite using a compound item-id
* request:
* <pre>
* http://servername/service/content/get?id="calItemId-invite_mail_item_id"
* <GetMsgRequest><m id="calItemId-invite_mail_item_id"
* </pre>
* <b>IMPORTANT NOTE</b>: DO NOT use the raw invite-mail-item-id to fetch the content: it might work sometimes,
* however the invite is a standard mail-message it can be deleted by the user at any time!
*/
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name=MailConstants.E_GET_APPOINTMENT_REQUEST)
public class GetAppointmentRequest extends GetCalendarItemRequestBase {
public GetAppointmentRequest() {
}
public static GetAppointmentRequest createForUidInvitesContent(String reqUid,
Boolean includeInvites, Boolean includeContent) {
GetAppointmentRequest req = new GetAppointmentRequest();
req.setUid(reqUid);
req.setIncludeContent(includeContent);
req.setIncludeInvites(includeInvites);
return req;
}
public static GetAppointmentRequest createForIdInvitesContent(String reqId,
Boolean includeInvites, Boolean includeContent, Boolean sync) {
GetAppointmentRequest req = new GetAppointmentRequest();
req.setId(reqId);
req.setIncludeContent(includeContent);
req.setIncludeInvites(includeInvites);
req.setSync(sync);
return req;
}
}
| 43.847222 | 121 | 0.74121 |
d7b6ce0cde08cfa1d0754f3be68e2f35dac5fcc4 | 1,751 | /**
* Copyright (c) 2019-2030 panguBpm All rights reserved.
* <p>
* http://www.pangubpm.com/
* <p>
* (盘古BPM工作流平台)
*/
package com.pangubpm.bpm.model.xml.impl.validation;
import java.util.Collection;
import com.pangubpm.bpm.model.xml.impl.ModelInstanceImpl;
import com.pangubpm.bpm.model.xml.instance.ModelElementInstance;
import com.pangubpm.bpm.model.xml.validation.ModelElementValidator;
import com.pangubpm.bpm.model.xml.validation.ValidationResults;
/**
* @author pangubpm([email protected])
*
*/
public class ModelInstanceValidator {
protected ModelInstanceImpl modelInstanceImpl;
protected Collection<ModelElementValidator<?>> validators;
public ModelInstanceValidator(ModelInstanceImpl modelInstanceImpl, Collection<ModelElementValidator<?>> validators) {
this.modelInstanceImpl = modelInstanceImpl;
this.validators = validators;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public ValidationResults validate() {
ValidationResultsCollectorImpl resultsCollector = new ValidationResultsCollectorImpl();
for (ModelElementValidator validator : validators) {
Class<? extends ModelElementInstance> elementType = validator.getElementType();
Collection<? extends ModelElementInstance> modelElementsByType = modelInstanceImpl.getModelElementsByType(elementType);
for (ModelElementInstance element : modelElementsByType) {
resultsCollector.setCurrentElement(element);
try {
validator.validate(element, resultsCollector);
}
catch(RuntimeException e) {
throw new RuntimeException("Validator " + validator + " threw an exception while validating "+element, e);
}
}
}
return resultsCollector.getResults();
}
}
| 29.677966 | 125 | 0.744146 |
8b8ab86224b058c9c0f75d82b4eb7f8a5796a0a7 | 1,905 | package com.myriad.auto2.model;
import java.io.Serializable;
import java.util.ArrayList;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;
public class TestCase implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private String location;
private ArrayList<JsonNode> events = new ArrayList<JsonNode>();
private String encoding;
public TestCase() {
}
public boolean addEvent(JsonNode event){
return events.add(event);
}
public String getEncoding() {
return encoding;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public void setEvents(ArrayList<JsonNode> events) {
this.events = events;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public TestCase(String testCaseName) {
this.name = testCaseName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ArrayList<JsonNode> getEvents() {
return events;
}
@Override
public int hashCode() {
int hash = 5;
hash = 67 * hash + Objects.hashCode(this.name);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final TestCase other = (TestCase) obj;
if (!Objects.equals(this.name, other.name)) {
return false;
}
return true;
}
}
| 20.052632 | 67 | 0.591076 |
f681a45c62ab23f7a86df75cdf61de101ecdcc98 | 4,587 | // Targeted by JavaCPP version 1.5.4: DO NOT EDIT THIS FILE
package org.bytedeco.opencv.opencv_face;
import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
import static org.bytedeco.javacpp.presets.javacpp.*;
import static org.bytedeco.openblas.global.openblas_nolapack.*;
import static org.bytedeco.openblas.global.openblas.*;
import org.bytedeco.opencv.opencv_core.*;
import static org.bytedeco.opencv.global.opencv_core.*;
import org.bytedeco.opencv.opencv_imgproc.*;
import static org.bytedeco.opencv.global.opencv_imgproc.*;
import static org.bytedeco.opencv.global.opencv_imgcodecs.*;
import org.bytedeco.opencv.opencv_videoio.*;
import static org.bytedeco.opencv.global.opencv_videoio.*;
import org.bytedeco.opencv.opencv_highgui.*;
import static org.bytedeco.opencv.global.opencv_highgui.*;
import org.bytedeco.opencv.opencv_flann.*;
import static org.bytedeco.opencv.global.opencv_flann.*;
import org.bytedeco.opencv.opencv_features2d.*;
import static org.bytedeco.opencv.global.opencv_features2d.*;
import org.bytedeco.opencv.opencv_calib3d.*;
import static org.bytedeco.opencv.global.opencv_calib3d.*;
import org.bytedeco.opencv.opencv_objdetect.*;
import static org.bytedeco.opencv.global.opencv_objdetect.*;
import org.bytedeco.opencv.opencv_photo.*;
import static org.bytedeco.opencv.global.opencv_photo.*;
import static org.bytedeco.opencv.global.opencv_face.*;
/** \brief Default predict collector
<p>
Trace minimal distance with treshhold checking (that is default behavior for most predict logic)
*/
@Namespace("cv::face") @NoOffset @Properties(inherit = org.bytedeco.opencv.presets.opencv_face.class)
public class StandardCollector extends PredictCollector {
static { Loader.load(); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public StandardCollector(Pointer p) { super(p); }
@NoOffset public static class PredictResult extends Pointer {
static { Loader.load(); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public PredictResult(Pointer p) { super(p); }
/** Native array allocator. Access with {@link Pointer#position(long)}. */
public PredictResult(long size) { super((Pointer)null); allocateArray(size); }
private native void allocateArray(long size);
@Override public PredictResult position(long position) {
return (PredictResult)super.position(position);
}
@Override public PredictResult getPointer(long i) {
return new PredictResult(this).position(position + i);
}
public native int label(); public native PredictResult label(int setter);
public native double distance(); public native PredictResult distance(double setter);
public PredictResult(int label_/*=-1*/, double distance_/*=DBL_MAX*/) { super((Pointer)null); allocate(label_, distance_); }
private native void allocate(int label_/*=-1*/, double distance_/*=DBL_MAX*/);
public PredictResult() { super((Pointer)null); allocate(); }
private native void allocate();
}
/** \brief Constructor
@param threshold_ set threshold
*/
public StandardCollector(double threshold_/*=DBL_MAX*/) { super((Pointer)null); allocate(threshold_); }
private native void allocate(double threshold_/*=DBL_MAX*/);
public StandardCollector() { super((Pointer)null); allocate(); }
private native void allocate();
/** \brief overloaded interface method */
public native @Override void init(@Cast("size_t") long size);
/** \brief overloaded interface method */
public native @Cast("bool") @Override boolean collect(int label, double dist);
/** \brief Returns label with minimal distance */
public native int getMinLabel();
/** \brief Returns minimal distance value */
public native double getMinDist();
/** \brief Return results as vector
@param sorted If set, results will be sorted by distance
Each values is a pair of label and distance.
*/
public native @ByVal IntDoublePairVector getResults(@Cast("bool") boolean sorted/*=false*/);
public native @ByVal IntDoublePairVector getResults();
/** \brief Return results as map
Labels are keys, values are minimal distances
*/
public native @ByVal IntDoubleMap getResultsMap();
/** \brief Static constructor
@param threshold set threshold
*/
public static native @Ptr StandardCollector create(double threshold/*=DBL_MAX*/);
public static native @Ptr StandardCollector create();
}
| 47.28866 | 132 | 0.729671 |
c3bf953517cd546c9e29fb8de800a25fa0e2be8b | 490 | package hardcoded.assembly.x86;
final class NumberUtils {
public static int getBitsSize(long value) {
value = (value < 0 ? - (value + 1):value);
// The eight was added because 0xff should be treated as 16 bit
// otherwise it would encode -1 as a 8 bit value and that is wrong.
if((value & 0xffffffff80000000L) != 0) return 64; else
if((value & 0xffff8000L) != 0) return 32; else
if((value & 0xff80L) != 0) return 16;
else return 8;
}
}
| 32.666667 | 70 | 0.626531 |
f204be0bf64dec2ae7c2043a1996e3d5b97481a0 | 1,112 | package io.ami2018.ntmy.model;
import org.json.JSONException;
import org.json.JSONObject;
public class Color {
private Integer red;
private Integer green;
private Integer blue;
private int intColor;
public Color(int red, int green, int blue) {
this.red = red;
this.green = green;
this.blue = blue;
}
public Color(JSONObject jsonObject) {
try {
red = Math.round(Float.valueOf(jsonObject.getString("red")) * 255);
green = Math.round(Float.valueOf(jsonObject.getString("green")) * 255);
blue = Math.round(Float.valueOf(jsonObject.getString("blue")) * 255);
intColor = getIntFromColor(this.red, this.green, this.blue);
} catch (JSONException e) {
e.printStackTrace();
}
}
public int getColor() {
return intColor;
}
private int getIntFromColor(int red, int green, int blue) {
red = (red << 16) & 0x00FF0000;
green = (green << 8) & 0x0000FF00;
blue = blue & 0x000000FF;
return 0xFF000000 | red | green | blue;
}
}
| 26.47619 | 83 | 0.594424 |
c4e42bdd114145dfb60cadac36101847975b6a6b | 1,925 | /**
*
*/
package org.atum.jvcp.net.codec.newcamd;
import org.atum.jvcp.net.codec.Packet;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
/**
* @author <a href="https://github.com/atum-martin">atum-martin</a>
* @since 20 Dec 2016 21:53:06
*/
public class NewcamdPacket implements Packet {
private int command;
private ByteBuf headers;
private ByteBuf payload = null;
private transient int strReaderIndex = 0;
public NewcamdPacket(int command) {
this.command = command;
this.headers = Unpooled.buffer(10);
headers.writeBytes(new byte[10]);
}
/**
* @param command
* @param headers
*/
public NewcamdPacket(int command, ByteBuf headers) {
this.command = command;
this.headers = headers;
}
public void setHeader(int index,int value){
headers.setByte(index, value);
}
public void setHeaderShort(int index,int value){
headers.setShort(index, value);
}
public void setPayload(ByteBuf payload){
this.payload = payload;
payload.resetReaderIndex();
}
public ByteBuf getPayload(){
return payload;
}
public int getCommand() {
return command;
}
public boolean isEcm(){
return command == 0x80 || command == 0x81;
}
public boolean isEmm(){
return command >= 0x82 && command <= 0x8F;
}
public boolean isDcw(){
return isEcm() && (payload == null || payload.capacity() == 16);
}
public String readStr(){
StringBuilder build = new StringBuilder();
for(; strReaderIndex < payload.capacity(); strReaderIndex++){
char c = (char) payload.getByte(strReaderIndex);
if(c == 0){
strReaderIndex++;
return build.toString();
}
build.append(c);
}
return build.toString();
}
/**
* @return
*/
public int getSize() {
return payload == null ? 0 : payload.capacity();
}
public ByteBuf getHeaders() {
return headers;
}
}
| 20.478723 | 68 | 0.641039 |
183bd390d7b5a6cbbaf452fb69288ffd0bd29702 | 1,653 | package com.eas.designer.explorer.project;
import java.io.File;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import org.netbeans.spi.search.SearchFilterDefinition;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
/**
* Platypus project's search filter.
*
* @author vv
*/
public final class SearchFilter extends SearchFilterDefinition {
private static final List<String> ignoredPaths = Arrays.asList(new String[] {"web/pwc", "web/pub", "web/META-INF", "web/WEB-INF/lib"});//NOI18N
private final PlatypusProjectImpl project;
private final Path projectPath;
public SearchFilter(PlatypusProjectImpl aProject) {
project = aProject;
projectPath = FileUtil.toFile(project.getProjectDirectory()).toPath();
}
@Override
public boolean searchFile(FileObject fo)
throws IllegalArgumentException {
if (fo.isFolder()) {
throw new java.lang.IllegalArgumentException("File (not folder) expected");//NOI18N
} else {
return !FileUtil.toFile(fo).isHidden();
}
}
@Override
public FolderResult traverseFolder(FileObject fo)
throws IllegalArgumentException {
if (!fo.isFolder()) {
throw new java.lang.IllegalArgumentException("Folder expected");//NOI18N
}
File file = FileUtil.toFile(fo);
String relPath = projectPath.relativize(file.toPath()).toString().replace(File.separator, "/");//NOI18N
return !file.isHidden() && !ignoredPaths.contains(relPath) ? FolderResult.TRAVERSE : FolderResult.DO_NOT_TRAVERSE;
}
}
| 34.4375 | 147 | 0.69026 |
2ff8be19ec5eea0caf08f986322236f4f173028e | 1,028 | package threads.server.utils;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.selection.ItemDetailsLookup;
import androidx.recyclerview.widget.RecyclerView;
public class PinsItemDetailsLookup extends ItemDetailsLookup<Long> {
@NonNull
private final RecyclerView mRecyclerView;
public PinsItemDetailsLookup(@NonNull RecyclerView recyclerView) {
this.mRecyclerView = recyclerView;
}
@Nullable
@Override
public ItemDetails<Long> getItemDetails(@NonNull MotionEvent e) {
View view = mRecyclerView.findChildViewUnder(e.getX(), e.getY());
if (view != null) {
RecyclerView.ViewHolder viewHolder = mRecyclerView.getChildViewHolder(view);
if (viewHolder instanceof PinsViewAdapter.PinsViewHolder) {
return ((PinsViewAdapter.PinsViewHolder) viewHolder).getPinsItemDetails();
}
}
return null;
}
}
| 32.125 | 90 | 0.723735 |
74b4f360645261e053918b7303a6215e9f5e0d76 | 96 |
class RangerParamEventHandler {
public void callback( RangerAppParamDesc param ) {
}
}
| 13.714286 | 52 | 0.71875 |
7a6196e10e912f7d558f074e8e519128bad61b7d | 1,000 | package it.unimib.disco.gruppoade.gamenow.fragments.shared;
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import java.util.ArrayList;
import it.unimib.disco.gruppoade.gamenow.models.PieceOfNews;
import it.unimib.disco.gruppoade.gamenow.repositories.NewsRepository;
public class NewsViewModel extends AndroidViewModel {
private MutableLiveData<ArrayList<PieceOfNews>> news;
public NewsViewModel(@NonNull Application application) {
super(application);
}
public LiveData<ArrayList<PieceOfNews>> getNews() {
if (news == null) {
news = new MutableLiveData<>();
NewsRepository.getInstance(getApplication().getResources()).getNews(news);
}
return news;
}
public void refreshNews(){
NewsRepository.getInstance(getApplication().getResources()).getNews(news);
}
} | 28.571429 | 86 | 0.738 |
fc37607e3351c2457d82cc1f55f9513316462551 | 375 | package cart;
/** Demo file, it may not be correct and/or complete.
* Please watch the corresponding lecture(s) for more explanations.
* @author ashesh
*/
import java.util.ArrayList;
public class ShippingAirTransport implements ShippingOption {
@Override
public double calculateCharges(ArrayList<Item> list) {
// TODO Auto-generated method stub
return 0;
}
}
| 20.833333 | 67 | 0.746667 |
3965d565fd471da2121f597f10b0b12f8517203a | 4,858 | package com.xkzhangsan.time.cron;
import com.xkzhangsan.time.formatter.DateTimeFormatterUtil;
import com.xkzhangsan.time.utils.CollectionUtil;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Cron表达式工具
* <p>
* Cron表达式从左到右(用空格隔开):秒(0~59) 分(0~59) 小时(0~23) 日期(1~31) 月份(1~12的整数或者 JAN-DEC) 星期(1~7的整数或者 SUN-SAT (1=SUN)) 年份(可选,1970~2099)<br>
* 所有字段均可使用特殊字符:, - * / 分别是枚举,范围,任意,间隔<br>
* 日期另外可使用:? L W 分别是任意,最后,有效工作日(周一到周五)<br>
* 星期另外可使用:? L # 分别是任意,最后,每个月第几个星期几<br>
* 常用cron表达式:<br>
* (1)0 0 2 1 * ? * 表示在每月的1日的凌晨2点触发<br>
* (2)0 15 10 ? * MON-FRI 表示周一到周五每天上午10:15执行作业<br>
* (3)0 15 10 ? * 6L 2002-2006 表示2002-2006年的每个月的最后一个星期五上午10:15执行作<br>
* (4)0 0/30 9-17 * * ? 朝九晚五工作时间内每半小时<br>
* (5)0 15 10 L * ? 每月最后一日的上午10:15触发<br>
* (6)0 15 10 ? * 6#3 每月的第三个星期五上午10:15触发<br>
* </p>
* <p>
* Cron表达式工具包含<br>
* 1.验证和格式化Cron表达式方法,isValidExpression和formatExpression<br>
* 2.生成下一个或多个执行时间方法,getNextTime和getNextTimeList<br>
* 3.生成下一个或多个执行时间的日期格式化(yyyy-MM-dd HH:mm:ss)方法,getNextTimeStr和getNextTimeStrList<br>
* 4.对比Cron表达式下一个执行时间是否与指定date相等方法,isSatisfiedBy<br>
* </p>
* @author xkzhangsan
*
*使用 quartz CronExpression
*/
public class CronExpressionUtil {
private CronExpressionUtil(){
}
/**
* 验证Cron表达式
* @param cronExpression Cron表达式
* @return boolean
*/
public static boolean isValidExpression(String cronExpression){
return CronExpression.isValidExpression(cronExpression);
}
/**
* 格式化Cron表达式
* @param cronExpression Cron表达式
* @return String
*/
public static String formatExpression(String cronExpression){
try {
return new CronExpression(cronExpression).toString();
} catch (ParseException e) {
throw new RuntimeException(e.getMessage());
}
}
/**
* 生成下一个执行时间
* @param cronExpression Cron表达式
* @param date 日期
* @return Date
*/
public static Date getNextTime(String cronExpression, Date date){
try {
if(date != null){
return new CronExpression(cronExpression).getNextValidTimeAfter(date);
}else{
return new CronExpression(cronExpression).getNextValidTimeAfter(new Date());
}
} catch (ParseException e) {
throw new RuntimeException(e.getMessage());
}
}
/**
* 生成下一个执行时间
* @param cronExpression Cron表达式
* @return Date
*/
public static Date getNextTime(String cronExpression){
return getNextTime(cronExpression, null);
}
/**
* 生成下一个执行时间的日期格式化
* @param cronExpression Cron表达式
* @param date 日期
* @return String 返回格式化时间 yyyy-MM-dd HH:mm:ss
*/
public static String getNextTimeStr(String cronExpression, Date date){
return DateTimeFormatterUtil.formatToDateTimeStr(getNextTime(cronExpression, date));
}
/**
* 生成下一个执行时间的日期格式化
* @param cronExpression Cron表达式
* @return String 返回格式化时间 yyyy-MM-dd HH:mm:ss
*/
public static String getNextTimeStr(String cronExpression){
return getNextTimeStr(cronExpression, null);
}
/**
* 生成多个执行时间
* @param cronExpression Cron表达式
* @param date 日期
* @param num 数量
* @return 时间列表
*/
public static List<Date> getNextTimeList(String cronExpression, Date date, int num){
List<Date> dateList = new ArrayList<>();
if(num < 1){
throw new RuntimeException("num must be greater than 0");
}
Date startDate = date != null ? date : new Date();
for(int i=0; i<num; i++){
startDate = getNextTime(cronExpression, startDate);
if(startDate != null){
dateList.add(startDate);
}
}
return dateList;
}
/**
* 生成多个执行时间
* @param cronExpression Cron表达式
* @param num 数量
* @return 时间列表
*/
public static List<Date> getNextTimeList(String cronExpression, int num){
return getNextTimeList(cronExpression, null, num);
}
/**
* 生成多个执行时间的日期格式化
* @param cronExpression Cron表达式
* @param date 日期
* @param num 数量
* @return 返回格式化时间列表 yyyy-MM-dd HH:mm:ss
*/
public static List<String> getNextTimeStrList(String cronExpression, Date date, int num){
List<String> dateStrList = new ArrayList<>();
List<Date> dateList = getNextTimeList(cronExpression, date, num);
if(CollectionUtil.isNotEmpty(dateList)){
dateList.stream().forEach(d->{
String dateStr = DateTimeFormatterUtil.formatToDateTimeStr(d);
dateStrList.add(dateStr);
});
}
return dateStrList;
}
/**
* 生成多个执行时间的日期格式化
* @param cronExpression Cron表达式
* @param num 数量
* @return 返回格式化时间列表 yyyy-MM-dd HH:mm:ss
*/
public static List<String> getNextTimeStrList(String cronExpression, int num){
return getNextTimeStrList(cronExpression, null, num);
}
/**
* 对比Cron表达式下一个执行时间是否与指定date相等
* @param cronExpression Cron表达式
* @param date 日期
* @return boolean
*/
public static boolean isSatisfiedBy(String cronExpression, Date date){
try {
return new CronExpression(cronExpression).isSatisfiedBy(date);
} catch (ParseException e) {
throw new RuntimeException(e.getMessage());
}
}
}
| 26.11828 | 127 | 0.702964 |
e25db1810db0fe4514f9ead12caf4e0be1b8b746 | 2,337 | package com.lc.dfs;
import java.util.HashSet;
import java.util.Set;
public class NumIslandsUnionFind {
private static int height;
private static int width;
private static int count;
private static int[] parent;
private static Set<Integer> set;
public static int numIslands(char[][] grid) {
height = grid.length;
if (height == 0) return 0;
width = grid[0].length;
count = 0;
parent = new int[height * width];
set = new HashSet<>();
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (grid[i][j] == '1') {
parent[i * width + j] = i * width + j;
} else {
parent[i * width + j] = -1;
}
}
}
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (grid[i][j] == '0') continue;
grid[i][j] = '0';
if (j + 1 < width && grid[i][j + 1] == '1') {
union(i * width + j, i * width + j + 1);
}
if (i + 1 < height && grid[i + 1][j] == '1') {
union(i * width + j, (i + 1) * width + j);
}
}
}
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
int index = i * width + j;
if (parent[index] == -1) continue;
parent[index] = find(index);
if (!set.contains(parent[index])) {
set.add(parent[index]);
count++;
}
}
}
return count;
}
public static int find(int n) {
while (parent[n] != n) n = parent[n];
return n;
}
public static void union(int v, int w) {
int vRoot = find(v);
int wRoot = find(w);
if (vRoot != wRoot) {
parent[vRoot] = wRoot;
}
}
//[["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]]
public static void main(String[] args) {
char[][] arr = {{'1', '1', '1', '1', '0'}, {'1', '1', '0', '1', '0'}, {'1', '1', '0', '0', '0'}, {'0', '0', '0', '0', '0'}};
System.out.println(numIslands(arr));
}
}
| 30.350649 | 132 | 0.389816 |
cd3c07e513c77b4eb6dc3ede782951c0166bb744 | 911 | package prototype;
import java.util.ArrayList;
public class PrototypeDemo {
static void plotShapeFamily(Shape prototype, int fromSize, int toSize) {
for (int size=fromSize; size<toSize; ++size) {
Shape shape = prototype.clone();
shape.setSize(size);
shape.plot();
}
}
static void simpleTest() {
Shape s = new Square(5,"blue");
plotShapeFamily(s, 10,20);
plotShapeFamily(new Triangle(6,"green"), 10,20);
s.plot();
}
static void complexTest() {
SquareList prototype = new SquareList(new ArrayList<Square>());
prototype.addSquare(new Square(5,"green"));
prototype.plot();
System.out.println();
SquareList c = (SquareList)prototype.clone();
c.addSquare(new Square(10,"green"));
c.getSquares().get(0).setSize(100);
c.plot();
System.out.println();
prototype.plot();
System.out.println();
}
public static void main(String[] args) {
complexTest();
}
}
| 22.219512 | 73 | 0.673985 |
121eab5970548998b77f440f3abffb36475b75d2 | 1,305 | package fhscs.snake;
import java.awt.Point;
/**
* Represents the board that the snake game plays on,
* a grid of squares.
*
* The bottom-left corner is (1,1), the top-right corner is (width, height)
*/
public interface Board {
/**
*
* @return the number of squares in the horizontal movement
*/
int getWidth();
/**
*
* @return the number of squares in the vertical movement
*/
int getHeight();
/**
* Checks whether a point is outside the grid or not.
*
* @param point the point to check
* @return true if the point is outside of the grid, false otherwise
*/
boolean isOutside(Point point);
/**
*
* @param score
*/
void setScore(int score);
/**
*
* @param incerase score by this amount
*/
void incrementScore(int amount);
/**
* increase score
*/
void incrementScore();
/**
*
* @return score
*/
int getScore();
/**
*
* @return high score
*/
int getHighScore();
/**
* set the value of the high score
*/
void setHighScore(int score);
/**
*
* @param Score
*/
void logScore(int Score);
/**
*
* @return
*/
int readScoreLog();
}
| 16.518987 | 75 | 0.529502 |
8114886372461329244adc654860651e4d3a3af9 | 10,664 | /*
* Copyright (C) 2013 Square, Inc.
*
* 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.squareup.picasso;
import android.app.Notification;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.net.NetworkInfo;
import android.net.Uri;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.RemoteViews;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import static android.content.ContentResolver.SCHEME_ANDROID_RESOURCE;
import static android.graphics.Bitmap.Config.ARGB_8888;
import static android.provider.ContactsContract.Contacts.CONTENT_URI;
import static android.provider.ContactsContract.Contacts.Photo.CONTENT_DIRECTORY;
import static com.squareup.picasso.Picasso.LoadedFrom.MEMORY;
import static com.squareup.picasso.Picasso.Priority;
import static com.squareup.picasso.Utils.createKey;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class TestUtils {
static final Answer<Object> TRANSFORM_REQUEST_ANSWER = new Answer<Object>() {
@Override public Object answer(InvocationOnMock invocation) throws Throwable {
return invocation.getArguments()[0];
}
};
static final Uri URI_1 = Uri.parse("http://example.com/1.png");
static final Uri URI_2 = Uri.parse("http://example.com/2.png");
static final String STABLE_1 = "stableExampleKey1";
static final String URI_KEY_1 = createKey(new Request.Builder(URI_1).build());
static final String URI_KEY_2 = createKey(new Request.Builder(URI_2).build());
static final String STABLE_URI_KEY_1 = createKey(new Request.Builder(URI_1).stableKey(STABLE_1).build());
static final File FILE_1 = new File("C:\\windows\\system32\\logo.exe");
static final String FILE_KEY_1 = createKey(new Request.Builder(Uri.fromFile(FILE_1)).build());
static final Uri FILE_1_URL = Uri.parse("file:///" + FILE_1.getPath());
static final Uri FILE_1_URL_NO_AUTHORITY = Uri.parse("file:/" + FILE_1.getParent());
static final Uri MEDIA_STORE_CONTENT_1_URL = Uri.parse("content://media/external/images/media/1");
static final String MEDIA_STORE_CONTENT_KEY_1 =
createKey(new Request.Builder(MEDIA_STORE_CONTENT_1_URL).build());
static final Uri CONTENT_1_URL = Uri.parse("content://zip/zap/zoop.jpg");
static final String CONTENT_KEY_1 = createKey(new Request.Builder(CONTENT_1_URL).build());
static final Uri CONTACT_URI_1 = CONTENT_URI.buildUpon().appendPath("1234").build();
static final String CONTACT_KEY_1 = createKey(new Request.Builder(CONTACT_URI_1).build());
static final Uri CONTACT_PHOTO_URI_1 =
CONTENT_URI.buildUpon().appendPath("1234").appendPath(CONTENT_DIRECTORY).build();
static final String CONTACT_PHOTO_KEY_1 =
createKey(new Request.Builder(CONTACT_PHOTO_URI_1).build());
static final int RESOURCE_ID_1 = 1;
static final String RESOURCE_ID_KEY_1 = createKey(new Request.Builder(RESOURCE_ID_1).build());
static final Uri ASSET_URI_1 = Uri.parse("file:///android_asset/foo/bar.png");
static final String ASSET_KEY_1 = createKey(new Request.Builder(ASSET_URI_1).build());
static final String RESOURCE_PACKAGE = "com.squareup.picasso";
static final String RESOURCE_TYPE = "drawable";
static final String RESOURCE_NAME = "foo";
static final Uri RESOURCE_ID_URI = new Uri.Builder().scheme(SCHEME_ANDROID_RESOURCE)
.authority(RESOURCE_PACKAGE)
.appendPath(Integer.toString(RESOURCE_ID_1))
.build();
static final String RESOURCE_ID_URI_KEY = createKey(new Request.Builder(RESOURCE_ID_URI).build());
static final Uri RESOURCE_TYPE_URI = new Uri.Builder().scheme(SCHEME_ANDROID_RESOURCE)
.authority(RESOURCE_PACKAGE)
.appendPath(RESOURCE_TYPE)
.appendPath(RESOURCE_NAME)
.build();
static final String RESOURCE_TYPE_URI_KEY =
createKey(new Request.Builder(RESOURCE_TYPE_URI).build());
static final Uri CUSTOM_URI = Uri.parse("foo://bar");
static final String CUSTOM_URI_KEY = createKey(new Request.Builder(CUSTOM_URI).build());
static Context mockPackageResourceContext() {
Context context = mock(Context.class);
PackageManager pm = mock(PackageManager.class);
Resources res = mock(Resources.class);
doReturn(pm).when(context).getPackageManager();
try {
doReturn(res).when(pm).getResourcesForApplication(RESOURCE_PACKAGE);
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException(e);
}
doReturn(RESOURCE_ID_1).when(res).getIdentifier(RESOURCE_NAME, RESOURCE_TYPE, RESOURCE_PACKAGE);
return context;
}
static Action mockAction(String key, Uri uri) {
return mockAction(key, uri, null, 0, null, null);
}
static Action mockAction(String key, Uri uri, Object target) {
return mockAction(key, uri, target, 0, null, null);
}
static Action mockAction(String key, Uri uri, Priority priority) {
return mockAction(key, uri, null, 0, priority, null);
}
static Action mockAction(String key, Uri uri, String tag) {
return mockAction(key, uri, null, 0, null, tag);
}
static Action mockAction(String key, Uri uri, Object target, String tag) {
return mockAction(key, uri, target, 0, null, tag);
}
static Action mockAction(String key, Uri uri, Object target, int resourceId) {
return mockAction(key, uri, target, resourceId, null, null);
}
static Action mockAction(String key, Uri uri, Object target, int resourceId, Priority priority,
String tag) {
Request request = new Request.Builder(uri, resourceId, ARGB_8888).build();
return mockAction(key, request, target, priority, tag);
}
static Action mockAction(String key, Request request) {
return mockAction(key, request, null, null, null);
}
static Action mockAction(String key, Request request, Object target, Priority priority,
String tag) {
Action action = mock(Action.class);
when(action.getKey()).thenReturn(key);
when(action.getRequest()).thenReturn(request);
when(action.getTarget()).thenReturn(target);
when(action.getPriority()).thenReturn(priority != null ? priority : Priority.NORMAL);
when(action.getTag()).thenReturn(tag != null ? tag : action);
Picasso picasso = mockPicasso();
when(action.getPicasso()).thenReturn(picasso);
return action;
}
static Action mockCanceledAction() {
Action action = mock(Action.class);
action.cancelled = true;
when(action.isCancelled()).thenReturn(true);
return action;
}
static ImageView mockImageViewTarget() {
return mock(ImageView.class);
}
static RemoteViews mockRemoteViews() {
return mock(RemoteViews.class);
}
static Notification mockNotification() {
return mock(Notification.class);
}
static ImageView mockFitImageViewTarget(boolean alive) {
ViewTreeObserver observer = mock(ViewTreeObserver.class);
when(observer.isAlive()).thenReturn(alive);
ImageView mock = mock(ImageView.class);
when(mock.getViewTreeObserver()).thenReturn(observer);
return mock;
}
static Target mockTarget() {
return mock(Target.class);
}
static RemoteViewsAction.RemoteViewsTarget mockRemoteViewsTarget() {
return mock(RemoteViewsAction.RemoteViewsTarget.class);
}
static Callback mockCallback() {
return mock(Callback.class);
}
static DeferredRequestCreator mockDeferredRequestCreator() {
return mock(DeferredRequestCreator.class);
}
static NetworkInfo mockNetworkInfo() {
return mockNetworkInfo(false);
}
static NetworkInfo mockNetworkInfo(boolean isConnected) {
NetworkInfo mock = mock(NetworkInfo.class);
when(mock.isConnected()).thenReturn(isConnected);
when(mock.isConnectedOrConnecting()).thenReturn(isConnected);
return mock;
}
static InputStream mockInputStream() throws IOException {
return mock(InputStream.class);
}
static BitmapHunter mockHunter(String key, Bitmap result, boolean skipCache) {
return mockHunter(key, result, skipCache, null);
}
static BitmapHunter mockHunter(String key, Bitmap result, boolean skipCache, Action action) {
int memoryPolicy = skipCache ? MemoryPolicy.NO_STORE.index | MemoryPolicy.NO_CACHE.index : 0;
return mockHunter(key, result, memoryPolicy, action);
}
static BitmapHunter mockHunter(String key, Bitmap result, int memoryPolicy, Action action) {
Request data = new Request.Builder(URI_1).build();
BitmapHunter hunter = mock(BitmapHunter.class);
when(hunter.getKey()).thenReturn(key);
when(hunter.getResult()).thenReturn(result);
when(hunter.getData()).thenReturn(data);
when(hunter.getMemoryPolicy()).thenReturn(memoryPolicy);
when(hunter.getAction()).thenReturn(action);
Picasso picasso = mockPicasso();
when(hunter.getPicasso()).thenReturn(picasso);
return hunter;
}
static Picasso mockPicasso() {
// Mock a RequestHandler that can handle any request.
RequestHandler requestHandler = mock(RequestHandler.class);
try {
Bitmap defaultResult = makeBitmap();
RequestHandler.Result result = new RequestHandler.Result(defaultResult, MEMORY);
when(requestHandler.load(any(Request.class), anyInt())).thenReturn(result);
when(requestHandler.canHandleRequest(any(Request.class))).thenReturn(true);
} catch (IOException e) {
throw new RuntimeException(e);
}
return mockPicasso(requestHandler);
}
static Picasso mockPicasso(RequestHandler requestHandler) {
Picasso picasso = mock(Picasso.class);
when(picasso.getRequestHandlers()).thenReturn(Arrays.asList(requestHandler));
return picasso;
}
static Bitmap makeBitmap() {
return makeBitmap(10, 10);
}
static Bitmap makeBitmap(int width, int height) {
return Bitmap.createBitmap(width, height, null);
}
private TestUtils() {
}
}
| 38.919708 | 107 | 0.74156 |
bdc890514db4c80153d9aadac5a35b17fa4af8d3 | 212 | package com.trunk.joda.clock;
import org.joda.time.DateTime;
/**
* A shim to allow the injection of time into objects that depend on
* {@link DateTime#now()}.
*/
public interface Clock {
DateTime now();
}
| 17.666667 | 68 | 0.698113 |
0f18ffd480480e08c73759a7e85de2342a9abbfb | 356 | package com.example.flight.application.web.model;
import com.example.flight.domain.model.BuyTicketInput;
import lombok.Data;
import java.util.UUID;
@Data
public class BuyTicketRequest {
private UUID ticketId;
private UUID customerId;
public BuyTicketInput toBuyTicketInput() {
return new BuyTicketInput(this.ticketId, this.customerId);
}
}
| 20.941176 | 62 | 0.783708 |
71d115d7a7186b3c8f2f492c41415196af4dcc86 | 3,916 | /**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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 io.gravitee.rest.api.portal.rest.resource;
import io.gravitee.common.http.MediaType;
import io.gravitee.repository.management.api.search.UserCriteria;
import io.gravitee.rest.api.model.UserEntity;
import io.gravitee.rest.api.model.common.PageableImpl;
import io.gravitee.rest.api.model.permissions.RolePermission;
import io.gravitee.rest.api.portal.rest.mapper.UserMapper;
import io.gravitee.rest.api.portal.rest.model.FinalizeRegistrationInput;
import io.gravitee.rest.api.portal.rest.model.RegisterUserInput;
import io.gravitee.rest.api.portal.rest.model.User;
import io.gravitee.rest.api.portal.rest.resource.param.PaginationParam;
import io.gravitee.rest.api.portal.rest.security.Permission;
import io.gravitee.rest.api.portal.rest.security.Permissions;
import io.gravitee.rest.api.service.UserService;
import javax.inject.Inject;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import java.util.List;
import java.util.stream.Collectors;
import static io.gravitee.rest.api.model.permissions.RolePermissionAction.READ;
/**
* @author Florent CHAMFROY (florent.chamfroy at graviteesource.com)
* @author GraviteeSource Team
*/
public class UsersResource extends AbstractResource {
@Inject
private UserMapper userMapper;
@Inject
private UserService userService;
@GET
@Produces(MediaType.APPLICATION_JSON)
@Permissions({ @Permission(value = RolePermission.MANAGEMENT_USERS, acls = READ) })
public Response getUsers(@BeanParam PaginationParam paginationParam) {
UserCriteria criteria = new UserCriteria.Builder().build();
List<User> users = userService
.search(criteria, new PageableImpl(paginationParam.getPage(), paginationParam.getSize())).getContent()
.stream().map(userMapper::convert).collect(Collectors.toList());
// No pagination, because userService did it already
return createListResponse(users, paginationParam, false);
}
/**
* Register a new user. Generate a token and send it in an email to allow a user
* to create an account.
*/
@POST
@Path("/registration")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response registerUser(@Valid @NotNull(message = "Input must not be null.") RegisterUserInput registerUserInput) {
UserEntity newUser = userService.register(userMapper.convert(registerUserInput), registerUserInput.getConfirmationPageUrl());
if (newUser != null) {
return Response.ok().entity(userMapper.convert(newUser)).build();
}
return Response.serverError().build();
}
@POST
@Path("/registration/_finalize")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response finalizeRegistration(@Valid @NotNull(message = "Input must not be null.") FinalizeRegistrationInput finalizeRegistrationInput) {
UserEntity newUser = userService.finalizeRegistration(userMapper.convert(finalizeRegistrationInput));
if (newUser != null) {
return Response.ok().entity(userMapper.convert(newUser)).build();
}
return Response.serverError().build();
}
}
| 39.959184 | 148 | 0.741318 |
81303325873d20eb78ce8ddc4461620d858563e7 | 454 | package model.command.zeroParameter.turtle;
import model.command.AbstractCommand;
import model.command.zeroParameter.IZeroParameterCommand;
import java.util.List;
public class Turtles extends AbstractCommandZeroParameterTurtle implements IZeroParameterCommand {
public Turtles (List<AbstractCommand> parameters) {
super(parameters);
}
public double turtleExecute() {
return getTurtles().getAllTurtleIDs().size();
}
}
| 25.222222 | 98 | 0.76652 |
3aa34db7f73a284578a96a9d85ad106c1fbba721 | 44,505 | package com.angadi.tripmanagementa.Activities;
import android.Manifest;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.location.Address;
import android.location.Geocoder;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.andexert.library.RippleView;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.angadi.tripmanagementa.Application.TripManagement;
import com.angadi.tripmanagementa.Custum.Blocker;
import com.angadi.tripmanagementa.Custum.GPSTracker;
import com.angadi.tripmanagementa.Extras.Keys;
import com.angadi.tripmanagementa.Fragments.LocationSearchFragment;
import com.angadi.tripmanagementa.Model.SignUpArray;
import com.angadi.tripmanagementa.R;
import com.crashlytics.android.Crashlytics;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;
import com.hbb20.CountryCodePicker;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.fabric.sdk.android.Fabric;
import io.intercom.android.sdk.Intercom;
import io.intercom.android.sdk.identity.Registration;
import com.android.volley.Response;
import static com.angadi.tripmanagementa.Activities.MapsActivity.REQUEST_CHECK_SETTINGS;
public class RegistrationActivity extends AppCompatActivity
{
Spinner spinner_state,spinner_city;
RelativeLayout bottom_otp_security;
private long mLastClickTime = 0;
boolean GpsStatus;
GPSTracker gps;
double latitude ;
double longitude;
String term_cond,devicetoken;
TextView TVClose,TV_Invali;
Dialog dialog_invalid_qr;
EditText nameEdittext,emailEdittext,mobileEdittext,passwordEdittext,conformpasswordEdittext,upldadharEdittext,addressEdittext;
CountryCodePicker ccp;
EditText cityEdittext,stateEdittext;
ArrayList<String> list_state = new ArrayList<>();
ArrayList<String> list_city = new ArrayList<>();
int count = 0;
ArrayList<SignUpArray> a1;
ProgressDialog dialog;
RequestQueue requestQueue;
LocationManager locationManager;
@BindView(R.id.RippleCreateAccount) RippleView RippleCreateAccount;
// @BindView(R.id.bottom) RelativeLayout bottom;
//@BindView(R.id.create_account_button) Button create_account_button;
@BindView(R.id.LinLayoutcamera) LinearLayout LinLayoutcamera;
@BindView(R.id.TextViewLogin) TextView TextViewLogin;
@BindView(R.id.nameTV) TextView nameTV;
@BindView(R.id.nameEdLinLayout) LinearLayout nameEdLinLayout;
@BindView(R.id.nameView) View nameView;
@BindView(R.id.nameImageView) ImageView nameImageView;
@BindView(R.id.emailimageView) ImageView emailimageView;
@BindView(R.id.pswrdImageView) ImageView pswrdImageView;
@BindView(R.id.confirmpswrdImageView) ImageView confirmpswrdImageView;
@BindView(R.id.upldadharImageView) ImageView upldadharImageView;
@BindView(R.id.addressImageView) ImageView addressImageView;
@BindView(R.id.cityimageView) ImageView cityimageView;
@BindView(R.id.stateimageView) ImageView stateimageView;
@BindView(R.id.emailTV) TextView emailTV;
@BindView(R.id.mobileTV) TextView mobileTV;
@BindView(R.id.passwordTV) TextView passwordTV;
@BindView(R.id.confirmpasswordTV) TextView confirmpasswordTV;
@BindView(R.id.upldadharTV) TextView upldadharTV;
@BindView(R.id.addressTV) TextView addressTV;
@BindView(R.id.cityTV) TextView cityTV;
@BindView(R.id.stateTV) TextView stateTV;
//confirmpasswordEdLinLayout
@BindView(R.id.emailEdLinLayout) LinearLayout emailEdLinLayout;
@BindView(R.id.mobileEdLinLayout) LinearLayout mobileEdLinLayout;
@BindView(R.id.passwordEdLinLayout) LinearLayout passwordEdLinLayout;
@BindView(R.id.confirmpasswordEdLinLayout) LinearLayout confirmpasswordEdLinLayout;
//addressView
@BindView(R.id.emailView) View emailView;
@BindView(R.id.mobileView) View mobileView;
@BindView(R.id.passwordView) View passwordView;
@BindView(R.id.confirmpasswordView) View confirmpasswordView;
@BindView(R.id.upldAdharView) View upldAdharView;
@BindView(R.id.addressView) View addressView;
@BindView(R.id.cityView) View cityView;
@BindView(R.id.stateView) View stateView;
@BindView(R.id.Scroll) ScrollView Scroll;
@BindView(R.id.RelLayoutFirst) RelativeLayout RelLayoutFirst;
@BindView(R.id.LinlayoutMale) LinearLayout LinlayoutMale;
@BindView(R.id.LinLayoutFemale) LinearLayout LinLayoutFemale;
@BindView(R.id.ImagevieFemale) ImageView ImagevieFemale;
@BindView(R.id.ImageviewMale) ImageView ImageviewMale;
@BindView(R.id.TextviewTermsCond) TextView TextviewTermsCond;
@BindView(R.id.TextviewIndicationForRegister) TextView TextviewIndicationForRegister;
@BindView(R.id.TextViewIndicationForGender) TextView TextViewIndicationForGender;
@BindView(R.id.TextViewIndicationForMale) TextView TextViewIndicationForMale;
@BindView(R.id.TextViewIndicationForFeMale) TextView TextViewIndicationForFeMale;
@BindView(R.id.TextViewIndicationForState) TextView TextViewIndicationForState;
@BindView(R.id.text_state) TextView text_state;
@BindView(R.id.TextViewIndicationForCity) TextView TextViewIndicationForCity;
@BindView(R.id.text_city) TextView text_city;
@BindView(R.id.terms) TextView terms;
@BindView(R.id.Alreadyhaveanacoount) TextView Alreadyhaveanacoount;
@BindView(R.id.create_account_button) Button create_account_button;
@BindView(R.id.LinlayoutTerms) LinearLayout LinlayoutTerms;
@BindView(R.id.mCheckbox) CheckBox mCheckbox;
@BindView(R.id.LinlayoutSingleMale) LinearLayout LinlayoutSingleMale;
@BindView(R.id.LinlayoutSingleFeMale) LinearLayout LinlayoutSingleFeMale;
@BindView(R.id.LinlayoutBothGender) LinearLayout LinlayoutBothGender;
@BindView(R.id.RellayoutEditFemale) RelativeLayout RellayoutEditFemale;
@BindView(R.id.RellayoutEditMale) RelativeLayout RellayoutEditMale;
ProgressDialog progressDialog;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_registration);
ButterKnife.bind(this);
Fabric.with(this, new Crashlytics());
Typeface montserrat_bold = Typeface.createFromAsset(getAssets(), "fonts/MONTSERRAT-BOLD.OTF");
Typeface montserrat_regular = Typeface.createFromAsset(getAssets(), "fonts/Montserrat-Regular.ttf");
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
@Override
public void onComplete(@NonNull Task<InstanceIdResult> task) {
if (!task.isSuccessful()) {
return;
}
// Get new Instance ID token
devicetoken = task.getResult().getToken();
Log.e("Token-->",devicetoken);
// Log and toast
// String msg = getString(R.string.msg_token_fmt, token);
// Log.d(TAG, msg);
// Toast.makeText(HomeActivity.this, msg, Toast.LENGTH_SHORT).show();
}
});
gps = new GPSTracker(this);
latitude = gps.getLatitude();
longitude = gps.getLongitude();
ImageviewMale.setImageResource(R.mipmap.radio_button_unselected);
ImagevieFemale.setImageResource(R.mipmap.radio_button_unselected);
nameEdittext = (EditText)findViewById(R.id.nameEdittext);
emailEdittext = (EditText)findViewById(R.id.emailEdittext);
mobileEdittext = (EditText)findViewById(R.id.mobileEdittext);
passwordEdittext = (EditText)findViewById(R.id.passwordEdittext);
conformpasswordEdittext = (EditText)findViewById(R.id.conformpasswordEdittext);
cityEdittext = (EditText)findViewById(R.id.cityEdittext);
stateEdittext = (EditText)findViewById(R.id.stateEdittext);
upldadharEdittext = (EditText)findViewById(R.id.upldadharEdittext);
addressEdittext = (EditText)findViewById(R.id.addressEdittext);
ccp = (CountryCodePicker)findViewById(R.id.ccp);
requestQueue = Volley.newRequestQueue(this);
WelcomeActivity.btnNext.setVisibility(View.GONE);
WelcomeActivity.btnSkip.setVisibility(View.GONE);
dialog = new ProgressDialog(this);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
dialog_invalid_qr = new Dialog(RegistrationActivity.this);
dialog_invalid_qr.setContentView(R.layout.layout_alert_dialog);
TVClose = (TextView) dialog_invalid_qr.findViewById(R.id.TVClose);
TV_Invali = (TextView) dialog_invalid_qr.findViewById(R.id.TV_Invali);
TVClose.setTypeface(montserrat_regular);
TV_Invali.setTypeface(montserrat_regular);
dialog_invalid_qr.setCanceledOnTouchOutside(false);
TVClose.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
dialog_invalid_qr.dismiss();
}
});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
Window window = this.getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(ContextCompat.getColor(this,R.color.black));
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
== PackageManager.PERMISSION_DENIED)
{
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.CAMERA}, 100);
}
TextviewIndicationForRegister.setTypeface(montserrat_bold);
TextViewIndicationForGender.setTypeface(montserrat_regular);
TextViewIndicationForMale.setTypeface(montserrat_regular);
TextViewIndicationForFeMale.setTypeface(montserrat_regular);
nameTV.setTypeface(montserrat_regular);
emailTV.setTypeface(montserrat_regular);
emailEdittext.setTypeface(montserrat_regular);
mobileTV.setTypeface(montserrat_regular);
mobileEdittext.setTypeface(montserrat_regular);
passwordTV.setTypeface(montserrat_regular);
passwordEdittext.setTypeface(montserrat_regular);
confirmpasswordTV.setTypeface(montserrat_regular);
conformpasswordEdittext.setTypeface(montserrat_regular);
TextViewIndicationForState.setTypeface(montserrat_regular);
text_state.setTypeface(montserrat_regular);
TextViewIndicationForCity.setTypeface(montserrat_regular);
text_city.setTypeface(montserrat_regular);
addressTV.setTypeface(montserrat_regular);
addressEdittext.setTypeface(montserrat_regular);
terms.setTypeface(montserrat_regular);
TextviewTermsCond.setTypeface(montserrat_regular);
Alreadyhaveanacoount.setTypeface(montserrat_regular);
TextViewLogin.setTypeface(montserrat_regular);
create_account_button.setTypeface(montserrat_regular);
nameEdittext.setTypeface(montserrat_regular);
cityTV.setTypeface(montserrat_regular);
stateTV.setTypeface(montserrat_regular);
mCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b)
{
if (mCheckbox.isChecked())
{
term_cond = "1";
}
else
{
term_cond = "0";
}
}
});
ShowEditTextsFunctions();
Scroll.fullScroll(View.FOCUS_DOWN);
InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
if (getCurrentFocus() != null)
{
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
GPSStatus();
if (GpsStatus == true)
{
setaddress(latitude,longitude);
}
else
{
displayLocationSettingsRequest(this);
}
}
@OnClick(R.id.LinLayoutcamera)
public void setLinLayoutcamera()
{
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivity(intent);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 100) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(RegistrationActivity.this, "camera permission granted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(RegistrationActivity.this, "camera permission denied", Toast.LENGTH_LONG).show();
}
}
}
public void ShowEditTextsFunctions()
{
// nameEditText
nameEdittext.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int start, int count, int after)
{
}
@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count)
{
if (count>0)
{
nameImageView.setImageResource(R.mipmap.profile_blue_icon);
nameView.setVisibility(View.INVISIBLE);
nameEdittext.setCursorVisible(true);
}
else if (count==0 && nameEdittext.getText().toString().length()==0)
{
nameImageView.setImageResource(R.mipmap.profile_orange_icon);
nameView.setVisibility(View.VISIBLE);
nameEdittext.setCursorVisible(false);
}
}
@Override
public void afterTextChanged(Editable editable)
{
if (nameEdittext.getText().toString().length()==0)
{
nameImageView.setImageResource(R.mipmap.profile_orange_icon);
nameView.setVisibility(View.VISIBLE);
nameEdittext.setCursorVisible(false);
}
}
});
//EmailEditText
emailEdittext.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2)
{
}
@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count)
{
if (count>0)
{
emailimageView.setImageResource(R.mipmap.envolope_blue_icon);
emailView.setVisibility(View.INVISIBLE);
emailEdittext.setCursorVisible(true);
}
else if (count==0 && emailEdittext.getText().toString().length()==0)
{
emailimageView.setImageResource(R.mipmap.envolope_orange_icon);
emailView.setVisibility(View.VISIBLE);
emailEdittext.setCursorVisible(false);
}
}
@Override
public void afterTextChanged(Editable editable)
{
if (emailEdittext.getText().toString().length()==0)
{
emailimageView.setImageResource(R.mipmap.envolope_orange_icon);
emailView.setVisibility(View.VISIBLE);
emailEdittext.setCursorVisible(false);
}
}
});
conformpasswordEdittext.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2)
{
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2)
{
if (i2>0)
{
confirmpswrdImageView.setImageResource(R.mipmap.password_blue_icon);
confirmpasswordView.setVisibility(View.INVISIBLE);
conformpasswordEdittext.setCursorVisible(true);
}
else if (i2==0 && conformpasswordEdittext.getText().toString().length()==0)
{
confirmpswrdImageView.setImageResource(R.mipmap.orange_password_icon);
confirmpasswordView.setVisibility(View.VISIBLE);
conformpasswordEdittext.setCursorVisible(false);
}
}
@Override
public void afterTextChanged(Editable editable)
{
if (conformpasswordEdittext.getText().toString().length()==0)
{
confirmpswrdImageView.setImageResource(R.mipmap.orange_password_icon);
confirmpasswordView.setVisibility(View.VISIBLE);
conformpasswordEdittext.setCursorVisible(false);
}
}
});
//PasswordEditText
passwordEdittext.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2)
{
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2)
{
if (i2>0)
{
pswrdImageView.setImageResource(R.mipmap.password_blue_icon);
passwordView.setVisibility(View.INVISIBLE);
passwordEdittext.setCursorVisible(true);
}
else if (i2==0 && passwordEdittext.length()==0)
{
pswrdImageView.setImageResource(R.mipmap.orange_password_icon);
passwordView.setVisibility(View.VISIBLE);
passwordEdittext.setCursorVisible(false);
}
}
@Override
public void afterTextChanged(Editable editable)
{
if (passwordEdittext.length()==0)
{
pswrdImageView.setImageResource(R.mipmap.orange_password_icon);
passwordView.setVisibility(View.VISIBLE);
passwordEdittext.setCursorVisible(false);
}
}
});
//AddressEditText
addressEdittext.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2)
{
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2)
{
if (i2>0)
{
addressImageView.setImageResource(R.mipmap.location_blue_icon);
addressView.setVisibility(View.INVISIBLE);
addressEdittext.setCursorVisible(true);
}
else if (i2==0 && addressEdittext.getText().toString().length()==0)
{
addressImageView.setImageResource(R.mipmap.location_orange_icon);
addressView.setVisibility(View.VISIBLE);
addressEdittext.setCursorVisible(false);
}
}
@Override
public void afterTextChanged(Editable editable)
{
if (addressEdittext.getText().toString().length()==0)
{
addressImageView.setImageResource(R.mipmap.location_orange_icon);
addressView.setVisibility(View.VISIBLE);
addressEdittext.setCursorVisible(false);
}
}
});
//stateEdittExt
stateEdittext.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2)
{
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2)
{
if (i2>0)
{
stateimageView.setImageResource(R.mipmap.location_blue_icon);
stateView.setVisibility(View.INVISIBLE);
stateEdittext.setCursorVisible(true);
}
else if (i2==0 && stateEdittext.getText().toString().length()==0)
{
stateimageView.setImageResource(R.mipmap.location_orange_icon);
stateView.setVisibility(View.VISIBLE);
stateEdittext.setCursorVisible(false);
}
}
@Override
public void afterTextChanged(Editable editable)
{
if (stateEdittext.getText().toString().length()==0)
{
stateimageView.setImageResource(R.mipmap.location_orange_icon);
stateView.setVisibility(View.VISIBLE);
stateEdittext.setCursorVisible(false);
}
}
});
//CityEcitText
cityEdittext.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2)
{
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2)
{
if (i2>0)
{
cityimageView.setImageResource(R.mipmap.location_blue_icon);
cityView.setVisibility(View.INVISIBLE);
cityEdittext.setCursorVisible(true);
}
else if (i2==0 && cityEdittext.getText().toString().length()==0)
{
cityimageView.setImageResource(R.mipmap.location_orange_icon);
cityView.setVisibility(View.VISIBLE);
cityEdittext.setCursorVisible(false);
}
}
@Override
public void afterTextChanged(Editable editable)
{
if (cityEdittext.getText().toString().length()==0)
{
cityimageView.setImageResource(R.mipmap.location_orange_icon);
cityView.setVisibility(View.VISIBLE);
cityEdittext.setCursorVisible(false);
}
}
});
}
@OnClick(R.id.TextViewLogin)
public void setTextViewLogin()
{
startActivity(new Intent(RegistrationActivity.this,LoginActivity.class));
}
public void UserRegistration()
{
// Showing progress dialog at user regist ration time.
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
final String HttpUrl = TripManagement.BASE_URL+"register";
// Creating string request with post method.
StringRequest stringRequest = new StringRequest(Request.Method.POST, HttpUrl,
new Response.Listener<String>()
{
@Override
public void onResponse(String ServerResponse)
{
Log.d("URLLLLL",HttpUrl);
Log.e("Responce",ServerResponse);
progressDialog.dismiss();
JSONObject jsonObject = null;
try
{
jsonObject = new JSONObject(ServerResponse);
if (jsonObject.getInt("success") == 1)
{
JSONObject userJson = jsonObject.getJSONObject(Keys.data);
JSONObject jsonObject_user = userJson.getJSONObject(Keys.user);
String email_verified = jsonObject_user.getString(Keys.email_verified);
String phone_verified = jsonObject_user.getString(Keys.phone_verified);
if (phone_verified.equals("1") && email_verified.equals("1"))
{
Toast.makeText(RegistrationActivity.this, "k1", Toast.LENGTH_SHORT).show();
startActivity(new Intent(RegistrationActivity.this,Qrcoderesult.class));
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
if (getCurrentFocus() != null)
{
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
}
else if (phone_verified.equals("0") && email_verified.equals("0"))
{
startActivity(new Intent(RegistrationActivity.this,VarifyOTPActiivty.class));
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
if (getCurrentFocus() != null)
{
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
}
else if (phone_verified.equals("1") && email_verified.equals("0"))
{
startActivity(new Intent(RegistrationActivity.this,VarifyEmailActivity.class));
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
if (getCurrentFocus() != null)
{
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
}
else if (phone_verified.equals("0") && email_verified.equals("1"))
{
startActivity(new Intent(RegistrationActivity.this,VarifyOTPActiivty.class));
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
if (getCurrentFocus() != null)
{
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
}
TripManagement.saveValueuToPreferences(RegistrationActivity.this,"UserName",jsonObject_user.getString(Keys.name));
TripManagement.saveValueuToPreferences(RegistrationActivity.this,"UserEmail",jsonObject_user.getString(Keys.email));
TripManagement.saveValueuToPreferences(RegistrationActivity.this,"UniqueID",jsonObject_user.getString(Keys.unique_id));
TripManagement.saveValueuToPreferences(RegistrationActivity.this,"accesstoken",userJson.getString(Keys.access_token));
TripManagement.saveValueuToPreferences(RegistrationActivity.this,"LoginSuccess","LoginSuccess");
TripManagement.saveValueuToPreferences(RegistrationActivity.this,"GENDER", String.valueOf(jsonObject_user.getInt(Keys.gender)));
Registration registration = Registration.create().withUserId(jsonObject_user.getString(Keys.id));
Intercom.client().registerIdentifiedUser(registration);
}
else if (jsonObject.getInt("success") == 0)
{
JSONObject jsonObject_error = jsonObject.getJSONObject(Keys.errors);
if (jsonObject_error.has(Keys.email))
{
TV_Invali.setText(""+jsonObject_error.getJSONArray(Keys.email).get(0));
dialog_invalid_qr.show();
}
else if (jsonObject_error.has(Keys.phone))
{
TV_Invali.setText(""+jsonObject_error.getJSONArray(Keys.phone).get(0));
dialog_invalid_qr.show();
}
else if (jsonObject_error.has(Keys.password))
{
TV_Invali.setText(""+jsonObject_error.getJSONArray(Keys.password).get(0));
dialog_invalid_qr.show();
}
else if (jsonObject_error.has(Keys.gender))
{
TV_Invali.setText(""+jsonObject_error.getJSONArray(Keys.gender).get(0));
dialog_invalid_qr.show();
}
}
} catch (JSONException e)
{
e.printStackTrace();
}
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError volleyError)
{
Log.e("VolleyError",volleyError.toString());
// Hiding the progress dialog after all task complete.
progressDialog.dismiss();
// Showing error message if something goes wrong.
TV_Invali.setText("Check Your Internet Connection");
dialog_invalid_qr.show();
}
})
{
@Override
public Map<String, String> getParams() throws AuthFailureError
{
// Creating Map String Params.
Map<String, String> params = new HashMap<String, String>();
// Adding All values to Params.
// The firs argument should be same sa your MySQL database table columns.
params.put(Keys.name, nameEdittext.getText().toString());
if (TripManagement.readValueFromPreferences(RegistrationActivity.this,"male","").equals("male"))
{
params.put(Keys.gender,"1");
}
else if (TripManagement.readValueFromPreferences(RegistrationActivity.this,"female","").equals("female"))
{
params.put(Keys.gender,"0");
}
params.put(Keys.email, emailEdittext.getText().toString());
params.put(Keys.isd_code, "91");
params.put(Keys.phone, mobileEdittext.getText().toString());
params.put(Keys.password, passwordEdittext.getText().toString());
params.put(Keys.password_confirmation, conformpasswordEdittext.getText().toString());
params.put(Keys.city, cityEdittext.getText().toString());
params.put(Keys.state, stateEdittext.getText().toString());
params.put(Keys.address, addressEdittext.getText().toString());
params.put(Keys.device, "0");
params.put(Keys.device_token, devicetoken);
params.put(Keys.terms_and_conditions, term_cond);
return params;
}
};
// Creating RequestQueue.
RequestQueue requestQueue = Volley.newRequestQueue(this);
stringRequest.setRetryPolicy(new RetryPolicy() {
@Override
public int getCurrentTimeout() {
return 50000;
}
@Override
public int getCurrentRetryCount() {
return 50000;
}
@Override
public void retry(VolleyError error) throws VolleyError {
}
});
// Adding the StringRequest object into requestQueue.
requestQueue.add(stringRequest);
}
@OnClick(R.id.RelLayoutFirst)
public void setRelLayoutFirst()
{
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
if (getCurrentFocus() != null)
{
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
}
@OnClick(R.id.RippleCreateAccount)
public void setRippleCreateAccount()
{
Blocker mBlocker = new Blocker();
if (!mBlocker.block(4000))
{
// do your action
if (nameEdittext.length() == 0 && emailEdittext.length() == 0 && passwordEdittext.length() == 0 && conformpasswordEdittext.length() == 0 && stateEdittext.length() == 0 && cityEdittext.length() == 0 && addressEdittext.length() == 0) {
TV_Invali.setText("Please fill all the deatails");
dialog_invalid_qr.show();
} else if (nameEdittext.length() == 0 || emailEdittext.length() == 0 || passwordEdittext.length() == 0 || conformpasswordEdittext.length() == 0 || stateEdittext.length() == 0 || cityEdittext.length() == 0 || addressEdittext.length() == 0) {
TV_Invali.setText("Please fill all the deatails");
dialog_invalid_qr.show();
} else if (!conformpasswordEdittext.getText().toString().equals(passwordEdittext.getText().toString())) {
TV_Invali.setText("Passwords do not match");
dialog_invalid_qr.show();
} else if (!mCheckbox.isChecked()) {
TV_Invali.setText("Please accept the terms and condtions");
dialog_invalid_qr.show();
}
else if (LinlayoutBothGender.getVisibility() == View.VISIBLE)
{
TV_Invali.setText("Please select your gender");
dialog_invalid_qr.show();
}
else {
UserRegistration();
}
}
}
@OnClick(R.id.LinlayoutMale)
public void setLinlayoutMale()
{
TripManagement.saveValueuToPreferences(this,"male","male");
TripManagement.saveValueuToPreferences(this,"female","");
LinlayoutBothGender.setVisibility(View.GONE);
LinlayoutSingleMale.setVisibility(View.VISIBLE);
}
@OnClick(R.id.LinLayoutFemale)
public void setLinLayoutFemale()
{
TripManagement.saveValueuToPreferences(this,"female","female");
TripManagement.saveValueuToPreferences(this,"male","");
LinlayoutBothGender.setVisibility(View.GONE);
LinlayoutSingleFeMale.setVisibility(View.VISIBLE);
}
@OnClick(R.id.RellayoutEditFemale)
public void setRellayoutEditFemale()
{
LinlayoutBothGender.setVisibility(View.VISIBLE);
LinlayoutSingleFeMale.setVisibility(View.GONE);
}
@OnClick(R.id.RellayoutEditMale)
public void setRellayoutEditMale()
{
LinlayoutBothGender.setVisibility(View.VISIBLE);
LinlayoutSingleMale.setVisibility(View.GONE);
}
@OnClick(R.id.LinlayoutTerms)
public void setLinlayoutTerms()
{
Uri uri = Uri.parse("https://www.planetzoom.co.in/tc"); // missing 'http://' will cause crashed
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
/* public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN)
{
if(keyCode == KeyEvent.KEYCODE_ENTER)
{
RippleCreateAccount.performClick(); // recherche is my button
return true;
}
}
return false;
}
*/
public void GPSStatus(){
locationManager = (LocationManager)this.getSystemService(this.LOCATION_SERVICE);
GpsStatus = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
public void displayLocationSettingsRequest(Context context) {
GoogleApiClient googleApiClient = new GoogleApiClient.Builder(context)
.addApi(LocationServices.API).build();
googleApiClient.connect();
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(10000 / 2);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// Log.i(TAG, "All location settings are satisfied.");
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Log.i(TAG, "Location settings are not satisfied. Show the user a dialog to upgrade location settings ");
try {
// Show the dialog by calling startResolutionForResult(), and check the result
// in onActivityResult().
status.startResolutionForResult(RegistrationActivity.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
// Log.i(TAG, "PendingIntent unable to execute request.");
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Log.i(TAG, "Location settings are inadequate, and cannot be fixed here. Dialog not created.");
break;
}
}
});
}
public String setaddress(double latitude, double longitude)
{
Geocoder geocoder;
List<Address> addressList;
geocoder = new Geocoder(this, Locale.getDefault());
try {
addressList = geocoder.getFromLocation(latitude, longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
if (addressList != null && addressList.size() > 0)
{
Address address = addressList.get(0);
LocationSearchFragment.address_current = addressList.get(0);
LocationSearchFragment.latlngcurrent = new LatLng( LocationSearchFragment.address_current.getLatitude(), LocationSearchFragment.address_current.getLongitude());
if (address.getAddressLine(1) == null)
{
LocationSearchFragment.full_address=address.getAddressLine(0);
addressEdittext.setText(LocationSearchFragment.full_address);
stateEdittext.setText(address.getAdminArea());
cityEdittext.setText(address.getLocality());
Log.e("11",address.getAdminArea());
Log.e("13",address.getFeatureName());
Log.e("12",address.getLocality());
}
else if (address.getAdminArea()== null)
{
LocationSearchFragment.full_address=address.getAddressLine(0)+" "+address.getAddressLine(1);
stateEdittext.setText( LocationSearchFragment.full_address);
}
else if (address.getLocality()== null)
{
LocationSearchFragment.full_address=address.getAddressLine(0)+" "+address.getAddressLine(1)+" "+" "+address.getAdminArea();
cityEdittext.setText( LocationSearchFragment.full_address);
}
else
{
LocationSearchFragment.full_address=address.getAddressLine(0)+" "+address.getAddressLine(1)+" "+address.getLocality()+" "+address.getAdminArea();
addressEdittext.setText( LocationSearchFragment.full_address);
}
}
} catch (IOException e) {
Toast.makeText(this, "Please Reboot/Restart your Device to get Current Address", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
return null;
}
}
| 38.399482 | 256 | 0.602517 |
82b3a3385e9983df3ee73db328afaf9d00cd0c20 | 10,288 | package datawave.ingest.data.config;
import java.util.Map;
import datawave.data.type.Type;
import org.junit.Assert;
import org.junit.Test;
public class NormalizedFieldAndValueTest {
public static class NonGroupedInstance implements NormalizedContentInterface {
private String _fieldName;
private String _indexedFieldName;
private String _indexedFieldValue;
private String _eventFieldName;
private String _eventFieldValue;
private Map<String,String> _markings;
private Throwable _error;
protected NonGroupedInstance() {
_fieldName = "TestNonGroupedInstance";
_indexedFieldName = "TestIndexedField";
_indexedFieldValue = "hello, world";
_eventFieldName = "TestEventField";
_eventFieldValue = "hello, world";
_markings = null;
_error = null;
}
@Override
public void setFieldName(String name) {
_fieldName = name;
}
public String getFieldName() {
return _fieldName;
}
@Override
public String getIndexedFieldName() {
return _indexedFieldName;
}
@Override
public String getEventFieldName() {
return _eventFieldName;
}
@Override
public String getEventFieldValue() {
return _eventFieldValue;
}
@Override
public void setEventFieldValue(String val) {
_eventFieldValue = val;
}
@Override
public String getIndexedFieldValue() {
return _indexedFieldValue;
}
@Override
public void setIndexedFieldValue(String val) {
_indexedFieldValue = val;
}
@Override
public void setMarkings(Map<String,String> markings) {
_markings = markings;
}
@Override
public void setError(Throwable e) {
_error = e;
}
@Override
public Map<String,String> getMarkings() {
return _markings;
}
@Override
public Throwable getError() {
return _error;
}
@Override
public Object clone() {
return this;
}
/*
* (non-Javadoc)
*
* @see datawave.ingest.data.config.NormalizedContentInterface#normalize(datawave.data.type.Type)
*/
@Override
public void normalize(Type<?> datawaveType) {
try {
this.setIndexedFieldValue(datawaveType.normalize(this.getIndexedFieldValue()));
} catch (Exception e) {
this.setError(e);
}
}
}
public static class GroupedInstance implements GroupedNormalizedContentInterface {
private String _fieldName;
private String _indexedFieldName;
private String _indexedFieldValue;
private String _eventFieldName;
private String _eventFieldValue;
private Map<String,String> _markings;
private Throwable _error;
private boolean _grouped;
private String _group;
private String _subGroup;
protected GroupedInstance() {
_fieldName = "TestNonGroupedInstance";
_indexedFieldName = "TestIndexedField";
_indexedFieldValue = "hello, world";
_eventFieldName = "TestEventField";
_eventFieldValue = "hello, world";
_markings = null;
_error = null;
_grouped = true;
_group = "group";
_subGroup = "subGroup";
}
@Override
public void setFieldName(String name) {
_fieldName = name;
}
public String getFieldName() {
return _fieldName;
}
@Override
public String getIndexedFieldName() {
return _indexedFieldName;
}
@Override
public String getEventFieldName() {
return _eventFieldName;
}
@Override
public String getEventFieldValue() {
return _eventFieldValue;
}
@Override
public void setEventFieldValue(String val) {
_eventFieldValue = val;
}
@Override
public String getIndexedFieldValue() {
return _indexedFieldValue;
}
@Override
public void setIndexedFieldValue(String val) {
_indexedFieldValue = val;
}
@Override
public void setMarkings(Map<String,String> markings) {
_markings = markings;
}
@Override
public void setError(Throwable e) {
_error = e;
}
@Override
public Map<String,String> getMarkings() {
return _markings;
}
@Override
public Throwable getError() {
return _error;
}
@Override
public boolean isGrouped() {
return _grouped;
}
@Override
public void setGrouped(boolean grouped) {
_grouped = grouped;
}
@Override
public String getSubGroup() {
return _subGroup;
}
@Override
public void setSubGroup(String group) {
_subGroup = group;
}
@Override
public String getGroup() {
return _group;
}
@Override
public void setGroup(String type) {
_group = type;
}
@Override
public Object clone() {
return this;
}
@Override
public void setEventFieldName(String name) {
_eventFieldName = name;
}
@Override
public void setIndexedFieldName(String name) {
_indexedFieldName = name;
}
@Override
public void normalize(Type<?> datawaveType) {
try {
this.setIndexedFieldValue(datawaveType.normalize(this.getIndexedFieldValue()));
} catch (Exception e) {
this.setError(e);
}
}
}
@Test
public void testConstructorPassedNonGroupedInterfaceInstance() {
NormalizedContentInterface nci = new NormalizedFieldAndValueTest.NonGroupedInstance();
NormalizedFieldAndValue uut = new NormalizedFieldAndValue(nci);
Assert.assertNull("Constructor created a non-existance Group for Test Content", uut.getGroup());
Assert.assertNull("Constructor created a non-existance SubGroup for Test Content", uut.getSubGroup());
}
@Test
public void testConstructorPassedGroupedInterfaceInstance() {
NormalizedContentInterface nci = new NormalizedFieldAndValueTest.GroupedInstance();
NormalizedFieldAndValue uut = new NormalizedFieldAndValue(nci);
Assert.assertTrue("Constructor failed to create a Group for the Test Content", uut.isGrouped());
Assert.assertNotNull("Constructor failed to create Group for Test Content", uut.getGroup());
Assert.assertNotNull("Constructor failed to create a SubGroup for Test Content", uut.getSubGroup());
}
@Test
public void testDecode() {
String testValue = "Hello, World";
// Test a simple String as bytes but not expecting it to be Binary
String results = NormalizedFieldAndValue.decode(testValue.getBytes(), false);
Assert.assertEquals("Decode failed to correctly decode test value", testValue, results);
// Test a simple String as bytes but expecting it to be Binary
results = NormalizedFieldAndValue.decode(testValue.getBytes(), true);
Assert.assertEquals("Decode failed to correctly decode test value", testValue, results);
String expected = "a";
byte[] binary = new byte[] {(byte) 0x61};
results = NormalizedFieldAndValue.decode(binary, false);
Assert.assertEquals("Decode failed to correctly decode binary test", expected, results);
results = NormalizedFieldAndValue.decode(binary, true);
Assert.assertEquals("Decode failed to correctly decode binary test", expected, results);
}
@Test
public void testGetDefaultEventFieldName() {
NormalizedContentInterface nci = new NormalizedFieldAndValueTest.GroupedInstance();
NormalizedFieldAndValue uut = new NormalizedFieldAndValue(nci);
uut.setEventFieldName(null);
String generatedEventFieldName = uut.getEventFieldName();
String expectedName = "TestIndexedField.GROUP.SUBGROUP";
Assert.assertEquals("NormalizedFieldAndValue.getEventFieldName failed to generate the expected default Event Field Name", expectedName,
generatedEventFieldName);
nci = new NormalizedFieldAndValueTest.NonGroupedInstance();
uut = new NormalizedFieldAndValue(nci);
expectedName = "TestIndexedField";
generatedEventFieldName = uut.getEventFieldName();
Assert.assertEquals("NormalizedFieldAndValue.getEventFieldName failed to generate the expected default Event Field Name", expectedName,
generatedEventFieldName);
}
}
| 28.186301 | 143 | 0.544032 |
ac9286b8cc1554ff7746dbc991e767abe2401db2 | 2,731 | package liquibase.parser.core.xml;
import liquibase.parser.LiquibaseParser;
import liquibase.parser.NamespaceDetails;
import liquibase.serializer.LiquibaseSerializable;
import liquibase.serializer.LiquibaseSerializer;
import liquibase.serializer.core.xml.XMLChangeLogSerializer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StandardNamespaceDetails implements NamespaceDetails {
public static final String GENERIC_EXTENSION_XSD = "http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd";
private final Pattern standardUrlPattern;
private final Pattern oldStandardUrlPattern;
public StandardNamespaceDetails() {
standardUrlPattern = Pattern.compile("http://www.liquibase.org/xml/ns/dbchangelog/(dbchangelog-[\\d\\.]+.xsd)");
oldStandardUrlPattern = Pattern.compile("http://www.liquibase.org/xml/ns/migrator/(dbchangelog-[\\d\\.]+.xsd)");
}
@Override
public int getPriority() {
return PRIORITY_DEFAULT;
}
@Override
public boolean supports(LiquibaseSerializer serializer, String namespaceOrUrl) {
return serializer instanceof XMLChangeLogSerializer;
}
@Override
public boolean supports(LiquibaseParser parser, String namespaceOrUrl) {
return parser instanceof XMLChangeLogSAXParser;
}
@Override
public String getShortName(String namespaceOrUrl) {
if (namespaceOrUrl.equals(LiquibaseSerializable.STANDARD_CHANGELOG_NAMESPACE)) {
return "";
}
return "ext";
}
@Override
public String[] getNamespaces() {
return new String[] {
LiquibaseSerializable.STANDARD_CHANGELOG_NAMESPACE,
LiquibaseSerializable.GENERIC_CHANGELOG_EXTENSION_NAMESPACE
};
}
@Override
public String getSchemaUrl(String namespaceOrUrl) {
if (namespaceOrUrl.equals(LiquibaseSerializable.STANDARD_CHANGELOG_NAMESPACE)) {
return "http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-" + XMLChangeLogSAXParser.getSchemaVersion() + ".xsd";
}
return GENERIC_EXTENSION_XSD;
}
@Override
public String getLocalPath(String namespaceOrUrl) {
if (namespaceOrUrl.equals(GENERIC_EXTENSION_XSD)) {
return "liquibase/parser/core/xml/dbchangelog-ext.xsd";
}
Matcher matcher = standardUrlPattern.matcher(namespaceOrUrl);
if (matcher.matches()) {
return "liquibase/parser/core/xml/"+matcher.group(1);
}
matcher = oldStandardUrlPattern.matcher(namespaceOrUrl);
if (matcher.matches()) {
return "liquibase/parser/core/xml/"+matcher.group(1);
}
return null;
}
}
| 33.716049 | 130 | 0.701575 |
5fd6eb42f14241ef6d952827bc5cefb68f02b1da | 27,512 | /*-
* ===============LICENSE_START=======================================================
* Acumos
* ===================================================================================
* Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
* ===================================================================================
* This Acumos software file is distributed by AT&T
* 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
*
* This file 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.
* ===============LICENSE_END=========================================================
*/
package org.acumos.datasource.service;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.core.Response.Status;
import org.acumos.datasource.common.CmlpApplicationEnum;
import org.acumos.datasource.common.DataSrcErrorList;
import org.acumos.datasource.common.DataSrcRestError;
import org.acumos.datasource.common.ErrorListEnum;
import org.acumos.datasource.common.HelperTool;
import org.acumos.datasource.common.KerberosConfigInfo;
import org.acumos.datasource.connection.DbUtilitiesV2;
import org.acumos.datasource.exception.DataSrcException;
import org.acumos.datasource.model.KerberosLogin;
import org.acumos.datasource.schema.DataSourceMetadata;
import org.acumos.datasource.schema.DataSourceModelGet;
import org.acumos.datasource.schema.NameValue;
import org.acumos.datasource.utils.ApplicationUtilities;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class HdpDataSourceSvcImpl implements HdpDataSourceSvc {
private static Logger log = LoggerFactory.getLogger(HdpDataSourceSvcImpl.class);
public HdpDataSourceSvcImpl() {
}
@Autowired
private DbUtilitiesV2 dbUtilities;
@Autowired
HelperTool helperTool;
@Autowired
ApplicationUtilities applicationUtilities;
@Override
public Configuration createConnWithoutKerberos(String hostName) throws DataSrcException, IOException {
log.info("Create a hadoop configuration without kerberos for " + hostName);
Configuration config = new Configuration();
config.set("fs.DefaultFS", hostName);
log.info("Hadoop configuration without kerberos with fs.DefaultFS as " + hostName);
return config;
}
@Override
public String getConnStatusWithKerberos(KerberosLogin objKerberosLogin, String hostName,String readWriteDescriptor) throws IOException, DataSrcException {
log.info("Checking kerberos keytab");
if (!(new File(
System.getProperty("user.dir") + System.getProperty("file.separator")
+ objKerberosLogin.getKerberosLoginUser().substring(0,
objKerberosLogin.getKerberosLoginUser().indexOf("@"))
+ "." + "kerberos.keytab").exists())) {
log.info("Kerberos keytab doesn't exist, creating a new one");
applicationUtilities.createKerberosKeytab(objKerberosLogin, objKerberosLogin.getKerberosKeyTabFileName(), objKerberosLogin.getKerberosConfigFileName());
}
log.info("Creating a hadoop configuration with kerberos for " + hostName);
String result = getConnStatusWithKerberos(hostName, objKerberosLogin.getKerberosLoginUser(), null,readWriteDescriptor);
return result;
}
@Override
public String getConnStatusWithoutKerberos(String hostName) throws IOException, DataSrcException {
log.info("Starting to establish a test connection to " + hostName + " for hdfs connectivity.");
log.info("Creating hadoop configuration for " + hostName);
Configuration config = createConnWithoutKerberos(hostName);
log.info("Initializing filesystem with kerberised settings for " + hostName + " for hdfs connectivity.");
FileSystem fs = FileSystem.get(config);
log.info("Reading filesystem with kerberised settings for " + hostName + " for hdfs connectivity.");
FileStatus[] fsStatus = fs.listStatus(new Path("/tmp"));
if (fsStatus.length > 0) {
log.info("Reading of temp folder succeeded for establishing hdfs connectivity on " + hostName);
return "success";
}
return "failed";
}
@Override
public void createKerberosKeytab(KerberosLogin objKerberosLogin) throws IOException, DataSrcException {
log.info("Creating kerberos keytab for principal " + objKerberosLogin.getKerberosLoginUser());
applicationUtilities.createKerberosKeytab(objKerberosLogin, objKerberosLogin.getKerberosKeyTabFileName(), objKerberosLogin.getKerberosConfigFileName());
log.info("Created kerberos keytab for principal " + objKerberosLogin.getKerberosLoginUser());
}
@Override
public String getConnStatusWithKerberos(String hostName, String kerberosLoginuser, String hdfsFolderName,String readWriteDescriptor)
throws IOException, DataSrcException {
if (hdfsFolderName == null) {
return "failed";
}
try {
log.info("Starting to establish a test connection to " + hostName + " for hdfs connectivity.");
Configuration config = helperTool.getKerberisedConfiguration(hostName,
kerberosLoginuser);
log.info("Initializing filesystem with kerberised settings for " + hostName + " for hdfs connectivity.");
FileSystem fs = FileSystem.get(config);
if (readWriteDescriptor.equalsIgnoreCase("read")) {
if (fs.exists(new Path(hdfsFolderName))) {
log.info("HDFS folder name " + hdfsFolderName+ " exist for readWriteDescriptor "+ readWriteDescriptor);
return "success";
} else {
log.info("HDFS folder name " + hdfsFolderName+ " does not exist for readWriteDescriptor "+ readWriteDescriptor);
return "failed";
}
}
if (readWriteDescriptor.equalsIgnoreCase("write")) {
if (fs.exists(new Path(hdfsFolderName))) {
log.info("HDFS folder name " + hdfsFolderName+ " exist for readWriteDescriptor "+ readWriteDescriptor);
return "success";
}
try {
FileStatus status = fs.getFileStatus(new Path(hdfsFolderName));
} catch (FileNotFoundException fnfe) {
log.info("HDFS folder name " + hdfsFolderName+ " does not exist. Received FileNotFoundException from HDFS");
log.info("creating File structure...");
// if the path is a folder, create an empty directory
// else create an empty file
if (hdfsFolderName.indexOf(".") < 0) {
log.info("HDFS folder name " + hdfsFolderName+ " does not exist for readWriteDescriptor "+ readWriteDescriptor);
log.info("Creating HDFS folder name: " + hdfsFolderName);
boolean isCreated = fs.mkdirs(new Path(hdfsFolderName));
if(isCreated) {
log.info("Successfully created HDFS folder name: " + hdfsFolderName);
return "success";
}
} else { //File
//create an empty file
FSDataOutputStream fsdo = fs.create(new Path(hdfsFolderName));
if(fsdo != null) {
fsdo.close();
log.info("Successfully created HDFS folder name: " + hdfsFolderName);
return "success";
}
}
}
}
} catch (Exception e) {
throw e;
}
log.info("HDFS folder name " + hdfsFolderName + "Connection Status failed for readWriteDescriptor "+readWriteDescriptor);
return "failed";
}
@Override
public String getConnStatusWithKerberos(KerberosLogin objKerberosLogin, String hostName, String hdfsFolderName,String readWriteDescriptor)
throws IOException, DataSrcException {
/*log.info("Checking kerberos keytab");
if (!(new File(
System.getProperty("user.dir") + System.getProperty("file.separator")
+ objKerberosLogin.getKerberosLoginUser().substring(0,
objKerberosLogin.getKerberosLoginUser().indexOf("@"))
+ "." + "kerberos.keytab").exists())) {
log.info("Kerberos keytab doesn't exist, creating a new one");
Utilities.createKerberosKeytab(objKerberosLogin);
}*/
StringBuilder sb1 = new StringBuilder();
sb1.append(System.getProperty("user.dir")).append(System.getProperty("file.separator"))
.append(objKerberosLogin.getKerberosLoginUser().substring(0, objKerberosLogin.getKerberosLoginUser().indexOf("@")))
.append(".kerberos.keytab");
if(!Files.exists(Paths.get(sb1.toString()))) {
log.info("Creating kerberos keytab for hostname " + hostName + " using principal "
+ objKerberosLogin.getKerberosLoginUser() + " for hdfs connectivity testing.");
applicationUtilities.createKerberosKeytab(objKerberosLogin, objKerberosLogin.getKerberosKeyTabFileName(), objKerberosLogin.getKerberosConfigFileName());
} else {
try {
log.info("overwriting kerberos keytab for hostname " + hostName + " using principal "
+ objKerberosLogin.getKerberosLoginUser() + " for hdfs connectivity testing.");
applicationUtilities.createKerberosKeytab(objKerberosLogin, objKerberosLogin.getKerberosKeyTabFileName(), objKerberosLogin.getKerberosConfigFileName());
} catch (Exception e) {
//ignore
log.info("Exception occurred while creating kereberos keytab" + e.getMessage());
}
}
log.info("Testing hive connectivity for hostname " + hostName + " using principal "
+ objKerberosLogin.getKerberosLoginUser() + " after creating kerberos keytab");
log.info("Creating a hadoop configuration with kerberos for " + hostName);
return getConnStatusWithKerberos(hostName, objKerberosLogin.getKerberosLoginUser(), hdfsFolderName,readWriteDescriptor);
}
@Override
public InputStream getResults(String user, String authorization, String namespace, String datasourceKey,String hdfsFilename)
throws DataSrcException, IOException {
ArrayList<String> dbDatasourceDetails = dbUtilities.getDataSourceDetails(user, null, null, datasourceKey, null, true, false, authorization);
//JSONObject objJson = new JSONObject(cassandraDetails.get(0));
DataSourceModelGet dbDataSource = applicationUtilities.getDataSourceModel(dbDatasourceDetails.get(0));
if (dbDataSource.getCategory().equals("hdfs") && dbDataSource.getOwnedBy().equals(user)) {
Map<String, String> decryptionMap = new HashMap<>();
//decryptionMap = Utilities.readFromCodeCloud(authorization, datasourceKey);
decryptionMap = applicationUtilities.readFromMongoCodeCloud(user, datasourceKey);
//if dataReferenceBox is checked, return config file/keytab file contents
//EE-2557
//String isDataReference = objJson.optString("isDataReference");
if (dbDataSource.isDataReference()) {
return getDataReference(dbDatasourceDetails.get(0), decryptionMap);
}
//Restore Kerberos Cache config files if they missed due to POD bounce
restoreKerberosCacheConfigFiles(decryptionMap);
log.info("Starting to establish a test connection to " + dbDataSource.getCommonDetails().getServerName()
+ " for hdfs connectivity.");
/*Configuration config = helperTool.getKerberisedConfiguration(
objJson.getString("serverName"), decrptionMap.get("kerberosLoginUser".toLowerCase()));*/
Configuration config = helperTool.getKerberisedConfiguration(
dbDataSource.getCommonDetails().getServerName(), decryptionMap.get("kerberosLoginUser".toLowerCase()));
log.info("Initializing filesystem with kerberised settings for " + dbDataSource.getCommonDetails().getServerName()
+ " for hdfs connectivity.");
FileSystem fs = FileSystem.get(config);
log.info("Reading filesystem with kerberised settings for " + dbDataSource.getCommonDetails().getServerName()
+ " for hdfs connectivity.");
try {
if (dbDataSource.getHdfsHiveDetails().getHdfsFoldername() != null) {
FSDataInputStream in;
if(hdfsFilename !=null && !hdfsFilename.isEmpty()) {
if(dbDataSource.getHdfsHiveDetails().getHdfsFoldername().trim().endsWith("/"))
in= fs.open(new Path(dbDataSource.getHdfsHiveDetails().getHdfsFoldername().trim() + hdfsFilename));
else
in= fs.open(new Path(dbDataSource.getHdfsHiveDetails().getHdfsFoldername().trim() + "/" + hdfsFilename));
} else {
in = fs.open(new Path(dbDataSource.getHdfsHiveDetails().getHdfsFoldername().trim()));
}
if (in.available() > 0) {
log.info("Reading of " + dbDataSource.getHdfsHiveDetails().getHdfsFoldername()
+ " succeeded for establishing hdfs connectivity on "
+ dbDataSource.getCommonDetails().getServerName());
//return in.getWrappedStream();
return applicationUtilities.getInputStream(in);
}
}
} catch(Exception e) {
log.info("Exception occurred Reading File System : " + e.getMessage());
throw e;
} finally {
if(fs != null)
fs.close();
}
}
//No information
String[] variables = { "hdfsHiveDetails" };
DataSrcRestError err = DataSrcErrorList.buildError(ErrorListEnum._0007, variables, null, CmlpApplicationEnum.DATASOURCE);
throw new DataSrcException(
"DataSource has invalid Connection parameters. No Sample Results found for the given DatasourceKey.", Status.BAD_REQUEST.getStatusCode(), err);
}
private InputStream getDataReference(String jsonStr, Map<String, String> decryptionMap) throws DataSrcException, IOException {
if (decryptionMap.size() == 0) {
DataSrcRestError err = DataSrcErrorList.buildError(new Exception("Unable to retrieve decryption files"), null, CmlpApplicationEnum.DATASOURCE);
throw new DataSrcException("Unable to retrieve decryption files",
Status.INTERNAL_SERVER_ERROR.getStatusCode(), err);
}
JSONObject objJson = new JSONObject(jsonStr);
//remove unwanted fields
objJson.remove("kerberosConfigFileId");
objJson.remove("kerberosKeyTabFileId");
objJson.remove("kerberosLoginUser");
objJson.remove("_id");
//Add the fields from code cloud
objJson.put("kerberosconfigfilecontents", applicationUtilities.htmlDecoding(decryptionMap.get("kerberosconfigfilecontents")));
objJson.put("kerberoskeytabcontent", decryptionMap.get("kerberoskeytabcontent"));
objJson.put("kerberosloginuser", decryptionMap.get("kerberosloginuser"));
return new ByteArrayInputStream(objJson.toString().getBytes());
}
@Override
public InputStream getSampleResults(String user, String authorization, String namespace, String datasourceKey,String hdfsFilename)
throws DataSrcException, IOException {
ArrayList<String> dbDatasourceDetails = dbUtilities.getDataSourceDetails(user, null, null, datasourceKey, null, true, false, authorization);
DataSourceModelGet dbDataSource = applicationUtilities.getDataSourceModel(dbDatasourceDetails.get(0));
if (dbDataSource.getCategory().equals("hdfs") && dbDataSource.getOwnedBy().equals(user)) {
Map<String, String> decryptionMap = new HashMap<>();
//decryptionMap = Utilities.readFromCodeCloud(authorization, datasourceKey);
decryptionMap = applicationUtilities.readFromMongoCodeCloud(user, datasourceKey);
//Restore Kerberos Cache config files if they missed due to POD bounce
restoreKerberosCacheConfigFiles(decryptionMap);
//successfully Restored the files
log.info("getSampleResults(), Kerberos files were restored successfully...Proceed with check connection");
log.info("Starting to establish a test connection to " + dbDataSource.getCommonDetails().getServerName()
+ " for hdfs connectivity.");
Configuration config = helperTool.getKerberisedConfiguration(
dbDataSource.getCommonDetails().getServerName(), decryptionMap.get("kerberosLoginUser".toLowerCase()));
// kerberosConfigFileName, kerberosKeyTabFileName);
log.info("Initializing filesystem with kerberised settings for " + dbDataSource.getCommonDetails().getServerName()
+ " for hdfs connectivity.");
FileSystem fs = FileSystem.get(config);
//connectivity test passed
if("write".equalsIgnoreCase(dbDataSource.getReadWriteDescriptor())) {
//validate connection call as there is no getSamples() allowed on write flag
return (new ByteArrayInputStream("Success".getBytes()));
}
log.info("Reading filesystem with kerberised settings for " + dbDataSource.getCommonDetails().getServerName()
+ " for hdfs connectivity.");
try {
if (dbDataSource.getHdfsHiveDetails().getHdfsFoldername() != null) {
FSDataInputStream in;
if(hdfsFilename !=null && !hdfsFilename.isEmpty()) {
if(dbDataSource.getHdfsHiveDetails().getHdfsFoldername().trim().endsWith("/"))
in= fs.open(new Path(dbDataSource.getHdfsHiveDetails().getHdfsFoldername().trim() + hdfsFilename));
else
in= fs.open(new Path(dbDataSource.getHdfsHiveDetails().getHdfsFoldername().trim() + "/" + hdfsFilename));
} else {
in = fs.open(new Path(dbDataSource.getHdfsHiveDetails().getHdfsFoldername().trim()));
}
if (in != null && in.available() > 0) {
log.info("Reading of " + dbDataSource.getHdfsHiveDetails().getHdfsFoldername()
+ " succeeded for establishing hdfs connectivity on "
+ dbDataSource.getCommonDetails().getServerName());
int limit = Integer.parseInt(helperTool.getEnv("datasource_sample_size",
helperTool.getComponentPropertyValue("datasource_sample_size"))) * 100;
byte[] buffer = new byte[limit];
int bytesRead = in.read(0l, buffer, 0, limit);
in.close();
return (new ByteArrayInputStream(buffer));
}
}
} catch(Exception e) {
log.info("Exception occurred Reading File System : " + e.getMessage());
throw e;
} finally {
if(fs != null)
fs.close();
}
}
//No information
String[] variables = { "hdfsHiveDetails" };
DataSrcRestError err = DataSrcErrorList.buildError(ErrorListEnum._0007, variables, null, CmlpApplicationEnum.DATASOURCE);
throw new DataSrcException(
"DataSource has invalid Connection parameters. No Sample Results found for the given DatasourceKey.", Status.BAD_REQUEST.getStatusCode(), err);
}
@Override
public DataSourceMetadata getMetadata(KerberosLogin objKerberosLogin, String hostName, String hdfsFolderName) throws IOException, DataSrcException {
ArrayList<NameValue> metaDataList = new ArrayList<NameValue>();
DataSourceMetadata metadata = new DataSourceMetadata();
/* log.info("Checking kerberos keytab");
if (!(new File(
System.getProperty("user.dir") + System.getProperty("file.separator")
+ objKerberosLogin.getKerberosLoginUser().substring(0,
objKerberosLogin.getKerberosLoginUser().indexOf("@"))
+ "." + "kerberos.keytab").exists())) {
log.info("Kerberos keytab doesn't exist, creating a new one");
Utilities.createKerberosKeytab(objKerberosLogin);
}*/
log.info("Creating a hadoop configuration with kerberos for " + hostName);
log.info("Starting to establish a test connection to " + hostName + " for hdfs connectivity.");
Configuration config = helperTool.getKerberisedConfiguration(hostName,
objKerberosLogin.getKerberosLoginUser());
log.info("Initializing filesystem with kerberised settings for " + hostName + " for hdfs connectivity.");
FileSystem fs = FileSystem.get(config);
log.info("Reading filesystem with kerberised settings for " + hostName + " for hdfs connectivity.");
if (hdfsFolderName != null) {
metaDataList.add(new NameValue("fileName", fs.getUri().toString() + hdfsFolderName));
metaDataList.add(new NameValue("fileLength", String.valueOf(fs.getContentSummary(new Path(hdfsFolderName)).getSpaceConsumed()) + " bytes"));
}
metadata.setMetaDataInfo(metaDataList);
return metadata;
}
private void restoreKerberosCacheConfigFiles(Map<String, String> decryptionMap) throws DataSrcException {
String krbLoginUser = decryptionMap.get("kerberosLoginUser".toLowerCase());
StringBuilder sb1 = new StringBuilder();
sb1.append(krbLoginUser.substring(0, krbLoginUser.indexOf("@"))).append(".krb5.conf");
StringBuilder sb2 = new StringBuilder();
sb2.append(krbLoginUser.substring(0, krbLoginUser.indexOf("@"))).append(".kerberos.keytab");
if(!applicationUtilities.isUserKerberosCacheConfigFilesExists(sb1.toString(), sb2.toString())) {
//Restore Kerberos Cache files if they are missed due to POD bounce
log.info("restoreKerberosCacheConfigFiles(), restoring config files from codecloud...");
boolean isWritten = applicationUtilities.writeToKerberosCacheFile(sb1.toString(), decryptionMap.get("KerberosConfigFileContents".toLowerCase()));
if(isWritten) {
isWritten = applicationUtilities.writeToKerberosCacheFile(sb2.toString(), decryptionMap.get("KerberosKeyTabContent".toLowerCase()));
}
if(!isWritten) {
//1. delete config files, if any
applicationUtilities.deleteUserKerberosCacheConfigFiles(sb1.toString(), sb2.toString());
//2. throw Exception
DataSrcRestError err = DataSrcErrorList.buildError(new Exception("Unable to retrieve connection parameters from the codecloud."), null, CmlpApplicationEnum.DATASOURCE);
throw new DataSrcException("Unable to retrieve connection parameters from the codecloud.",
Status.INTERNAL_SERVER_ERROR.getStatusCode(), err);
}
}
}
@Override
public InputStream getSampleResults(DataSourceModelGet dataSource) throws DataSrcException, IOException {
log.info("Starting to establish a test connection to " + dataSource.getCommonDetails().getServerName()
+ " for hdfs connectivity.");
applicationUtilities.validateConnectionParameters(dataSource);
String kerberosConfigFileName = dataSource.getHdfsHiveDetails().getKerberosConfigFileId();
String kerberosKeyTabFileName = dataSource.getHdfsHiveDetails().getKerberosKeyTabFileId();
KerberosConfigInfo kerberosConfig = applicationUtilities.getKerberosConfigInfo(kerberosConfigFileName, kerberosKeyTabFileName);
log.info("getSampleResults, Received following Kerberos config info from ConfigFile : "
+ dataSource.getHdfsHiveDetails().getKerberosConfigFileId());
log.info(kerberosConfig.toString());
KerberosLogin objKerberosLogin = new KerberosLogin();
objKerberosLogin.setKerberosDomainName(kerberosConfig.getDomainName());
objKerberosLogin.setKerberosKdc(kerberosConfig.getKerberosKdc());
objKerberosLogin.setKerberosKeyTabContent(kerberosConfig.getKerberosKeyTabContent());
objKerberosLogin.setKerberosLoginUser(dataSource.getHdfsHiveDetails().getKerberosLoginUser());
objKerberosLogin.setKerberosPasswordServer(kerberosConfig.getKerberosPasswordServer());
objKerberosLogin.setKerberosRealms(kerberosConfig.getKerberosRealms());
objKerberosLogin.setKerbersoAdminServer(kerberosConfig.getKerberosAdminServer());
objKerberosLogin.setKerberosKeyTabFileName(kerberosKeyTabFileName);
objKerberosLogin.setKerberosConfigFileName(kerberosConfigFileName);
StringBuilder sb1 = new StringBuilder();
sb1.append(System.getProperty("user.dir")).append(System.getProperty("file.separator"))
.append(objKerberosLogin.getKerberosLoginUser().substring(0, objKerberosLogin.getKerberosLoginUser().indexOf("@")))
.append(".kerberos.keytab");
if(!Files.exists(Paths.get(sb1.toString()))) {
log.info("Creating kerberos keytab for hostname " + dataSource.getCommonDetails().getServerName() + " using principal "
+ objKerberosLogin.getKerberosLoginUser() + " for hdfs connectivity testing.");
applicationUtilities.createKerberosKeytab(objKerberosLogin, objKerberosLogin.getKerberosKeyTabFileName(), objKerberosLogin.getKerberosConfigFileName());
} else {
try {
log.info("overwriting kerberos keytab for hostname " + dataSource.getCommonDetails().getServerName() + " using principal "
+ objKerberosLogin.getKerberosLoginUser() + " for hdfs connectivity testing.");
applicationUtilities.createKerberosKeytab(objKerberosLogin, objKerberosLogin.getKerberosKeyTabFileName(), objKerberosLogin.getKerberosConfigFileName());
} catch (Exception e) {
//ignore
log.info("Issue while creating kerberosKeyTab: " + e.getMessage());
}
}
Configuration config = helperTool.getKerberisedConfiguration(
dataSource.getCommonDetails().getServerName(), dataSource.getHdfsHiveDetails().getKerberosLoginUser());
log.info("Initializing filesystem with kerberised settings for " + dataSource.getCommonDetails().getServerName()
+ " for hdfs connectivity.");
FileSystem fs = FileSystem.get(config);
FSDataInputStream in = fs.open(new Path(dataSource.getHdfsHiveDetails().getHdfsFoldername()));
log.info("Reading filesystem with kerberised settings for " + dataSource.getCommonDetails().getServerName()
+ " for hdfs connectivity.");
byte[] buffer = null;
if (in.available() > 0) {
log.info("Reading of " + dataSource.getHdfsHiveDetails().getHdfsFoldername()
+ " succeeded for establishing hdfs connectivity on " + dataSource.getCommonDetails().getServerName());
int limit = Integer.parseInt(helperTool.getEnv("datasource_sample_size",
helperTool.getComponentPropertyValue("datasource_sample_size"))) * 100;
buffer = new byte[limit];
@SuppressWarnings("unused")
int bytesRead = in.read(0l, buffer, 0, limit);
// return in.getWrappedStream();s
}
applicationUtilities.deleteUserKerberosConfigFiles(dataSource.getHdfsHiveDetails().getKerberosConfigFileId(),
dataSource.getHdfsHiveDetails().getKerberosKeyTabFileId());
return (new ByteArrayInputStream(buffer));
}
@Override
public boolean writebackPrediction(String user, String authorization, DataSourceModelGet dataSource, String data,String hdfsFilename) throws IOException, DataSrcException {
boolean status = false;
Map<String, String> decryptionMap = new HashMap<>();
//decryptionMap = Utilities.readFromCodeCloud(authorization, dataSource.getDatasourceKey());
decryptionMap = applicationUtilities.readFromMongoCodeCloud(user, dataSource.getDatasourceKey());
Configuration config = helperTool.getKerberisedConfiguration(
dataSource.getCommonDetails().getServerName(),
decryptionMap.get("kerberosLoginUser".toLowerCase()));
try {
FileSystem fs = FileSystem.get(config);
if (dataSource.getHdfsHiveDetails().getHdfsFoldername() != null || hdfsFilename!=null && dataSource.getReadWriteDescriptor().equalsIgnoreCase("write")) {
log.info("writebackPrediction : create hdfs file "+dataSource.getHdfsHiveDetails().getHdfsFoldername()+"/"+hdfsFilename);
FSDataOutputStream out = fs.create(new Path(dataSource.getHdfsHiveDetails().getHdfsFoldername()+"/"+hdfsFilename));
log.info("writebackPrediction : write data-->"+data+" to hdfs file "+dataSource.getHdfsHiveDetails().getHdfsFoldername());
out.writeBytes(data);
out.close();
status = true;
}
} catch (Exception e) {
String[] variables = { e.getMessage()};
DataSrcRestError err = DataSrcErrorList.buildError(ErrorListEnum._0003, variables, null, CmlpApplicationEnum.DATASOURCE);
throw new DataSrcException("Invalid insert query parameter",
Status.BAD_REQUEST.getStatusCode(), err);
}
return status;
}
}
| 46.238655 | 173 | 0.742403 |
2bb011aca4ec55fb6365f724b2ddad226d5e7e1d | 3,033 | package cn.itsite.aguider.demo;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import cn.itsite.aguider.demo.demo.AnywhereActivity;
import cn.itsite.aguider.demo.demo.CombinationActivity;
import cn.itsite.aguider.demo.demo.FragmentActivity;
import cn.itsite.aguider.demo.demo.ListActivity;
import cn.itsite.aguider.demo.demo.NextActivity;
import cn.itsite.aguider.demo.demo.SimpleActivity;
import cn.itsite.aguider.demo.demo.TogetherActivity;
/**
* @author leguang
* @version v0.0.0
* @E-mail [email protected]
* @time 2016/11/24 0024 9:08
*/
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "MainActivity";
private Button btSimple;
private Button btNext;
private Button btTogether;
private Button btList;
private Button btFragment;
private Button btAny;
private Button btCombination;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initData();
}
private void initView() {
btSimple = (Button) findViewById(R.id.bt_simple);
btNext = (Button) findViewById(R.id.bt_next);
btTogether = (Button) findViewById(R.id.bt_together);
btList = (Button) findViewById(R.id.bt_list);
btFragment = (Button) findViewById(R.id.bt_fragment);
btAny = (Button) findViewById(R.id.bt_any);
btCombination = (Button) findViewById(R.id.bt_combination);
}
private void initData() {
btSimple.setOnClickListener(this);
btNext.setOnClickListener(this);
btTogether.setOnClickListener(this);
btList.setOnClickListener(this);
btFragment.setOnClickListener(this);
btAny.setOnClickListener(this);
btCombination.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.bt_simple:
startActivity(new Intent(this, SimpleActivity.class));
break;
case R.id.bt_next:
startActivity(new Intent(this, NextActivity.class));
break;
case R.id.bt_together:
startActivity(new Intent(this, TogetherActivity.class));
break;
case R.id.bt_list:
startActivity(new Intent(this, ListActivity.class));
break;
case R.id.bt_fragment:
startActivity(new Intent(this, FragmentActivity.class));
break;
case R.id.bt_any:
startActivity(new Intent(this, AnywhereActivity.class));
break;
case R.id.bt_combination:
startActivity(new Intent(this, CombinationActivity.class));
break;
default:
}
}
}
| 34.078652 | 85 | 0.652819 |
23a4dbf641f08d40f3185ea359e33f51d53d990a | 465 | package com.realz.swords.swordeffects;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.SwordItem;
import net.minecraft.world.item.Tier;
public class HellIronSword extends SwordItem {
public HellIronSword(Tier tier, int attackDamageIn, float attackSpeedIn, Properties builderIn) {
super(tier, attackDamageIn, attackSpeedIn, builderIn);
}
public boolean hasEffect(ItemStack itemstack) {
return true;
}
}
| 27.352941 | 100 | 0.756989 |
428cc9e9f952f74c9c7681e30a172e99dd636113 | 521 | // Copyright 2021 The Terasology Foundation
// SPDX-License-Identifier: Apache-2.0
package org.terasology.engine.logic.players.event;
import org.terasology.engine.entitySystem.event.Event;
/**
* This event gets sent when the player respawns.<br/>
* The player entity is preserved along with its components during respawn.<br/>
* This event should be received and handled by systems that need to reset
* some components attached to the player entity.
*/
public class OnPlayerRespawnedEvent implements Event {
}
| 34.733333 | 81 | 0.775432 |
e12cdfe1e563295dc35b110ee7603d4a769634a0 | 3,200 | /*
* Copyright 2010-2012 VMware and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springsource.loaded.test;
import org.junit.Before;
import org.junit.Test;
import org.springsource.loaded.ReloadableType;
import org.springsource.loaded.TypeRegistry;
import org.springsource.loaded.test.infra.TestClassloaderWithRewriting;
public class GroovyBenchmarkTests extends SpringLoadedTests {
@Before
public void setUp() throws Exception {
switchToGroovy();
}
/**
* I'm interested in checking the performance difference between having compilable call sites on and off. So let's
* load a program that simply makes a method call 1000s of times. No reloading, this is just to check the runtime
* cost of rewriting.
*/
@Test
public void benchmarkingGroovyMethodInvocations() throws Exception {
binLoader = new TestClassloaderWithRewriting();
String t = "simple.BasicH";
String target = "simple.BasicETarget";
TypeRegistry r = getTypeRegistry(t + "," + target);
ReloadableType rtype = r.addType(t, loadBytesForClass(t));
// ReloadableType rtypeTarget =
r.addType(target, loadBytesForClass(target));
// result = runUnguarded(rtype.getClazz(), "run");
// System.out.println(result.returnValue + "ms");
// compilable off
// 2200,2331,2117
// arrays rather than collections:
// 1775, 1660
// compilable on (but still using collections)
// 516, 716, 669
// compilable on and arrays:
// 238ms (compilable on configurable in GroovyPlugin)
// ok - avoid rewriting field references to $callSiteArray (drops to 319ms)
// 116ms! (this change not yet active)
// changing it so that we dont intercept $getCallSiteArray either
// 92ms
// run directly (main method in BasicH)
// 56 !
System.out.print("warmup ... ");
for (int loop = 0; loop < 10; loop++) {
System.out.print(loop + " ");
result = runUnguarded(rtype.getClazz(), "run");
// System.out.println(result.returnValue + "ms");
}
System.out.println();
long total = 0;
result = runUnguarded(rtype.getClazz(), "run");
total += new Long((String) result.returnValue).longValue();
result = runUnguarded(rtype.getClazz(), "run");
total += new Long((String) result.returnValue).longValue();
result = runUnguarded(rtype.getClazz(), "run");
total += new Long((String) result.returnValue).longValue();
System.out.println("Average for 3 iterations is " + (total / 3) + "ms");
// rtype.loadNewVersion("2", retrieveRename(t, t + "2"));
// rtypeTarget.loadNewVersion("2", retrieveRename(target, target + "2"));
//
// result = runUnguarded(rtype.getClazz(), "run");
// assertEquals("foobar", result.returnValue);
}
}
| 34.782609 | 115 | 0.709063 |
a793fc20fe80f1cb530309f750d3ea00db4b6ef0 | 1,182 | package tests;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.testng.annotations.Test;
import java.util.List;
public class MenuItemsTest extends LoginAdminFixture {
@Test
public void clickAllMenuItems() {
List<WebElement> outerMenuItems = driver.findElements(By.cssSelector("li[id^='app"));
String outerMenuItemLocator = "li[id^='app']:nth-child(%s)";
String innerMenuItemLocator = "li[id^='doc']:nth-child(%s)";
for (int i = 1; i <= outerMenuItems.size(); i++) {
driver.findElement(By.cssSelector(String.format(outerMenuItemLocator, i))).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("h1")));
List<WebElement> innerMenuItems = driver.findElements(By.cssSelector("li[id^='doc']"));
for (int j = 2; j <= innerMenuItems.size(); j++) {
driver.findElement(By.cssSelector(String.format(innerMenuItemLocator, j))).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("h1")));
}
}
}
}
| 40.758621 | 99 | 0.669205 |
fc0541ec1e93caf091a45cc7d798da5d9696ad49 | 2,986 | package io.moonman.emergingtechnology.helpers.machines;
import io.moonman.emergingtechnology.config.EmergingTechnologyConfig;
import io.moonman.emergingtechnology.helpers.StackHelper;
import io.moonman.emergingtechnology.item.items.BlueBulb;
import io.moonman.emergingtechnology.item.items.BulbItem;
import io.moonman.emergingtechnology.item.items.GreenBulb;
import io.moonman.emergingtechnology.item.items.PurpleBulb;
import io.moonman.emergingtechnology.item.items.RedBulb;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
/**
Provides useful methods for the Hydroponic Grow Light
*/
public class LightHelper {
public static final int BULB_COUNT = 4;
public static boolean isGlowstonePowered(ItemStack itemStack) {
return StackHelper.compareItemStacks(itemStack, new ItemStack(Blocks.GLOWSTONE));
}
public static boolean isItemStackValidBulb(ItemStack itemStack) {
if (StackHelper.isItemStackEmpty(itemStack)) {
return false;
}
if (itemStack.getItem() instanceof BulbItem) {
return true;
}
return false;
};
public static int getBulbTypeIdFromStack(ItemStack itemStack) {
if (isItemStackValidBulb(itemStack)) {
Item item = itemStack.getItem();
if (item instanceof RedBulb) {
return 1;
} else if (item instanceof GreenBulb) {
return 2;
} else if (item instanceof BlueBulb) {
return 3;
} else if (item instanceof PurpleBulb) {
return 4;
}
}
return 0;
}
public static int getGrowthProbabilityForBulbById(int bulbTypeId) {
switch (bulbTypeId) {
case 0:
return 0;
case 1:
return EmergingTechnologyConfig.HYDROPONICS_MODULE.GROWLIGHT.growthRedBulbModifier;
case 2:
return EmergingTechnologyConfig.HYDROPONICS_MODULE.GROWLIGHT.growthGreenBulbModifier;
case 3:
return EmergingTechnologyConfig.HYDROPONICS_MODULE.GROWLIGHT.growthBlueBulbModifier;
case 4:
return EmergingTechnologyConfig.HYDROPONICS_MODULE.GROWLIGHT.growthPurpleBulbModifier;
default:
return 0;
}
}
public static int getEnergyUsageModifierForBulbById(int bulbTypeId) {
switch (bulbTypeId) {
case 0:
return 1;
case 1:
return EmergingTechnologyConfig.HYDROPONICS_MODULE.GROWLIGHT.energyRedBulbModifier;
case 2:
return EmergingTechnologyConfig.HYDROPONICS_MODULE.GROWLIGHT.energyGreenBulbModifier;
case 3:
return EmergingTechnologyConfig.HYDROPONICS_MODULE.GROWLIGHT.energyBlueBulbModifier;
case 4:
return EmergingTechnologyConfig.HYDROPONICS_MODULE.GROWLIGHT.energyPurpleBulbModifier;
default:
return 1;
}
}
} | 32.813187 | 98 | 0.67716 |
8db94ebf77bce7db7ec4aca5dd71a3d26de18e81 | 534 | package com.github.payments.service;
import com.github.payments.service.impl.EthereumService;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
@FeignClient(
name = "ethereum",
fallback = EthereumService.class
)
public interface IEthereumService {
@DeleteMapping(
path = "/v1/accounts/{address}"
)
void remove(@PathVariable(name = "address") String address);
}
| 26.7 | 64 | 0.745318 |
44babb590596c1c7f8e1f1e786d5c29e120a56cf | 4,165 | package jp.co.rediscovery.firstflight;
/*
* By downloading, copying, installing or using the software you agree to this license.
* If you do not agree to this license, do not download, install,
* copy or use the software.
*
*
* License Agreement
* (3-clause BSD License)
*
* Copyright (C) 2015-2018, saki [email protected]
*
* 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 names of the copyright holders nor the names of the 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 copyright holders 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.
*/
import android.database.DataSetObserver;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.viewpager.widget.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.serenegiant.mediastore.MediaStoreImageAdapter;
/** 端末内の静止画を表示するためのFragment */
public class PhotoFragment extends BaseFragment {
private static final boolean DEBUG = false; // FIXME 実働時はfalseにすること
private static final String TAG = PhotoFragment.class.getSimpleName();
private static final String KEY_FILE_ID = "PhotoFragment_KEY_FILE_ID";
private ViewPager mViewPager;
private MediaStoreImageAdapter mAdapter;
private long mId;
public static PhotoFragment newInstance(final long id) {
PhotoFragment fragment = new PhotoFragment();
final Bundle args = new Bundle();
args.putLong(KEY_FILE_ID, id);
fragment.setArguments(args);
return fragment;
}
public PhotoFragment() {
super();
// デフォルトコンストラクタが必要
}
@Override
public View onCreateView(@NonNull final LayoutInflater inflater,
final ViewGroup container, final Bundle savedInstanceState) {
loadArguments(savedInstanceState);
final View rootView = inflater.inflate(R.layout.fragment_photo, container, false);
initView(rootView);
return rootView;
}
@Override
protected void loadArguments(final Bundle savedInstanceState) {
Bundle args = savedInstanceState;
if (args == null) {
args = getArguments();
}
mId = args.getLong(KEY_FILE_ID);
}
private void initView(final View rootView) {
mViewPager = rootView.findViewById(R.id.viewpager);
mViewPager.setKeepScreenOn(true);
mAdapter = new MediaStoreImageAdapter(getActivity(), R.layout.grid_item_media, false);
// MediaStoreImageAdapterのCursorクエリーは非同期で実行されるので
// 生成直後はアイテム数が0になるのでクエリー完了時にViewPager#setAdapterを実行する
mAdapter.registerDataSetObserver(new DataSetObserver() {
@Override
public void onChanged() {
super.onChanged();
mViewPager.setAdapter(mAdapter);
mViewPager.setCurrentItem(mAdapter.getItemPositionFromID(mId));
mAdapter.unregisterDataSetObserver(this); // 初回だけでOKなので登録解除する
}
@Override
public void onInvalidated() {
super.onInvalidated();
}
});
mAdapter.startQuery(); // 非同期クエリー開始
}
}
| 35.905172 | 88 | 0.757023 |
1264bf839f94e3af2e5a0d429c10a201532af5cf | 1,029 | package org.hsmak.reactive.repository;
import org.hsmak.reactive.entity.Movie;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;
import java.time.Duration;
import java.util.List;
@Repository
public class MovieRepositoryImp implements MovieRepository {
private final List<Movie> movies = List.of(
new Movie("Polar (2019)", 64),
new Movie("Iron Man (2008)", 79),
new Movie("The Shawshank Redemption (1994)", 93),
new Movie("Forrest Gump (1994)", 83),
new Movie("Glass (2019)", 70)
);
@Override
public Flux<Movie> findAll() {
// Stream data with 1 second delay.
return Flux.fromIterable(movies)
.delayElements(Duration.ofSeconds(1));
// Nonstop & Repeatedly, Stream the whole List every 2 second
/*return Flux.interval(Duration.ofSeconds(2))
.onBackpressureDrop()
.map(x -> movie)
.flatMapIterable(x -> x);*/
}
}
| 29.4 | 69 | 0.620991 |
c05241e450f5fbb4752ccfc3cbb2ebbd1fc9aee0 | 750 | package com.easymicro.persistence.config;
import com.easymicro.persistence.core.factory.CustomRepositoryFactoryBean;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
/**************************************
* 配置打开JPA配置
* @author LinYingQiang
* @date 2018-08-09 20:05
* @qq 961410800
*
************************************/
@Configuration
@EnableJpaRepositories(repositoryFactoryBeanClass = CustomRepositoryFactoryBean.class, basePackages = {"com.easymicro.persistence.modular.repository"})
@EntityScan(basePackages = {"com.easymicro.persistence.modular.model"})
public class JpaConfig {
}
| 35.714286 | 151 | 0.742667 |
f76fde9ef19c8521a7dc783c7370e8a756561b44 | 5,051 | /*-
* ============LICENSE_START=======================================================
* ONAP - SO
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (c) 2019 Samsung
* ================================================================================
* 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.
* ============LICENSE_END=========================================================
*/
package org.onap.so.bpmn.common.workflow.service;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.onap.so.logger.LoggingAnchor;
import org.onap.so.bpmn.common.workflow.service.CallbackHandlerService.CallbackError;
import org.onap.so.bpmn.common.workflow.service.CallbackHandlerService.CallbackResult;
import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
/**
* Generalized REST interface that injects a message event into a waiting BPMN process. Examples:
*
* <pre>
* /WorkflowMessage/SDNCAResponse/6d10d075-100c-42d0-9d84-a52432681cae-1478486185286
* /WorkflowMessage/SDNCAEvent/USOSTCDALTX0101UJZZ01
* </pre>
*/
@Path("/")
@Api(description = "Provides a generic service to inject messages into a waiting BPMN Proccess")
@Component
public class WorkflowMessageResource {
private static final Logger logger = LoggerFactory.getLogger(WorkflowMessageResource.class);
private static final String LOGMARKER = "[WORKFLOW-MESSAGE]";
@Autowired
CallbackHandlerService callback;
@POST
@Path("/WorkflowMessage/{messageType}/{correlator}")
@ApiOperation(value = "Workflow message correlator", notes = "")
@Consumes("*/*")
@Produces(MediaType.TEXT_PLAIN)
public Response deliver(@HeaderParam("Content-Type") String contentType,
@PathParam("messageType") String messageType, @PathParam("correlator") String correlator, String message) {
String method = "receiveWorkflowMessage";
logger.debug(LOGMARKER + " Received workflow message" + " type='" + messageType + "'" + " correlator='"
+ correlator + "'" + (contentType == null ? "" : " contentType='" + contentType + "'") + " message="
+ System.lineSeparator() + message);
if (messageType == null || messageType.isEmpty()) {
String msg = "Missing message type";
logger.debug(LOGMARKER + " " + msg);
logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN",
ErrorCode.DataError.getValue(), LOGMARKER + ":" + msg);
return Response.status(400).entity(msg).build();
}
if (correlator == null || correlator.isEmpty()) {
String msg = "Missing correlator";
logger.debug(LOGMARKER + " " + msg);
logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN",
ErrorCode.DataError.getValue(), LOGMARKER + ":" + msg);
return Response.status(400).entity(msg).build();
}
String messageEventName = "WorkflowMessage";
String messageVariable = messageType + "_MESSAGE";
String correlationVariable = messageType + "_CORRELATOR";
String correlationValue = correlator;
String contentTypeVariable = messageType + "_CONTENT_TYPE";
Map<String, Object> variables = new HashMap<>();
if (contentType != null) {
variables.put(contentTypeVariable, contentType);
}
CallbackResult result = callback.handleCallback(method, message, messageEventName, messageVariable,
correlationVariable, correlationValue, LOGMARKER, variables);
if (result instanceof CallbackError) {
return Response.status(500).entity(((CallbackError) result).getErrorMessage()).build();
} else {
return Response.status(204).build();
}
}
}
| 43.17094 | 119 | 0.641457 |
3517b0dd1337a114d8c0b6eefbf0b3468c3e8d70 | 8,917 | package com.enderio.base.common.item.tool;
import com.enderio.base.common.capability.EIOCapabilities;
import com.enderio.base.common.capability.entity.EntityStorage;
import com.enderio.base.common.capability.entity.IEntityStorage;
import com.enderio.base.common.item.EIOCreativeTabs;
import com.enderio.base.common.item.EIOItems;
import com.enderio.base.common.util.EntityCaptureUtils;
import com.enderio.core.common.capability.IMultiCapabilityItem;
import com.enderio.core.common.capability.MultiCapabilityProvider;
import com.enderio.core.common.util.EntityUtil;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.NonNullList;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.TextComponent;
import net.minecraft.network.chat.TranslatableComponent;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.Mth;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.CreativeModeTab;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.level.Level;
import net.minecraftforge.common.util.LazyOptional;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
public class SoulVialItem extends Item implements IMultiCapabilityItem {
public SoulVialItem(Properties pProperties) {
super(pProperties);
}
// Item appearance and description
@Override
public boolean isFoil(@Nonnull ItemStack pStack) {
return getEntityType(pStack).isPresent();
}
@Override
public void appendHoverText(@Nonnull ItemStack pStack, @Nullable Level pLevel, @Nonnull List<Component> pTooltipComponents,
@Nonnull TooltipFlag pIsAdvanced) {
super.appendHoverText(pStack, pLevel, pTooltipComponents, pIsAdvanced);
// Add entity information
getEntityType(pStack).ifPresent(entityType -> {
pTooltipComponents.add(new TranslatableComponent(EntityUtil.getEntityDescriptionId(entityType)));
// TODO: Also add health data
});
}
// endregion
// region Interactions
// Capture logic
@Nonnull
@Override
public InteractionResult interactLivingEntity(@Nonnull ItemStack pStack, @Nonnull Player pPlayer, @Nonnull LivingEntity pInteractionTarget,
@Nonnull InteractionHand pUsedHand) {
if (pPlayer.level.isClientSide) {
return InteractionResult.FAIL;
}
if (getEntityType(pStack).isEmpty()) {
// Don't allow bottled player.
if (pInteractionTarget instanceof Player) {
// TODO: Language keys
pPlayer.displayClientMessage(new TextComponent("You cannot put player in a bottle"), true);
return InteractionResult.FAIL;
}
// Get the entity type and verify it isn't blacklisted
// TODO: maybe make the method give a rejection reason so we can give accurate status messages?
if (!EntityCaptureUtils.canCapture(pInteractionTarget)) {
pPlayer.displayClientMessage(new TextComponent("This entity cannot be captured"), true);
return InteractionResult.FAIL;
}
// No dead mobs.
if (!pInteractionTarget.isAlive()) {
pPlayer.displayClientMessage(new TextComponent("Cannot capture dead mob"), true);
return InteractionResult.FAIL;
}
// Create a filled vial and put the entity's NBT inside.
ItemStack filledVial = new ItemStack(EIOItems.FILLED_SOUL_VIAL.get());
setEntityNBT(filledVial, pInteractionTarget.serializeNBT());
// Consume a soul vial
ItemStack hand = pPlayer.getItemInHand(pUsedHand);
hand.shrink(1);
// Give the player the filled vial
if (hand.isEmpty()) {
pPlayer.setItemInHand(pUsedHand, filledVial);
} else {
if (!pPlayer.addItem(filledVial)) {
pPlayer.drop(filledVial, false);
}
}
// Remove the captured mob.
pInteractionTarget.discard();
}
return InteractionResult.SUCCESS;
}
// Release logic
@Nonnull
@Override
public InteractionResult useOn(UseOnContext pContext) {
if (pContext.getLevel().isClientSide) {
return InteractionResult.FAIL;
}
ItemStack itemStack = pContext.getItemInHand();
Player player = pContext.getPlayer();
// Only players may use the soul vial
if (player == null) {
return InteractionResult.FAIL;
}
// Try to get the entity type from the item stack.
getEntityType(itemStack).ifPresent(entityType -> {
// Get the face of the block we clicked and its position.
Direction face = pContext.getClickedFace();
BlockPos spawnPos = pContext.getClickedPos();
// Get the spawn location for the mob.
double spawnX = spawnPos.getX() + face.getStepX() + 0.5;
double spawnY = spawnPos.getY() + face.getStepY();
double spawnZ = spawnPos.getZ() + face.getStepZ() + 0.5;
// Get a random rotation for the entity.
float rotation = Mth.wrapDegrees(pContext
.getLevel()
.getRandom()
.nextFloat() * 360.0f);
// Try to get the entity NBT from the item.
getEntityNBT(itemStack).ifPresent(entityTag -> {
Optional<Entity> entity = EntityType.create(entityTag, pContext.getLevel());
// Position the entity and add it.
entity.ifPresent(ent -> {
ent.setPos(spawnX, spawnY, spawnZ);
ent.setYRot(rotation);
pContext
.getLevel()
.addFreshEntity(ent);
});
});
// Empty the soul vial.
player.setItemInHand(pContext.getHand(), new ItemStack(EIOItems.EMPTY_SOUL_VIAL.get()));
});
return InteractionResult.SUCCESS;
}
// endregion
// region Creative tabs
@Override
public void fillItemCategory(@Nonnull CreativeModeTab pCategory, @Nonnull NonNullList<ItemStack> pItems) {
if (pCategory == getItemCategory()) {
pItems.add(new ItemStack(EIOItems.EMPTY_SOUL_VIAL.get()));
} else if (pCategory == EIOCreativeTabs.SOULS) {
// Register for every mob that can be captured.
for (ResourceLocation entity : EntityCaptureUtils.getCapturableEntities()) {
ItemStack is = new ItemStack(EIOItems.FILLED_SOUL_VIAL.get());
setEntityType(is, entity);
pItems.add(is);
}
}
}
@Override
public Collection<CreativeModeTab> getCreativeTabs() {
return Arrays.asList(getItemCategory(), EIOCreativeTabs.SOULS);
}
// endregion
// region Entity Storage
public static Optional<ResourceLocation> getEntityType(ItemStack stack) {
return stack
.getCapability(EIOCapabilities.ENTITY_STORAGE)
.map(IEntityStorage::getEntityType)
.orElse(Optional.empty());
}
public static Optional<CompoundTag> getEntityNBT(ItemStack stack) {
return stack
.getCapability(EIOCapabilities.ENTITY_STORAGE)
.map(IEntityStorage::getEntityNBT)
.orElse(Optional.empty());
}
private static void setEntityType(ItemStack stack, ResourceLocation entityType) {
stack
.getCapability(EIOCapabilities.ENTITY_STORAGE)
.ifPresent(storage -> {
storage.setEntityType(entityType);
});
}
private static void setEntityNBT(ItemStack stack, CompoundTag entity) {
stack
.getCapability(EIOCapabilities.ENTITY_STORAGE)
.ifPresent(storage -> {
storage.setEntityNBT(entity);
});
}
@Nullable
@Override
public MultiCapabilityProvider initCapabilities(ItemStack stack, @Nullable CompoundTag nbt, MultiCapabilityProvider provider) {
provider.addSerialized(EIOCapabilities.ENTITY_STORAGE, LazyOptional.of(EntityStorage::new));
return provider;
}
// endregion
}
| 36.395918 | 143 | 0.652798 |
31b1f9f968ac553fb00544562f27c356508b0531 | 3,629 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* 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.intellij.javaee;
import com.intellij.xml.util.HtmlUtil;
import com.intellij.xml.util.XmlUtil;
/**
* @author Dmitry Avdeev
*/
public class InternalResourceProvider implements StandardResourceProvider{
@Override
public void registerResources(ResourceRegistrar registrar) {
ResourceRegistrarImpl impl = (ResourceRegistrarImpl)registrar;
impl.addInternalResource(XmlUtil.XSLT_URI,"xslt-1_0.xsd");
impl.addInternalResource(XmlUtil.XSLT_URI,"2.0", "xslt-2_0.xsd");
impl.addInternalResource(XmlUtil.XINCLUDE_URI,"xinclude.xsd");
impl.addInternalResource(XmlUtil.XML_SCHEMA_URI, "XMLSchema.xsd");
impl.addInternalResource(XmlUtil.XML_SCHEMA_URI + ".xsd", "XMLSchema.xsd");
impl.addInternalResource("http://www.w3.org/2001/XMLSchema.dtd", "XMLSchema.dtd");
impl.addInternalResource(XmlUtil.XML_SCHEMA_INSTANCE_URI, "XMLSchema-instance.xsd");
impl.addInternalResource(XmlUtil.XML_SCHEMA_VERSIONING_URI, "XMLSchema-versioning.xsd");
impl.addInternalResource("http://www.w3.org/2001/xml.xsd","xml.xsd");
impl.addInternalResource(XmlUtil.XML_NAMESPACE_URI,"xml.xsd");
impl.addInternalResource(XmlUtil.XHTML_URI,"xhtml1-transitional.xsd");
impl.addInternalResource("http://www.w3.org/2002/08/xhtml/xhtml1-strict.xsd","xhtml1-strict.xsd");
impl.addInternalResource("http://www.w3.org/TR/html4/strict.dtd","xhtml1-strict.dtd");
impl.addInternalResource(XmlUtil.HTML4_LOOSE_URI,"xhtml1-transitional.dtd");
impl.addInternalResource("http://www.w3.org/TR/html4/frameset.dtd","xhtml1-frameset.dtd");
impl.addInternalResource("http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd","xhtml1-strict.dtd");
impl.addInternalResource("http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd","xhtml1-transitional.dtd");
impl.addInternalResource("http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd","xhtml1-frameset.dtd");
impl.addInternalResource("http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd","xhtml11/xhtml11.dtd");
impl.addInternalResource("urn:oasis:names:tc:entity:xmlns:xml:catalog", "catalog.xsd");
// Plugins DTDs // stathik
impl.addInternalResource("http://plugins.intellij.net/plugin.dtd", "plugin.dtd");
impl.addInternalResource("http://plugins.intellij.net/plugin-repository.dtd", "plugin-repository.dtd");
// mobile
impl.addInternalResource("http://www.wapforum.org/DTD/xhtml-mobile10.dtd", "xhtml-mobile/xhtml-mobile10.dtd");
impl.addInternalResource("http://www.wapforum.org/DTD/xhtml-mobile10-flat.dtd", "xhtml-mobile/xhtml-mobile10-flat.dtd");
impl.addInternalResource("http://www.wapforum.org/DTD/xhtml-mobile12.dtd", "xhtml-mobile/xhtml-mobile12.dtd");
impl.addInternalResource("http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd", "xhtml-mobile/xhtml-mobile12.dtd");
// svg and mathML
impl.addIgnoredResource(HtmlUtil.MATH_ML_NAMESPACE);
impl.addIgnoredResource(HtmlUtil.SVG_NAMESPACE);
impl.addInternalResource("http://www.w3.org/1999/xlink", "xlink.dtd");
}
}
| 50.402778 | 129 | 0.754202 |
f4104921df223b18f3c181526cf3b630c7cb14de | 245 | package com.giffing.wicket.spring.boot.example.web.general.action.panel.items;
import org.apache.wicket.markup.html.panel.Panel;
public abstract class AbstrractActionItem extends Panel {
public AbstrractActionItem() {
super("item");
}
}
| 20.416667 | 78 | 0.779592 |
5e8cab191eddd3aeb60e9003fdf84c373575be32 | 563 | package com.stormmq.java.parsing.adaptors.javaparser.voidVisitors.bodyDeclarations.usefuls;
import com.github.javaparser.ast.expr.Expression;
import com.stormmq.java.parsing.ast.details.fieldValueDetails.FieldValueDetail;
import org.jetbrains.annotations.NotNull;
public final class UsefulFieldValueDetail implements FieldValueDetail
{
private final boolean shouldBeConstant;
public UsefulFieldValueDetail(@NotNull final Expression init, final boolean shouldBeConstant, final boolean isAnnotationConstant)
{
this.shouldBeConstant = shouldBeConstant;
}
}
| 35.1875 | 130 | 0.849023 |
f8b3bc03e36152bdd173faaa2905feeee8ec458d | 1,072 | package xws.util;
import xws.neuron.Tensor;
import java.util.ArrayList;
import java.util.List;
/**
* RNN DATA
* Created by xws on 2019/5/19.
*/
public class RnnSequence {
private List<Cifar10> list = new ArrayList<>();
public Cifar10 get(int index) {
return list.get(index);
}
public Tensor getData(int index) {
return list.get(index).getRgb();
}
public double[] getExpect(int index) {
return new double[]{list.get(index).getValue()};
}
public void add(Cifar10 cifar10) {
list.add(cifar10);
}
public void add(double[] key, double val) {
Tensor tensor = new Tensor();
tensor.setWidth(key.length);
tensor.setArray(key);
Cifar10 cifar10 = new Cifar10();
cifar10.setRgb(tensor);
cifar10.setValue(val);
list.add(cifar10);
}
public int size() {
return list.size();
}
public List<Cifar10> getList() {
return list;
}
public void setList(List<Cifar10> list) {
this.list = list;
}
}
| 18.482759 | 56 | 0.587687 |
aa9c63a3c1c031a5984c884b033e8ce531640fa9 | 3,015 | /*
* Copyright [2013-2021], Alibaba Group Holding Limited
*
* 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.alibaba.polardbx.server.response;
import com.alibaba.polardbx.CobarServer;
import com.alibaba.polardbx.executor.cursor.ResultCursor;
import com.alibaba.polardbx.executor.cursor.impl.ArrayResultCursor;
import com.alibaba.polardbx.executor.sync.ISyncAction;
import com.alibaba.polardbx.matrix.jdbc.TDataSource;
import com.alibaba.polardbx.optimizer.core.datatype.DataTypes;
import com.alibaba.polardbx.optimizer.utils.ITransaction;
import com.alibaba.polardbx.transaction.BaseTransaction;
import com.alibaba.polardbx.transaction.TransactionManager;
import java.util.Collection;
public class ShowTransSyncAction implements ISyncAction {
private String db;
public ShowTransSyncAction() {
}
public ShowTransSyncAction(String db) {
this.db = db;
}
public String getDb() {
return db;
}
public void setDb(String db) {
this.db = db;
}
@Override
public ResultCursor sync() {
TDataSource ds = CobarServer.getInstance().getConfig().getSchemas().get(db).getDataSource();
TransactionManager tm =
(TransactionManager) ds.getConfigHolder().getExecutorContext().getTransactionManager();
Collection<ITransaction> transactions = tm.getTransactions().values();
ArrayResultCursor result = new ArrayResultCursor("TRANSACTIONS");
result.addColumn("TRANS_ID", DataTypes.StringType);
result.addColumn("TYPE", DataTypes.StringType);
result.addColumn("DURATION_MS", DataTypes.LongType);
result.addColumn("STATE", DataTypes.StringType);
result.addColumn("PROCESS_ID", DataTypes.LongType);
long currentTimeMs = System.currentTimeMillis();
for (ITransaction transaction : transactions) {
if (transaction.isBegun()) {
final BaseTransaction tx = (BaseTransaction) transaction;
final String transId = Long.toHexString(tx.getId());
final String type = tx.getTransactionClass().toString();
final long duration = currentTimeMs - tx.getStartTime();
final String state = transaction.getState().toString();
final long processId = transaction.getExecutionContext().getConnection().getId();
result.addRow(new Object[] {transId, type, duration, state, processId});
}
}
return result;
}
}
| 37.6875 | 100 | 0.701161 |
52c7e249613fefd87830a1e0731b7233e693769e | 6,852 | package org.vandeseer.integrationtest;
import org.apache.pdfbox.io.IOUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.junit.Before;
import org.junit.Test;
import org.vandeseer.TestUtils;
import org.vandeseer.easytable.structure.Row;
import org.vandeseer.easytable.structure.Table;
import org.vandeseer.easytable.structure.cell.AbstractCell;
import org.vandeseer.easytable.structure.cell.ImageCell;
import org.vandeseer.easytable.structure.cell.TextCell;
import org.vandeseer.easytable.structure.cell.VerticalTextCell;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import static org.apache.pdfbox.pdmodel.font.PDType1Font.HELVETICA;
import static org.vandeseer.easytable.settings.VerticalAlignment.MIDDLE;
public class VerticalTextCellTest {
private static final Color LIGHT_GREEN = new Color(221, 255, 217);
private PDFont ownFont;
private PDImageXObject checkImage;
@Before
public void before() throws IOException {
PDDocument document = new PDDocument();
// Load a custom font
final InputStream resourceAsStream = this.getClass()
.getClassLoader()
.getResourceAsStream("OpenSansCondensed-Light.ttf");
ownFont = PDType0Font.load(document, resourceAsStream);
// Load custom image
final byte[] sampleBytes = IOUtils.toByteArray(Objects.requireNonNull(this.getClass().getClassLoader()
.getResourceAsStream("check.png")));
checkImage = PDImageXObject.createFromByteArray(document, sampleBytes, "check");
}
@Test
public void testVerticalTextCell() throws IOException {
TestUtils.createAndSaveDocumentWithTables("cellVerticalText.pdf",
createSimpleTable(),
createKnowledgeBaseExampleTable()
);
}
private static Table createSimpleTable() {
final Table.TableBuilder tableBuilder = Table.builder()
.addColumnsOfWidth(100, 100, 100, 100)
.fontSize(8)
.font(HELVETICA);
tableBuilder
.addRow(Row.builder()
.add(VerticalTextCell.builder().minHeight(80f).borderWidth(1).text("This is a super long text that does not fit in one line").build())
.add(VerticalTextCell.builder().borderWidth(1).text("Two").build())
.add(VerticalTextCell.builder().rowSpan(2).borderWidth(1).text("This is again a very long text that will break at one point :)").build())
.add(VerticalTextCell.builder().borderWidth(1).text("Four").build())
.build())
.addRow(Row.builder()
.add(TextCell.builder().borderWidth(1).text("One 1\nFubarbar").build())
.add(TextCell.builder().borderWidth(1).text("Abc").build())
.add(VerticalTextCell.builder().borderWidth(1).text("Four").build())
.build());
return tableBuilder.build();
}
private Table createKnowledgeBaseExampleTable() {
final Table.TableBuilder tableBuilder = Table.builder()
.addColumnsOfWidth(200, 20, 20, 20, 20, 20)
.fontSize(8)
.font(ownFont)
.addRow(Row.builder()
.add(createEmptySpacingCell())
.add(createPersonCell("Ralph"))
.add(createPersonCell("Homer"))
.add(createPersonCell("Bart"))
.add(createPersonCell("Moe"))
.add(createPersonCell("Krusty"))
.build())
.addRow(Row.builder()
.add(createTechCell("Machine Learning"))
.add(createCheckCell())
.add(createCheckCell())
.add(createCheckCell())
.add(createEmptyCellWithBorders())
.add(createCheckCell())
.backgroundColor(LIGHT_GREEN)
.build())
.addRow(Row.builder()
.add(createTechCell("Software Engineering"))
.add(createCheckCell())
.add(createEmptyCellWithBorders())
.add(createCheckCell())
.add(createCheckCell())
.add(createEmptyCellWithBorders())
.build())
.addRow(Row.builder()
.add(createTechCell("Databases"))
.add(createCheckCell())
.add(createCheckCell())
.add(createCheckCell())
.add(createEmptyCellWithBorders())
.add(createCheckCell())
.backgroundColor(LIGHT_GREEN)
.build())
.addRow(Row.builder()
.add(createTechCell("Network Technology"))
.add(createCheckCell())
.add(createEmptyCellWithBorders())
.add(createCheckCell())
.add(createEmptyCellWithBorders())
.add(createCheckCell())
.build())
.addRow(Row.builder()
.add(createTechCell("Security"))
.add(createCheckCell())
.add(createCheckCell())
.add(createEmptyCellWithBorders())
.add(createEmptyCellWithBorders())
.add(createEmptyCellWithBorders())
.backgroundColor(LIGHT_GREEN)
.build());
return tableBuilder.build();
}
private AbstractCell createEmptySpacingCell() {
return TextCell.builder().minHeight(50f).text("").build();
}
private AbstractCell createPersonCell(String ralph) {
return VerticalTextCell.builder().borderWidth(1).text(ralph).build();
}
private AbstractCell createTechCell(String tech) {
return TextCell.builder().borderWidth(1).text(tech).verticalAlignment(MIDDLE).build();
}
private AbstractCell createCheckCell() {
return ImageCell.builder().borderWidth(1).image(checkImage).build();
}
private AbstractCell createEmptyCellWithBorders() {
return TextCell.builder().text("").borderWidth(1).build();
}
}
| 42.03681 | 161 | 0.561734 |
53da9fd5f47f9c5b95212d346223d388604fe610 | 5,737 | package com.sauzny.ssq.oak.stream;
import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.sauzny.ssq.ForecastHong;
import com.sauzny.ssq.entity.YuCeHongTemp;
/**
* *************************************************************************
* @文件名称: Ssq2.java
*
* @包路径 : com.sauzny.jkitchen_note.oak.stream
*
* @版权所有: Personal xinxin (C) 2017
*
* @类描述: TODO
*
* @创建人: ljx
*
* @创建时间: 2017年12月4日 - 上午9:51:02
*
**************************************************************************
*/
public class Ssq3 {
public static void foo01(){
try {
// 定义数据文件位置
String userDir = System.getProperty("user.dir");
Path historyPath = Paths.get(userDir+"/history_ssq.dat");
// 读取数据
List<String> lines = Files.readAllLines(historyPath);
lines.remove(0);
// 变换数据类型, String -> SsqEntity
Stream<SsqEntity> stream = lines.stream().map(line -> {
String[] values = line.split("\t");
return new SsqEntity(values);
});
List<SsqEntity> list = stream.collect(toList());
// 定义最终结果
List<Integer> result = Lists.newArrayList();
for(int i=1;i<list.size();i++){
if(list.get(i).getLan() == list.get(i-1).getLan()){
result.add(list.get(i-1).getId());
result.add(list.get(i).getId());
}
}
System.out.println(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 根据最后一期蓝球数字,找到历史上所有 此数字 的下一期的 id
public static void foo02(){
try {
// 定义数据文件位置
String userDir = System.getProperty("user.dir");
Path historyPath = Paths.get(userDir+"/history_ssq.dat");
// 读取数据
List<String> lines = Files.readAllLines(historyPath);
lines.remove(0);
// 最后一期蓝球数字
String[] lastValues = Iterators.getLast(lines.iterator()).split("\t");
int lastLan = new SsqEntity(lastValues).getLan();
// 1. 变换数据类型, String -> SsqEntity
List<SsqEntity> ssqEntityList1 = lines.stream()
.map(line -> {
String[] values = line.split("\t");
return new SsqEntity(values);
})
.collect(toList());
List<SsqEntity> ssqEntityList2 = Lists.newArrayList();
// 2. 过滤数据
for(int i=1; i<ssqEntityList1.size(); i++){
if(ssqEntityList1.get(i-1).getLan() == lastLan){
ssqEntityList2.add(ssqEntityList1.get(i));
}
}
// 3. 分组
Map<Integer, Long> map = ssqEntityList2.stream().collect(groupingBy(SsqEntity::getLan, counting()));
map.forEach((k,v) -> System.out.println("lan:" + k + ", 次数:" + v) );
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String lastLine(File file, String charset) {
if (!file.exists() || file.isDirectory() || !file.canRead()) {
return null;
}
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(file, "r");
long len = raf.length();
if (len == 0L) {
return "";
} else {
long pos = len - 1;
while (pos > 0) {
pos--;
raf.seek(pos);
if (raf.readByte() == '\n') {
break;
}
}
if (pos == 0) {
raf.seek(0);
}
byte[] bytes = new byte[(int) (len - pos)];
raf.read(bytes);
if (charset == null) {
return new String(bytes);
} else {
return new String(bytes, charset);
}
}
} catch (Exception e) {
} finally {
if (raf != null) {
try {
raf.close();
} catch (Exception e2) {
}
}
}
return null;
}
public static SsqEntity lastSsqEntity(){
String userDir = System.getProperty("user.dir");
String line = lastLine(new File(userDir+"/history_ssq.dat"), StandardCharsets.UTF_8.toString());
String[] values = line.split("\t");
return new SsqEntity(values);
}
public static void main(String[] args) {
Ssq3.foo02();
int lastLan = lastSsqEntity().getLan();
List<YuCeHongTemp> yuCeHongList = ForecastHong.forecast(lastLan);
yuCeHongList.forEach(temp -> System.out.print(temp.getHongNum() + " ") );
System.out.println(" " + lastLan);
}
}
| 30.515957 | 112 | 0.469583 |
2682b0f013e38752a67ade97e5f36964616dc9e5 | 25,015 | package rastreio;
/**
* Inferred tracking object service type from object code.
* @see <a href="https://www.correios.com.br/enviar-e-receber/precisa-de-ajuda/siglas-utilizadas-no-rastreamento-de-objeto"></a>
*/
public enum TrackObjectServiceType {
/**
* AA - ETIQUETA LÓGICA SEDEX.
*/
AA("AA", "ETIQUETA LÓGICA SEDEX"),
/**
* AB - ETIQUETA LÓGICA SEDEX.
*/
AB("AB", "ETIQUETA LÓGICA SEDEX"),
/**
* AL - AGENTES DE LEITURA.
*/
AL("AL", "AGENTES DE LEITURA"),
/**
* AR - AVISO DE RECEBIMENTO.
*/
AR("AR", "AVISO DE RECEBIMENTO"),
/**
* AS - ENCOMENDA PAC - ACAO SOCIAL.
*/
AS("AS", "ENCOMENDA PAC - ACAO SOCIAL"),
/**
* BE - REMESSA ECONÔMICA S/ AR DIGITAL.
*/
BE("BE", "REMESSA ECONÔMICA S/ AR DIGITAL"),
/**
* BF - REMESSA EXPRESSA S/ AR DIGITAL.
*/
BF("BF", "REMESSA EXPRESSA S/ AR DIGITAL"),
/**
* BG - ETIQUETA LOG REM ECON C/AR BG.
*/
BG("BG", "ETIQUETA LOG REM ECON C/AR BG"),
/**
* BH - MENSAGEM FÍSICO-DIGITAL.
*/
BH("BH", "MENSAGEM FÍSICO-DIGITAL"),
/**
* BI - ETIQUETA LÓG REGIST URG.
*/
BI("BI", "ETIQUETA LÓG REGIST URG"),
/**
* CA - OBJETO INTERNACIONAL COLIS.
*/
CA("CA", "OBJETO INTERNACIONAL COLIS"),
/**
* CB - OBJETO INTERNACIONAL COLIS.
*/
CB("CB", "OBJETO INTERNACIONAL COLIS"),
/**
* CC - OBJETO INTERNACIONAL COLIS.
*/
CC("CC", "OBJETO INTERNACIONAL COLIS"),
/**
* CD - OBJETO INTERNACIONAL COLIS.
*/
CD("CD", "OBJETO INTERNACIONAL COLIS"),
/**
* CE - OBJETO INTERNACIONAL COLIS.
*/
CE("CE", "OBJETO INTERNACIONAL COLIS"),
/**
* CF - OBJETO INTERNACIONAL COLIS.
*/
CF("CF", "OBJETO INTERNACIONAL COLIS"),
/**
* CG - OBJETO INTERNACIONAL COLIS.
*/
CG("CG", "OBJETO INTERNACIONAL COLIS"),
/**
* CH - OBJETO INTERNACIONAL COLIS.
*/
CH("CH", "OBJETO INTERNACIONAL COLIS"),
/**
* CI - OBJETO INTERNACIONAL COLIS.
*/
CI("CI", "OBJETO INTERNACIONAL COLIS"),
/**
* CJ - OBJETO INTERNACIONAL COLIS.
*/
CJ("CJ", "OBJETO INTERNACIONAL COLIS"),
/**
* CK - OBJETO INTERNACIONAL COLIS.
*/
CK("CK", "OBJETO INTERNACIONAL COLIS"),
/**
* CL - OBJETO INTERNACIONAL COLIS.
*/
CL("CL", "OBJETO INTERNACIONAL COLIS"),
/**
* CM - OBJETO INTERNACIONAL COLIS.
*/
CM("CM", "OBJETO INTERNACIONAL COLIS"),
/**
* CN - OBJETO INTERNACIONAL COLIS.
*/
CN("CN", "OBJETO INTERNACIONAL COLIS"),
/**
* CO - OBJETO INTERNACIONAL COLIS.
*/
CO("CO", "OBJETO INTERNACIONAL COLIS"),
/**
* CP - OBJETO INTERNACIONAL COLIS.
*/
CP("CP", "OBJETO INTERNACIONAL COLIS"),
/**
* CQ - OBJETO INTERNACIONAL COLIS.
*/
CQ("CQ", "OBJETO INTERNACIONAL COLIS"),
/**
* CR - OBJETO INTERNACIONAL COLIS.
*/
CR("CR", "OBJETO INTERNACIONAL COLIS"),
/**
* CS - OBJETO INTERNACIONAL COLIS.
*/
CS("CS", "OBJETO INTERNACIONAL COLIS"),
/**
* CT - OBJETO INTERNACIONAL COLIS.
*/
CT("CT", "OBJETO INTERNACIONAL COLIS"),
/**
* CU - OBJETO INTERNACIONAL COLIS.
*/
CU("CU", "OBJETO INTERNACIONAL COLIS"),
/**
* CV - OBJETO INTERNACIONAL COLIS.
*/
CV("CV", "OBJETO INTERNACIONAL COLIS"),
/**
* CW - OBJETO INTERNACIONAL COLIS.
*/
CW("CW", "OBJETO INTERNACIONAL COLIS"),
/**
* CX - OBJETO INTERNACIONAL COLIS.
*/
CX("CX", "OBJETO INTERNACIONAL COLIS"),
/**
* CY - OBJETO INTERNACIONAL COLIS.
*/
CY("CY", "OBJETO INTERNACIONAL COLIS"),
/**
* CZ - OBJETO INTERNACIONAL COLIS.
*/
CZ("CZ", "OBJETO INTERNACIONAL COLIS"),
/**
* DA - ENCOMENDA SEDEX C/ AR DIGITAL.
*/
DA("DA", "ENCOMENDA SEDEX C/ AR DIGITAL"),
/**
* DB - REMESSA EXPRESSA C/ AR DIGITAL-BRADESCO.
*/
DB("DB", "REMESSA EXPRESSA C/ AR DIGITAL-BRADESCO"),
/**
* DC - REMESSA EXPRESSA (ORGAO TRANSITO).
*/
DC("DC", "REMESSA EXPRESSA (ORGAO TRANSITO)"),
/**
* DD - DEVOLUÇÃO DE DOCUMENTOS.
*/
DD("DD", "DEVOLUÇÃO DE DOCUMENTOS"),
/**
* DE - REMESSA EXPRESSA C/ AR DIGITAL.
*/
DE("DE", "REMESSA EXPRESSA C/ AR DIGITAL"),
/**
* DF - ENCOMENDA SEDEX (ETIQ LOGICA).
*/
DF("DF", "ENCOMENDA SEDEX (ETIQ LOGICA)"),
/**
* DG - ENCOMENDA SEDEX (ETIQ LOGICA).
*/
DG("DG", "ENCOMENDA SEDEX (ETIQ LOGICA)"),
/**
* DI - REM EXPRES COM AR DIGITAL ITAU.
*/
DI("DI", "REM EXPRES COM AR DIGITAL ITAU"),
/**
* DJ - ENCOMENDA SEDEX.
*/
DJ("DJ", "ENCOMENDA SEDEX"),
/**
* DK - SEDEX EXTRA GRANDE.
*/
DK("DK", "SEDEX EXTRA GRANDE"),
/**
* DL - SEDEX LÓGICO.
*/
DL("DL", "SEDEX LÓGICO"),
/**
* DM - ENCOMENDA SEDEX.
*/
DM("DM", "ENCOMENDA SEDEX"),
/**
* DN - ENCOMENDA SEDEX.
*/
DN("DN", "ENCOMENDA SEDEX"),
/**
* DO - REM EXPRES COM AR DIGITAL ITAU UNIBANCO.
*/
DO("DO", "REM EXPRES COM AR DIGITAL ITAU UNIBANCO"),
/**
* DP - SEDEX PAGAMENTO ENTREGA.
*/
DP("DP", "SEDEX PAGAMENTO ENTREGA"),
/**
* DQ - REM EXPRES COM AR DIGITAL BRADESCO.
*/
DQ("DQ", "REM EXPRES COM AR DIGITAL BRADESCO"),
/**
* DR - REM EXPRES COM AR DIGITAL SANTANDER.
*/
DR("DR", "REM EXPRES COM AR DIGITAL SANTANDER"),
/**
* DS - REM EXPRES COM AR DIGITAL SANTANDER.
*/
DS("DS", "REM EXPRES COM AR DIGITAL SANTANDER"),
/**
* DT - REMESSA ECON.SEG.TRANSITO C/AR DIGITAL.
*/
DT("DT", "REMESSA ECON.SEG.TRANSITO C/AR DIGITAL"),
/**
* DU - ENCOMENDA SEDEX.
*/
DU("DU", "ENCOMENDA SEDEX"),
/**
* DV - SEDEX COM AR DIGITAL.
*/
DV("DV", "SEDEX COM AR DIGITAL"),
/**
* DW - ENCOMENDA SEDEX (ETIQ LÓGICA).
*/
DW("DW", "ENCOMENDA SEDEX (ETIQ LÓGICA)"),
/**
* DX - SEDEX 10 LÓGICO.
*/
DX("DX", "SEDEX 10 LÓGICO"),
/**
* DY - ENCOMENDA SEDEX (ETIQ FÍSICA).
*/
DY("DY", "ENCOMENDA SEDEX (ETIQ FÍSICA)"),
/**
* DZ - ENCOMENDA SEDEX (ETIQ LOGICA).
*/
DZ("DZ", "ENCOMENDA SEDEX (ETIQ LOGICA)"),
/**
* EA - OBJETO INTERNACIONAL EMS.
*/
EA("EA", "OBJETO INTERNACIONAL EMS"),
/**
* EB - OBJETO INTERNACIONAL EMS.
*/
EB("EB", "OBJETO INTERNACIONAL EMS"),
/**
* EC - ENCOMENDA PAC.
*/
EC("EC", "ENCOMENDA PAC"),
/**
* ED - OBJETO INTERNACIONAL PACKET EXPRESS.
*/
ED("ED", "OBJETO INTERNACIONAL PACKET EXPRESS"),
/**
* EE - OBJETO INTERNACIONAL EMS.
*/
EE("EE", "OBJETO INTERNACIONAL EMS"),
/**
* EF - OBJETO INTERNACIONAL EMS.
*/
EF("EF", "OBJETO INTERNACIONAL EMS"),
/**
* EG - OBJETO INTERNACIONAL EMS.
*/
EG("EG", "OBJETO INTERNACIONAL EMS"),
/**
* EH - OBJETO INTERNACIONAL EMS.
*/
EH("EH", "OBJETO INTERNACIONAL EMS"),
/**
* EI - OBJETO INTERNACIONAL EMS.
*/
EI("EI", "OBJETO INTERNACIONAL EMS"),
/**
* EJ - OBJETO INTERNACIONAL EMS.
*/
EJ("EJ", "OBJETO INTERNACIONAL EMS"),
/**
* EK - OBJETO INTERNACIONAL EMS.
*/
EK("EK", "OBJETO INTERNACIONAL EMS"),
/**
* EL - OBJETO INTERNACIONAL EMS.
*/
EL("EL", "OBJETO INTERNACIONAL EMS"),
/**
* EM - SEDEX MUNDI.
*/
EM("EM", "SEDEX MUNDI"),
/**
* EN - OBJETO INTERNACIONAL EMS.
*/
EN("EN", "OBJETO INTERNACIONAL EMS"),
/**
* EO - OBJETO INTERNACIONAL EMS.
*/
EO("EO", "OBJETO INTERNACIONAL EMS"),
/**
* EP - OBJETO INTERNACIONAL EMS.
*/
EP("EP", "OBJETO INTERNACIONAL EMS"),
/**
* EQ - ENCOMENDA SERVIÇO NÃO EXPRESSA ECT.
*/
EQ("EQ", "ENCOMENDA SERVIÇO NÃO EXPRESSA ECT"),
/**
* ER - REGISTRADO.
*/
ER("ER", "REGISTRADO"),
/**
* ES - OBJETO INTERNACIONAL EMS.
*/
ES("ES", "OBJETO INTERNACIONAL EMS"),
/**
* ET - OBJETO INTERNACIONAL EMS.
*/
ET("ET", "OBJETO INTERNACIONAL EMS"),
/**
* EU - OBJETO INTERNACIONAL EMS.
*/
EU("EU", "OBJETO INTERNACIONAL EMS"),
/**
* EV - OBJETO INTERNACIONAL EMS.
*/
EV("EV", "OBJETO INTERNACIONAL EMS"),
/**
* EW - OBJETO INTERNACIONAL EMS.
*/
EW("EW", "OBJETO INTERNACIONAL EMS"),
/**
* EX - OBJETO INTERNACIONAL EMS.
*/
EX("EX", "OBJETO INTERNACIONAL EMS"),
/**
* EY - OBJETO INTERNACIONAL EMS.
*/
EY("EY", "OBJETO INTERNACIONAL EMS"),
/**
* EZ - OBJETO INTERNACIONAL EMS.
*/
EZ("EZ", "OBJETO INTERNACIONAL EMS"),
/**
* FA - FAC REGISTRADO.
*/
FA("FA", "FAC REGISTRADO"),
/**
* FB - FAC REGISTRADO.
*/
FB("FB", "FAC REGISTRADO"),
/**
* FC - FAC REGISTRADO (5 DIAS).
*/
FC("FC", "FAC REGISTRADO (5 DIAS)"),
/**
* FD - FAC REGISTRADO (10 DIAS).
*/
FD("FD", "FAC REGISTRADO (10 DIAS)"),
/**
* FE - ENCOMENDA FNDE.
*/
FE("FE", "ENCOMENDA FNDE"),
/**
* FF - REGISTRADO DETRAN.
*/
FF("FF", "REGISTRADO DETRAN"),
/**
* FH - FAC REGISTRADO C/ AR DIGITAL.
*/
FH("FH", "FAC REGISTRADO C/ AR DIGITAL"),
/**
* FJ - REMESSA ECONÔMICA C/ AR DIGITAL.
*/
FJ("FJ", "REMESSA ECONÔMICA C/ AR DIGITAL"),
/**
* FM - FAC REGISTRADO (MONITORADO).
*/
FM("FM", "FAC REGISTRADO (MONITORADO)"),
/**
* FR - FAC REGISTRADO.
*/
FR("FR", "FAC REGISTRADO"),
/**
* IA - INTEGRADA AVULSA.
*/
IA("IA", "INTEGRADA AVULSA"),
/**
* IC - INTEGRADA A COBRAR.
*/
IC("IC", "INTEGRADA A COBRAR"),
/**
* ID - INTEGRADA DEVOLUCAO DE DOCUMENTO.
*/
ID("ID", "INTEGRADA DEVOLUCAO DE DOCUMENTO"),
/**
* IE - INTEGRADA ESPECIAL.
*/
IE("IE", "INTEGRADA ESPECIAL"),
/**
* IF - CPF.
*/
IF("IF", "CPF"),
/**
* II - INTEGRADA INTERNO.
*/
II("II", "INTEGRADA INTERNO"),
/**
* IK - INTEGRADA COM COLETA SIMULTANEA.
*/
IK("IK", "INTEGRADA COM COLETA SIMULTANEA"),
/**
* IM - INTEGRADA MEDICAMENTOS.
*/
IM("IM", "INTEGRADA MEDICAMENTOS"),
/**
* IN - OBJ DE CORRESP E EMS REC EXTERIOR.
*/
IN("IN", "OBJ DE CORRESP E EMS REC EXTERIOR"),
/**
* IP - INTEGRADA PROGRAMADA.
*/
IP("IP", "INTEGRADA PROGRAMADA"),
/**
* IR - IMPRESSO REGISTRADO.
*/
IR("IR", "IMPRESSO REGISTRADO"),
/**
* IS - INTEGRADA STANDARD.
*/
IS("IS", "INTEGRADA STANDARD"),
/**
* IT - INTEGRADA TERMOLÁBIL.
*/
IT("IT", "INTEGRADA TERMOLÁBIL"),
/**
* IU - INTEGRADA URGENTE.
*/
IU("IU", "INTEGRADA URGENTE"),
/**
* IX - EDEI ENCOMENDA EXPRESSA.
*/
IX("IX", "EDEI ENCOMENDA EXPRESSA"),
/**
* JA - REMESSA ECONOMICA C/AR DIGITAL.
*/
JA("JA", "REMESSA ECONOMICA C/AR DIGITAL"),
/**
* JB - REMESSA ECONOMICA C/AR DIGITAL.
*/
JB("JB", "REMESSA ECONOMICA C/AR DIGITAL"),
/**
* JC - REMESSA ECONOMICA C/AR DIGITAL.
*/
JC("JC", "REMESSA ECONOMICA C/AR DIGITAL"),
/**
* JD - REMESSA ECONOMICA S/AR DIGITAL.
*/
JD("JD", "REMESSA ECONOMICA S/AR DIGITAL"),
/**
* JE - REMESSA ECONOMICA C/AR DIGITAL.
*/
JE("JE", "REMESSA ECONOMICA C/AR DIGITAL"),
/**
* JF - REMESSA ECONOMICA C/AR DIGITAL.
*/
JF("JF", "REMESSA ECONOMICA C/AR DIGITAL"),
/**
* JG - REGISTRADO PRIORITÁRIO.
*/
JG("JG", "REGISTRADO PRIORITÁRIO"),
/**
* JH - REGISTRADO PRIORITÁRIO.
*/
JH("JH", "REGISTRADO PRIORITÁRIO"),
/**
* JI - REMESSA ECONOMICA S/AR DIGITAL.
*/
JI("JI", "REMESSA ECONOMICA S/AR DIGITAL"),
/**
* JJ - REGISTRADO JUSTIÇA.
*/
JJ("JJ", "REGISTRADO JUSTIÇA"),
/**
* JK - REMESSA ECONÔMICA S/AR DIGITAL.
*/
JK("JK", "REMESSA ECONÔMICA S/AR DIGITAL"),
/**
* JL - REGISTRADO LÓGICO.
*/
JL("JL", "REGISTRADO LÓGICO"),
/**
* JM - MALA DIRETA POSTAL ESPECIAL.
*/
JM("JM", "MALA DIRETA POSTAL ESPECIAL"),
/**
* JN - MALA DIRETA POSTAL ESPECIAL.
*/
JN("JN", "MALA DIRETA POSTAL ESPECIAL"),
/**
* JO - REGISTRADO PRIORITÁRIO.
*/
JO("JO", "REGISTRADO PRIORITÁRIO"),
/**
* JP - OBJETO RECEITA FEDERAL (EXCLUSIVO).
*/
JP("JP", "OBJETO RECEITA FEDERAL (EXCLUSIVO)"),
/**
* JQ - REMESSA ECONOMICA C/AR DIGITAL.
*/
JQ("JQ", "REMESSA ECONOMICA C/AR DIGITAL"),
/**
* JR - REGISTRADO PRIORITÁRIO.
*/
JR("JR", "REGISTRADO PRIORITÁRIO"),
/**
* JS - REGISTRADO LÓGICO.
*/
JS("JS", "REGISTRADO LÓGICO"),
/**
* JT - REGISTRADO URGENTE.
*/
JT("JT", "REGISTRADO URGENTE"),
/**
* JU - ETIQUETA FÍS REGIST URG.
*/
JU("JU", "ETIQUETA FÍS REGIST URG"),
/**
* JV - REMESSA ECONÔMICA C/AR DIGITAL.
*/
JV("JV", "REMESSA ECONÔMICA C/AR DIGITAL"),
/**
* JW - CARTA COMERCIAL A FATURAR (5 DIAS).
*/
JW("JW", "CARTA COMERCIAL A FATURAR (5 DIAS)"),
/**
* JX - CARTA COMERCIAL A FATURAR (10 DIAS).
*/
JX("JX", "CARTA COMERCIAL A FATURAR (10 DIAS)"),
/**
* JY - REMESSA ECONOMICA (5 DIAS).
*/
JY("JY", "REMESSA ECONOMICA (5 DIAS)"),
/**
* JZ - REMESSA ECONOMICA (10 DIAS).
*/
JZ("JZ", "REMESSA ECONOMICA (10 DIAS)"),
/**
* LA - LOGÍSTICA REVERSA SIMULTÂNEA SEDEX.
*/
LA("LA", "LOGÍSTICA REVERSA SIMULTÂNEA SEDEX"),
/**
* LB - LOGÍSTICA REVERSA SIMULTÂNEA SEDEX.
*/
LB("LB", "LOGÍSTICA REVERSA SIMULTÂNEA SEDEX"),
/**
* LC - OBJETO INTERNACIONAL PRIME.
*/
LC("LC", "OBJETO INTERNACIONAL PRIME"),
/**
* LD - OBJETO INTERNACIONAL PRIME.
*/
LD("LD", "OBJETO INTERNACIONAL PRIME"),
/**
* LE - LOGÍSTICA REVERSA ECONOMICA.
*/
LE("LE", "LOGÍSTICA REVERSA ECONOMICA"),
/**
* LF - OBJETO INTERNACIONAL PRIME.
*/
LF("LF", "OBJETO INTERNACIONAL PRIME"),
/**
* LG - OBJETO INTERNACIONAL PRIME.
*/
LG("LG", "OBJETO INTERNACIONAL PRIME"),
/**
* LH - OBJETO INTERNACIONAL PRIME.
*/
LH("LH", "OBJETO INTERNACIONAL PRIME"),
/**
* LI - OBJETO INTERNACIONAL PRIME.
*/
LI("LI", "OBJETO INTERNACIONAL PRIME"),
/**
* LJ - OBJETO INTERNACIONAL PRIME.
*/
LJ("LJ", "OBJETO INTERNACIONAL PRIME"),
/**
* LK - OBJETO INTERNACIONAL PRIME.
*/
LK("LK", "OBJETO INTERNACIONAL PRIME"),
/**
* LL - OBJETO INTERNACIONAL PRIME.
*/
LL("LL", "OBJETO INTERNACIONAL PRIME"),
/**
* LM - OBJETO INTERNACIONAL PRIME.
*/
LM("LM", "OBJETO INTERNACIONAL PRIME"),
/**
* LN - OBJETO INTERNACIONAL PRIME.
*/
LN("LN", "OBJETO INTERNACIONAL PRIME"),
/**
* LP - LOGÍSTICA REVERSA SIMULTÂNEA PAC.
*/
LP("LP", "LOGÍSTICA REVERSA SIMULTÂNEA PAC"),
/**
* LQ - OBJETO INTERNACIONAL PRIME.
*/
LQ("LQ", "OBJETO INTERNACIONAL PRIME"),
/**
* LS - LOGISTICA REVERSA SEDEX.
*/
LS("LS", "LOGISTICA REVERSA SEDEX"),
/**
* LV - LOGISTICA REVERSA EXPRESSA.
*/
LV("LV", "LOGISTICA REVERSA EXPRESSA"),
/**
* LW - OBJETO INTERNACIONAL PRIME.
*/
LW("LW", "OBJETO INTERNACIONAL PRIME"),
/**
* LX - OBJETO INTERNACIONAL PACKET ECONOMIC.
*/
LX("LX", "OBJETO INTERNACIONAL PACKET ECONOMIC"),
/**
* LY - OBJETO INTERNACIONAL PRIME.
*/
LY("LY", "OBJETO INTERNACIONAL PRIME"),
/**
* LZ - OBJETO INTERNACIONAL PRIME.
*/
LZ("LZ", "OBJETO INTERNACIONAL PRIME"),
/**
* MA - TELEGRAMA - SERVICOS ADICIONAIS.
*/
MA("MA", "TELEGRAMA - SERVICOS ADICIONAIS"),
/**
* MB - TELEGRAMA DE BALCAO.
*/
MB("MB", "TELEGRAMA DE BALCAO"),
/**
* MC - TELEGRAMA FONADO.
*/
MC("MC", "TELEGRAMA FONADO"),
/**
* MD - MAQUINA DE FRANQUEAR (LOGICA).
*/
MD("MD", "MAQUINA DE FRANQUEAR (LOGICA)"),
/**
* ME - TELEGRAMA.
*/
ME("ME", "TELEGRAMA"),
/**
* MF - TELEGRAMA FONADO.
*/
MF("MF", "TELEGRAMA FONADO"),
/**
* MH - CARTA VIA INTERNET.
*/
MH("MH", "CARTA VIA INTERNET"),
/**
* MK - TELEGRAMA CORPORATIVO.
*/
MK("MK", "TELEGRAMA CORPORATIVO"),
/**
* MM - TELEGRAMA GRANDES CLIENTES.
*/
MM("MM", "TELEGRAMA GRANDES CLIENTES"),
/**
* MP - TELEGRAMA PRÉ-PAGO.
*/
MP("MP", "TELEGRAMA PRÉ-PAGO"),
/**
* MS - ENCOMENDA SAUDE.
*/
MS("MS", "ENCOMENDA SAUDE"),
/**
* MT - TELEGRAMA VIA TELEMAIL.
*/
MT("MT", "TELEGRAMA VIA TELEMAIL"),
/**
* MY - TELEGRAMA INTERNACIONAL ENTRANTE.
*/
MY("MY", "TELEGRAMA INTERNACIONAL ENTRANTE"),
/**
* MZ - TELEGRAMA VIA CORREIOS ON LINE.
*/
MZ("MZ", "TELEGRAMA VIA CORREIOS ON LINE"),
/**
* NE - TELE SENA RESGATADA.
*/
NE("NE", "TELE SENA RESGATADA"),
/**
* NX - EDEI ENCOMENDA NAO URGENTE.
*/
NX("NX", "EDEI ENCOMENDA NAO URGENTE"),
/**
* OA - ENCOMENDA SEDEX (ETIQ LOGICA).
*/
OA("OA", "ENCOMENDA SEDEX (ETIQ LOGICA)"),
/**
* OB - ENCOMENDA SEDEX (ETIQ LOGICA).
*/
OB("OB", "ENCOMENDA SEDEX (ETIQ LOGICA)"),
/**
* OC - ENCOMENDA SEDEX (ETIQ LOGICA).
*/
OC("OC", "ENCOMENDA SEDEX (ETIQ LOGICA)"),
/**
* OD - ENCOMENDA SEDEX (ETIQ FÍSICA).
*/
OD("OD", "ENCOMENDA SEDEX (ETIQ FÍSICA)"),
/**
* OF - ETIQUETA LÓGICA SEDEX.
*/
OF("OF", "ETIQUETA LÓGICA SEDEX"),
/**
* OG - ETIQUETA LÓGICA SEDEX.
*/
OG("OG", "ETIQUETA LÓGICA SEDEX"),
/**
* OH - ETIQUETA LÓGICA SEDEX.
*/
OH("OH", "ETIQUETA LÓGICA SEDEX"),
/**
* OI - ETIQUETA LOGICA SEDEX.
*/
OI("OI", "ETIQUETA LOGICA SEDEX"),
/**
* PA - PASSAPORTE.
*/
PA("PA", "PASSAPORTE"),
/**
* PB - ENCOMENDA PAC - NÃO URGENTE.
*/
PB("PB", "ENCOMENDA PAC - NÃO URGENTE"),
/**
* PC - ENCOMENDA PAC A COBRAR.
*/
PC("PC", "ENCOMENDA PAC A COBRAR"),
/**
* PD - ENCOMENDA PAC.
*/
PD("PD", "ENCOMENDA PAC"),
/**
* PE - ENCOMENDA PAC (ETIQUETA FISICA).
*/
PE("PE", "ENCOMENDA PAC (ETIQUETA FISICA)"),
/**
* PF - PASSAPORTE.
*/
PF("PF", "PASSAPORTE"),
/**
* PG - ENCOMENDA PAC (ETIQUETA FISICA).
*/
PG("PG", "ENCOMENDA PAC (ETIQUETA FISICA)"),
/**
* PH - ENCOMENDA PAC (ETIQUETA LOGICA).
*/
PH("PH", "ENCOMENDA PAC (ETIQUETA LOGICA)"),
/**
* PI - ENCOMENDA PAC.
*/
PI("PI", "ENCOMENDA PAC"),
/**
* PJ - ENCOMENDA PAC.
*/
PJ("PJ", "ENCOMENDA PAC"),
/**
* PK - PAC EXTRA GRANDE.
*/
PK("PK", "PAC EXTRA GRANDE"),
/**
* PL - ENCOMENDA PAC.
*/
PL("PL", "ENCOMENDA PAC"),
/**
* PM - ENCOMENDA PAC (ETIQ FÍSICA).
*/
PM("PM", "ENCOMENDA PAC (ETIQ FÍSICA)"),
/**
* PN - ENCOMENDA PAC (ETIQ LOGICA).
*/
PN("PN", "ENCOMENDA PAC (ETIQ LOGICA)"),
/**
* PO - ENCOMENDA PAC (ETIQ LOGICA).
*/
PO("PO", "ENCOMENDA PAC (ETIQ LOGICA)"),
/**
* PP - ETIQUETA LÓGICA PAC.
*/
PP("PP", "ETIQUETA LÓGICA PAC"),
/**
* PQ - ETIQUETA LOGICA PAC MINI.
*/
PQ("PQ", "ETIQUETA LOGICA PAC MINI"),
/**
* PR - REEMBOLSO POSTAL - CLIENTE AVULSO.
*/
PR("PR", "REEMBOLSO POSTAL - CLIENTE AVULSO"),
/**
* PS - ETIQUETA LÓGICA PAC.
*/
PS("PS", "ETIQUETA LÓGICA PAC"),
/**
* PT - ETIQUETA LÓGICA PAC.
*/
PT("PT", "ETIQUETA LÓGICA PAC"),
/**
* PU - ETIQUETA LÓGICA PAC.
*/
PU("PU", "ETIQUETA LÓGICA PAC"),
/**
* PV - ETIQUETA LÓGICA PAC ADMINISTRATIVO.
*/
PV("PV", "ETIQUETA LÓGICA PAC ADMINISTRATIVO"),
/**
* PW - ETIQUETA LÓGICA PAC.
*/
PW("PW", "ETIQUETA LÓGICA PAC"),
/**
* PX - ETIQUETA LÓGICA PAC.
*/
PX("PX", "ETIQUETA LÓGICA PAC"),
/**
* RA - REGISTRADO PRIORITÁRIO.
*/
RA("RA", "REGISTRADO PRIORITÁRIO"),
/**
* RB - CARTA REGISTRADA.
*/
RB("RB", "CARTA REGISTRADA"),
/**
* RC - CARTA REGISTRADA COM VALOR DECLARADO.
*/
RC("RC", "CARTA REGISTRADA COM VALOR DECLARADO"),
/**
* RD - REMESSA ECONOMICA DETRAN.
*/
RD("RD", "REMESSA ECONOMICA DETRAN"),
/**
* RE - MALA DIRETA POSTAL ESPECIAL.
*/
RE("RE", "MALA DIRETA POSTAL ESPECIAL"),
/**
* RF - OBJETO DA RECEITA FEDERAL.
*/
RF("RF", "OBJETO DA RECEITA FEDERAL"),
/**
* RG - REGISTRADO DO SISTEMA SARA.
*/
RG("RG", "REGISTRADO DO SISTEMA SARA"),
/**
* RH - REGISTRADO COM AR DIGITAL.
*/
RH("RH", "REGISTRADO COM AR DIGITAL"),
/**
* RI - REGISTRADO PRIORITÁRIO INTERNACIONAL.
*/
RI("RI", "REGISTRADO PRIORITÁRIO INTERNACIONAL"),
/**
* RJ - REGISTRADO AGÊNCIA.
*/
RJ("RJ", "REGISTRADO AGÊNCIA"),
/**
* RK - REGISTRADO AGÊNCIA.
*/
RK("RK", "REGISTRADO AGÊNCIA"),
/**
* RL - REGISTRADO LÓGICO.
*/
RL("RL", "REGISTRADO LÓGICO"),
/**
* RM - REGISTRADO AGÊNCIA.
*/
RM("RM", "REGISTRADO AGÊNCIA"),
/**
* RN - REGISTRADO AGÊNCIA.
*/
RN("RN", "REGISTRADO AGÊNCIA"),
/**
* RO - REGISTRADO AGÊNCIA.
*/
RO("RO", "REGISTRADO AGÊNCIA"),
/**
* RP - REEMBOLSO POSTAL - CLIENTE INSCRITO.
*/
RP("RP", "REEMBOLSO POSTAL - CLIENTE INSCRITO"),
/**
* RQ - REGISTRADO AGÊNCIA.
*/
RQ("RQ", "REGISTRADO AGÊNCIA"),
/**
* RR - REGISTRADO INTERNACIONAL.
*/
RR("RR", "REGISTRADO INTERNACIONAL"),
/**
* RS - REM ECON ORG TRANSITO COM OU SEM AR.
*/
RS("RS", "REM ECON ORG TRANSITO COM OU SEM AR"),
/**
* RT - REM ECON TALAO/CARTAO SEM AR DIGITA.
*/
RT("RT", "REM ECON TALAO/CARTAO SEM AR DIGITA"),
/**
* RU - REGISTRADO SERVIÇO ECT.
*/
RU("RU", "REGISTRADO SERVIÇO ECT"),
/**
* RV - REM ECON CRLV/CRV/CNH COM AR DIGITAL.
*/
RV("RV", "REM ECON CRLV/CRV/CNH COM AR DIGITAL"),
/**
* RW - REGISTRADO INTERNACIONAL.
*/
RW("RW", "REGISTRADO INTERNACIONAL"),
/**
* RX - REGISTRADO INTERNACIONAL.
*/
RX("RX", "REGISTRADO INTERNACIONAL"),
/**
* RY - REM ECON TALAO/CARTAO COM AR DIGITAL.
*/
RY("RY", "REM ECON TALAO/CARTAO COM AR DIGITAL"),
/**
* RZ - REGISTRADO.
*/
RZ("RZ", "REGISTRADO"),
/**
* SA - ETIQUETA SEDEX AGÊNCIA.
*/
SA("SA", "ETIQUETA SEDEX AGÊNCIA"),
/**
* SB - SEDEX 10.
*/
SB("SB", "SEDEX 10"),
/**
* SC - SEDEX A COBRAR.
*/
SC("SC", "SEDEX A COBRAR"),
/**
* SD - REMESSA EXPRESSA DETRAN.
*/
SD("SD", "REMESSA EXPRESSA DETRAN"),
/**
* SE - ENCOMENDA SEDEX.
*/
SE("SE", "ENCOMENDA SEDEX"),
/**
* SF - SEDEX AGENCIA.
*/
SF("SF", "SEDEX AGENCIA"),
/**
* SG - SEDEX DO SISTEMA SARA.
*/
SG("SG", "SEDEX DO SISTEMA SARA"),
/**
* SH - SEDEX COM AR DIGITAL.
*/
SH("SH", "SEDEX COM AR DIGITAL"),
/**
* SI - SEDEX AGÊNCIA.
*/
SI("SI", "SEDEX AGÊNCIA"),
/**
* SJ - SEDEX HOJE.
*/
SJ("SJ", "SEDEX HOJE"),
/**
* SK - SEDEX AGÊNCIA.
*/
SK("SK", "SEDEX AGÊNCIA"),
/**
* SL - SEDEX LÓGICO.
*/
SL("SL", "SEDEX LÓGICO"),
/**
* SM - SEDEX 12.
*/
SM("SM", "SEDEX 12"),
/**
* SN - SEDEX AGÊNCIA.
*/
SN("SN", "SEDEX AGÊNCIA"),
/**
* SO - SEDEX AGÊNCIA.
*/
SO("SO", "SEDEX AGÊNCIA"),
/**
* SP - SEDEX PRÉ-FRANQUEADO.
*/
SP("SP", "SEDEX PRÉ-FRANQUEADO"),
/**
* SQ - SEDEX.
*/
SQ("SQ", "SEDEX"),
/**
* SR - SEDEX.
*/
SR("SR", "SEDEX"),
/**
* SS - SEDEX FÍSICO.
*/
SS("SS", "SEDEX FÍSICO"),
/**
* ST - REM EXPRES TALAO/CARTAO SEM AR DIGITAL.
*/
ST("ST", "REM EXPRES TALAO/CARTAO SEM AR DIGITAL"),
/**
* SU - ENCOMENDA SERVIÇO EXPRESSA ECT.
*/
SU("SU", "ENCOMENDA SERVIÇO EXPRESSA ECT"),
/**
* SV - REM EXPRES CRLV/CRV/CNH COM AR DIGITAL.
*/
SV("SV", "REM EXPRES CRLV/CRV/CNH COM AR DIGITAL"),
/**
* SW - ENCOMENDA SEDEX.
*/
SW("SW", "ENCOMENDA SEDEX"),
/**
* SX - SEDEX 10.
*/
SX("SX", "SEDEX 10"),
/**
* SY - REM EXPRES TALAO/CARTAO COM AR DIGITAL.
*/
SY("SY", "REM EXPRES TALAO/CARTAO COM AR DIGITAL"),
/**
* SZ - SEDEX AGÊNCIA.
*/
SZ("SZ", "SEDEX AGÊNCIA"),
/**
* TC - TESTE (OBJETO PARA TREINAMENTO).
*/
TC("TC", "TESTE (OBJETO PARA TREINAMENTO)"),
/**
* TE - TESTE (OBJETO PARA TREINAMENTO).
*/
TE("TE", "TESTE (OBJETO PARA TREINAMENTO)"),
/**
* TR - OBJETO TREINAMENTO - NÃO GERA PRÉ-ALERTA.
*/
TR("TR", "OBJETO TREINAMENTO - NÃO GERA PRÉ-ALERTA"),
/**
* TS - TESTE (OBJETO PARA TREINAMENTO).
*/
TS("TS", "TESTE (OBJETO PARA TREINAMENTO)"),
/**
* VA - OBJETO INTERNACIONAL COM VALOR DECLARADO.
*/
VA("VA", "OBJETO INTERNACIONAL COM VALOR DECLARADO"),
/**
* VC - OBJETO INTERNACIONAL COM VALOR DECLARADO.
*/
VC("VC", "OBJETO INTERNACIONAL COM VALOR DECLARADO"),
/**
* VD - OBJETO INTERNACIONAL COM VALOR DECLARADO.
*/
VD("VD", "OBJETO INTERNACIONAL COM VALOR DECLARADO"),
/**
* VE - OBJETO INTERNACIONAL COM VALOR DECLARADO.
*/
VE("VE", "OBJETO INTERNACIONAL COM VALOR DECLARADO"),
/**
* VF - OBJETO INTERNACIONAL COM VALOR DECLARADO.
*/
VF("VF", "OBJETO INTERNACIONAL COM VALOR DECLARADO"),
/**
* VV - OBJETO INTERNACIONAL COM VALOR DECLARADO.
*/
VV("VV", "OBJETO INTERNACIONAL COM VALOR DECLARADO"),
/**
* XA - AVISO CHEGADA OBJETO INT TRIBUTADO.
*/
XA("XA", "AVISO CHEGADA OBJETO INT TRIBUTADO"),
/**
* XM - SEDEX MUNDI.
*/
XM("XM", "SEDEX MUNDI"),
/**
* XR - OBJETO INTERNACIONAL (PPS TRIBUTADO).
*/
XR("XR", "OBJETO INTERNACIONAL (PPS TRIBUTADO)"),
/**
* XX - OBJETO INTERNACIONAL (PPS TRIBUTADO).
*/
XX("XX", "OBJETO INTERNACIONAL (PPS TRIBUTADO)"),
/**
* Unknown service type.
*/
UNKNOWN("", "");
private String mInitials;
private String mDescription;
TrackObjectServiceType(String initials, String description) {
this.mInitials = initials;
this.mDescription = description;
}
/**
* Return service type initials.
* @return service type initials
*/
public String getInitials() {
return mInitials;
}
/**
* Return service type description.
* @return service type description
*/
public String getDescription() {
return mDescription;
}
}
| 22.078553 | 128 | 0.559624 |
320ba45d236948406fd9670880ea22e13a6abe74 | 2,753 | // Copyright 2019 Marco Bavagnoli <[email protected]>
//
// 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.bavagnoli.flutteropengl;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import java.io.IOException;
import io.flutter.plugin.common.PluginRegistry.Registrar;
/**
* Used by NDK code to read assets images
*/
public class BmpManager {
static String TAG = BmpManager.class.getSimpleName();
static private Registrar mRegistrar;
/**
* Inizialized when the app starts in FlutteropenglPlugin.registerWith()
* @param activity
*/
public static void setAssetsManager(Registrar registrar) {
mRegistrar = registrar;
}
// https://flutter.dev/docs/development/ui/assets-and-images
private AssetFileDescriptor getAssetsImage(String imagePath) {
Log.i(TAG, "getAssetsImage: " + imagePath);
AssetFileDescriptor fd = null;
try {
AssetManager assetManager = mRegistrar.context().getAssets();
String key = mRegistrar.lookupKeyForAsset(imagePath);
fd = assetManager.openFd(key);
} catch (IOException e) {
Log.e(TAG, "getAssetsImage error: " + e );
}
return fd;
}
public Bitmap open(String path)
{
AssetFileDescriptor fd = getAssetsImage(path);
Log.i(TAG, "************************ open: " + path + " " + fd.getFileDescriptor().toString());
try
{
return BitmapFactory.decodeStream(fd.createInputStream());
}
catch (Exception e) {
Log.e(TAG, "open error: " +e + " cannot open: " + path );
}
return null;
}
public int getWidth(Bitmap bmp) { return bmp.getWidth(); }
public int getHeight(Bitmap bmp) { return bmp.getHeight(); }
public void getPixels(Bitmap bmp, int[] pixels)
{
int w = bmp.getWidth();
int h = bmp.getHeight();
// bmp = bmp.copy(Bitmap.Config.ARGB_8888, false);
bmp.getPixels(pixels, 0, w, 0, 0, w, h);
}
public void close(Bitmap bmp)
{
bmp.recycle();
}
}
| 32.011628 | 105 | 0.65129 |
96c0de93612cdf1f61c01aca2474070fe19fb19e | 8,665 | package com.wherehoo;
import java.net.*;
import java.io.*;
import java.util.*;
import java.sql.*;
import java.security.*;
public class WHInsertOperation extends WHOperation {
private WHPolygon poly;
private double height;
private byte[] data;
private WHTimeInterval time;
private String mimetype;
private String protocol;
private String uniqueidSHA;
private String idt;
private String meta;
private boolean meta_is_set;
/**
* Constructs new WHInsertOperation
* @param _idt user id of the client who wishes to insert an entry into wherehoo
* @param _poly WHPolygon representation of the geographical area of wherehoo object
* @param _height the height of locale of the wherehoo object
* @param _data the actual data to be inserted
* @param _time the time interval when this wherehoo object is active
* @param _mimetype mimetype of the data to be inserted
* @param _protocol protocol of the data to be inserted
*/
public WHInsertOperation(String _idt,WHPolygon _poly,double _height,byte[] _data, WHTimeInterval _time, String _mimetype, String _protocol){
poly=_poly;
height=_height;
data=_data;
time=_time;
mimetype=_mimetype;
protocol=_protocol;
idt=_idt;
meta="";
meta_is_set=false;
}
/**
* sets meta field to _meta
* @param _meta the metadata string of the wherehoo object
*/
public void setMeta(String _meta){
meta=_meta;
meta_is_set=true;
if (this.getVeryVerbose()) System.out.println("Meta is set to :"+ _meta);
}
/**
* Returns an SQL query string.
* @return SQL query string of this WHInsertOperation
*/
public String getQueryString(){
return this.getQueryString(0);
}
/**
* Returns an SQL query string, for the case when there is a zero crossing.
* @param type the integer representing the case
* @return SQL query string of this WHInsertOperation
*/
public String getQueryString(int type){
String queryString;
queryString = "insert into wherehoo_polygons (";
queryString += "area,height,begin_time,end_time,";
queryString += "authority,data,mimetype,protocol,uniqueidsha";
if (meta_is_set)
queryString+=",meta";
queryString += ") values (polygon(pclose(path'";
switch (type){
//180<lon<540
case -1: {
queryString +=poly.toString(360);
break;
}
//no zero crossing case, 0<lon<360
case 0: {
queryString += poly.toString();
break;
}
//-180<lon<180
case 1: {
queryString += poly.toString(0);
break;
}
}
queryString +="')),"+height+",?,?,'"+idt+"',?,'"+mimetype+"','"+protocol+"','"+uniqueidSHA+"'";
if (meta_is_set)
queryString+=",?"; queryString += ")";
if (this.getVerbose()||this.getVeryVerbose()) System.out.println(queryString);
return queryString;
}
/**
* Inserts an entry into the database, and sends an uid to the client as a confirmation
* @param client_socket a socket of the connecting client. After executing an insert operation, this method sends
* uid to the client via client_socket.
*/
public synchronized void executeAndOutputToClient(Socket client_socket) throws IOException{
String queryString;
Connection C;
PreparedStatement pps;
String client_address = client_socket.getInetAddress().getHostAddress();
int st;
PrintWriter out;
if (this.getVeryVerbose()) System.out.println("Opening PrintWriter");
out = new PrintWriter(client_socket.getOutputStream(),true);
try {
uniqueidSHA=getUniqueID(client_address);
if (this.getVeryVerbose()) System.out.println("Calculated uniqueID :"+uniqueidSHA);
C = DriverManager.getConnection("jdbc:"+WHServer.DB,"postgres","");
if (this.getVeryVerbose()) System.out.println("Connected to database");
C.setAutoCommit(false);
if ( ! poly.zeroCrossing()){
if (this.getVeryVerbose()) System.out.println("No zero crossing");
queryString=this.getQueryString(0);
pps = C.prepareStatement(queryString);
if (this.getVeryVerbose()) System.out.println("Prepared statement");
pps.setTimestamp(1,time.getBegin());
pps.setTimestamp(2,time.getEnd());
if (this.getVeryVerbose()) System.out.println("Set the timestamps in SQL query string");
pps.setBytes(3, data);
if (this.getVeryVerbose()) System.out.println("Set data bytes in SQL query string");
if (meta_is_set){
pps.setString(4,meta);
if (this.getVeryVerbose()) System.out.println("Set meta in SQL query string");
}
st = pps.executeUpdate();
if (this.getVeryVerbose()) System.out.println("Executed query, result : "+st);
C.commit();
if (this.getVeryVerbose()) System.out.println("Commited changes");
if (st == 1){
out.println(uniqueidSHA);
if (this.getVeryVerbose())System.out.println("Sent UID to client");
}
} else {
if (this.getVeryVerbose()) System.out.println("Zero crossing");
//insert two objects, each with different coordinates
//object represented by polygon with 180<lon<540;
queryString=this.getQueryString(-1);
if (this.getVeryVerbose()) System.out.println("Prepared statement centered around zero meridian");
pps = C.prepareStatement(queryString);
pps.setTimestamp(1,time.getBegin());
pps.setTimestamp(2,time.getEnd());
pps.setBytes(3, data);
if (meta_is_set)
pps.setString(4,meta);
st = pps.executeUpdate();
if (this.getVeryVerbose()) System.out.println("Executed statement");
//object represented by polygon with -180<lon<180
queryString=this.getQueryString(1);
pps = C.prepareStatement(queryString);
if (this.getVeryVerbose()) System.out.println("Prepared statement centered around 360 meridian");
pps.setTimestamp(1,time.getBegin());
pps.setTimestamp(2,time.getEnd());
pps.setBytes(3, data);
if (meta_is_set)
pps.setString(4,meta);
st = st + pps.executeUpdate();
if (this.getVeryVerbose()) System.out.println("Executed statement");
C.commit();
if (st == 2)
out.println(uniqueidSHA);
if (this.getVeryVerbose()) System.out.println("Insert fully sucessfull, sent uniqueidSHA to client");
}
C.close();
}
catch (SQLException sqle) {
System.out.println("SQLException: " + sqle.getMessage());
System.out.println("SQLState: " + sqle.getSQLState());
System.out.println("VendorError: " + sqle.getErrorCode());
}
catch (NoSuchAlgorithmException nsae){
System.out.println("NoSuchAlgorithmException: "+nsae.getMessage());
}
catch (UnknownHostException uhe){
System.out.println("UnknownHostException: "+uhe.getMessage());
}
//out.close();
}
private String getUniqueID(String client_address) throws NoSuchAlgorithmException , UnknownHostException{
String server_address=InetAddress.getLocalHost().getHostAddress();
MessageDigest md = MessageDigest.getInstance("SHA-1");
// the server where the record was created
md.update(server_address.getBytes());
// and the client that made the record
md.update(client_address.getBytes());
// and the data that's recorded in it
md.update(data);
// and a random number
md.update(Double.toString(Math.random()).getBytes());
// and a timestamp in msec
md.update(Long.toString(new java.util.Date().getTime()).getBytes());
byte[] mdfinal = md.digest();
String idSHA = new String();
for (int i = 0; i < mdfinal.length; i++) {
int z;
z = ((int) mdfinal[i]) & (0x000000FF);
// need an INT because Byte does not have "toHexString" method
// but AND out the leading bytes so it does not go negative
idSHA += (z < 16) ? "0" : ""; // pad leading zero if needed (conversion to hex strips it)
idSHA += Integer.toHexString(z); // and convert the value to hex string
}
return idSHA;
}
/**
* Returns the String representation of this InsertOperation
* @return a String object representation of this InsertOperation. It comprises information on area of the
* wherehoo entry to be inserted, its height, begin time, end time, mimetype, protocol, idt and metadata.
*/
public String toString(){
String s="Poly: "+poly.toString()+"\n";
s+="Height "+height+"\n";
s+="Begin "+time.getBegin().toString()+"\n";
s+="End "+time.getEnd().toString()+"\n";
s+="Mimetype "+mimetype+"\n";
s+="Protocol "+protocol+"\n";
s+="IDT "+idt+"\n";
if (meta_is_set)
s+="Meta "+meta;
else
s+="Meta not set";
return s;
}
}
| 34.384921 | 145 | 0.664974 |
da6d164a4b51c94b7948a259fb3ac52963845c9a | 939 | package com.unity3d.ads.android.zone;
import org.json.JSONException;
import org.json.JSONObject;
import com.unity3d.ads.android.item.UnityAdsRewardItem;
import com.unity3d.ads.android.item.UnityAdsRewardItemManager;
import com.unity3d.ads.android.properties.UnityAdsConstants;
public class UnityAdsIncentivizedZone extends UnityAdsZone {
private UnityAdsRewardItemManager _rewardItems = null;
public UnityAdsIncentivizedZone(JSONObject zoneObject) throws JSONException {
super(zoneObject);
UnityAdsRewardItem defaultItem = new UnityAdsRewardItem(zoneObject.getJSONObject(UnityAdsConstants.UNITY_ADS_ZONE_DEFAULT_REWARD_ITEM_KEY));
_rewardItems = new UnityAdsRewardItemManager(zoneObject.getJSONArray(UnityAdsConstants.UNITY_ADS_ZONE_REWARD_ITEMS_KEY), defaultItem.getKey());
}
@Override
public boolean isIncentivized() {
return true;
}
public UnityAdsRewardItemManager itemManager() {
return _rewardItems;
}
}
| 31.3 | 145 | 0.832801 |
a0fbcf3707893ed630d03c2e359217e242b917b7 | 2,687 | /**
* Copyright (DigitalChina) 2016-2020, DigitalChina.
*
* 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.dc.city.common.filters;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
/**
* 解决get请求的乱码,只需在web。xml中配置如下代码就可以解决乱码
* <!--resolve url Chinese filter -->
* <filter>
* <filter-name>resloveMessyCodeFilter</filter-name>
* <filter-class>com.dc.city.common.filters.ResloveMessyCodeFilter</filter-class>
* <init-param>
* <param-name>DEFAULT_URI_ENCODE</param-name>
* <param-value>UTF-8</param-value>
* </init-param>
* </filter>
* <filter-mapping>
* <filter-name>resloveMessyCodeFilter</filter-name>
* <url-pattern>/*</url-pattern>
* </filter-mapping>
*
* @author xutaog
* @version V1.0 创建时间:2015年8月31日 下午3:19:00
* Copyright 2015 by DigitalChina
*/
public class ResloveMessyCodeFilter implements Filter {
private final static String DEFAULT_URI_ENCODE = "GBK";
private final static String METHOD = "GET";
private String encode = null;
@Override
public void init(FilterConfig config) throws ServletException {
encode = config.getInitParameter("DEFAULT_URI_ENCODE");
if (StringUtils.isBlank(this.encode)) {
encode = DEFAULT_URI_ENCODE;
}
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
// 设置请求响应字符编码
request.setCharacterEncoding(encode);
// 解决返回值的乱码
response.setCharacterEncoding(encode);
HttpServletRequest req = (HttpServletRequest) request;
if (req.getMethod().equalsIgnoreCase(METHOD)) {
req = new GetHttpServletRequestWrapper(req, encode);
}
// 传递包装器对象的引用
chain.doFilter(req, response);
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
| 31.988095 | 113 | 0.710086 |
5c4ddc7d9eea9d616aae6293a92de6439066771d | 2,183 | package com.avast.syringe.aop.cglib;
import com.avast.syringe.aop.Interceptor;
import com.avast.syringe.aop.MethodPointcut;
import com.avast.syringe.aop.ProxyFactory;
import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.CallbackFilter;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.NoOp;
/**
* User: vacata
* Date: 1/29/13
* Time: 4:27 PM
*/
public class CglibProxyFactory implements ProxyFactory {
@Override
public boolean canCreate(Class<?>[] types) {
return (evalProxyType(types) != ProxyType.UNSUPPORTED);
}
@Override
public Object createProxy(Interceptor interceptor, Class<?>[] types, MethodPointcut methodPointcut) {
ProxyType proxyType = evalProxyType(types);
Enhancer eh = new Enhancer();
DefaultMethodInterceptor dmi = new DefaultMethodInterceptor(interceptor);
DefaultDispatcher dispatcher = new DefaultDispatcher(interceptor.getTarget());
Callback[] callbacks = new Callback[] {
dmi, dispatcher
};
eh.setCallbacks(callbacks);
CallbackFilter cf = new CallbackFilterAdapter(methodPointcut);
eh.setCallbackFilter(cf);
switch (proxyType) {
case CLASS:
Class<?> clazz = types[0];
eh.setSuperclass(clazz);
return eh.create();
case INTERFACES:
eh.setInterfaces(types);
return eh.create();
}
throw new UnsupportedOperationException("Unsupported proxy types!");
}
private static enum ProxyType {
CLASS, INTERFACES, UNSUPPORTED
}
public ProxyType evalProxyType(Class<?>[] types) {
if (types.length == 0) {
return ProxyType.UNSUPPORTED;
}
//Proxy a collection of interfaces
if (types[0].isInterface()) {
for (Class<?> clazz : types) {
if (!clazz.isInterface()) {
return ProxyType.INTERFACES;
}
}
}
//Proxy a single class
if (types.length == 1) {
return ProxyType.CLASS;
}
return ProxyType.UNSUPPORTED;
}
}
| 30.319444 | 105 | 0.610628 |
e39319d3407e27d34fc87769d978c0051ffa6ca6 | 7,629 | /**
* Copyright 2014 Google Inc. All Rights Reserved.
*
* 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.example.locationservices.home;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.text.TextUtils;
import android.util.Log;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingEvent;
import com.example.locationservices.R;
import java.util.ArrayList;
import java.util.List;
/**
* Listener for geofence transition changes.
*
* Receives geofence transition events from Location Services in the form of an Intent containing
* the transition type and geofence id(s) that triggered the transition. Creates a notification
* as the output.
*/
public class GeofenceTransitionsIntentService extends IntentService {
protected static final String TAG = "GeofenceTransitionsIS";
/**
* This constructor is required, and calls the super IntentService(String)
* constructor with the name for a worker thread.
*/
public GeofenceTransitionsIntentService() {
// Use the TAG to name the worker thread.
super(TAG);
}
@Override
public void onCreate() {
super.onCreate();
}
/**
* Handles incoming intents.
* @param intent sent by Location Services. This Intent is provided to Location
* Services (inside a PendingIntent) when addGeofences() is called.
*/
@Override
protected void onHandleIntent(Intent intent) {
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
if (geofencingEvent.hasError()) {
String errorMessage = GeofenceErrorMessages.getErrorString(this,
geofencingEvent.getErrorCode());
Log.e(TAG, errorMessage);
return;
}
// Get the transition type.
int geofenceTransition = geofencingEvent.getGeofenceTransition();
// Test that the reported transition was of interest.
if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER) {
// Get the geofences that were triggered. A single event can trigger multiple geofences.
List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();
// Get the transition details as a String.
String geofenceTransitionDetails = getGeofenceTransitionDetails(
this,
geofenceTransition,
triggeringGeofences
);
// Send notification and log the transition details.
//TODO: sendNotification
Log.d(TAG, "Entered a challenge");
sendNotification("Aviso!");
Log.i(TAG, geofenceTransitionDetails);
// Toast.makeText(this, geofenceTransitionDetails, Toast.LENGTH_SHORT).show();
} else {
// Log the error.
Log.e(TAG, getString(R.string.geofence_transition_invalid_type, geofenceTransition));
}
}
/**
* Gets transition details and returns them as a formatted string.
*
* @param context The app context.
* @param geofenceTransition The ID of the geofence transition.
* @param triggeringGeofences The geofence(s) triggered.
* @return The transition details formatted as String.
*/
private String getGeofenceTransitionDetails(
Context context,
int geofenceTransition,
List<Geofence> triggeringGeofences) {
String geofenceTransitionString = getTransitionString(geofenceTransition);
// Get the Ids of each geofence that was triggered.
ArrayList triggeringGeofencesIdsList = new ArrayList();
for (Geofence geofence : triggeringGeofences) {
triggeringGeofencesIdsList.add(geofence.getRequestId());
}
String triggeringGeofencesIdsString = TextUtils.join(", ", triggeringGeofencesIdsList);
return geofenceTransitionString + ": " + triggeringGeofencesIdsString;
}
/**
* Posts a notification in the notification bar when a transition is detected.
* If the user clicks the notification, control goes to the MainActivity.
*/
private void sendNotification(String notificationDetails) {
// Create an explicit content Intent that starts the main Activity.
Intent notificationIntent = new Intent(getApplicationContext(), MenuActivity.class);
// Construct a task stack.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Add the main Activity to the task stack as the parent.
stackBuilder.addParentStack(MenuActivity.class);
// Push the content Intent onto the stack.
stackBuilder.addNextIntent(notificationIntent);
// Get a PendingIntent containing the entire back stack.
PendingIntent notificationPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
// Get a notification builder that's compatible with platform versions >= 4
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
// Define the notification settings.
builder.setSmallIcon(R.drawable.logo)
// In a real app, you may want to use a library like Volley
// to decode the Bitmap.
.setLargeIcon(BitmapFactory.decodeResource(getResources(),
R.drawable.logo))
.setColor(Color.RED)
.setContentTitle(notificationDetails)
.setContentText(getString(R.string.geofence_transition_notification_text))
.setContentIntent(notificationPendingIntent);
// Dismiss notification once the user touches it.
builder.setAutoCancel(true);
// Get an instance of the Notification manager
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Issue the notification
mNotificationManager.notify(0, builder.build());
}
/**
* Maps geofence transition types to their human-readable equivalents.
*
* @param transitionType A transition type constant defined in Geofence
* @return A String indicating the type of transition
*/
private String getTransitionString(int transitionType) {
switch (transitionType) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
return getString(R.string.geofence_transition_entered);
case Geofence.GEOFENCE_TRANSITION_EXIT:
return getString(R.string.geofence_transition_exited);
default:
return getString(R.string.unknown_geofence_transition);
}
}
}
| 39.324742 | 100 | 0.679643 |
9e085d1cb15b03f22ef4cf35433a963fe2a62687 | 6,672 | package com.group_track.model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class Group_trackDAO implements Group_trackDAO_interface{
private static DataSource ds = null;
static {
try {
Context ctx = new InitialContext();
ds = (DataSource) ctx.lookup("java:comp/env/jdbc/CA101G2");
} catch (NamingException e) {
e.printStackTrace();
}
}
private static final String INSERT_STMT =
"INSERT INTO GROUP_TRACK (mem_id,grou_id) VALUES (?, ?)";
private static final String GET_ALL_STMT =
"SELECT mem_id,grou_id FROM group_track";
private static final String GET_ONE_STMT_mem_id=
"SELECT mem_id,grou_id FROM group_track where mem_id=?";
private static final String GET_ONE_STMT_grou_id =
"SELECT mem_id,grou_id FROM group_track where grou_id=?";
private static final String DELETE =
"DELETE FROM GROUP_TRACK where mem_id = ? and grou_id = ?";
@Override
public void insert(Group_trackVO group_trackVO) {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = ds.getConnection();
pstmt = con.prepareStatement(INSERT_STMT);
pstmt.setString(1, group_trackVO.getMem_id());
pstmt.setString(2, group_trackVO.getGrou_id());
pstmt.executeUpdate();
// Handle any driver errors
} catch (SQLException se) {
throw new RuntimeException("A database error occured. "
+ se.getMessage());
// Clean up JDBC resources
} finally {
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (con != null) {
try {
con.close();
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
}
@Override
public void delete(String mem_id,String grou_id) {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = ds.getConnection();
pstmt = con.prepareStatement(DELETE);
pstmt.setString(1, mem_id);
pstmt.setString(2, grou_id);
pstmt.executeUpdate();
// Handle any driver errors
} catch (SQLException se) {
throw new RuntimeException("A database error occured. "
+ se.getMessage());
// Clean up JDBC resources
} finally {
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (con != null) {
try {
con.close();
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
}
@Override
public List<Group_trackVO> findByMem_id(String mem_id) {
List<Group_trackVO> list = new ArrayList<Group_trackVO>();
Group_trackVO group_trackVO = null;
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = ds.getConnection();
pstmt = con.prepareStatement(GET_ONE_STMT_mem_id);
pstmt.setString(1, mem_id);
rs = pstmt.executeQuery();
while (rs.next()) {
// empVo �]�٬� Domain objects
group_trackVO = new Group_trackVO();
group_trackVO.setMem_id(rs.getString("mem_id"));
group_trackVO.setGrou_id(rs.getString("grou_id"));
list.add(group_trackVO);
}
// Handle any driver errors
} catch (SQLException se) {
throw new RuntimeException("A database error occured. "
+ se.getMessage());
// Clean up JDBC resources
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (con != null) {
try {
con.close();
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
return list;
}
@Override
public List<Group_trackVO> findByGrou_id(String grou_id) {
List<Group_trackVO> list = new ArrayList<Group_trackVO>();
Group_trackVO group_trackVO = null;
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = ds.getConnection();
pstmt = con.prepareStatement(GET_ONE_STMT_grou_id);
pstmt.setString(1, grou_id);
rs = pstmt.executeQuery();
while (rs.next()) {
// empVo �]�٬� Domain objects
group_trackVO = new Group_trackVO();
group_trackVO.setMem_id(rs.getString("mem_id"));
group_trackVO.setGrou_id(rs.getString("grou_id"));
list.add(group_trackVO);
}
// Handle any driver errors
} catch (SQLException se) {
throw new RuntimeException("A database error occured. "
+ se.getMessage());
// Clean up JDBC resources
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (con != null) {
try {
con.close();
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
return list;
}
@Override
public List<Group_trackVO> getAll() {
List<Group_trackVO> list1 = new ArrayList<Group_trackVO>();
Group_trackVO group_trackVO = null;
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = ds.getConnection();
pstmt = con.prepareStatement(GET_ALL_STMT);
rs = pstmt.executeQuery();
while (rs.next()) {
// group_trackVO �]�٬� Domain objects
group_trackVO = new Group_trackVO();
group_trackVO.setMem_id(rs.getString("mem_id"));
group_trackVO.setGrou_id(rs.getString("Grou_id"));
list1.add(group_trackVO); // Store the row in the list
}
// Handle any driver errors
}catch (SQLException se) {
throw new RuntimeException("A database error occured. "
+ se.getMessage());
// Clean up JDBC resources
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (con != null) {
try {
con.close();
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
return list1;
}
}
| 23.410526 | 64 | 0.625749 |
c902775e583ded1cc43e7f917dce7a5633d943fb | 972 | package org.jeecg.modules.business.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jeecg.modules.business.entity.SourceDirectory;
import java.util.List;
import java.util.Map;
/**
* @Description: 污染源名录库
* @Author: jeecg-boot
* @Date: 2020-09-15
* @Version: V1.0
*/
public interface SourceDirectoryMapper extends BaseMapper<SourceDirectory> {
IPage<Map<String, Object>> getSourceDirectoryList(Page<Map<String, Object>> page, String area, String companyId, String companyType, String industry, String intensiveUnit, String intensiveCompany, String siteType, String siteLevel, String siteState);
IPage<Map<String, Object>> getUnSelectCompany(Page<Map<String, Object>> page, List<String> companyIds);
IPage<Map<String, Object>> getSelectCompany(Page<Map<String, Object>> page, List<String> companyIds);
}
| 38.88 | 254 | 0.781893 |
b45677bb309b712ac60c6db8cb73755fdfac3868 | 424 | package edu.wmi.blindsign;
import java.security.SecureRandom;
/**
* Created by lupus on 02.11.16.
*/
public class MessageGenerator {
private SecureRandom secureRandom;
public MessageGenerator() {
this.secureRandom = new SecureRandom();
}
public byte[] getRandomBytes(int size) {
byte[] outcome = new byte[size];
secureRandom.nextBytes(outcome);
return outcome;
}
}
| 19.272727 | 47 | 0.658019 |
235ed166c1fa716f792c144d4dfc2c446ca7ea5b | 336 | package com.tduck.cloud.wx.mp.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class WxMpUserVO {
/**
* 昵称
*/
private String nickname;
/**
* 头像
*/
private String headImgUrl;
private String openId;
}
| 15.272727 | 33 | 0.678571 |
07051a07040175fa4d17246f8ea6e8fb41bb1b4b | 4,423 | /*
* Copyright 2005-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.ws.soap.axiom;
import java.io.StringReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import org.springframework.ws.soap.SoapFault;
import org.springframework.ws.soap.SoapFaultDetail;
import org.apache.axiom.soap.SOAPMessage;
import org.apache.axiom.soap.impl.builder.StAXSOAPModelBuilder;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
@SuppressWarnings("Since15")
public class AxiomSoapFaultDetailTest {
private static final String FAILING_FAULT =
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n " + "<soapenv:Body>\n " +
"<soapenv:Fault>\n " + "<faultcode>Client</faultcode>\n " +
"<faultstring>Client Error</faultstring>\n " + "<detail>\n " +
"<ns1:dispositionReport xmlns:ns1=\"urn:uddi-org:api_v3\">\n " +
"<ns1:result errno=\"10210\"/>\n " + "</ns1:dispositionReport>" + "</detail>" +
"</soapenv:Fault>" + "</soapenv:Body>" + "</soapenv:Envelope>";
private static final String SUCCEEDING_FAULT =
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n " + "<soapenv:Body>\n " +
"<soapenv:Fault>\n " + "<faultcode>Client</faultcode>\n " +
"<faultstring>Client Error</faultstring>\n " + "<detail>" +
"<ns1:dispositionReport xmlns:ns1=\"urn:uddi-org:api_v3\">\n " +
"<ns1:result errno=\"10210\"/>\n " + "</ns1:dispositionReport>" + "</detail>" +
"</soapenv:Fault>" + "</soapenv:Body>" + "</soapenv:Envelope>";
private AxiomSoapMessage failingMessage;
private AxiomSoapMessage succeedingMessage;
@Before
public void setUp() throws Exception {
XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(FAILING_FAULT));
StAXSOAPModelBuilder builder = new StAXSOAPModelBuilder(parser);
SOAPMessage soapMessage = builder.getSoapMessage();
failingMessage = new AxiomSoapMessage(soapMessage, null, false, true);
parser = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(SUCCEEDING_FAULT));
builder = new StAXSOAPModelBuilder(parser);
soapMessage = builder.getSoapMessage();
succeedingMessage = new AxiomSoapMessage(soapMessage, null, false, true);
}
@Test
public void testGetDetailEntriesWorksWithWhitespaceNodes() throws Exception {
SoapFault fault = failingMessage.getSoapBody().getFault();
Assert.assertNotNull("Fault is null", fault);
Assert.assertNotNull("Fault detail is null", fault.getFaultDetail());
SoapFaultDetail detail = fault.getFaultDetail();
Assert.assertTrue("No next detail entry present", detail.getDetailEntries().hasNext());
detail.getDetailEntries().next();
}
@Test
public void testGetDetailEntriesWorksWithoutWhitespaceNodes() throws Exception {
SoapFault fault = succeedingMessage.getSoapBody().getFault();
Assert.assertNotNull("Fault is null", fault);
Assert.assertNotNull("Fault detail is null", fault.getFaultDetail());
SoapFaultDetail detail = fault.getFaultDetail();
Assert.assertTrue("No next detail entry present", detail.getDetailEntries().hasNext());
detail.getDetailEntries().next();
}
} | 46.072917 | 118 | 0.664255 |
ef598bea8d18047053b6959f5ac90a569c23dba5 | 5,039 | package com.mercandalli.android.apps.files.file.local.provider;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.test.espresso.Espresso;
import android.support.test.espresso.idling.CountingIdlingResource;
import android.util.Log;
import java.util.List;
/**
* Block espresso with {@link CountingIdlingResource} during load.
*/
/* package */
class FileLocalProviderManagerTest extends FileLocalProviderManager {
private static final String TAG = "FileLocalProvManTest";
private final FileLocalProviderManager mFileLocalProviderManager;
private final CountingIdlingResource mCountingIdlingResource;
/**
* The manager constructor.
*
* @param contextApp The {@link Context} of this application.
*/
public FileLocalProviderManagerTest(Context contextApp) {
mFileLocalProviderManager = new FileLocalProviderManagerImpl(contextApp);
mCountingIdlingResource = new CountingIdlingResource(TAG + "#load", true);
Espresso.registerIdlingResources(mCountingIdlingResource);
mFileLocalProviderManager.registerFileProviderListener(new FileProviderListener() {
@Override
public void onFileProviderReloadStarted() {
super.onFileProviderReloadStarted();
}
@Override
protected void onFileProviderAllBasicLoaded(@NonNull final List<String> filePaths) {
decrement();
super.onFileProviderAllBasicLoaded(filePaths);
}
@Override
public void onFileProviderAudioLoaded(@NonNull final List<String> fileAudioPaths) {
super.onFileProviderAudioLoaded(fileAudioPaths);
}
@Override
protected void onFileProviderImageLoaded(@NonNull final List<String> fileImagePaths) {
super.onFileProviderImageLoaded(fileImagePaths);
}
@Override
protected void onFileProviderFailed(@LoadingError int error) {
decrement();
super.onFileProviderFailed(error);
}
private void decrement() {
mCountingIdlingResource.decrement();
Log.d(TAG, "decrement");
}
});
}
@Override
public void load() {
if (mCountingIdlingResource.isIdleNow()) {
mCountingIdlingResource.increment();
Log.d(TAG, "increment load");
}
mFileLocalProviderManager.load();
}
@Override
public void load(@Nullable FileProviderListener fileProviderListener) {
if (mCountingIdlingResource.isIdleNow()) {
mCountingIdlingResource.increment();
Log.d(TAG, "increment load");
}
mFileLocalProviderManager.load(fileProviderListener);
}
@NonNull
@Override
public List<String> getFilePaths() {
return mFileLocalProviderManager.getFilePaths();
}
@Override
public void getFilePaths(GetFilePathsListener getFilePathsListener) {
mFileLocalProviderManager.getFilePaths(getFilePathsListener);
}
@Override
public void removeGetFilePathsListener(final GetFilePathsListener getFilePathsListener) {
mFileLocalProviderManager.removeGetFilePathsListener(getFilePathsListener);
}
@Override
public void getFileAudioPaths(GetFileAudioListener getFileAudioListener) {
mFileLocalProviderManager.getFileAudioPaths(getFileAudioListener);
}
@Override
public void removeGetFileAudioListener(final GetFileAudioListener getFileAudioListener) {
mFileLocalProviderManager.removeGetFileAudioListener(getFileAudioListener);
}
@Override
public void getFileImagePaths(GetFileImageListener getFileImageListener) {
mFileLocalProviderManager.getFileImagePaths(getFileImageListener);
}
@Override
public void removeGetFileImageListener(final GetFileImageListener getFileImageListener) {
mFileLocalProviderManager.removeGetFileImageListener(getFileImageListener);
}
@Override
public void getFileVideoPaths(final GetFileVideoListener getFileVideoListener) {
mFileLocalProviderManager.getFileVideoPaths(getFileVideoListener);
}
@Override
public void removeGetFileVideoListener(final GetFileVideoListener getFileVideoListener) {
mFileLocalProviderManager.removeGetFileVideoListener(getFileVideoListener);
}
@Override
public boolean registerFileProviderListener(FileProviderListener fileProviderListener) {
return mFileLocalProviderManager.registerFileProviderListener(fileProviderListener);
}
@Override
public boolean unregisterFileProviderListener(FileProviderListener fileProviderListener) {
return mFileLocalProviderManager.unregisterFileProviderListener(fileProviderListener);
}
@Override
public void clearCache() {
mFileLocalProviderManager.clearCache();
}
}
| 34.513699 | 98 | 0.713435 |
cb6ea9bfd8ff2f842dfb3cf71191c083a3e866be | 5,367 | package org.pubref.grpc.greetertimer;
import com.google.common.base.Preconditions;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.StatusRuntimeException;
import io.grpc.stub.StreamObserver;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.pubref.rules_protobuf.examples.helloworld.GreeterGrpc;
import org.pubref.rules_protobuf.examples.helloworld.HelloRequest;
import org.pubref.rules_protobuf.examples.helloworld.HelloReply;
/**
* Server that responds to timer check request and reports aggregated
* responses.
*/
public class GreeterTimerServer {
/* The port on which the server should run */
private final int port;
private Server server;
public GreeterTimerServer(int port) {
this.port = port;
}
public void start() throws IOException {
server = ServerBuilder.forPort(port).addService(new GreeterTimerImpl()).build().start();
System.out.println("GreeterTimerServer started, listening on port " + port);
Runtime.getRuntime()
.addShutdownHook(
new Thread() {
@Override
public void run() {
GreeterTimerServer.this.stop();
}
});
}
public void stop() {
System.out.println("GreeterTimerServer stopping...");
if (server != null) {
server.shutdown();
}
}
/**
* Await termination on the main thread since the grpc library uses daemon threads.
*/
private void blockUntilShutdown() throws InterruptedException {
if (server != null) {
server.awaitTermination();
}
}
/**
* Main launches the server from the command line.
*/
public static void main(String[] args) throws IOException, InterruptedException {
final GreeterTimerServer server = new GreeterTimerServer(50053);
server.start();
server.blockUntilShutdown();
}
private class BatchGreeterClient implements Runnable {
private final TimerRequest request;
private final StreamObserver<BatchResponse> observer;
private final ManagedChannel channel;
private final GreeterGrpc.GreeterBlockingStub blockingStub;
/** Construct client connecting to HelloWorld server at {@code host:port}. */
BatchGreeterClient(TimerRequest request, StreamObserver<BatchResponse> observer) {
Preconditions.checkNotNull(request, "request required");
Preconditions.checkNotNull(observer, "response observer required");
Preconditions.checkArgument(request.getHost().length() > 0, "hostname required");
Preconditions.checkArgument(request.getPort() > 0, "grpc port required");
Preconditions.checkArgument(port > 0, "grpc port must be greater than zero");
Preconditions.checkArgument(
request.getTotalSize() > 0, "total request count must be greater than zero");
Preconditions.checkArgument(
request.getBatchSize() > 0, "batch request size must be greater than zero");
this.request = request;
this.observer = observer;
this.channel =
ManagedChannelBuilder.forAddress(request.getHost(), request.getPort())
.usePlaintext(true)
.build();
this.blockingStub = GreeterGrpc.newBlockingStub(channel);
}
public void shutdown() throws InterruptedException {
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
}
/** Aggegate total time for all tests. */
public void run() {
int remaining = request.getTotalSize();
int batchSize = request.getBatchSize();
int batchCount = 0;
int errCount = 0;
long startTime = System.currentTimeMillis();
while (remaining-- > 0) {
try {
if (batchCount++ == batchSize) {
respond(remaining, batchCount, errCount, startTime);
batchCount = 0;
errCount = 0;
startTime = System.currentTimeMillis();
}
blockingStub.sayHello(HelloRequest.newBuilder().setName("#" + remaining).build());
} catch (StatusRuntimeException e) {
errCount++;
System.err.println("RPC failed: " + e.getStatus());
}
}
if (batchCount < batchSize) {
respond(remaining, batchCount, errCount, startTime);
}
try {
shutdown();
} catch (InterruptedException iex) {
throw new RuntimeException(iex);
}
}
private void respond(int remaining, int batchCount, int errCount, long startTime) {
long endTime = System.currentTimeMillis();
long batchTime = endTime - startTime;
BatchResponse response =
BatchResponse.newBuilder()
.setRemaining(remaining)
.setBatchCount(batchCount)
.setBatchTimeMillis(batchTime)
.setErrCount(errCount)
.build();
observer.onNext(response);
}
}
private class GreeterTimerImpl extends GreeterTimerGrpc.GreeterTimerImplBase {
@Override
public void timeGreetings(TimerRequest req, StreamObserver<BatchResponse> observer) {
try {
System.out.println("TimerRequest recvd: " + req);
new BatchGreeterClient(req, observer).run();
} catch (RuntimeException rex) {
observer.onError(rex);
} finally {
observer.onCompleted();
}
}
}
}
| 31.757396 | 92 | 0.664431 |
8e190195778eb8ff1ca4c0210f127ccadc751ba1 | 8,716 | package org.synyx.urlaubsverwaltung.absence;
import org.synyx.urlaubsverwaltung.person.Person;
import java.time.LocalDate;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/**
* Defines absence periods of a {@link Person}.
*
* e.g. Bruce Wayne is absent on:
* <ul>
* <li>24.March 2021 to 28. March 2021 (vacation full day)</li>
* <li>31.March 2021 (vacation morning)</li>
* <li>9.June 2021 (vacation noon)</li>
* <li>26.August 2021 to 27.August 2021 (sick full day)</li>
* </ul>
*/
public class AbsencePeriod {
public enum AbsenceType {
VACATION,
SICK,
}
public enum AbsenceStatus {
// vacation
WAITING,
TEMPORARY_ALLOWED,
ALLOWED,
ALLOWED_CANCELLATION_REQUESTED,
// sick note
ACTIVE,
}
private final List<AbsencePeriod.Record> absenceRecords;
public AbsencePeriod(List<Record> absenceRecords) {
this.absenceRecords = absenceRecords;
}
public List<AbsencePeriod.Record> getAbsenceRecords() {
return Collections.unmodifiableList(absenceRecords);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AbsencePeriod that = (AbsencePeriod) o;
return Objects.equals(absenceRecords, that.absenceRecords);
}
@Override
public int hashCode() {
return Objects.hash(absenceRecords);
}
@Override
public String toString() {
return "AbsencePeriod{" +
"absenceRecords=" + absenceRecords +
'}';
}
/**
* Specifies an absence for one date. The absence consists of `morning` and `evening`.
* You may have to handle information yourself for "full absence vacation". In This case morning and evening are
* defined.
*/
public static class Record {
private final LocalDate date;
private final Person person;
private final RecordMorning morning;
private final RecordNoon noon;
public Record(LocalDate date, Person person, RecordMorning morning) {
this(date, person, morning, null);
}
public Record(LocalDate date, Person person, RecordNoon noon) {
this(date, person, null, noon);
}
public Record(LocalDate date, Person person, RecordMorning morning, RecordNoon noon) {
this.date = date;
this.person = person;
this.morning = morning;
this.noon = noon;
}
public LocalDate getDate() {
return date;
}
public Person getPerson() {
return person;
}
public boolean isHalfDayAbsence() {
return (this.morning == null && this.noon != null) || (this.morning != null && this.noon == null);
}
/**
* Morning RecordInfo is empty when this Record specifies a noon absence only.
*
* @return the morning RecordInfo if it exists, empty Optional otherwise.
*/
public Optional<RecordInfo> getMorning() {
return Optional.ofNullable(morning);
}
/**
* Noon RecordInfo is empty when this Record specifies a morning absence only.
*
* @return the noon RecordInfo if it exists, empty Optional otherwise.
*/
public Optional<RecordInfo> getNoon() {
return Optional.ofNullable(noon);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record absenceRecord = (Record) o;
return Objects.equals(date, absenceRecord.date) && Objects.equals(person, absenceRecord.person);
}
@Override
public int hashCode() {
return Objects.hash(date, person);
}
@Override
public String toString() {
return "Record{" +
"date=" + date +
", person=" + person +
", morning=" + morning +
", noon=" + noon +
'}';
}
}
/**
* Describes an absence record. (e.g. {@link RecordMorning} absence or {@link RecordNoon} absence)
*/
public interface RecordInfo {
Person getPerson();
AbsenceType getType();
AbsenceStatus getStatus();
Integer getId();
boolean hasStatusWaiting();
boolean hasStatusAllowed();
Optional<Integer> getVacationTypeId();
boolean isVisibleToEveryone();
}
/**
* Describes an absence this morning.
*/
public interface RecordMorning extends RecordInfo {}
/**
* Describes an absence this noon.
*/
public interface RecordNoon extends RecordInfo {}
/**
* Describes an absence record. (e.g. morning absence or noon absence)
*/
public abstract static class AbstractRecordInfo implements RecordInfo {
private final Person person;
private final AbsenceType type;
private final Integer id;
private final AbsenceStatus status;
private final Integer vacationTypeId;
private final boolean visibleToEveryone;
private AbstractRecordInfo(Person person, AbsenceType type, Integer id, AbsenceStatus status) {
this(person, type, id, status, null, false);
}
private AbstractRecordInfo(Person person, AbsenceType type, Integer id, AbsenceStatus status, Integer vacationTypeId, boolean visibleToEveryone) {
this.person = person;
this.type = type;
this.id = id;
this.status = status;
this.vacationTypeId = vacationTypeId;
this.visibleToEveryone = visibleToEveryone;
}
@Override
public Person getPerson() {
return person;
}
@Override
public AbsenceType getType() {
return type;
}
@Override
public Integer getId() {
return id;
}
@Override
public AbsenceStatus getStatus() {
return status;
}
public boolean hasStatusOneOf(AbsenceStatus... status) {
return List.of(status).contains(this.status);
}
public boolean hasStatusWaiting() {
return hasStatusOneOf(AbsenceStatus.WAITING, AbsenceStatus.TEMPORARY_ALLOWED);
}
public boolean hasStatusAllowed() {
return !hasStatusWaiting();
}
public Optional<Integer> getVacationTypeId() {
return Optional.ofNullable(vacationTypeId);
}
public boolean isVisibleToEveryone() {
return visibleToEveryone;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AbstractRecordInfo that = (AbstractRecordInfo) o;
return type == that.type && status == that.status;
}
@Override
public int hashCode() {
return Objects.hash(type, status);
}
@Override
public String toString() {
return "AbstractRecordInfo{" +
"id=" + id +
'}';
}
}
public static class RecordMorningVacation extends AbstractRecordInfo implements RecordMorning {
public RecordMorningVacation(Person person, Integer applicationId, AbsenceStatus status, Integer vacationTypeId, boolean visibleToEveryone) {
super(person, AbsenceType.VACATION, applicationId, status, vacationTypeId, visibleToEveryone);
}
}
public static class RecordMorningSick extends AbstractRecordInfo implements RecordMorning {
public RecordMorningSick(Person person, Integer sickNoteId) {
super(person, AbsenceType.SICK, sickNoteId, AbsenceStatus.ACTIVE);
}
}
public static class RecordNoonVacation extends AbstractRecordInfo implements RecordNoon {
public RecordNoonVacation(Person person, Integer applicationId, AbsenceStatus status, Integer vacationTypeId, boolean visibleToEveryone) {
super(person, AbsenceType.VACATION, applicationId, status, vacationTypeId, visibleToEveryone);
}
}
public static class RecordNoonSick extends AbstractRecordInfo implements RecordNoon {
public RecordNoonSick(Person person, Integer sickNoteId) {
super(person, AbsenceType.SICK, sickNoteId, AbsenceStatus.ACTIVE);
}
}
}
| 30.582456 | 154 | 0.605438 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.