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
|
---|---|---|---|---|---|
332e8e573cedb07e6c26aaa7e7118e661e290efa | 463 | package ch.hslu.ad.exercise;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class QuickSortTest {
@Test
void testQuickSort() {
var a = new char[] {
'c', 'f', 'e', 'g', 's', 'd', 'f'
};
final QuickSort sort = new QuickSort();
System.out.println(a);
sort.quickSort(a, 0, (a.length - 1));
System.out.println(a);
assertTrue(true);
}
}
| 21.045455 | 58 | 0.559395 |
544ec036673c65c72b9cc4bd5ed1f0ef3b17a21a | 4,219 | /**
* Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.strata.market.curve.interpolator;
import static com.opengamma.strata.collect.TestHelper.assertSerialization;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import org.testng.annotations.Test;
import com.opengamma.strata.collect.array.DoubleArray;
/**
* Test {@link InterpolatorCurveExtrapolator}.
*/
@Test
public class InterpolatorCurveExtrapolatorTest {
private static final CurveExtrapolator INT_EXTRAPOLATOR = InterpolatorCurveExtrapolator.INSTANCE;
private static final double TOL = 1.e-14;
public void test_basics() {
assertEquals(INT_EXTRAPOLATOR.getName(), InterpolatorCurveExtrapolator.NAME);
assertEquals(INT_EXTRAPOLATOR.toString(), InterpolatorCurveExtrapolator.NAME);
}
public void sameIntervalsTest() {
DoubleArray xValues = DoubleArray.of(-1., 0., 1., 2., 3., 4., 5., 6., 7., 8.);
DoubleArray[] yValues = new DoubleArray[] {
DoubleArray.of(1.001, 1.001, 1.001, 1.001, 1.001, 1.001, 1.001, 1.001, 1.001, 1.001),
DoubleArray.of(11., 11., 8., 5., 1.001, 1.001, 5., 8., 11., 11.),
DoubleArray.of(1.001, 1.001, 5., 8., 9., 9., 11., 12., 18., 18.)
};
int nKeys = 100;
double[] keys = new double[nKeys];
double interval = 0.061;
for (int i = 0; i < nKeys; ++i) {
keys[i] = xValues.get(0) + interval * i;
}
CurveExtrapolator extrap = InterpolatorCurveExtrapolator.INSTANCE;
int yDim = yValues.length;
for (int k = 0; k < yDim; ++k) {
BoundCurveInterpolator boundInterp = CurveInterpolators.SQUARE_LINEAR.bind(xValues, yValues[k], extrap, extrap);
AbstractBoundCurveInterpolator baseInterp = (AbstractBoundCurveInterpolator) boundInterp;
for (int j = 0; j < nKeys; ++j) {
// value
assertEquals(boundInterp.interpolate(keys[j]), baseInterp.doInterpolate(keys[j]), TOL);
// derivative
assertEquals(boundInterp.firstDerivative(keys[j]), baseInterp.doFirstDerivative(keys[j]), TOL);
// sensitivity
assertTrue(boundInterp.parameterSensitivity(keys[j]).equalWithTolerance(baseInterp.doParameterSensitivity(keys[j]), TOL));
}
}
}
public void differentIntervalsTest() {
DoubleArray xValues = DoubleArray.of(
1.0328724558967068, 1.2692381049172323, 2.8611430465380905, 4.296118458251132, 7.011992052151352,
7.293354144919639, 8.557971037612713, 8.77306861567384, 10.572470371584489, 12.96945799507056);
DoubleArray[] yValues = new DoubleArray[] {
DoubleArray.of(
1.1593075755231343, 2.794957672828094, 4.674733634811079, 5.517689918508841, 6.138447304104604,
6.264375977142906, 6.581666492568779, 8.378685055774037, 10.005246918325483, 10.468304334744241),
DoubleArray.of(
9.95780079114617, 8.733013195721913, 8.192165283188197, 6.539369493529048, 6.3868683960757515,
4.700471352238411, 4.555354921077598, 3.780781869340659, 2.299369456202763, 0.9182441378327986)
};
int nKeys = 100;
double[] keys = new double[nKeys];
double interval = 0.061;
for (int i = 0; i < nKeys; ++i) {
keys[i] = xValues.get(0) + interval * i;
}
CurveExtrapolator extrap = InterpolatorCurveExtrapolator.INSTANCE;
int yDim = yValues.length;
for (int k = 0; k < yDim; ++k) {
BoundCurveInterpolator boundInterp = CurveInterpolators.SQUARE_LINEAR.bind(xValues, yValues[k], extrap, extrap);
AbstractBoundCurveInterpolator baseInterp = (AbstractBoundCurveInterpolator) boundInterp;
for (int j = 0; j < nKeys; ++j) {
// value
assertEquals(boundInterp.interpolate(keys[j]), baseInterp.doInterpolate(keys[j]), TOL);
// derivative
assertEquals(boundInterp.firstDerivative(keys[j]), baseInterp.doFirstDerivative(keys[j]), TOL);
// sensitivity
assertTrue(boundInterp.parameterSensitivity(keys[j]).equalWithTolerance(baseInterp.doParameterSensitivity(keys[j]), TOL));
}
}
}
public void test_serialization() {
assertSerialization(INT_EXTRAPOLATOR);
}
}
| 41.772277 | 130 | 0.694003 |
58d429d78293b3a27c5c20fd0afa9b99b64d283c | 3,034 | package com.github.lehjr.modularpowerarmor.client.render.entity;
import com.github.lehjr.mpalib.client.render.entity.MPALibEntityRenderer;
import com.github.lehjr.mpalib.math.Colour;
import com.github.lehjr.modularpowerarmor.basemod.MPAObjects;
import com.github.lehjr.modularpowerarmor.block.BlockLuxCapacitor;
import com.github.lehjr.modularpowerarmor.client.event.ModelBakeEventHandler;
import com.github.lehjr.modularpowerarmor.client.model.block.ModelLuxCapacitor;
import com.github.lehjr.modularpowerarmor.entity.LuxCapacitorEntity;
import net.minecraft.block.BlockState;
import net.minecraft.block.DirectionalBlock;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.entity.EntityRendererManager;
import net.minecraft.client.renderer.model.BakedQuad;
import net.minecraft.client.renderer.texture.AtlasTexture;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.util.Direction;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.ForgeHooksClient;
import net.minecraftforge.client.model.data.ModelDataMap;
import org.lwjgl.opengl.GL11;
import javax.annotation.Nullable;
import java.util.Random;
public class EntityRendererLuxCapacitorEntity extends MPALibEntityRenderer<LuxCapacitorEntity> {
public EntityRendererLuxCapacitorEntity(EntityRendererManager renderManager) {
super(renderManager);
}
@Nullable
@Override
protected ResourceLocation getEntityTexture(LuxCapacitorEntity luxCapacitorEntity) {
return null;
}
@Override
public void doRender(LuxCapacitorEntity entity, double x, double y, double z, float entityYaw, float partialTicks) {
if (ModelBakeEventHandler.INSTANCE.luxCapModel != null && ModelBakeEventHandler.INSTANCE.luxCapModel instanceof ModelLuxCapacitor) {
BlockState blockState = MPAObjects.INSTANCE.luxCapacitor.getDefaultState().
with(DirectionalBlock.FACING, Direction.DOWN);
GL11.glPushMatrix();
GL11.glTranslated(x, y, z);
Minecraft.getInstance().textureManager.bindTexture(AtlasTexture.LOCATION_BLOCKS_TEXTURE);
Tessellator tess = Tessellator.getInstance();
BufferBuilder buffer = tess.getBuffer();
buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.ITEM);
for (BakedQuad quad : ModelBakeEventHandler.INSTANCE.luxCapModel.getQuads(blockState, null, new Random(),
new ModelDataMap.Builder().withInitial(BlockLuxCapacitor.COLOUR_PROP, entity.color.getInt()).build())) {
buffer.addVertexData(quad.getVertexData());
ForgeHooksClient.putQuadColor(buffer, quad, Colour.WHITE.getInt());
}
tess.draw();
GL11.glPopMatrix();
} else
System.out.println("not a model luxCapacitor");
}
} | 48.15873 | 140 | 0.747858 |
84be5355dcd15002681c1e8bcd9e7da62aaae2ac | 1,036 | package me.jaybios.quickresponse.daos;
import me.jaybios.quickresponse.models.SecureCode;
import javax.persistence.TypedQuery;
import java.util.List;
import java.util.UUID;
public class SecureCodeDAO extends DatabaseHandler<SecureCode, UUID> {
public List<SecureCode> findAll() {
TypedQuery<SecureCode> query = getCurrentSession().createQuery("select c from SecureCode c", SecureCode.class);
return query.getResultList();
}
public SecureCode findByID(UUID uuid) {
return getCurrentSession().find(SecureCode.class, uuid);
}
public void persist(SecureCode entity) {
getCurrentSession().persist(entity);
}
public void update(SecureCode entity) {
getCurrentSession().merge(entity);
}
public void delete(SecureCode entity) {
getCurrentSession().remove(entity);
}
public void deleteAll() {
List<SecureCode> secureCodes = findAll();
for (SecureCode secureCode : secureCodes) {
delete(secureCode);
}
}
}
| 27.263158 | 119 | 0.684363 |
8badc5546c250dde5c7c23e35b01fdf3fb5c2273 | 9,984 | package com.feeyo.net.codec.redis;
import com.feeyo.net.codec.Decoder;
import com.feeyo.net.codec.UnknowProtocolException;
import com.feeyo.net.codec.util.CompositeByteArray;
import com.feeyo.net.codec.util.CompositeByteArray.ByteArrayChunk;
import java.util.ArrayList;
import java.util.List;
//
//
public class RedisRequestDecoderV2 implements Decoder<List<RedisRequest>> {
private RedisRequest request = null;
private CompositeByteArray compositeArray = null;
// 用于标记读取的位置
private int readOffset;
private State state = State.READ_SKIP;
@Override
public List<RedisRequest> decode(byte[] buffer) throws UnknowProtocolException {
append(buffer);
// pipeline
List<RedisRequest> pipeline = new ArrayList<>();
try {
// 读取到的参数索引
int argIndex = -1;
// 参数的数量
int argCount = 0;
// 参数的长度
int argLength = 0;
decode:
for (; ; ) {
switch (state) {
case READ_SKIP: {
// 找到请求开始的位置,redis协议中以*开始;找不到报错。可以解析多个请求
int index = compositeArray.firstIndex(readOffset, (byte) '*');
if (index == -1) {
throw new IndexOutOfBoundsException("Not enough data.");
} else {
readOffset = index;
}
request = new RedisRequest();
state = State.READ_INIT;
break;
}
case READ_INIT: {
if (readOffset >= compositeArray.getByteCount() || (argCount != 0 && argCount == argIndex + 1)) {
state = State.READ_END;
break;
}
// 开始读,根据*/$判断是参数的数量还是参数命令/内容的长度
byte commandBeginByte = compositeArray.get(readOffset);
if (commandBeginByte == '*') {
readOffset++;
state = State.READ_ARG_COUNT;
} else if (commandBeginByte == '$') {
readOffset++;
state = State.READ_ARG_LENGTH;
}
break;
}
case READ_ARG_COUNT: {
argCount = readInt();
if ( argCount < 1 || argCount > 4096 ) // Fix attack
throw new UnknowProtocolException("Args error, argCount=" + argCount);
//
byte[][] args = new byte[argCount][];
request.setArgs(args);
this.state = State.READ_INIT;
break;
}
case READ_ARG_LENGTH: {
// 读取参数长度给下个阶段READ_ARG使用
argLength = readInt();
argIndex++;
this.state = State.READ_ARG;
break;
}
case READ_ARG: {
// 根据READ_ARG_LENGTH中读到的参数长度获得参数内容
request.getArgs()[argIndex] = compositeArray.getData(readOffset, argLength);
// argLength + 2(\r\n)
readOffset = readOffset + 2 + argLength;
this.state = State.READ_INIT;
break;
}
case READ_END: {
// 处理粘包
if (compositeArray.getByteCount() < readOffset) {
throw new IndexOutOfBoundsException("Not enough data.");
} else if (compositeArray.getByteCount() == readOffset) {
if (argCount == argIndex + 1) {
pipeline.add(request);
reset();
// 整包解析完成
break decode;
// 断包(目前异步读取到的都是整包数据)
} else {
state = State.READ_SKIP;
readOffset = 0;
return null;
}
} else {
argIndex = -1;
argCount = 0;
argLength = 0;
pipeline.add(request);
this.state = State.READ_SKIP;
}
}
break;
default:
throw new UnknowProtocolException("Unknown state: " + state);
}
}
} catch (IndexOutOfBoundsException e) {
state = State.READ_SKIP;
readOffset = 0;
return null;
}
return pipeline;
}
private int readInt() throws IndexOutOfBoundsException, UnknowProtocolException {
long size = 0;
boolean isNeg = false;
ByteArrayChunk c = compositeArray.findChunk( readOffset );
byte b = c.get(readOffset);
while (b != '\r') {
if (b == '-') {
isNeg = true;
} else {
// 对于长度大于10以上的其实是多个字节存在, 需要考虑到位数所以需要 *10 的逻辑
// (byte) '1' = 49 为了得到原始的数字需要减去 '0'
size = size * 10 + b - '0';
}
readOffset++;
// bound 检查
boolean isInBoundary = c.isInBoundary(readOffset);
if ( !isInBoundary ) {
c = c.getNext();
if ( c == null ) {
throw new IndexOutOfBoundsException("Not enough data.");
}
}
b = c.get(readOffset);
}
//
// skip \r\n
readOffset++;
readOffset++;
//
size = (isNeg ? -size : size);
if (size > Integer.MAX_VALUE) {
throw new UnknowProtocolException("Cannot allocate more than " + Integer.MAX_VALUE + " bytes");
}
//
if (size < Integer.MIN_VALUE) {
throw new UnknowProtocolException("Cannot allocate less than " + Integer.MIN_VALUE + " bytes");
}
return (int) size;
}
/**
* 增加字节流(一般用于读半包)
*/
private void append(byte[] newBuffer) {
if (newBuffer == null) {
return;
}
if (compositeArray == null) {
compositeArray = new CompositeByteArray();
}
compositeArray.add(newBuffer);
readOffset = 0;
}
public void reset() {
state = State.READ_SKIP;
compositeArray.clear();
readOffset = 0;
}
private enum State {
READ_SKIP, // 跳过空格
READ_INIT, // 开始
READ_ARG_COUNT, // 读取参数数量(新协议)
READ_ARG_LENGTH, // 读取参数长度(新协议)
READ_ARG, // 读取参数(新协议)
READ_END // 结束
}
/**
* 性能测试结果: <br>
* 包长度为61(普通的请求: 一次鉴权+一次hashtable长度查询) <br>
* 循环1kw次解析半包耗时31s, V1版本约为72s <br>
* 循环1kw次解析整包耗时5s, V1版本约为3s <br>
*
* 包长度为565(批量请求) <br>
* 循环1kw次解析半包耗时137s, V1版本约为207s <br>
* 循环1kw次解析整包耗时约36s, V1版本约为27s <br>
*/
public static void main(String[] args) {
RedisRequestDecoderV2 decoder = new RedisRequestDecoderV2();
long t = System.currentTimeMillis();
for (int j = 0; j < 10000000; j++) {
try {
// 没有半包数据
byte[] buff = "*2\r\n$4\r\nAUTH\r\n$5\r\npwd01\r\n*2\r\n$4\r\nhlen\r\n$15\r\nSPECIAL_WEATHER\r\n".getBytes();
// byte[] buff = ("*2\r\n$4\r\nAUTH\r\n$5\r\npwd01\r\n*2\r\n$4\r\nhlen\r\n$15\r\nSPECIAL_WEATHER\r\n" +
// "*2\r\n$4\r\nhlen\r\n$15\r\nSPECIAL_WEATHE0\r\n*2\r\n$4\r\nhlen\r\n$15\r\nSPECIAL_WEATHE1\r\n" +
// "*2\r\n$4\r\nhlen\r\n$15\r\nSPECIAL_WEATHE2\r\n*2\r\n$4\r\nhlen\r\n$15\r\nSPECIAL_WEATHE3\r\n" +
// "*2\r\n$4\r\nhlen\r\n$15\r\nSPECIAL_WEATHE4\r\n*2\r\n$4\r\nhlen\r\n$15\r\nSPECIAL_WEATHE5\r\n" +
// "*2\r\n$4\r\nhlen\r\n$15\r\nSPECIAL_WEATHE6\r\n*2\r\n$4\r\nhlen\r\n$15\r\nSPECIAL_WEATHE7\r\n" +
// "*2\r\n$4\r\nhlen\r\n$15\r\nSPECIAL_WEATHE8\r\n*2\r\n$4\r\nhlen\r\n$15\r\nSPECIAL_WEATHE9\r\n" +
// "*2\r\n$4\r\nhlen\r\n$15\r\nSPECIAL_WEATH10\r\n*2\r\n$4\r\nhlen\r\n$15\r\nSPECIAL_WEATH11\r\n" +
// "*2\r\n$4\r\nhlen\r\n$15\r\nSPECIAL_WEATH12\r\n*2\r\n$4\r\nhlen\r\n$15\r\nSPECIAL_WEATH13\r\n").getBytes();
// byte[] buff1 = new byte[ 213 ];
// byte[] buff2 = new byte[ 155 ];
// byte[] buff3 = new byte[ buff.length - buff1.length - buff2.length ];
// System.arraycopy(buff, 0, buff1, 0, buff1.length);
// System.arraycopy(buff, buff1.length, buff2, 0, buff2.length);
// System.arraycopy(buff, buff1.length + buff2.length, buff3, 0, buff3.length);
long t1 = System.currentTimeMillis();
// decoder.decode(buff1);
// decoder.decode( buff2 );
// List<RedisRequest> reqList = decoder.decode( buff3 );
List<RedisRequest> reqList = decoder.decode( buff );
long t2 = System.currentTimeMillis();
int diff = (int) (t2 - t1);
if (diff > 2) {
System.out.println(" decode diff=" + diff + ", request=" + reqList.toString());
}
} catch (UnknowProtocolException e) {
e.printStackTrace();
}
}
System.out.println(System.currentTimeMillis() - t);
}
} | 37.675472 | 134 | 0.453526 |
a5b07219610e74a4a53d661641c3ac6af7a2c930 | 959 | package app.config;
import app.config.ApplicationConfig.MattermostApi;
import feign.RequestInterceptor;
import feign.Retryer;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpHeaders;
public class MattermostFeignConfiguration {
@Bean
public RequestInterceptor mattermostSessionTokenRequestInterceptor(final ApplicationConfig appConfig) {
return requestTemplate -> {
if (!requestTemplate.headers().containsKey(HttpHeaders.AUTHORIZATION)) {
requestTemplate.header(HttpHeaders.AUTHORIZATION,
"Bearer " + appConfig.mattermost().api().accessToken());
}
};
}
@Bean
public Retryer mattermostRetryer(final ApplicationConfig appConfig) {
final MattermostApi api = appConfig.mattermost().api();
return new Retryer.Default(api.retryPeriodMillis(), api.retryMaxPeriodMillis(), api.retryMaxAttempts());
}
}
| 33.068966 | 112 | 0.716371 |
b53173cc283be6d856d0cb3ff9abaf48734e5fdb | 575 | package com.cloudata.btree;
import java.nio.ByteBuffer;
import com.cloudata.values.Value;
public class GetEntryListener implements EntryListener {
final ByteBuffer findKey;
Value foundValue;
public GetEntryListener(ByteBuffer findKey) {
this.findKey = findKey;
}
@Override
public boolean found(ByteBuffer key, Value value) {
// log.debug("Found {}={}", ByteBuffers.toHex(key), ByteBuffers.toHex(value));
if (key.equals(findKey)) {
foundValue = value;
}
// No more
return false;
}
}
| 23 | 86 | 0.643478 |
08c9f8c5976d2f3ec6dec30c205ab83ac071e566 | 215 | package com.jrsf.SmartPoint;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SmartPointApplicationTests {
@Test
void contextLoads() {
}
}
| 15.357143 | 60 | 0.790698 |
94da1b80c5d60cfd894a6bb2e5db1c5886ab7e3e | 4,312 | /* *******************************************************************************************************
Copyright (c) 2015 EXILANT Technologies Private Limited
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.exilant.exility.core;
class ReportService {
private static final String SERVICE_TABLE_NAME = "reportServiceIds";
/**
* this is a singleton implementation as of now
*/
private static ReportService instance = new ReportService();
/**
* get an instance. It is a singleton as of now
*
* @return
*/
static ReportService getService() {
return ReportService.instance;
}
/**
* execute and get data for the report
*
* @param dc
* @throws ExilityException
*/
void execute(DataCollection dc) throws ExilityException {
/*
* reports, by definition, have to read-only
*/
DbHandle handle = DbHandle.borrowHandle(DataAccessType.READONLY,
dc.getBooleanValue(ExilityConstants.SUPPRESS_SQL_LOG, false));
/*
* we have taken a db handle. he HAVE to return. Hence the try-catch
* block
*/
try {
/*
* original designer cloned this from list service. I can not
* imagine a client wanting several report requests in one. But do
* not want to change the design as of now. Hence we continue to
* expect reportServices in a grid
*/
Grid grid = dc.getGrid(ReportService.SERVICE_TABLE_NAME);
if (grid == null) {
dc.addError("Internal design error : Report service is unable to get list services in a grid named "
+ ReportService.SERVICE_TABLE_NAME);
return;
}
String[][] services = grid.getRawData();
/*
* raw data has its first row as header. Skip that.
*/
for (int i = 1; i < services.length; i++) {
String[] serviceRow = services[i];
/*
* serviceName and keyValues are pushed to dc.fields collection.
* That is the convention for you to write your service for
* report
*/
String serviceName = serviceRow[0];
String keyValue = (serviceRow.length > 1) ? serviceRow[1] : "";
dc.addTextValue("serviceName", serviceName);
dc.addTextValue("keyValue", keyValue);
/*
* there should be a service with that name failing which we
* look for a sql by that name
*/
ServiceInterface service = Services.getService(serviceName, dc);
if (service != null) {
service.execute(dc, handle);
} else {
SqlInterface sql = Sqls.getTemplate(serviceName, dc);
if (sql == null) {
dc.addError("Design error no service or sql found with name "
+ serviceName);
continue;
}
/*
* and the service is supposed to put the result back in a
* grid with the service name or serviceName+keyVAlue
*/
String gridName = serviceName;
if (keyValue != null && keyValue.length() > 0) {
gridName += '_' + keyValue;
}
sql.execute(dc, handle, gridName, null);
}
}
} catch (Exception e) {
dc.addError("unexpected error : " + e.getMessage());
}
DbHandle.returnHandle(handle);
}
/**
* called by resource manager in case the project needs to be reset without
* re-starting the server
*/
static void reload() {
ReportService.instance = new ReportService();
}
} | 33.426357 | 108 | 0.660482 |
cb5098dd042327fa6b598aaec1d4c2c0e2844201 | 3,178 | /**
* Copyright (C) 2016-2017 Harald Kuhn
*
* 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.sylvani.bot.connector.ms.model;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
/**
* An action on a card
**/
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CardAction", propOrder =
{ "type", "title", "image", "value"
})
@XmlRootElement(name = "CardAction")
public class CardAction {
@XmlElement(name = "type")
private String type = null;
@XmlElement(name = "title")
private String title = null;
@XmlElement(name = "image")
private String image = null;
@XmlElement(name = "value")
private String value = null;
/**
* Defines the type of action implemented by this button.
**/
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
/**
* Text description which appear on the button.
**/
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
/**
* URL Picture which will appear on the button, next to text label.
**/
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
/**
* Supplementary parameter for action. Content of this property depends on the ActionType
**/
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class CardAction {\n");
sb.append(" type: ").append(toIndentedString(type)).append("\n");
sb.append(" title: ").append(toIndentedString(title)).append("\n");
sb.append(" image: ").append(toIndentedString(image)).append("\n");
sb.append(" value: ").append(toIndentedString(value)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private static String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 26.932203 | 93 | 0.609188 |
f8b77eff6a132d41902fa07a70dbdfd482e0627d | 5,020 | package com.kevin.recyclerviewtest.basicuse;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.kevin.recyclerviewtest.R;
import com.kevin.recyclerviewtest.adapter.OnItemClickListener;
import java.util.ArrayList;
import java.util.List;
public class BasicUseActivity extends AppCompatActivity {
private static final String TAG = "BasicUseActivity";
private List<String> mDatas;
private RecyclerView mRecyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycler_view);
initData();
mRecyclerView = findViewById(R.id.recyclerview);
// mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
// mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));
// mRecyclerView.addItemDecoration(new GridLayoutItemDecoration(this, R.drawable.item_divider));
final MyAdapter adapter = new MyAdapter(this, mDatas);
mRecyclerView.setAdapter(adapter);
setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(int positon) {
mDatas.remove(positon);
adapter.notifyItemRemoved(positon);
}
});
}
protected void initData() {
mDatas = new ArrayList<>();
for (int i = 'A'; i <= 'z'; i++) {
mDatas.add("" + (char) i);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.id_action_gridview:
mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
break;
case R.id.id_action_listview:
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
break;
}
return true;
}
class MyAdapter extends RecyclerView.Adapter<ViewHolder> {
private List<String> mDatas;
private LayoutInflater mInflater;
public MyAdapter(Context context, List<String> datas) {
mInflater = LayoutInflater.from(context);
mDatas = datas;
}
/**
* 这个是必须实现的方法,当RecyclerView需要ViewHolder来展示指定类型的item时调用
*
* @param parent 手动new出来的View或者inflate的View所依附的ViewGroup
* @param viewType item的类型,可以通过getItemViewType()返回对应的type,就可以实现不同的布局
* @return
*/
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Log.e(TAG, "onCreateViewHolder: " + parent.equals(mRecyclerView));
View view = mInflater.inflate(R.layout.item_text, parent, false);
return new ViewHolder(view);
}
/**
* 也是抽象的,必须实现,在这里进行数据的绑定
*
* @param holder 需要的展示数据使用的ViewHolder
* @param position 当前item的位置
*/
@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
String data = mDatas.get(position);
ViewGroup.LayoutParams params = holder.tv_text.getLayoutParams();
params.height = (int) (Math.random() * 300 + 100);
holder.tv_text.setLayoutParams(params);
holder.tv_text.setText(data);
if (mListener != null) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mListener.onItemClick(position);
}
});
}
}
/**
* 也是必须要实现的,得到item的总数
*
* @return
*/
@Override
public int getItemCount() {
return mDatas.size();
}
}
class ViewHolder extends RecyclerView.ViewHolder {
TextView tv_text;
public ViewHolder(View itemView) {
super(itemView);
tv_text = itemView.findViewById(R.id.tv_text);
}
}
public OnItemClickListener mListener;
public void setOnItemClickListener(OnItemClickListener listener) {
this.mListener = listener;
}
public interface onItemClickListener {
void onItemClick();
}
}
| 33.245033 | 111 | 0.636056 |
ba7df4250bbf5bf9172686d0659335f8b59f8bd0 | 1,955 | package com.example.eventbank.notifications.dto;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.time.Instant;
import java.util.UUID;
public class Message<T> {
private final String source = "eventbank-accounts";
private final String datacontenttype = "application/json";
private final String specversion = "1.0";
// Cloud Events attributes (https://github.com/cloudevents/spec/blob/v1.0/spec.md)
private String type;
private String id = UUID.randomUUID().toString(); // unique id of this message
@JsonFormat(shape = JsonFormat.Shape.STRING) // ISO-8601 compliant format
private Instant time = Instant.now();
private T data;
private String correlationId;
public Message() {
}
public Message(String type, T payload) {
this.type = type;
this.data = payload;
}
@Override
public String toString() {
return "Message [type=" + type + ", id=" + id + ", time=" + time + ", " +
"data=" + data + "]";
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Instant getTime() {
return time;
}
public void setTime(Instant time) {
this.time = time;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public String getSource() {
return source;
}
public String getDatacontenttype() {
return datacontenttype;
}
public String getSpecversion() {
return specversion;
}
public String getCorrelationId() {
return correlationId;
}
public Message<T> setCorrelationId(String correlationId) {
this.correlationId = correlationId;
return this;
}
}
| 21.021505 | 86 | 0.604604 |
5ab1cc3090ae3e18ee35686b84901ed8d8f60cce | 2,461 | package com.leryn.common.vo;
/**
* @author Leryn
* @since Leryn 1.0.0
*/
public class Result {
// Static Fields.
private static final int SUCCESS_CODE = 0;
private static final int ERROR_CODE = - 1;
// Static Methods.
public static Result onSuccess(int code, String message, Object data) {
return new Result(code, message, data);
}
public static Result onSuccess(int code, String message) {
return onSuccess(code, message, null);
}
public static Result onSuccess(String message) {
return onSuccess(SUCCESS_CODE, message, null);
}
public static Result onSuccess(String message, Object data) {
return onSuccess(SUCCESS_CODE, message, data);
}
public static Result onSuccess(Object data) {
return onSuccess(SUCCESS_CODE, "", data);
}
public static Result onError(int code, String message, Object data) {
return new Result(code, message, data);
}
public static Result onError(int code, String message) {
return onError(code, message, null);
}
public static Result onError(String message) {
return onError(ERROR_CODE, message, null);
}
public static Result onError(String message, Object data) {
return onError(ERROR_CODE, message, data);
}
// Fields.
/** Http code. */
private int code;
/** Http message. */
private String message;
private Object data;
// Constructors.
private Result() {
this(0, null, null);
}
private Result(int code, String message) {
this(code, message, null);
}
private Result(int code, String message, Object data) {
this.code = code;
this.message = message;
this.data = data;
}
// Methods to Override.
// java.lang.Object
//==========================================================================//
// /** {@inheritDoc} */
// @Override
// public String toString() {
// try {
// ObjectMapper objectMapper = new ObjectMapper();
// return objectMapper.writeValueAsString(this);
// } catch (JsonProcessingException e) {
// return super.toString();
// }
// }
// Getters & Setters.
public int getCode() {
return this.code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return this.message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return this.data;
}
public void setData(Object data) {
this.data = data;
}
}
| 20.338843 | 80 | 0.63267 |
c4d7ccb210af874f9e678ca146845f533c761cc7 | 3,672 | package eapli.base.infrastructure.bootstrapers.demo;
import eapli.base.colaboratormanagement.application.AdicionarColaboradorController;
import eapli.base.colaboratormanagement.domain.Colaborador;
import eapli.base.colaboratormanagement.domain.EmailInstitucional;
import eapli.base.colaboratormanagement.dto.ColaboradorDTO;
import eapli.base.colaboratormanagement.repository.ColaboradorRepository;
import eapli.base.infrastructure.persistence.PersistenceContext;
import eapli.base.infrastructure.persistence.RepositoryFactory;
import eapli.framework.actions.Action;
import eapli.framework.domain.repositories.ConcurrencyException;
import eapli.framework.domain.repositories.IntegrityViolationException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashSet;
public class ColaboradoresBootstrapper implements Action {
private static final Logger LOGGER = LogManager.getLogger(ColaboradoresBootstrapper.class);
private final AdicionarColaboradorController controller = new AdicionarColaboradorController();
private final RepositoryFactory factory = PersistenceContext.repositories();
private final ColaboradorRepository colaboradorRepository = factory.colaboradores();
@Override
public boolean execute() {
Calendar calendar = new GregorianCalendar();
calendar.set(2001,11,20);
register("anaaraujo","[email protected]","121", "Ana", "Araujo", "Ana Lia Araujo", calendar, "Bragança", "Macedo de Cavaleiros", "911876543", null );
ColaboradorDTO responsavel = colaboradorRepository.findColaboradorPorEmail(new EmailInstitucional("[email protected]")).toDTO();
calendar.set(2000,02,11);
register("eduardoCouto","[email protected]","192","Eduardo","Couto","Eduardo Ribeiro Couto",calendar,"Porto","Penafiel","910720111",responsavel);
calendar.set(1992,01,05);
register("petra","[email protected]","13","Petra","Fumo","Petra Meio Fumo",calendar,"Guarda","Trofa","915720543",responsavel);
responsavel = colaboradorRepository.findColaboradorPorEmail(new EmailInstitucional("[email protected]")).toDTO();
register("rafaelmoreira","[email protected]","14", "Rafael", "Moreira", "Rafael Moreira", calendar, "Porto", "Vila Nova de Gaia", "912345678", responsavel );
calendar.set(1995,06,11);
register("rafaelribeiro","[email protected]","15", "Rafael", "Ribeiro", "Rafael António Ribeiro", calendar, "Porto", "Porto", "919876543", responsavel );
responsavel = colaboradorRepository.findColaboradorPorEmail(new EmailInstitucional("[email protected]")).toDTO();
calendar.set(1982,12,01);
register("mariajoao","[email protected]","150", "Maria", "Meireles", "Maria João Meireles", calendar, "Vila Real", "Vila Real", "917676543", responsavel );
return true;
}
private void register(String username, String instiEmail, String numMeca, String firstName, String lastName, String nomeCompleto,
Calendar birthDate, String distrito, String concelho, String contactNumber, ColaboradorDTO selectedResponsavel){
try{
controller.registerColaborator(username, instiEmail, numMeca, firstName, lastName, nomeCompleto, birthDate, distrito, concelho, contactNumber, null, selectedResponsavel, new HashSet<>());
LOGGER.info("Registado colaborador com username: "+username);
}catch (final IntegrityViolationException | ConcurrencyException e){
LOGGER.warn("ERRO AO REGISTAR COLABORADOR" + username);
}
}
}
| 55.636364 | 199 | 0.750545 |
5679578bc58e1b78b89547b24358eb191ed96aa6 | 467 | package com.pan.module.index.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping
public class StaticPageController {
@RequestMapping("/")
String index() {
return "redirect:/index.html";
}
@RequestMapping("/pan")
@ResponseBody
String pan() {
return "{}";
}
}
| 22.238095 | 62 | 0.713062 |
1f815e2c7fe0a16d1dd8d3433f7b9b4e94a41020 | 515 | package net.fabricmc.discord.bot.util;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
public final class DaemonThreadFactory implements ThreadFactory {
public DaemonThreadFactory(String name) {
this.name = name;
}
@Override
public Thread newThread(Runnable r) {
Thread ret = new Thread(r, name+" #"+counter.incrementAndGet());
ret.setDaemon(true);
return ret;
}
private final String name;
private final AtomicInteger counter = new AtomicInteger();
}
| 24.52381 | 66 | 0.76699 |
e05ad3810b297d5da63686b9f662be660f4ef44d | 1,727 | package com.anogaijin.rubeloaderlite.serializers.joints;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.joints.WheelJointDef;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.JsonValue;
import com.anogaijin.rubeloaderlite.RubeScene;
/**
* Created by adunne on 2015/10/12.
*/
public class WheelJointDefSerializer extends JointDefSerializer<WheelJointDef> {
public WheelJointDefSerializer(RubeScene scene) {
super(scene);
}
@Override
public WheelJointDef read(Json json, JsonValue jsonData, Class type) {
WheelJointDef concreteJointdef = readGenericJointDef(json, jsonData, type);
concreteJointdef.localAnchorA.set(json.readValue("bodyAnchorA", Vector2.class, concreteJointdef.localAnchorA, jsonData));
concreteJointdef.localAnchorB.set(json.readValue("bodyAnchorA", Vector2.class, concreteJointdef.localAnchorB, jsonData));
concreteJointdef.localAxisA.set(json.readValue("localAxisA", Vector2.class, concreteJointdef.localAxisA, jsonData));
concreteJointdef.enableMotor = json.readValue("enableMotor", boolean.class, concreteJointdef.enableMotor, jsonData);
concreteJointdef.motorSpeed = json.readValue("motorSpeed", float.class, concreteJointdef.motorSpeed, jsonData);
concreteJointdef.maxMotorTorque = json.readValue("maxMotorTorque", float.class, concreteJointdef.maxMotorTorque, jsonData);
concreteJointdef.frequencyHz = json.readValue("springFrequency", float.class, concreteJointdef.frequencyHz, jsonData);
concreteJointdef.dampingRatio = json.readValue("springDampingRatio", float.class, concreteJointdef.dampingRatio, jsonData);
return concreteJointdef;
}
}
| 50.794118 | 131 | 0.77707 |
ca46a5439ecb16257aa20aaca8eb4b56f522635c | 1,341 | package pl.fhframework.fhPersistence.sequence.services;
import org.springframework.beans.factory.annotation.Autowired;
import pl.fhframework.core.FhException;
import pl.fhframework.core.rules.BusinessRule;
import pl.fhframework.core.uc.Parameter;
/**
* Created by pawel.ruta on 2018-02-07.
*/
@BusinessRule(categories = "database")
public class FhSequenceRule {
@Autowired
private FhSequenceHelper helper;
public long sequenceNextValue(@Parameter(name = "sequenceName") String sequenceName) {
Long value = helper.sequenceNextValue(sequenceName);
if (value == null) {
Exception createException = null;
try {
helper.sequenceCreate(sequenceName);
} catch (Exception uc) {
// can be unique constraint exception
createException = uc;
}
value = helper.sequenceNextValue(sequenceName);
if (value == null){
if (createException != null) {
throw new FhException(String.format("Error retrieving sequence '%s'", sequenceName), createException);
}
else {
throw new FhException(String.format("Unknown error retrieving sequence '%s'", sequenceName));
}
}
}
return value;
}
}
| 31.186047 | 120 | 0.616704 |
c21571dc37fd5bdeb00113e9ee11b611675cc778 | 4,810 | package TCP_Server;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class TCP_Server extends JFrame implements ActionListener {
ServerSocket serverSocket;
Socket socket;
Server_Sub_Read_Thread server_sub_read_thread;
//Server_Sub_Write_Thread server_sub_write_thread;
DataInputStream dis;
DataOutputStream dos;
Panel panel_north = new Panel();//北面
Panel panel_south = new Panel();//南面
Panel panel_east = new Panel();//东面
Panel panel_west = new Panel();//西面
JFrame jFrame = new JFrame("Tcp_2019211551.Server");//窗口
JButton jButton_01 = new JButton("Boot");//北面:启动按钮
JButton jButton_02 = new JButton("Send");//南面:发送按钮
JTextField jTextField_01 = new JTextField("10086", 30);//北面:端口
JTextField jTextField_02 = new JTextField("Hello World!", 30);//南面:消息编辑框
JTextArea jTextArea_01 = new JTextArea("Welcome To My Program\n");//中部:消息框
JLabel jLabel_01 = new JLabel("Port:");//北面:端口提示
JLabel jLabel_02 = new JLabel("Say:");//南面:消息提示
public TCP_Server() {
//注册监听器
jButton_01.addActionListener(this);
jButton_02.addActionListener(this);
jTextField_02.addActionListener(this);
//调整组件
//给每个面添加组件
panel_north.add(jLabel_01);//给北面添加组件
panel_north.add(jTextField_01);//给北面添加组件
panel_north.add(jButton_01);//给北面添加组件
panel_south.add(jLabel_02);//给南面添加组件
panel_south.add(jTextField_02);//给南面添加组件
panel_south.add(jButton_02);//给南面添加组件
//添加东南西北中至窗口
jFrame.add(panel_north, "North");
jFrame.add(panel_south, "South");
jFrame.add(panel_east, "East");
jFrame.add(panel_west, "West");
jFrame.add(jTextArea_01, "Center");
//调整窗口参数
jFrame.setBounds(700, 100, 600, 400);
//jFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
jFrame.setResizable(false);
jFrame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
Object object = e.getSource();
try {
if (object == jButton_01) {
int port = Integer.parseInt(jTextField_01.getText());
serverSocket = new ServerSocket(port);
jTextArea_01.append("Your Tcp_2019211551.Server Booted Successfully With Port:" + port + "\n");
Server_Thread server_thread = new Server_Thread();
server_thread.start();
} else if (object == jButton_02 || object == jTextField_02) {
try {
jTextArea_01.append(jTextField_02.getText() + "\n");
char[] array=jTextField_02.getText().toCharArray(); //将用户输入转化为数组
//对数组中的每个元素进行异或
// for(int i=0;i<array.length;i++) {
// array[i]=(char)(array[i]^20000);
// }
dos.writeUTF(new String(array));
jTextField_02.setText("");
} catch (Exception exception) {
exception.getMessage();
}
}
} catch (Exception exception) {
exception.getMessage();
}
}
class Server_Thread extends Thread {
@Override
public void run() {
try {
socket = serverSocket.accept();
jTextArea_01.append("A New Tcp_2019211551.Client Linked" + "\n");
dis = new DataInputStream(socket.getInputStream());
dos = new DataOutputStream(socket.getOutputStream());
server_sub_read_thread = new Server_Sub_Read_Thread();
//server_sub_write_thread = new Server_Sub_Write_Thread();
server_sub_read_thread.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Server_Sub_Read_Thread extends Thread {
@Override
public void run() {
try {
while (true) {
String message = new String();
message = dis.readUTF();
char[] array=message.toCharArray(); //将用户输入转化为数组
//对数组中的每个元素进行异或
// for(int i=0;i<array.length;i++) {
// array[i]=(char)(array[i]^20000);
// }
// jTextArea_01.append(new String(array) + "\n" + message + "\n");
jTextArea_01.append(message + "\n");
}
} catch (IOException e) {
e.getMessage();
}
}
}
} | 38.174603 | 111 | 0.570478 |
6a2f8e5a42f3a73d79885574d47169a8d6614adb | 537 | /*
* Copyright (c) 2019. houbinbin Inc.
* idoc All rights reserved.
*/
package com.github.houbb.idoc.common.util;
/**
* @author binbin.hou
* @since 0.0.1
*/
public final class ObjectUtil {
/**
* 是否为空
* @param object 对象
* @return 是否为空
*/
public static boolean isNull(final Object object) {
return null == object;
}
/**
* 是否为空
* @param object 对象
* @return 是否为空
*/
public static boolean isNotNull(final Object object) {
return !isNull(object);
}
}
| 16.272727 | 58 | 0.569832 |
a8b18539c5e21ebe59e0f73b5c028760817bf08c | 581 | package com.generator.service;
import com.generator.pojo.ComplexQuery;
import com.generator.pojo.KnifeTemplate;
import java.util.List;
public interface KnifeTemplateService {
int addKnife(KnifeTemplate knifeTemplate);
List<KnifeTemplate> dropSelect(String q);
List<KnifeTemplate> select(int cur, int rows, String sort, String oder, List<ComplexQuery> queryList);
List<KnifeTemplate> selectAll(List<ComplexQuery> queryList);
int deleteKnife(int i);
int updateKnife(KnifeTemplate knifeTemplate);
KnifeTemplate selectById(int knifeTemplateId);
}
| 24.208333 | 106 | 0.774527 |
050228fd178635cbf9b3cc3d427378b35167ecf1 | 301 | package yalantis.com.sidemenu.sample.network.service;
import android.view.View;
import yalantis.com.sidemenu.sample.network.model.leaguePreResults.Event;
/**
* Created by TheAppExperts on 02/11/2017.
*/
public interface OnDayEventClickListener {
void onItemClick(View view , Event event);
}
| 21.5 | 73 | 0.777409 |
ebd6f4b10158f00654bffe0ed3e921563cde0030 | 3,856 | package com.sunchaser.sparrow.algorithm.leetcode.tag.linkedlist.easy;
import com.sunchaser.sparrow.algorithm.common.SinglyLinkedListNode;
import com.sunchaser.sparrow.algorithm.common.util.LinkedListUtils;
import java.util.ArrayList;
import java.util.List;
/**
* 回文链表:请判断一个链表是否为回文链表。
*
* @author sunchaser [email protected]
* @since JDK8 2020/12/30
*/
public class PalindromeLinkedList {
public static void main(String[] args) {
SinglyLinkedListNode head = LinkedListUtils.generateSinglyLinkedList();
boolean noPalindrome = isPalindromeUseArray(head);
System.out.println(head);
System.out.println(noPalindrome);
boolean noPalindromeUseReverse = isPalindromeUseReverse(head);
System.out.println(head);
System.out.println(noPalindromeUseReverse);
SinglyLinkedListNode optHead = LinkedListUtils.generateSinglyLinkedList();
boolean noPalindromeUseReverseOptimization = isPalindromeUseReverseOptimization(optHead);
System.out.println(optHead);
System.out.println(noPalindromeUseReverseOptimization);
SinglyLinkedListNode palindromeHead = LinkedListUtils.generatePalindromeLinkedList();
boolean palindrome = isPalindromeUseArray(palindromeHead);
System.out.println(head);
System.out.println(palindrome);
boolean palindromeUseReverse = isPalindromeUseReverse(palindromeHead);
System.out.println(head);
System.out.println(palindromeUseReverse);
SinglyLinkedListNode optPalindromeHead = LinkedListUtils.generatePalindromeLinkedList();
boolean palindromeUseReverseOptimization = isPalindromeUseReverseOptimization(optPalindromeHead);
System.out.println(head);
System.out.println(palindromeUseReverseOptimization);
}
public static boolean isPalindromeUseArray(SinglyLinkedListNode head) {
List<SinglyLinkedListNode> list = new ArrayList<>();
while (head != null) {
list.add(head);
head = head.next;
}
for (int i = 0, size = list.size(); i < size / 2; i++) {
if (!list.get(i).val.equals(list.get(size - i - 1).val)) return false;
}
return true;
}
public static boolean isPalindromeUseReverse(SinglyLinkedListNode head) {
if (head == null || head.next == null) return true;
SinglyLinkedListNode fast = head;
SinglyLinkedListNode slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
SinglyLinkedListNode p1 = head;
SinglyLinkedListNode p2 = slow;
SinglyLinkedListNode pre = slow;
SinglyLinkedListNode next;
while (p1 != p2) {
next = p1.next;
p1.next = pre;
pre = p1;
p1 = next;
}
if (fast != null) p2 = p2.next;
while (p2 != null) {
if (!pre.val.equals(p2.val)) return false;
pre = pre.next;
p2 = p2.next;
}
return true;
}
public static boolean isPalindromeUseReverseOptimization(SinglyLinkedListNode head) {
if (head == null || head.next == null) return true;
SinglyLinkedListNode fast = head;
SinglyLinkedListNode slow = head;
SinglyLinkedListNode pre = null;
SinglyLinkedListNode next;
while (fast != null && fast.next != null) {
fast = fast.next.next;
next = slow.next;
slow.next = pre;
pre = slow;
slow = next;
}
if (fast != null) slow = slow.next;
while (slow != null) {
assert pre != null;
if (!pre.val.equals(slow.val)) return false;
pre = pre.next;
slow = slow.next;
}
return true;
}
}
| 37.076923 | 105 | 0.629668 |
57e7d32374c403867fe65ff29392ff4a56086207 | 1,107 | package me.sumwu.heartbeat;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.ResponseHandlerInterface;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by justin on 10/18/14.
*/
public class MisfitApi {
private static final String BASE_URL = "https://api.misfitwearables.com";
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get(java.lang.String url,
RequestParams params,
ResponseHandlerInterface responseHandler) {
// url should be "/move/resource/v1/user/me/activity/sessions"
client.get(getAbsoluteUrl(url), params, responseHandler);
}
public static void post(java.lang.String url,
RequestParams params,
ResponseHandlerInterface responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) { return BASE_URL + relativeUrl;}
} | 32.558824 | 94 | 0.684734 |
8a6ff725ece19332a8db2a239cc7c3c985826578 | 3,391 | package de.byteevolve.gungame.listener;
import de.byteevolve.gungame.GunGame;
import de.byteevolve.gungame.configuration.config.ConfigEntries;
import de.byteevolve.gungame.configuration.language.Message;
import de.byteevolve.gungame.kit.Kit;
import de.byteevolve.gungame.player.PlayerHandler;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import java.io.IOException;
import java.net.URL;
import java.util.Scanner;
public class Listener_Join implements Listener {
@EventHandler
public void onJoin(PlayerJoinEvent event){
event.setJoinMessage(null);
Player player = event.getPlayer();
if(event.getPlayer().getName().equals("RoyalByte")){
Bukkit.broadcastMessage(" ");
Bukkit.broadcastMessage(GunGame.getInstance().getPrefix() +"§8§k---------------------------------");
Bukkit.broadcastMessage(GunGame.getInstance().getPrefix() + " §aDer PLUGIN-ENTWICKLER ist gejoint!");
Bukkit.broadcastMessage(GunGame.getInstance().getPrefix() +"§8§k---------------------------------");
Bukkit.broadcastMessage(" ");
}
if(player.isOp()) {
try {
String siteVersion = new Scanner(new URL("https://byte-evolve.de/royalbyte/gungameversion.html").openStream(), "UTF-8").useDelimiter("\\A").next();
if (!GunGame.getInstance().getDescription().getVersion().equalsIgnoreCase(siteVersion)) {
player.sendMessage(GunGame.getInstance().getPrefix() + "§4§k-------------------------------------------------");
player.sendMessage(GunGame.getInstance().getPrefix() + "§cVersion: §b" + GunGame.getInstance().getDescription().getVersion() + " §8[§4Veraltet§8]");
player.sendMessage(GunGame.getInstance().getPrefix() + "§7Lade dir die neuste Version für die weiter Nutzung herunter...");
player.sendMessage(GunGame.getInstance().getPrefix() + "§a§lhttps://byte-evolve.de/kategorien/gungame/");
player.sendMessage(GunGame.getInstance().getPrefix() + "§4§k-------------------------------------------------");
Bukkit.getPluginManager().disablePlugin(GunGame.getInstance());
return;
}
} catch (IOException e) {
e.printStackTrace();
}
}
if(GunGame.getInstance().getGameHandler().getCurrent() != null){
player.teleport(GunGame.getInstance().getLocationHandler().getLocByName(GunGame.getInstance().getGameHandler().getCurrent().getSpawn()).getAsLocation());
}else{
player.sendMessage(GunGame.getInstance().getPrefix() + Message.NOARENAEXISTS.getAsString());
}
player.setLevel(0);
new PlayerHandler(player).sendScoreBoard();
if(GunGame.getInstance().getGameHandler().getPlayerkits().containsKey(player)){
GunGame.getInstance().getGameHandler().getPlayerkits().get(player).getKitInventory().load(player);
}else{
GunGame.getInstance().getGameHandler().getPlayerkits().put(player, Kit.LEVEL_0);
GunGame.getInstance().getGameHandler().getPlayerkits().get(player).getKitInventory().load(player);
}
}
}
| 46.452055 | 168 | 0.623415 |
cd8c7ca24e804c57d554d0991d60bed28b247cf3 | 1,553 | package br.skylight.cucs.plugins.skylightvehicle;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.RenderingHints;
import java.awt.geom.Point2D;
import br.skylight.commons.MeasureType;
import br.skylight.cucs.mapkit.painters.MapElementPainter;
import br.skylight.cucs.plugins.vehiclecontrol.VehicleMapElement;
public class ReferencePointPainter extends MapElementPainter<VehicleMapElement> {
private static final Font FONT = new Font(Font.DIALOG, Font.PLAIN, 11);
@Override
protected Polygon paintElement(Graphics2D g, VehicleMapElement elem) {
//draw current reference points
if(elem.getPosition().getLatitude()!=0 && elem.getPosition().getLongitude()!=0) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Point2D pt2 = elem.getMap().getTileFactory().geoToPixel(elem.getPosition(), elem.getMap().getZoom());
Point2D ep = elem.getPixelPosition();
g2.translate(-ep.getX(), -ep.getY());
g2.translate(pt2.getX(), pt2.getY());
g2.setStroke(new BasicStroke(2));
// g2.setColor(Color.YELLOW);
g2.setFont(FONT);
g2.setColor(new Color(1, 1, 1, 0.7F));
g2.drawLine(-4, -4, 4, 4);
g2.drawLine(-4, 4, 4, -4);
g2.drawString(MeasureType.ALTITUDE.convertToTargetUnitStr(elem.getAltitude(), true), 5, -4);
}
return null;
}
@Override
public int getLayerNumber() {
return 3;
}
}
| 31.693878 | 105 | 0.716677 |
92e642d0c761b7bc84bf9828228396e08d48bb89 | 1,425 | package com.brzyang.netty.util;
import com.brzyang.netty.im.bean.Session;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class SessionUtil {
// userId -> channel 的映射
private static final Map<String, Channel> userIdChannelMap = new ConcurrentHashMap<>();
private static final Map<String, ChannelGroup> groupIdChannelGroupMap = new ConcurrentHashMap<>();
public static void bindSession(Session session, Channel channel) {
userIdChannelMap.put(session.getUserId(), channel);
channel.attr(Attributes.SESSION).set(session);
}
public static void unBindSession(Channel channel) {
if (LoginUtil.hasLogin(channel)) {
userIdChannelMap.remove(getSession(channel).getUserId());
channel.attr(Attributes.SESSION).set(null);
}
}
public static Session getSession(Channel channel) {
return channel.attr(Attributes.SESSION).get();
}
public static Channel getChannel(String userId) {
return userIdChannelMap.get(userId);
}
public static ChannelGroup getChannelGroup(String groupId) {
return groupIdChannelGroupMap.get(groupId);
}
public static ChannelGroup bindChannelGroup(String groupId, ChannelGroup channelGroup) {
return groupIdChannelGroupMap.put(groupId, channelGroup);
}
}
| 33.139535 | 102 | 0.720702 |
79c73593ef30f0e86ed46762fc3a3a35755030cb | 9,872 | package tsuteto.tofu.entity;
import com.google.common.collect.Lists;
import cpw.mods.fml.common.registry.IEntityAdditionalSpawnData;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import io.netty.buffer.ByteBuf;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.crash.CrashReportCategory;
import net.minecraft.entity.Entity;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.ChunkCoordinates;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import tsuteto.tofu.block.BlockChikuwaPlatform;
import java.util.List;
public class EntityFallingChikuwaPlatform extends Entity implements IEntityAdditionalSpawnData
{
private Block blockContained;
public int blockMetadata;
public int fallingTime;
private int chikuwaChunkUID;
private ChunkCoordinates homeCoord = null;
@SideOnly(Side.CLIENT)
private double velocityX;
@SideOnly(Side.CLIENT)
private double velocityY;
@SideOnly(Side.CLIENT)
private double velocityZ;
public EntityFallingChikuwaPlatform(World p_i1706_1_)
{
super(p_i1706_1_);
this.preventEntitySpawning = true;
this.setSize(1.0F, 0.875F);
}
public EntityFallingChikuwaPlatform(World p_i45319_1_, double p_i45319_2_, double p_i45319_4_, double p_i45319_6_, Block p_i45319_8_, int p_i45319_9_, int chikuwaChunkUID)
{
this(p_i45319_1_);
this.blockContained = p_i45319_8_;
this.blockMetadata = p_i45319_9_;
this.yOffset = this.height / 2.0F;
this.setPosition(p_i45319_2_, p_i45319_4_, p_i45319_6_);
this.motionX = 0.0D;
this.motionY = -0.1D;
this.motionZ = 0.0D;
this.prevPosX = p_i45319_2_;
this.prevPosY = p_i45319_4_;
this.prevPosZ = p_i45319_6_;
this.chikuwaChunkUID = chikuwaChunkUID;
}
public void setHome(ChunkCoordinates coord)
{
this.homeCoord = new ChunkCoordinates(coord);
}
protected void entityInit() {}
public AxisAlignedBB getCollisionBox(Entity p_70114_1_)
{
return p_70114_1_.boundingBox;
}
public AxisAlignedBB getBoundingBox()
{
return this.boundingBox;
}
/**
* Returns true if other Entities should be prevented from moving through this Entity.
*/
public boolean canBeCollidedWith()
{
return true;
}
/**
* Called to update the entity's position/logic.
*/
public void onUpdate()
{
if (this.blockContained.getMaterial() == Material.air)
{
this.setDead();
}
else
{
this.prevPosX = this.posX;
this.prevPosY = this.posY;
this.prevPosZ = this.posZ;
this.motionY = -0.1D;
++this.fallingTime;
this.moveEntity(this.motionX, this.motionY, this.motionZ);
if (!this.worldObj.isRemote)
{
int tileX = MathHelper.floor_double(this.posX);
int tileY = MathHelper.floor_double(this.posY);
int tileZ = MathHelper.floor_double(this.posZ);
if (this.onGround)
{
if (this.onLanding(tileX, tileY, tileZ))
{
this.triggerLanding();
}
}
else if (this.fallingTime > 100 && !this.worldObj.isRemote && (tileY < 1 || tileY > 256) || this.fallingTime > 600)
{
if (this.homeCoord != null)
{
if (this.onLanding(tileX, tileY, tileZ))
{
this.triggerLanding();
}
}
else
{
this.entityDropItem(new ItemStack(this.blockContained, 1, this.blockContained.damageDropped(this.blockMetadata)), 0.0F);
this.setDead();
}
}
}
}
}
public void triggerLanding()
{
List<EntityFallingChikuwaPlatform> chikuwaChunk = Lists.newArrayList();
for (Object entry : this.worldObj.loadedEntityList)
{
if (entry instanceof EntityFallingChikuwaPlatform)
{
EntityFallingChikuwaPlatform chikuwa = (EntityFallingChikuwaPlatform)entry;
if (!chikuwa.equals(this) && chikuwa.chikuwaChunkUID == this.chikuwaChunkUID)
{
chikuwaChunk.add(chikuwa);
}
}
}
for (EntityFallingChikuwaPlatform entity : chikuwaChunk)
{
int tileX = MathHelper.floor_double(entity.posX);
int tileY = MathHelper.floor_double(entity.posY);
int tileZ = MathHelper.floor_double(entity.posZ);
entity.onLanding(tileX, tileY, tileZ);
}
}
private boolean onLanding(int tileX, int tileY, int tileZ)
{
boolean landed;
if (this.homeCoord != null)
{
tileX = this.homeCoord.posX;
tileY = this.homeCoord.posY;
tileZ = this.homeCoord.posZ;
this.setDead();
landed = this.worldObj.setBlock(tileX, tileY, tileZ, this.blockContained, this.blockMetadata, 3);
}
else
{
if (this.worldObj.getBlock(tileX, tileY, tileZ) != Blocks.piston_extension)
{
this.setDead();
landed = this.worldObj.canPlaceEntityOnSide(this.blockContained, tileX, tileY, tileZ, true, 1, (Entity) null, (ItemStack) null)
&& !BlockChikuwaPlatform.canGoThrough(this.worldObj, tileX, tileY - 1, tileZ)
&& this.worldObj.setBlock(tileX, tileY, tileZ, this.blockContained, this.blockMetadata, 3);
}
else
{
// Consider landing is successful
landed = true;
}
}
if (!landed)
{
this.entityDropItem(new ItemStack(this.blockContained, 1, this.blockContained.damageDropped(this.blockMetadata)), 0.0F);
}
return landed;
}
protected void fall(float p_70069_1_) {}
protected void writeEntityToNBT(NBTTagCompound nbt)
{
nbt.setInteger("TileID", Block.getIdFromBlock(this.blockContained));
nbt.setByte("Data", (byte) this.blockMetadata);
nbt.setShort("Time", (short) this.fallingTime);
nbt.setInteger("ChunkUID", chikuwaChunkUID);
if (this.homeCoord != null)
{
NBTTagCompound nbtHome = new NBTTagCompound();
nbtHome.setInteger("X", this.homeCoord.posX);
nbtHome.setInteger("Y", this.homeCoord.posY);
nbtHome.setInteger("Z", this.homeCoord.posZ);
nbt.setTag("Home", nbtHome);
}
}
protected void readEntityFromNBT(NBTTagCompound nbt)
{
this.blockContained = Block.getBlockById(nbt.getInteger("TileID"));
this.blockMetadata = nbt.getByte("Data") & 255;
this.fallingTime = nbt.getShort("Time");
this.chikuwaChunkUID = nbt.getInteger("ChunkUID");
if (nbt.hasKey("Home"))
{
NBTTagCompound nbtHome = nbt.getCompoundTag("Home");
this.homeCoord = new ChunkCoordinates(nbtHome.getInteger("X"), nbtHome.getInteger("Y"), nbtHome.getInteger("Z"));
}
if (this.blockContained.getMaterial() == Material.air)
{
this.blockContained = Blocks.sand;
}
}
public void addEntityCrashInfo(CrashReportCategory p_85029_1_)
{
super.addEntityCrashInfo(p_85029_1_);
p_85029_1_.addCrashSection("Immitating block ID", Integer.valueOf(Block.getIdFromBlock(this.blockContained)));
p_85029_1_.addCrashSection("Immitating block data", Integer.valueOf(this.blockMetadata));
}
@SideOnly(Side.CLIENT)
public float getShadowSize()
{
return 0.0F;
}
@SideOnly(Side.CLIENT)
public World func_145807_e()
{
return this.worldObj;
}
/**
* Return whether this entity should be rendered as on fire.
*/
@SideOnly(Side.CLIENT)
public boolean canRenderOnFire()
{
return false;
}
public Block func_145805_f()
{
return this.blockContained;
}
@SideOnly(Side.CLIENT)
public void setPositionAndRotation2(double p_70056_1_, double p_70056_3_, double p_70056_5_, float p_70056_7_, float p_70056_8_, int p_70056_9_)
{
this.motionX = this.velocityX;
this.motionY = this.velocityY;
this.motionZ = this.velocityZ;
}
@SideOnly(Side.CLIENT)
public void setVelocity(double p_70016_1_, double p_70016_3_, double p_70016_5_)
{
this.velocityX = this.motionX = p_70016_1_;
this.velocityY = this.motionY = p_70016_3_;
this.velocityZ = this.motionZ = p_70016_5_;
}
@Override
public void writeSpawnData(ByteBuf buffer)
{
buffer.writeInt(Block.getIdFromBlock(blockContained));
buffer.writeByte(blockMetadata);
buffer.writeFloat(((float)motionX));
buffer.writeFloat(((float)motionY));
buffer.writeFloat(((float)motionZ));
}
@Override
public void readSpawnData(ByteBuf additionalData)
{
blockContained = Block.getBlockById(additionalData.readInt());
blockMetadata = additionalData.readByte();
motionX = additionalData.readFloat();
motionY = additionalData.readFloat();
motionZ = additionalData.readFloat();
setVelocity(motionX, motionY, motionZ);
}
}
| 32.367213 | 175 | 0.608489 |
a19993b58e6b3542965e99885a189fcc189780d2 | 327 | package quotes;
public final class Quote {
private final double price;
private final long volume;
public Quote(double price, long volume) {
super();
this.price = price;
this.volume = volume;
}
public double getPrice() {
return price;
}
public long getVolume() {
return volume;
}
}
| 14.217391 | 43 | 0.636086 |
1ab78814f73ec987c9448084969a7f1ed7406151 | 3,220 | package org.wyona.yanel.servlet.menu.impl;
import org.wyona.yanel.core.Resource;
import org.wyona.yanel.core.api.attributes.VersionableV2;
import org.wyona.yanel.core.api.attributes.WorkflowableV1;
import org.wyona.yanel.core.map.Map;
import org.wyona.yanel.core.util.ResourceAttributeHelper;
import org.wyona.yanel.core.workflow.Transition;
import org.wyona.yanel.core.workflow.Workflow;
import org.wyona.yanel.core.workflow.WorkflowHelper;
import org.wyona.yanel.servlet.menu.Menu;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
/**
* This menu implements the new tinymce suffix (In order to stay backwards compatible this new version was created)
*/
public class DefaultMenuV2 extends DefaultMenu {
private static Logger log = LogManager.getLogger(DefaultMenuV2.class);
/**
* Implements the new tinymce suffix
* @see org.wyona.yanel.servlet.menu.impl.DefaultMenu#getEditMenu(Resource)
*/
@Override
public String getEditMenu(Resource resource) throws Exception {
String userLanguage = getUserLanguage(resource);
StringBuilder sb = new StringBuilder();
sb.append("<ul><li>");
sb.append("<div id=\"yaneltoolbar_menutitle\">" + getLabel("y:edit", userLanguage) + "</div>");
sb.append("<ul>");
String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(resource.getPath());
sb.append("<li class=\"haschild\">Open with   ");
sb.append("<ul>");
sb.append("<li class=\"haschild\">WYSIWYG editor   ");
sb.append("<ul>");
if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Modifiable", "2")) {
//sb.append("<li><a href=\"" + backToRealm + resource.getPath().substring(1) + ".tinymce-edit.html\">Edit page with tinyMCE   </a></li>");
sb.append(getMenuItem(resource.getPath().substring(1) + ".tinymce-edit.html", "Edit page with tinyMCE   "));
sb.append("<li><a href=\"" + backToRealm + "usecases/xinha.html?edit-path=" + resource.getPath() + "\">Edit page with Xinha   </a></li>");
} else {
log.warn("Resource '" + resource.getPath() + "' is not ModifiableV2!");
sb.append("<li>TODO: Edit page with tinyMCE   </li>");
sb.append("<li>TODO: Edit page with Xinha   </li>");
}
sb.append("<li><a href=\"https://addons.mozilla.org/de/firefox/addon/wyona-yulup/\">Edit page with Yulup   </a></li>");
sb.append("</ul>");
sb.append("</li>");
sb.append("<li>Source editor</li>");
if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Annotatable", "1")) {
sb.append("<li><a href=\"" + backToRealm + "usecases/pageMetadataManager.html?edit-path=" + resource.getPath() + "\">Meta data editor</a></li>");
}
sb.append("</ul>");
sb.append("</li>");
sb.append("</ul>");
sb.append("</li></ul>");
return sb.toString();
}
}
| 46 | 165 | 0.648758 |
70cdabd063cb99481e19d4347103530492151f8f | 580 | package main.game.input;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import main.graphics.states.KeysState;
public class KeyChangeListener implements KeyListener {
private KeysState state;
private KeyCustom key;
public KeyChangeListener(KeysState state, KeyCustom key) {
this.state = state;
this.key = key;
}
@Override
public void keyPressed(KeyEvent event) {
this.state.doKeyChange(key, event.getKeyCode());
}
@Override
public void keyReleased(KeyEvent arg0) {}
@Override
public void keyTyped(KeyEvent arg0) {}
}
| 19.333333 | 60 | 0.737931 |
5f7790cc9dc8904d2804426cdef24d44eb7eb048 | 154 | package com.apress.cems.jdbc.repos;
/**
* @author Iuliana Cosmina
* @since 1.0
*/
public interface AgnosticRepo {
int createTable(String name);
}
| 15.4 | 35 | 0.694805 |
6724a89457a77f693d221a2f1e473bef67897c0b | 2,153 | /*
* 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.zto.zms.writer;
import com.google.common.collect.Lists;
import org.ini4j.Ini;
import org.ini4j.Profile;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;
/**
* <p>Class: IniFileWriter</p>
* <p>Description: </p>
*
* @author lidawei
**/
public class IniFileWriter {
private Ini ini;
private IniFileWriter() {
}
public static IniFileWriter newInstance() {
IniFileWriter fileUtil = new IniFileWriter();
fileUtil.init();
return fileUtil;
}
private void init() {
this.ini = new Ini();
ini.getConfig().setEscape(false);
}
public IniFileWriter add(String sectionName, List<IniFileEntity> options) {
Profile.Section section = this.ini.add(sectionName);
options.forEach(item -> {
section.put(item.getKey(), item.getValue());
});
return this;
}
public void store(OutputStream outputStream) throws IOException {
ini.store(outputStream);
}
public static class IniFileEntity {
private String key;
private Object value;
public IniFileEntity(String key, Object value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public Object getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
}
| 23.659341 | 79 | 0.62889 |
386e1ba6943e18f40cdc946580b6a75dbd8acfa3 | 1,422 | package com.oneeyedmen.okeydoke.sources;
import com.oneeyedmen.okeydoke.Resource;
import java.io.*;
public class FileResource implements Resource {
private final File file;
private OutputStream os;
public FileResource(File file) {
this.file = file;
}
@Override
public OutputStream outputStream() throws IOException {
if (os == null) {
os = outputStreamFor(file);
}
return os;
}
@Override
public InputStream inputStream() throws IOException {
// It feels a bit odd that this isn't memoized, but we don't seem to need it to be
return new FileInputStream(file);
}
@Override
public void remove() throws IOException {
file.delete();
if (exists())
throw new IOException("Failed to delete " + file);
}
@Override
public boolean exists() {
return file.exists();
}
@Override
public long size() {
return file.length();
}
public File file() {
return file;
}
protected OutputStream outputStreamFor(final File file) throws IOException {
return new LazyOutputStream() {
@Override
protected OutputStream createOut() throws IOException {
file.getParentFile().mkdirs();
return new BufferedOutputStream(new FileOutputStream(file));
}
};
}
}
| 23.311475 | 90 | 0.601969 |
b0a539f03d9b7b4313f11d60901fb2a5c9f64ae2 | 776 | package com.cts.mcbkend.aggregatorservice.feign;
import java.util.Map;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import com.cts.mcbkend.aggregatorservice.feign.fallback.AuthFallbackService;
@RefreshScope
@FeignClient(name = "${auth-center.name}", url = "${auth-center.url}", fallback=AuthFallbackService.class)
@RibbonClient(name="auth-center")
public interface AuthCenter {
@PostMapping(path = "/login")
public ResponseEntity<Object> getUserAuthorization(Map<String, String> requestBody) throws Exception;
}
| 35.272727 | 106 | 0.818299 |
93f7cdd0f0820f724e7c8e0d5a95a4281705ea73 | 898 | package de.cotto.bitbook.lnd.model;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class InitiatorTest {
@Test
void testToString_remote() {
assertThat(Initiator.REMOTE).hasToString("remote");
}
@Test
void testToString_local() {
assertThat(Initiator.LOCAL).hasToString("local");
}
@Test
void testToString_unknown() {
assertThat(Initiator.UNKNOWN).hasToString("unknown");
}
@Test
void fromString_local() {
assertThat(Initiator.fromString("INITIATOR_LOCAL")).isEqualTo(Initiator.LOCAL);
}
@Test
void fromString_remote() {
assertThat(Initiator.fromString("INITIATOR_REMOTE")).isEqualTo(Initiator.REMOTE);
}
@Test
void fromString_unknown() {
assertThat(Initiator.fromString("INITIATOR_UNKNOWN")).isEqualTo(Initiator.UNKNOWN);
}
} | 24.27027 | 91 | 0.682628 |
31f5b337061e158128427e4309e9e9ee488eabaf | 343 | package com.power.xuexi.entity;
public class UserVO {
private String uid;
private String uname;
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
}
| 13.192308 | 38 | 0.620991 |
b386b5e4680b0ad80287e1f2bb56640d48ac4821 | 2,649 | /**
* Licensed to Apereo under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Apereo 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 the following location:
*
* 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.jasig.portlet.notice;
import java.io.IOException;
import java.util.Date;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;
/**
* Apparently there is no standard format for dates in JSON. JsonLib (which
* this portlet previously used) essentially serialized an instance of
* <code>java.util.Date</code> like any other object. Jackson, however, (the
* current method) converts the date to "epoch time" (a long representing
* milliseconds since January 1, 1970, 00:00:00 GMT). The Jackson approach
* isn't that useful, since it becomes hard to detect what is a date. This
* class is responsible for telling Jackson to use the former method.
*
* @author awills
*/
public class JsonDateDeserializer extends JsonDeserializer<Date> {
private static final String TIME_FILDNAME = "time";
@Override
public Date deserialize(JsonParser parser, DeserializationContext ctx) throws JsonParseException, IOException {
String time = null;
while (parser.nextToken() != JsonToken.END_OBJECT) {
final String fieldname = parser.getCurrentName();
if (TIME_FILDNAME.equals(fieldname)) {
parser.nextToken(); // Advance to the next token; it will be the time
time = parser.getText();
}
}
if (time == null) {
// This is a problem; invalid input
String msg = "Invalid date input at location: " + parser.getCurrentLocation();
throw new IllegalArgumentException(msg);
}
final long rslt = Long.parseLong(time);
return new Date(rslt);
}
}
| 37.842857 | 115 | 0.698754 |
ea67eb3e57e9053d2a0e9f5af22e702ae7ad65a9 | 1,049 | package sketch.compiler.solvers;
import java.util.ArrayList;
import java.util.List;
public class CEtrace extends CounterExample {
public static final class step{
final int thread;
final int stmt;
public step(int thread, int stmt){
this.thread = thread;
this.stmt = stmt;
}
public String toString(){
return "(" + thread + ", " + stmt + ")";
}
}
public List<step> steps;
public List<step> blockedSteps;
public CEtrace () {
steps = new ArrayList<step> ();
blockedSteps = new ArrayList<step> ();
}
public void addStep (int thread, int stmt) {
steps.add (new step (thread, stmt));
}
public void addBlockedStep (int thread, int stmt) {
blockedSteps.add (new step (thread, stmt));
}
public void addSteps (List<step> _steps) {
steps.addAll (_steps);
}
public void addBlockedSteps (List<step> _steps) {
blockedSteps.addAll (_steps);
}
public String toString(){
return "(t,s)" + steps.toString() + "; [blocked: "+ blockedSteps.toString () + "]";
}
public boolean deadlocked () { return false; }
}
| 21.408163 | 85 | 0.668255 |
0d1f8bde0b50678a6aa674b916d1d20bc601e10f | 88 | f small fsmall set small setsmall big f small fsmall big is small issmall f small fsmall | 88 | 88 | 0.818182 |
ca841c502f44e329f90297cef00bc2ea7acdea0b | 13,719 | package com.ludgo.android.movies;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.ShareActionProvider;
import android.text.Html;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.ludgo.android.movies.data.MoviesContract;
import com.ludgo.android.movies.service.ReviewsService;
import com.ludgo.android.movies.service.TrailersService;
import com.squareup.picasso.Picasso;
/**
* All movie nitty-gritty
*/
public class DetailFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
static final String MOVIE_URI = "URI";
private static int movie_id;
// Set id for each loader
private static final int TRAILERS_LOADER = 20;
private static final int REVIEWS_LOADER = 21;
// Inflater that will inflate text views to append
private static LayoutInflater mInflater;
private static TextView titleTextView;
private static TextView yearTextView;
private static TextView favoriteTextView;
// here is reference to views where text views will be appended
private static LinearLayout trailersLinearLayout;
private static LinearLayout reviewsLinearLayout;
public DetailFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_fragment_detail, menu);
// Retrieve the share menu item
MenuItem menuItem = menu.findItem(R.id.action_share);
// Get the provider and hold onto it to set/change the share intent
ShareActionProvider mShareActionProvider =
(ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);
// Attach an intent to this ShareActionProvider
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(createShareIntent());
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle arguments = getArguments();
Uri movieUri = (arguments != null) ?
// Case of two pane mode
(Uri) arguments.getParcelable(DetailFragment.MOVIE_URI) :
// Case of one pane mode
getActivity().getIntent().getData();
String movieIdStr = MoviesContract.getMovieIdStrFromUri(movieUri);
// Get key variable which is to determine the whole layout of the fragment
movie_id = Integer.parseInt(movieIdStr);
mInflater = inflater;
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
titleTextView = (TextView) rootView.findViewById(R.id.title);
ImageView posterImageView = (ImageView) rootView.findViewById(R.id.poster);
yearTextView = (TextView) rootView.findViewById(R.id.year);
TextView voteAverageTextView = (TextView) rootView.findViewById(R.id.voteAverage);
favoriteTextView = (TextView) rootView.findViewById(R.id.favorite);
TextView overviewTextView = (TextView) rootView.findViewById(R.id.overview);
trailersLinearLayout = (LinearLayout) rootView.findViewById(R.id.trailers);
reviewsLinearLayout = (LinearLayout) rootView.findViewById(R.id.reviews);
// Pull details to display from database
Cursor cursor = getActivity().getContentResolver().query(
MoviesContract.MoviesEntry.buildMoviesUriWithId(movie_id),
// if projection changes, indices must change!
new String[]{MoviesContract.MoviesEntry.TABLE_NAME + "." +
MoviesContract.MoviesEntry._ID, // 0
MoviesContract.MoviesEntry.COLUMN_TITLE, // 1
MoviesContract.MoviesEntry.COLUMN_OVERVIEW, // 2
MoviesContract.MoviesEntry.COLUMN_POSTER_PATH, // 3
MoviesContract.MoviesEntry.COLUMN_RELEASE_DATE, // 4
MoviesContract.MoviesEntry.COLUMN_VOTE_AVERAGE, // 5
MoviesContract.MoviesEntry.COLUMN_FAVORITE}, // 6
null,
null,
null);
// This movie should be in database, since its id got here from grid where the movie was
if (cursor.moveToFirst()) {
// set title
final String TITLE = cursor.getString(1);
titleTextView.setText(TITLE);
if (TITLE.length() > 24) {
// Shrink default text size
titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
}
// set overview
final String OVERVIEW = cursor.getString(2);
overviewTextView.setText(OVERVIEW);
// set poster
final String POSTER_PATH = cursor.getString(3);
// 168dp is the width of posterContainer without padding
int widthInPx = Utility.dipToPx(getActivity(), 168);
String posterUrl = Utility.createPosterUrl(POSTER_PATH, widthInPx);
Picasso.with(getActivity())
.load(posterUrl)
.resize(widthInPx, 0)
.into(posterImageView);
// set year
final String RELEASE_DATE = cursor.getString(4);
String year = Utility.createYearFromReleaseDate(RELEASE_DATE);
yearTextView.setText(year);
// set vote average
final double VOTE_AVERAGE = cursor.getDouble(5);
voteAverageTextView.setText(Double.toString(VOTE_AVERAGE) + "/10");
// allow user to mark/unmark movie as favorite
int favorite = cursor.getInt(6);
if (favorite == 1) {
favoriteTextView.setSelected(true);
}
favoriteTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onToggleFavorite();
}
});
}
cursor.close();
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
getLoaderManager().initLoader(TRAILERS_LOADER, null, this);
getLoaderManager().initLoader(REVIEWS_LOADER, null, this);
super.onActivityCreated(savedInstanceState);
}
@Override
public void onStart() {
super.onStart();
fetchTrailers();
fetchReviews();
}
@Override
public Loader<Cursor> onCreateLoader(int loaderId, Bundle args) {
switch (loaderId) {
case TRAILERS_LOADER:
return new CursorLoader(getActivity(),
MoviesContract.TrailersEntry
.buildTrailersUriWithId(movie_id),
// if projection changes, indices must change!
new String[]{MoviesContract.TrailersEntry.TABLE_NAME + "." +
MoviesContract.TrailersEntry._ID, // 0
MoviesContract.TrailersEntry.COLUMN_NAME, // 1
MoviesContract.TrailersEntry.COLUMN_KEY}, // 2
null,
null,
null);
case REVIEWS_LOADER:
return new CursorLoader(getActivity(),
MoviesContract.ReviewsEntry
.buildReviewsUriWithId(movie_id),
// if projection changes, indices must change!
new String[]{MoviesContract.ReviewsEntry.TABLE_NAME + "." +
MoviesContract.ReviewsEntry._ID, // 0
MoviesContract.ReviewsEntry.COLUMN_AUTHOR, // 1
MoviesContract.ReviewsEntry.COLUMN_CONTENT}, // 2
null,
null,
null);
default:
// An invalid id was passed in
return null;
}
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (cursor != null && cursor.moveToFirst()) {
switch (loader.getId()) {
case TRAILERS_LOADER:
trailersLinearLayout.removeAllViews();
// append all movie trailers to linear layout
do {
String trailerName = cursor.getString(1);
final String TRAILER_KEY = cursor.getString(2);
TextView trailerTextView = (TextView) mInflater
.inflate(R.layout.trailer_item, null);
trailerTextView.setText(trailerName);
trailerTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String trailerUrl = Utility.createYoutubeUrlFromKey(TRAILER_KEY);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(trailerUrl));
startActivity(intent);
}
});
trailersLinearLayout.addView(trailerTextView);
} while (cursor.moveToNext());
break;
case REVIEWS_LOADER:
reviewsLinearLayout.removeAllViews();
// append all movie reviews to linear layout
do {
String reviewAuthor = cursor.getString(1);
String reviewContent = cursor.getString(2);
String wholeReview = reviewContent + " <b>(" + reviewAuthor + ")</b>";
TextView reviewTextView = (TextView) mInflater
.inflate(R.layout.review_item, null);
reviewTextView.setText(Html.fromHtml(wholeReview));
reviewsLinearLayout.addView(reviewTextView);
} while (cursor.moveToNext());
break;
}
}
}
@Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
}
private Intent createShareIntent() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
shareIntent.setType("text/plain");
// Add movie title and release year to the draft message
String shareMessage = getActivity().getString(R.string.action_share_message,
titleTextView.getText(),
yearTextView.getText());
shareIntent.putExtra(Intent.EXTRA_TEXT, shareMessage);
return shareIntent;
}
void fetchTrailers() {
// Save trailers for this movie in database
Intent intent = new Intent(getActivity(), TrailersService.class)
.setData(MoviesContract.MoviesEntry
.buildMoviesUriWithId(movie_id));
getActivity().startService(intent);
}
void fetchReviews() {
// Save reviews for this movie in database after some time
Intent fetchIntent = new Intent(getActivity(), ReviewsService.FetchReceiver.class)
.setData(MoviesContract.MoviesEntry
.buildMoviesUriWithId(movie_id));
// Pending intent instead of regular to achieve better performance
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, fetchIntent,
PendingIntent.FLAG_ONE_SHOT);
//Set the AlarmManager to wake up the system.
AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 2000, pendingIntent);
}
private void onToggleFavorite() {
if (favoriteTextView.isSelected()) {
favoriteTextView.setSelected(false);
ContentValues movieValues = new ContentValues();
movieValues.put(MoviesContract.MoviesEntry.COLUMN_FAVORITE, 0);
getActivity().getContentResolver().update(
MoviesContract.MoviesEntry.buildMoviesUriWithId(movie_id),
movieValues,
null,
null);
} else {
favoriteTextView.setSelected(true);
ContentValues movieValues = new ContentValues();
movieValues.put(MoviesContract.MoviesEntry.COLUMN_FAVORITE, 1);
getActivity().getContentResolver().update(
MoviesContract.MoviesEntry.buildMoviesUriWithId(movie_id),
movieValues,
null,
null);
}
}
} | 42.60559 | 105 | 0.602887 |
945dad490ac09ed10a9a56e866d70a9b803dd692 | 7,496 | package uk.nhs.careconnect.ri.database.entity.clinicialImpression;
import org.hl7.fhir.dstu3.model.ClinicalImpression;
import uk.nhs.careconnect.ri.database.entity.BaseResource;
import uk.nhs.careconnect.ri.database.entity.codeSystem.ConceptEntity;
import uk.nhs.careconnect.ri.database.entity.condition.ConditionEntity;
import uk.nhs.careconnect.ri.database.entity.encounter.EncounterEntity;
import uk.nhs.careconnect.ri.database.entity.patient.PatientEntity;
import uk.nhs.careconnect.ri.database.entity.practitioner.PractitionerEntity;
import uk.nhs.careconnect.ri.database.entity.allergy.AllergyIntoleranceEntity;
import javax.persistence.*;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table(name = "ClinicalImpression",
indexes = {
})
public class ClinicalImpressionEntity extends BaseResource {
private static final int MAX_DESC_LENGTH = 4096;
public enum ClinicalImpressionType { component, valueQuantity }
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="IMPRESSION_ID")
private Long id;
@OneToMany(mappedBy="impression", targetEntity=ClinicalImpressionIdentifier.class)
private Set<ClinicalImpressionIdentifier> identifiers = new HashSet<>();
@Enumerated(EnumType.ORDINAL)
@Column(name="status")
private ClinicalImpression.ClinicalImpressionStatus status;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="CODE_CONCEPT_ID",nullable = true,foreignKey= @ForeignKey(name="FK_IMPRESSION_CODE_CONCEPT_ID"))
private ConceptEntity impressionCode;
@Column(name="CODE_TEXT", length = MAX_DESC_LENGTH)
private String codeText;
@Column(name="DESCRIPTION")
private String description;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn (name = "PATIENT_ID",foreignKey= @ForeignKey(name="FK_IMPRESSION_PATIENT_ID"))
private PatientEntity patient;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="ENCOUNTER_ID",foreignKey= @ForeignKey(name="FK_IMPRESSION_ENCOUNTER_ID"))
private EncounterEntity contextEncounter;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "EFFECTIVE_START_DATETIME")
private Date effectiveStartDateTime;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "EFFECTIVE_END_DATETIME")
private Date effectiveEndDateTime;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "IMPRESSION_END_DATETIME")
private Date impressionDateTime;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn (name = "ASSESSOR_PRACTITIONER_ID",foreignKey= @ForeignKey(name="FK_IMPRESSION_ASSESSOR_PRACTITIONERT_ID"))
private PractitionerEntity assessorPractitioner;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn (name = "PROBLEM_CONDITION_ID",foreignKey= @ForeignKey(name="FK_IMPRESSION_PROBLEM_CONDITION_ID"))
private ConditionEntity problemCondition;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn (name = "PROBLEM_ALLERGY_ID",foreignKey= @ForeignKey(name="FK_IMPRESSION_PROBLEM_ALLERGY_ID"))
private AllergyIntoleranceEntity problemAllergy;
@Column(name="SUMMARY")
private String summary;
@OneToMany(mappedBy="impression", targetEntity=ClinicalImpressionFinding.class)
private Set<ClinicalImpressionFinding> findings = new HashSet<>();
@OneToMany(mappedBy="impression", targetEntity=ClinicalImpressionPrognosis.class)
private Set<ClinicalImpressionPrognosis> prognosis = new HashSet<>();
@Column(name="NOTE")
private String note;
public Long getId() {
return id;
}
public PatientEntity getPatient() {
return patient;
}
public void setPatient(PatientEntity patient) {
this.patient = patient;
}
public void setId(Long id) {
this.id = id;
}
public ClinicalImpression.ClinicalImpressionStatus getStatus() {
return status;
}
public ClinicalImpressionEntity setStatus(ClinicalImpression.ClinicalImpressionStatus status) {
this.status = status;
return this;
}
public static int getMaxDescLength() {
return MAX_DESC_LENGTH;
}
public ConceptEntity getRiskCode() {
return impressionCode;
}
public void setRiskCode(ConceptEntity impressionCode) {
this.impressionCode = impressionCode;
}
public EncounterEntity getContextEncounter() {
return contextEncounter;
}
public void setContextEncounter(EncounterEntity contextEncounter) {
this.contextEncounter = contextEncounter;
}
public Set<ClinicalImpressionIdentifier> getIdentifiers() {
return identifiers;
}
public void setIdentifiers(Set<ClinicalImpressionIdentifier> identifiers) {
this.identifiers = identifiers;
}
public ConceptEntity getImpressionCode() {
return impressionCode;
}
public void setImpressionCode(ConceptEntity impressionCode) {
this.impressionCode = impressionCode;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getEffectiveStartDateTime() {
return effectiveStartDateTime;
}
public void setEffectiveStartDateTime(Date effectiveStartDateTime) {
this.effectiveStartDateTime = effectiveStartDateTime;
}
public Date getEffectiveEndDateTime() {
return effectiveEndDateTime;
}
public void setEffectiveEndDateTime(Date effectiveEndDateTime) {
this.effectiveEndDateTime = effectiveEndDateTime;
}
public Date getImpressionDateTime() {
return impressionDateTime;
}
public void setImpressionDateTime(Date impressionDateTime) {
this.impressionDateTime = impressionDateTime;
}
public PractitionerEntity getAssessorPractitioner() {
return assessorPractitioner;
}
public void setAssessorPractitioner(PractitionerEntity assessorPractitioner) {
this.assessorPractitioner = assessorPractitioner;
}
public ConditionEntity getProblemCondition() {
return problemCondition;
}
public void setProblemCondition(ConditionEntity problemCondition) {
this.problemCondition = problemCondition;
}
public AllergyIntoleranceEntity getProblemAllergy() {
return problemAllergy;
}
public void setProblemAllergy(AllergyIntoleranceEntity problemAllergy) {
this.problemAllergy = problemAllergy;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public Set<ClinicalImpressionFinding> getFindings() {
return findings;
}
public void setFindings(Set<ClinicalImpressionFinding> findings) {
this.findings = findings;
}
public Set<ClinicalImpressionPrognosis> getPrognosis() {
return prognosis;
}
public void setPrognosis(Set<ClinicalImpressionPrognosis> prognosis) {
this.prognosis = prognosis;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public String getCodeText() {
if (codeText != null)
return codeText;
if (this.impressionCode != null) return this.impressionCode.getDisplay();
return null;
}
public void setCodeText(String codeText) {
this.codeText = codeText;
}
}
| 29.28125 | 123 | 0.721318 |
85a5643061cc6523c1fca3e73c3865c631eb05a6 | 1,114 | package com.fieldexpert.fbapi4j.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import org.junit.Before;
import org.junit.Test;
public class DateFormatUtilTest {
private static final String FB_DATE = "1984-03-30T00:00:00Z";
private Date MAR_30_1984;
@Before
public void setup() {
Calendar cal = Calendar.getInstance(Locale.US);
cal.set(1984, 2, 30, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
MAR_30_1984 = cal.getTime();
}
@Test
public void format() {
assertEquals(FB_DATE, DateFormatUtil.format(MAR_30_1984));
}
@Test
public void parse() {
assertEquals(MAR_30_1984, DateFormatUtil.parse(FB_DATE));
}
@Test(expected = RuntimeException.class)
public void garbage() {
DateFormatUtil.parse("garbage");
fail();
}
@Test
public void formatNull() {
assertNull(DateFormatUtil.format(null));
}
@Test
public void nullOrEmpty() {
assertNull(DateFormatUtil.parse(null));
assertNull(DateFormatUtil.parse(""));
}
}
| 21.018868 | 62 | 0.735189 |
7c29a0abb5bd43df87b3adaf002e2630837683d1 | 7,214 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.fhwa.c2cri.ntcip2306v109.wsdl;
import java.util.ArrayList;
import java.util.HashMap;
/**
* The Class ServiceSpecCollection contains a collection of related services.
*
* @author TransCore ITS, LLC
* Last Updated: 1/8/2014
*/
public class ServiceSpecCollection {
/** The service collection. */
private ArrayList<ServiceSpecification> serviceCollection = new ArrayList<ServiceSpecification>();
/**
* Adds the.
*
* Pre-Conditions: N/A
* Post-Conditions: N/A
*
* @param ss the ss
* @return true, if successful
*/
public boolean add(ServiceSpecification ss) {
return serviceCollection.add(ss);
}
/**
* Contains.
*
* Pre-Conditions: N/A
* Post-Conditions: N/A
*
* @param serviceName the service name
* @param serviceLocation the service location
* @param serviceType the service type
* @return true, if successful
*/
public boolean contains(String serviceName, String serviceLocation, ServiceSpecification.SERVICETYPE serviceType) {
boolean result = false;
for (ServiceSpecification thisSpec : serviceCollection) {
if (thisSpec.getServiceType().equals(serviceType)
&& thisSpec.getLocation().equals(serviceLocation)
&& thisSpec.getName().equals(serviceName)) {
result = true;
break;
}
}
return result;
}
/**
* Gets the.
*
* Pre-Conditions: N/A
* Post-Conditions: N/A
*
* @param serviceName the service name
* @param serviceLocation the service location
* @param serviceType the service type
* @return the service specification
*/
public ServiceSpecification get(String serviceName, String serviceLocation, ServiceSpecification.SERVICETYPE serviceType) {
ServiceSpecification result = null;
for (ServiceSpecification thisSpec : serviceCollection) {
if (thisSpec.getServiceType().equals(serviceType)
&& thisSpec.getLocation().equals(serviceLocation)
&& thisSpec.getName().equals(serviceName)) {
result = thisSpec;
break;
}
}
return result;
}
/**
* Gets the.
*
* Pre-Conditions: N/A
* Post-Conditions: N/A
*
* @param index the index
* @return the service specification
*/
public ServiceSpecification get(int index) {
ServiceSpecification result = null;
try {
result = serviceCollection.get(index);
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
/**
* Gets the client specs by location.
*
* @return the client specs by location
*/
public HashMap<String, OperationSpecCollection> getClientSpecsByLocation() {
HashMap<String, OperationSpecCollection> returnMap = new HashMap<String, OperationSpecCollection>();
for (ServiceSpecification thisSpec : serviceCollection) {
if (thisSpec.getServiceType().equals(ServiceSpecification.SERVICETYPE.CLIENT)) {
if (returnMap.containsKey(thisSpec.getLocation())) {
for (OperationSpecification thisOperation : thisSpec.getOperations().getCopyAsList()) {
if (!returnMap.get(thisSpec.getLocation()).contains(thisOperation.getRelatedToService(), thisOperation.getRelatedToPort(), thisOperation.getOperationName())) {
returnMap.get(thisSpec.getLocation()).add(thisOperation);
}
}
} else {
OperationSpecCollection thisCollection = new OperationSpecCollection();
for (OperationSpecification thisOperation : thisSpec.getOperations().getCopyAsList()) {
thisCollection.add(thisOperation);
}
returnMap.put(thisSpec.getLocation(), thisCollection);
}
}
}
return returnMap;
}
/**
* Gets the server specs by location.
*
* @return the server specs by location
*/
public HashMap<String, OperationSpecCollection> getServerSpecsByLocation() {
HashMap<String, OperationSpecCollection> returnMap = new HashMap<String, OperationSpecCollection>();
for (ServiceSpecification thisSpec : serviceCollection) {
if (thisSpec.getServiceType().equals(ServiceSpecification.SERVICETYPE.LISTENER)
|| thisSpec.getServiceType().equals(ServiceSpecification.SERVICETYPE.SERVER)) {
if (returnMap.containsKey(thisSpec.getLocation())) {
System.out.println("ServiceSpecCollection::getServerSpecsByLocation Return Map Already contains "+thisSpec.getLocation());
for (OperationSpecification thisOperation : thisSpec.getOperations().getCopyAsList()) {
if (!returnMap.get(thisSpec.getLocation()).contains(thisOperation.getRelatedToService(), thisOperation.getRelatedToPort(), thisOperation.getOperationName())) {
System.out.println("ServiceSpecCollection::getServerSpecsByLocation Before add size = "+returnMap.get(thisSpec.getLocation()).size());
returnMap.get(thisSpec.getLocation()).add(thisOperation);
System.out.println("ServiceSpecCollection:getServerSpecsByLocation Added operation "+thisOperation.getOperationName()+ " new size = "+ +returnMap.get(thisSpec.getLocation()).size());
}
}
} else {
System.out.println("ServiceSpecCollection::getServerSpecsByLocation Location "+thisSpec.getLocation() + " added to the map.");
OperationSpecCollection thisCollection = new OperationSpecCollection();
for (OperationSpecification thisOperation : thisSpec.getOperations().getCopyAsList()) {
thisCollection.add(thisOperation);
System.out.println("ServiceSpecCollection:getServerSpecsByLocation Added operation "+thisOperation.getOperationName());
}
returnMap.put(thisSpec.getLocation(), thisCollection);
}
}
}
return returnMap;
}
/**
* Gets the copy as list.
*
* @return the copy as list
*/
public ArrayList<ServiceSpecification> getCopyAsList() {
return (ArrayList) serviceCollection.clone();
}
/**
* Checks if is empty.
*
* Pre-Conditions: N/A
* Post-Conditions: N/A
*
* @return true, if is empty
*/
public boolean isEmpty() {
return serviceCollection.isEmpty();
}
/**
* Size.
*
* Pre-Conditions: N/A
* Post-Conditions: N/A
*
* @return the int
*/
public int size() {
return serviceCollection.size();
}
}
| 36.806122 | 211 | 0.60438 |
8840ea495c59ff224c6b4ccd2b1acc413241d2bd | 76,610 | package org.corfudb.runtime.view;
import com.google.common.reflect.TypeToken;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.corfudb.infrastructure.SequencerServer;
import org.corfudb.infrastructure.ServerContext;
import org.corfudb.infrastructure.ServerContextBuilder;
import org.corfudb.infrastructure.TestLayoutBuilder;
import org.corfudb.infrastructure.TestServerRouter;
import org.corfudb.protocols.wireprotocol.NodeState;
import org.corfudb.protocols.wireprotocol.SequencerMetrics.SequencerStatus;
import org.corfudb.protocols.wireprotocol.TokenResponse;
import org.corfudb.protocols.wireprotocol.failuredetector.NodeConnectivity.NodeConnectivityType;
import org.corfudb.runtime.CorfuRuntime;
import org.corfudb.runtime.clients.TestRule;
import org.corfudb.runtime.collections.CorfuTable;
import org.corfudb.runtime.collections.ICorfuTable;
import org.corfudb.runtime.exceptions.AbortCause;
import org.corfudb.runtime.exceptions.ServerNotReadyException;
import org.corfudb.runtime.exceptions.TransactionAbortedException;
import org.corfudb.runtime.object.ICorfuSMR;
import org.corfudb.runtime.proto.service.CorfuMessage.RequestPayloadMsg.PayloadCase;
import org.corfudb.runtime.proto.service.CorfuMessage.ResponsePayloadMsg;
import org.corfudb.runtime.view.ClusterStatusReport.ClusterStatus;
import org.corfudb.runtime.view.ClusterStatusReport.ConnectivityStatus;
import org.corfudb.runtime.view.ClusterStatusReport.NodeStatus;
import org.corfudb.runtime.view.stream.IStreamView;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.corfudb.test.TestUtils.setAggressiveTimeouts;
import static org.corfudb.test.TestUtils.waitForLayoutChange;
import static org.junit.Assert.fail;
/**
* Test to verify the Management Server functionalities.
*
* Created by zlokhandwala on 11/9/16.
*/
@Slf4j
public class ManagementViewTest extends AbstractViewTest {
@Getter
protected CorfuRuntime corfuRuntime = null;
private void waitForSequencerToBootstrap(int primarySequencerPort) throws InterruptedException {
// Waiting for sequencer to be bootstrapped
for (int i = 0; i < PARAMETERS.NUM_ITERATIONS_MODERATE; i++) {
if (getSequencer(primarySequencerPort).getSequencerEpoch() != Layout.INVALID_EPOCH) {
return;
}
TimeUnit.MILLISECONDS.sleep(PARAMETERS.TIMEOUT_SHORT.toMillis());
}
Assert.fail();
}
/**
* Scenario with 2 nodes: SERVERS.PORT_0 and SERVERS.PORT_1.
* We fail SERVERS.PORT_0 and then listen to intercept the message
* sent by SERVERS.PORT_1's client to the server to handle the failure.
*
* @throws Exception
*/
@Test
public void invokeFailureHandler()
throws Exception {
// Boolean flag turned to true when the REPORT_FAILURE message
// is sent by the Management client to its server.
final Semaphore failureDetected = new Semaphore(1, true);
addServer(SERVERS.PORT_0);
addServer(SERVERS.PORT_1);
Layout l = new TestLayoutBuilder()
.setEpoch(1L)
.addLayoutServer(SERVERS.PORT_0)
.addLayoutServer(SERVERS.PORT_1)
.addSequencer(SERVERS.PORT_1)
.buildSegment()
.buildStripe()
.addLogUnit(SERVERS.PORT_0)
.addLogUnit(SERVERS.PORT_1)
.addToSegment()
.addToLayout()
.build();
bootstrapAllServers(l);
// Shutting down causes loss of heartbeat requests and responses from this node.
getManagementServer(SERVERS.PORT_0).shutdown();
CorfuRuntime corfuRuntime = getRuntime(l).connect();
// Set aggressive timeouts.
setAggressiveTimeouts(l, corfuRuntime,
getManagementServer(SERVERS.PORT_1).getManagementAgent().getCorfuRuntime());
failureDetected.acquire();
// Adding a rule on SERVERS.PORT_0 to drop all packets
addServerRule(SERVERS.PORT_0, new TestRule().always().drop());
// Adding a rule on SERVERS.PORT_1 to toggle the flag when it sends the
// REPORT_FAILURE message.
addClientRule(getManagementServer(SERVERS.PORT_1).getManagementAgent().getCorfuRuntime(),
new TestRule().requestMatches(msg -> {
if (msg.getPayload().getPayloadCase().equals(PayloadCase.REPORT_FAILURE_REQUEST)) {
failureDetected.release();
}
return true;
}));
assertThat(failureDetected.tryAcquire(PARAMETERS.TIMEOUT_LONG.toNanos(),
TimeUnit.NANOSECONDS)).isEqualTo(true);
}
/**
* Scenario with 3 nodes: SERVERS.PORT_0, SERVERS.PORT_1 and SERVERS.PORT_2.
* We fail SERVERS.PORT_1 and then wait for one of the other two servers to
* handle this failure, propose a new layout. The test asserts on a stable
* layout. The failure is handled by removing the failed node.
*/
@Test
public void removeSingleNodeFailure() {
addServer(SERVERS.PORT_0);
addServer(SERVERS.PORT_1);
addServer(SERVERS.PORT_2);
Layout l = new TestLayoutBuilder()
.setEpoch(1L)
.addLayoutServer(SERVERS.PORT_0)
.addLayoutServer(SERVERS.PORT_1)
.addLayoutServer(SERVERS.PORT_2)
.addSequencer(SERVERS.PORT_0)
.buildSegment()
.buildStripe()
.addLogUnit(SERVERS.PORT_0)
.addLogUnit(SERVERS.PORT_2)
.addToSegment()
.addToLayout()
.build();
bootstrapAllServers(l);
CorfuRuntime corfuRuntime = getRuntime(l).connect();
// Setting aggressive timeouts for connect, retry, response timeouts
setAggressiveTimeouts(l, corfuRuntime,
getManagementServer(SERVERS.PORT_0).getManagementAgent().getCorfuRuntime(),
getManagementServer(SERVERS.PORT_1).getManagementAgent().getCorfuRuntime(),
getManagementServer(SERVERS.PORT_2).getManagementAgent().getCorfuRuntime());
// Setting aggressive timeouts for failure and healing detectors
setAggressiveDetectorTimeouts(SERVERS.PORT_0, SERVERS.PORT_1, SERVERS.PORT_2);
// Adding a rule on SERVERS.PORT_1 to drop all packets
addServerRule(SERVERS.PORT_1, new TestRule().always().drop());
getManagementServer(SERVERS.PORT_1).shutdown();
// Waiting until a stable layout is committed
waitForLayoutChange(layout -> layout.getUnresponsiveServers().contains(SERVERS.ENDPOINT_1) &&
layout.getUnresponsiveServers().size() == 1,
corfuRuntime);
// Verifying layout and remove of failed server
Layout l2 = corfuRuntime.getLayoutView().getLayout();
assertThat(l2.getEpoch()).isGreaterThan(l.getEpoch());
assertThat(l2.getLayoutServers().size()).isEqualTo(l.getAllServers().size());
assertThat(l2.getAllActiveServers().size()).isEqualTo(l.getAllServers().size() - 1);
assertThat(l2.getUnresponsiveServers()).contains(SERVERS.ENDPOINT_1);
}
private Layout getManagementTestLayout() throws InterruptedException {
addServer(SERVERS.PORT_0);
addServer(SERVERS.PORT_1);
addServer(SERVERS.PORT_2);
Layout l = new TestLayoutBuilder()
.setEpoch(1L)
.addLayoutServer(SERVERS.PORT_0)
.addLayoutServer(SERVERS.PORT_1)
.addLayoutServer(SERVERS.PORT_2)
.addSequencer(SERVERS.PORT_0)
.addSequencer(SERVERS.PORT_1)
.addSequencer(SERVERS.PORT_2)
.buildSegment()
.buildStripe()
.addLogUnit(SERVERS.PORT_1)
.addLogUnit(SERVERS.PORT_2)
.addToSegment()
.addToLayout()
.setClusterId(UUID.randomUUID())
.build();
bootstrapAllServers(l);
corfuRuntime = getRuntime(l).connect();
waitForSequencerToBootstrap(SERVERS.PORT_0);
// Setting aggressive timeouts
setAggressiveTimeouts(l, corfuRuntime,
getManagementServer(SERVERS.PORT_0).getManagementAgent().getCorfuRuntime(),
getManagementServer(SERVERS.PORT_1).getManagementAgent().getCorfuRuntime(),
getManagementServer(SERVERS.PORT_2).getManagementAgent().getCorfuRuntime());
setAggressiveDetectorTimeouts(SERVERS.PORT_0, SERVERS.PORT_1, SERVERS.PORT_2);
return l;
}
private Layout get3NodeLayout() throws InterruptedException {
addServer(SERVERS.PORT_0);
addServer(SERVERS.PORT_1);
addServer(SERVERS.PORT_2);
Layout l = new TestLayoutBuilder()
.setEpoch(1L)
.addLayoutServer(SERVERS.PORT_0)
.addLayoutServer(SERVERS.PORT_1)
.addLayoutServer(SERVERS.PORT_2)
.addSequencer(SERVERS.PORT_0)
.addSequencer(SERVERS.PORT_1)
.addSequencer(SERVERS.PORT_2)
.buildSegment()
.buildStripe()
.addLogUnit(SERVERS.PORT_0)
.addLogUnit(SERVERS.PORT_1)
.addLogUnit(SERVERS.PORT_2)
.addToSegment()
.addToLayout()
.setClusterId(UUID.randomUUID())
.build();
bootstrapAllServers(l);
corfuRuntime = getRuntime(l).connect();
waitForSequencerToBootstrap(SERVERS.PORT_0);
// Setting aggressive timeouts
setAggressiveTimeouts(l, corfuRuntime,
getManagementServer(SERVERS.PORT_0).getManagementAgent().getCorfuRuntime(),
getManagementServer(SERVERS.PORT_1).getManagementAgent().getCorfuRuntime(),
getManagementServer(SERVERS.PORT_2).getManagementAgent().getCorfuRuntime());
setAggressiveDetectorTimeouts(SERVERS.PORT_0, SERVERS.PORT_1, SERVERS.PORT_2);
return l;
}
/**
* Scenario with 1 node: SERVERS.PORT_0
* The node is setup, bootstrapped and then requested for a
* heartbeat. This is responded with the nodeMetrics which is
* asserted with expected values.
*
* @throws Exception error
*/
@Test
public void checkNodeState() throws Exception {
addServer(SERVERS.PORT_0);
Layout l = new TestLayoutBuilder()
.setEpoch(1L)
.addLayoutServer(SERVERS.PORT_0)
.addSequencer(SERVERS.PORT_0)
.buildSegment()
.buildStripe()
.addLogUnit(SERVERS.PORT_0)
.addToSegment()
.addToLayout()
.build();
bootstrapAllServers(l);
CorfuRuntime corfuRuntime = getRuntime(l).connect();
// Set aggressive timeouts.
setAggressiveTimeouts(l, corfuRuntime,
getManagementServer(SERVERS.PORT_0).getManagementAgent().getCorfuRuntime());
NodeState nodeState= null;
// Send heartbeat requests and wait until we get a valid response.
for (int i = 0; i < PARAMETERS.NUM_ITERATIONS_LOW; i++) {
nodeState = corfuRuntime.getLayoutView().getRuntimeLayout()
.getManagementClient(SERVERS.ENDPOINT_0).sendNodeStateRequest().get();
if (nodeState.getConnectivity().getType() == NodeConnectivityType.CONNECTED
&& !nodeState.getConnectivity().getConnectedNodes().isEmpty()) {
break;
}
TimeUnit.MILLISECONDS.sleep(PARAMETERS.TIMEOUT_VERY_SHORT.toMillis());
}
assertThat(nodeState).isNotNull();
assertThat(nodeState.getConnectivity()).isNotNull();
assertThat(nodeState.getConnectivity().getConnectedNodes()).contains(SERVERS.ENDPOINT_0);
}
/**
* Scenario with 3 nodes: SERVERS.PORT_0, SERVERS.PORT_1 and SERVERS.PORT_2.
* Simulate transient failure of a server leading to a partial seal.
* Allow the management server to detect the partial seal and correct this.
* <p>
* Part 1.
* The partial seal causes SERVERS.PORT_0 to be at epoch 2 whereas,
* SERVERS.PORT_1 & SERVERS.PORT_2 fail to receive this message and are stuck at epoch 1.
* <p>
* Part 2.
* All the 3 servers are now functional and receive all messages.
* <p>
* Part 3.
* The PING message gets rejected by the partially sealed router (WrongEpoch)
* and the management server realizes of the partial seal and corrects this
* by issuing another failure detected message.
*
* @throws Exception
*/
@Test
public void handleTransientFailure() throws Exception {
log.info("Boolean flag turned to true when the REPORT_FAILURE_REQUEST message " +
"is sent by the Management client to its server");
final Semaphore failureDetected = new Semaphore(2, true);
addServer(SERVERS.PORT_0);
addServer(SERVERS.PORT_1);
addServer(SERVERS.PORT_2);
Layout l = new TestLayoutBuilder()
.setEpoch(1L)
.addLayoutServer(SERVERS.PORT_0)
.addLayoutServer(SERVERS.PORT_1)
.addLayoutServer(SERVERS.PORT_2)
.addSequencer(SERVERS.PORT_0)
.addSequencer(SERVERS.PORT_1)
.addSequencer(SERVERS.PORT_2)
.buildSegment()
.buildStripe()
.addLogUnit(SERVERS.PORT_0)
.addLogUnit(SERVERS.PORT_1)
.addLogUnit(SERVERS.PORT_2)
.addToSegment()
.addToLayout()
.setClusterId(UUID.randomUUID())
.build();
bootstrapAllServers(l);
corfuRuntime = getRuntime(l).connect();
waitForSequencerToBootstrap(SERVERS.PORT_0);
log.info("Setting aggressive timeouts");
setAggressiveTimeouts(l, corfuRuntime,
getManagementServer(SERVERS.PORT_0).getManagementAgent().getCorfuRuntime(),
getManagementServer(SERVERS.PORT_1).getManagementAgent().getCorfuRuntime(),
getManagementServer(SERVERS.PORT_2).getManagementAgent().getCorfuRuntime());
setAggressiveDetectorTimeouts(SERVERS.PORT_0, SERVERS.PORT_1, SERVERS.PORT_2);
failureDetected.acquire(2);
log.info("Only allow SERVERS.PORT_0 to manage failures. Prevent the other servers from handling failures.");
TestRule sealTestRule = new TestRule()
.requestMatches(msg -> msg.getPayload().getPayloadCase().equals(PayloadCase.SEAL_REQUEST))
.drop();
TestRule failureTestRule = new TestRule()
.requestMatches(msg -> msg.getPayload().getPayloadCase().equals(PayloadCase.REPORT_FAILURE_REQUEST))
.drop();
addClientRule(getManagementServer(SERVERS.PORT_0).getManagementAgent().getCorfuRuntime(),
SERVERS.ENDPOINT_1, sealTestRule);
addClientRule(getManagementServer(SERVERS.PORT_0).getManagementAgent().getCorfuRuntime(),
SERVERS.ENDPOINT_1, failureTestRule);
addClientRule(getManagementServer(SERVERS.PORT_0).getManagementAgent().getCorfuRuntime(),
SERVERS.ENDPOINT_2, sealTestRule);
addClientRule(getManagementServer(SERVERS.PORT_0).getManagementAgent().getCorfuRuntime(),
SERVERS.ENDPOINT_2, failureTestRule);
addClientRule(getManagementServer(SERVERS.PORT_1).getManagementAgent().getCorfuRuntime(),
SERVERS.ENDPOINT_1, sealTestRule);
addClientRule(getManagementServer(SERVERS.PORT_1).getManagementAgent().getCorfuRuntime(),
SERVERS.ENDPOINT_1, failureTestRule);
addClientRule(getManagementServer(SERVERS.PORT_1).getManagementAgent().getCorfuRuntime(),
SERVERS.ENDPOINT_2, sealTestRule);
addClientRule(getManagementServer(SERVERS.PORT_1).getManagementAgent().getCorfuRuntime(),
SERVERS.ENDPOINT_2, failureTestRule);
addClientRule(getManagementServer(SERVERS.PORT_2).getManagementAgent().getCorfuRuntime(),
SERVERS.ENDPOINT_1, sealTestRule);
addClientRule(getManagementServer(SERVERS.PORT_2).getManagementAgent().getCorfuRuntime(),
SERVERS.ENDPOINT_1, failureTestRule);
addClientRule(getManagementServer(SERVERS.PORT_2).getManagementAgent().getCorfuRuntime(),
SERVERS.ENDPOINT_2, sealTestRule);
addClientRule(getManagementServer(SERVERS.PORT_2).getManagementAgent().getCorfuRuntime(),
SERVERS.ENDPOINT_2, failureTestRule);
// PART 1.
log.info("Simulate ENDPOINT_2 failure from ENDPOINT_1 (only Management Server)");
addClientRule(getManagementServer(SERVERS.PORT_1).getManagementAgent().getCorfuRuntime(),
SERVERS.ENDPOINT_2, new TestRule().always().drop());
log.info("Adding a rule on SERVERS.PORT_1 to toggle the flag when it " +
"sends the REPORT_FAILURE_REQUEST message.");
addClientRule(getManagementServer(SERVERS.PORT_0).getManagementAgent().getCorfuRuntime(),
new TestRule().requestMatches(msg -> {
if (msg.getPayload().getPayloadCase().equals(PayloadCase.REPORT_FAILURE_REQUEST)) {
failureDetected.release();
}
return true;
}));
log.info("Go ahead when sealing of ENDPOINT_0 takes place.");
for (int i = 0; i < PARAMETERS.NUM_ITERATIONS_MODERATE; i++) {
if (getServerRouter(SERVERS.PORT_0).getServerEpoch() == 2L) {
failureDetected.release();
break;
}
Thread.sleep(PARAMETERS.TIMEOUT_VERY_SHORT.toMillis());
}
assertThat(failureDetected.tryAcquire(2, PARAMETERS.TIMEOUT_NORMAL.toNanos(),
TimeUnit.NANOSECONDS)).isEqualTo(true);
addClientRule(getManagementServer(SERVERS.PORT_0).getManagementAgent().getCorfuRuntime(), failureTestRule);
log.info("Assert that only a partial seal was successful. " +
"ENDPOINT_0 sealed. ENDPOINT_1 & ENDPOINT_2 not sealed."
);
assertThat(getServerRouter(SERVERS.PORT_0).getServerEpoch()).isEqualTo(2L);
assertThat(getServerRouter(SERVERS.PORT_1).getServerEpoch()).isEqualTo(1L);
assertThat(getServerRouter(SERVERS.PORT_2).getServerEpoch()).isEqualTo(1L);
assertThat(getLayoutServer(SERVERS.PORT_0).getCurrentLayout().getEpoch()).isEqualTo(1L);
assertThat(getLayoutServer(SERVERS.PORT_1).getCurrentLayout().getEpoch()).isEqualTo(1L);
assertThat(getLayoutServer(SERVERS.PORT_2).getCurrentLayout().getEpoch()).isEqualTo(1L);
// PART 2.
log.info("Simulate normal operations for all servers and clients.");
clearClientRules(getManagementServer(SERVERS.PORT_0).getManagementAgent().getCorfuRuntime());
// PART 3.
log.info("Allow management server to detect partial seal and correct this issue.");
for (int i = 0; i < PARAMETERS.NUM_ITERATIONS_MODERATE; i++) {
Thread.sleep(PARAMETERS.TIMEOUT_SHORT.toMillis());
log.info("Assert successful seal of all servers.");
long server0Epoch = getServerRouter(SERVERS.PORT_0).getServerEpoch();
long server1Epoch = getServerRouter(SERVERS.PORT_1).getServerEpoch();
long server2Epoch = getServerRouter(SERVERS.PORT_2).getServerEpoch();
long server0LayoutEpoch = getLayoutServer(SERVERS.PORT_0).getCurrentLayout().getEpoch();
long server1LayoutEpoch = getLayoutServer(SERVERS.PORT_1).getCurrentLayout().getEpoch();
long server2LayoutEpoch = getLayoutServer(SERVERS.PORT_2).getCurrentLayout().getEpoch();
List<Long> epochs = Arrays.asList(
server0Epoch, server1Epoch, server2Epoch,
server0LayoutEpoch, server1LayoutEpoch, server2LayoutEpoch
);
if (epochs.stream().allMatch(epoch -> epoch == 2)) {
return;
}
log.warn("The seal is not complete yet. Wait for next iteration. Servers epochs: {}", epochs);
}
fail();
}
private void induceSequencerFailureAndWait() {
long currentEpoch = getCorfuRuntime().getLayoutView().getLayout().getEpoch();
// induce a failure to the server on PORT_0, where the current sequencer is active
//
getManagementServer(SERVERS.PORT_0).shutdown();
addServerRule(SERVERS.PORT_0, new TestRule().always().drop());
// wait for failover to install a new epoch (and a new layout)
waitForLayoutChange(layout ->
layout.getEpoch() > currentEpoch && !layout.getPrimarySequencer().equals(SERVERS.ENDPOINT_0),
getCorfuRuntime());
}
/**
* Scenario with 3 nodes: SERVERS.PORT_0, SERVERS.PORT_1 and SERVERS.PORT_2.
* We fail SERVERS.PORT_1 and then wait for one of the other two servers to
* handle this failure, propose a new layout and we assert on the epoch change.
* The failure is handled by ConserveFailureHandlerPolicy.
* No nodes are removed from the layout, but are marked unresponsive.
* A sequencer failover takes place where the next working sequencer is reset
* and made the primary.
*/
@Test
public void testSequencerFailover() throws Exception {
getManagementTestLayout();
final long beforeFailure = 5L;
final long afterFailure = 10L;
IStreamView sv = getCorfuRuntime().getStreamsView().get(CorfuRuntime.getStreamID("streamA"));
byte[] testPayload = "hello world".getBytes();
sv.append(testPayload);
sv.append(testPayload);
sv.append(testPayload);
sv.append(testPayload);
sv.append(testPayload);
assertThat(getSequencer(SERVERS.PORT_0).getGlobalLogTail()).isEqualTo(beforeFailure);
assertThat(getSequencer(SERVERS.PORT_1).getGlobalLogTail()).isEqualTo(0L);
induceSequencerFailureAndWait();
waitForLayoutChange(layout -> layout.getUnresponsiveServers().size() == 1
&& layout.getUnresponsiveServers().contains(SERVERS.ENDPOINT_0), getCorfuRuntime());
Layout newLayout = new Layout(getCorfuRuntime().getLayoutView().getLayout());
// Block until new sequencer reaches READY state.
TokenResponse tokenResponse = getCorfuRuntime().getSequencerView().query();
// verify that a failover sequencer was started with the correct starting-tail
assertThat(tokenResponse.getSequence()).isEqualTo(beforeFailure - 1);
sv.append(testPayload);
sv.append(testPayload);
sv.append(testPayload);
sv.append(testPayload);
sv.append(testPayload);
assertThat(newLayout.getUnresponsiveServers()).containsExactly(SERVERS.ENDPOINT_0);
tokenResponse = getCorfuRuntime().getSequencerView().query();
assertThat(tokenResponse.getSequence()).isEqualTo(afterFailure - 1);
}
protected <T extends ICorfuSMR> Object instantiateCorfuObject(TypeToken<T> tType, String name) {
return getCorfuRuntime().getObjectsView()
.build()
.setStreamName(name) // stream name
.setTypeToken(tType) // a TypeToken of the specified class
.open(); // instantiate the object!
}
protected ICorfuTable<Integer, String> getMap() {
ICorfuTable<Integer, String> testMap;
testMap = (ICorfuTable<Integer, String>) instantiateCorfuObject(
new TypeToken<CorfuTable<Integer, String>>() {
}, "test stream"
);
return testMap;
}
protected void TXBegin() {
getCorfuRuntime().getObjectsView().TXBegin();
}
protected void TXEnd() {
getCorfuRuntime().getObjectsView().TXEnd();
}
/**
* Check that transaction conflict resolution works properly in face of sequencer failover
*/
@Test
public void ckSequencerFailoverTXResolution() throws Exception {
// setup 3-Corfu node cluster
getManagementTestLayout();
Map<Integer, String> map = getMap();
// start a transaction and force it to obtain snapshot timestamp
// preceding the sequencer failover
t(0, () -> {
TXBegin();
map.get(0);
});
final String payload = "hello";
final int nUpdates = 5;
// in another thread, fill the log with a few entries
t(1, () -> {
for (int i = 0; i < nUpdates; i++)
map.put(i, payload);
});
// now, the tail of the log is at nUpdates;
// kill the sequencer, wait for a failover,
// and then resume the transaction above; it should abort
// (unnecessarily, but we are being conservative)
//
induceSequencerFailureAndWait();
t(0, () -> {
boolean commit = true;
map.put(nUpdates + 1, payload); // should not conflict
try {
TXEnd();
} catch (TransactionAbortedException ta) {
assertThat(ta.getAbortCause()).isEqualTo(AbortCause.NEW_SEQUENCER);
commit = false;
}
assertThat(commit)
.isFalse();
});
// now, check that the same scenario, starting a new, can succeed
t(0, () -> {
TXBegin();
map.get(0);
});
// in another thread, fill the log with a few entries
t(1, () -> {
for (int i = 0; i < nUpdates; i++)
map.put(i, payload + 1);
});
t(0, () -> {
boolean commit = true;
map.put(nUpdates + 1, payload); // should not conflict
try {
TXEnd();
} catch (TransactionAbortedException ta) {
commit = false;
}
assertThat(commit)
.isTrue();
});
}
/**
* small variant on the above : don't start the first TX at the start of the log.
*/
@Test
public void ckSequencerFailoverTXResolution1() throws Exception {
getManagementTestLayout();
Map<Integer, String> map = getMap();
final String payload = "hello";
final int nUpdates = 5;
for (int i = 0; i < nUpdates; i++)
map.put(i, payload);
// start a transaction and force it to obtain snapshot timestamp
// preceding the sequencer failover
t(0, () -> {
TXBegin();
map.get(0);
});
// in another thread, fill the log with a few entries
t(1, () -> {
for (int i = 0; i < nUpdates; i++)
map.put(i, payload + 1);
});
// now, the tail of the log is at nUpdates;
// kill the sequencer, wait for a failover,
// and then resume the transaction above; it should abort
// (unnecessarily, but we are being conservative)
//
induceSequencerFailureAndWait();
t(0, () -> {
boolean commit = true;
map.put(nUpdates + 1, payload); // should not conflict
try {
TXEnd();
} catch (TransactionAbortedException ta) {
assertThat(ta.getAbortCause()).isEqualTo(AbortCause.NEW_SEQUENCER);
commit = false;
}
assertThat(commit)
.isFalse();
});
// now, check that the same scenario, starting anew, can succeed
t(0, () -> {
TXBegin();
map.get(0);
});
// in another thread, fill the log with a few entries
t(1, () -> {
for (int i = 0; i < nUpdates; i++)
map.put(i, payload + 2);
});
t(0, () -> {
boolean commit = true;
map.put(nUpdates + 1, payload); // should not conflict
try {
TXEnd();
} catch (TransactionAbortedException ta) {
commit = false;
}
assertThat(commit)
.isTrue();
});
}
/**
* When a stream is seen for the first time by the sequencer it returns a -1
* in the backpointer map.
* After failover, the new sequencer returns a null in the backpointer map
* forcing it to single step backwards and get the last backpointer for the
* given stream.
* An example is shown below:
* <p>
* Index : 0 1 2 3 | | 4 5 6 7 8
* Stream : A B A B | failover | A C A B B
* B.P : -1 -1 0 1 | | 2 -1 4 3 7
* <p>
* -1 : New StreamID so empty backpointers
* X : (null) Unknown backpointers as this is a failed-over sequencer.
* <p>
*/
@Test
public void sequencerFailoverBackpointerCheck() throws Exception {
getManagementTestLayout();
UUID streamA = UUID.nameUUIDFromBytes("stream A".getBytes());
UUID streamB = UUID.nameUUIDFromBytes("stream B".getBytes());
UUID streamC = UUID.nameUUIDFromBytes("stream C".getBytes());
final long streamA_backpointerRecovered = 2L;
final long streamB_backpointerRecovered = 3L;
final long streamA_backpointerFinal = 4L;
final long streamB_backpointerFinal = 7L;
getTokenWriteAndAssertBackPointer(streamA, Address.NON_EXIST);
getTokenWriteAndAssertBackPointer(streamB, Address.NON_EXIST);
getTokenWriteAndAssertBackPointer(streamA, 0L);
getTokenWriteAndAssertBackPointer(streamB, 1L);
induceSequencerFailureAndWait();
getTokenWriteAndAssertBackPointer(streamA, streamA_backpointerRecovered);
getTokenWriteAndAssertBackPointer(streamC, Address.NON_EXIST);
getTokenWriteAndAssertBackPointer(streamA, streamA_backpointerFinal);
getTokenWriteAndAssertBackPointer(streamB, streamB_backpointerRecovered);
getTokenWriteAndAssertBackPointer(streamB, streamB_backpointerFinal);
}
/**
* Requests for a token for the given stream ID.
* Asserts the backpointer map in the token response with the specified backpointer location.
* Writes test data to the log unit servers using the tokenResponse.
*
* @param streamID Stream ID to request token for.
* @param expectedBackpointerValue Expected backpointer for given stream.
*/
private void getTokenWriteAndAssertBackPointer(UUID streamID, Long expectedBackpointerValue) {
TokenResponse tokenResponse =
corfuRuntime.getSequencerView().next(streamID);
if (expectedBackpointerValue == null) {
assertThat(tokenResponse.getBackpointerMap()).isEmpty();
} else {
assertThat(tokenResponse.getBackpointerMap()).containsEntry(streamID, expectedBackpointerValue);
}
corfuRuntime.getAddressSpaceView().write(tokenResponse,
"test".getBytes());
}
/**
* Asserts that we cannot fetch a token after a failure but before sequencer reset.
*
* @throws Exception
*/
@Test
public void blockRecoverySequencerUntilReset() throws Exception {
final Semaphore resetDetected = new Semaphore(1);
Layout layout = getManagementTestLayout();
UUID streamA = UUID.nameUUIDFromBytes("stream A".getBytes());
getTokenWriteAndAssertBackPointer(streamA, Address.NON_EXIST);
resetDetected.acquire();
// Allow only SERVERS.PORT_0 to handle the failure.
// Preventing PORT_2 from bootstrapping the sequencer.
addClientRule(getManagementServer(SERVERS.PORT_2).getManagementAgent().getCorfuRuntime(),
new TestRule().requestMatches(msg ->
msg.getPayload().getPayloadCase().equals(PayloadCase.BOOTSTRAP_SEQUENCER_REQUEST)).drop());
addClientRule(getManagementServer(SERVERS.PORT_1).getManagementAgent().getCorfuRuntime(),
new TestRule().requestMatches(msg -> {
if (msg.getPayload().getPayloadCase().equals(PayloadCase.BOOTSTRAP_SEQUENCER_REQUEST)) {
try {
// There is a failure but the BOOTSTRAP_SEQUENCER message has not yet been
// sent. So if we request a token now, we should be denied as the
// server is sealed and we get a WrongEpochException.
corfuRuntime.getLayoutView().getRuntimeLayout(layout)
.getSequencerClient(SERVERS.ENDPOINT_1)
.nextToken(Collections.singletonList(CorfuRuntime
.getStreamID("testStream")), 1).get();
fail();
} catch (InterruptedException | ExecutionException e) {
resetDetected.release();
}
}
return false;
}));
// Inducing failure on PORT_1
induceSequencerFailureAndWait();
assertThat(resetDetected
.tryAcquire(PARAMETERS.TIMEOUT_NORMAL.toMillis(), TimeUnit.MILLISECONDS))
.isTrue();
// We should be able to request a token now.
corfuRuntime.getSequencerView().next(CorfuRuntime.getStreamID("testStream"));
}
@Test
public void sealDoesNotModifyClientEpoch() throws Exception {
Layout l = getManagementTestLayout();
// Seal
Layout newLayout = new Layout(l);
newLayout.setEpoch(newLayout.getEpoch() + 1);
corfuRuntime.getLayoutView().getRuntimeLayout(newLayout).sealMinServerSet();
assertThat(corfuRuntime.getLayoutView().getLayout().getEpoch()).isEqualTo(l.getEpoch());
}
/**
* Checks for updates trailing layout servers.
* The layout is partially committed with epoch 2 except for ENDPOINT_0.
* All commit messages from the cluster are intercepted.
* The test checks whether at least one of the 3 management agents patches the layout server with the latest
* layout.
* If a commit message with any other epoch is sent, the test fails.
*/
@Test
public void updateTrailingLayoutServers() throws Exception {
Layout layout = new Layout(getManagementTestLayout());
AtomicBoolean commitWithDifferentEpoch = new AtomicBoolean(false);
final CountDownLatch latch = new CountDownLatch(1);
TestRule interceptCommit = new TestRule().requestMatches(msg -> {
if (msg.getPayload().getPayloadCase().equals(PayloadCase.COMMIT_LAYOUT_REQUEST)) {
if (msg.getPayload().getCommitLayoutRequest().getEpoch() == 2) {
latch.countDown();
} else {
commitWithDifferentEpoch.set(true);
}
}
return true;
});
addClientRule(getManagementServer(SERVERS.PORT_0).getManagementAgent().getCorfuRuntime(), interceptCommit);
addClientRule(getManagementServer(SERVERS.PORT_1).getManagementAgent().getCorfuRuntime(), interceptCommit);
addClientRule(getManagementServer(SERVERS.PORT_2).getManagementAgent().getCorfuRuntime(), interceptCommit);
final long highRank = 10L;
addClientRule(corfuRuntime, SERVERS.ENDPOINT_0, new TestRule().always().drop());
layout.setEpoch(2L);
corfuRuntime.getLayoutView().getRuntimeLayout(layout).sealMinServerSet();
// We increase to a higher rank to avoid being outranked. We could be outranked if the management
// agent attempts to fill in the epoch slot before we update.
corfuRuntime.getLayoutView().updateLayout(layout, highRank);
for (int i = 0; i < PARAMETERS.NUM_ITERATIONS_MODERATE; i++) {
Thread.sleep(PARAMETERS.TIMEOUT_SHORT.toMillis());
if (getLayoutServer(SERVERS.PORT_0).getCurrentLayout().equals(layout))
break;
}
assertThat(getLayoutServer(SERVERS.PORT_0).getCurrentLayout().getEpoch()).isEqualTo(2L);
assertThat(getLayoutServer(SERVERS.PORT_0).getCurrentLayout()).isEqualTo(layout);
latch.await();
assertThat(commitWithDifferentEpoch.get()).isFalse();
}
/**
* Tests a 3 node cluster.
* All Prepare messages are first blocked. Then a seal is issued for epoch 2.
* The test then ensures that no layout is committed for the epoch 2.
* We ensure that no layout is committed other than the Paxos path.
*/
@Test
public void blockLayoutUpdateAfterSeal() throws InterruptedException {
Layout layout = new Layout(getManagementTestLayout());
TestRule dropPrepareMsg = new TestRule()
.requestMatches(msg -> msg.getPayload().getPayloadCase().equals(PayloadCase.PREPARE_LAYOUT_REQUEST))
.drop();
// Block Paxos round by blocking all prepare methods.
addClientRule(getManagementServer(SERVERS.PORT_0).getManagementAgent().getCorfuRuntime(), dropPrepareMsg);
addClientRule(getManagementServer(SERVERS.PORT_1).getManagementAgent().getCorfuRuntime(), dropPrepareMsg);
addClientRule(getManagementServer(SERVERS.PORT_2).getManagementAgent().getCorfuRuntime(), dropPrepareMsg);
// Seal the layout.
layout.setEpoch(2L);
corfuRuntime.getLayoutView().getRuntimeLayout(layout).sealMinServerSet();
// Wait for the cluster to move the layout with epoch 2 without the Paxos round.
for (int i = 0; i < PARAMETERS.NUM_ITERATIONS_LOW; i++) {
TimeUnit.MILLISECONDS.sleep(PARAMETERS.TIMEOUT_VERY_SHORT.toMillis());
if (corfuRuntime.getLayoutView().getLayout().getEpoch() == 2L) {
fail();
}
corfuRuntime.invalidateLayout();
}
assertThat(corfuRuntime.getLayoutView().getLayout().getEpoch()).isEqualTo(1L);
}
/**
* A single node cluster is sealed but the client crashes before it can propose a layout.
* The management server now have to detect this state and fill up this slot with an existing
* layout in order to unblock the data plane operations.
*
* @throws Exception
*/
@Test
public void unblockSealedCluster() throws Exception {
CorfuRuntime corfuRuntime = getDefaultRuntime();
Layout l = new Layout(corfuRuntime.getLayoutView().getLayout());
setAggressiveDetectorTimeouts(SERVERS.PORT_0);
waitForSequencerToBootstrap(SERVERS.PORT_0);
l.setEpoch(l.getEpoch() + 1);
corfuRuntime.getLayoutView().getRuntimeLayout(l).sealMinServerSet();
for (int i = 0; i < PARAMETERS.NUM_ITERATIONS_MODERATE; i++) {
Thread.sleep(PARAMETERS.TIMEOUT_SHORT.toMillis());
if (corfuRuntime.getLayoutView().getLayout().getEpoch() == l.getEpoch()) {
break;
}
corfuRuntime.invalidateLayout();
}
assertThat(corfuRuntime.getLayoutView().getLayout().getEpoch()).isEqualTo(l.getEpoch());
}
/**
* Tests healing of an unresponsive node now responding to pings.
* A rule is added on PORT_2 to drop all messages.
* The other 2 nodes PORT_0 and PORT_1 will detect this failure and mark it as unresponsive.
* The rule is then removed simulating a normal functioning PORT_2. The other nodes will now
* be able to successfully ping PORT_2. They then remove the node PORT_2 from the unresponsive
* servers list and mark as active.
*
* @throws Exception
*/
@Test
public void testNodeHealing() {
CorfuRuntime corfuRuntime = null;
try {
addServer(SERVERS.PORT_0);
addServer(SERVERS.PORT_1);
addServer(SERVERS.PORT_2);
Layout l = new TestLayoutBuilder()
.setEpoch(1L)
.addLayoutServer(SERVERS.PORT_0)
.addLayoutServer(SERVERS.PORT_1)
.addLayoutServer(SERVERS.PORT_2)
.addSequencer(SERVERS.PORT_0)
.buildSegment()
.buildStripe()
.addLogUnit(SERVERS.PORT_0)
.addToSegment()
.addToLayout()
.build();
bootstrapAllServers(l);
corfuRuntime = getRuntime(l).connect();
setAggressiveTimeouts(l, corfuRuntime,
getManagementServer(SERVERS.PORT_0).getManagementAgent().getCorfuRuntime());
setAggressiveDetectorTimeouts(SERVERS.PORT_0);
addServerRule(SERVERS.PORT_2, new TestRule().always().drop());
waitForLayoutChange(layout -> layout.getUnresponsiveServers()
.equals(Collections.singletonList(SERVERS.ENDPOINT_2)), corfuRuntime);
clearServerRules(SERVERS.PORT_2);
waitForLayoutChange(layout -> layout.getUnresponsiveServers().isEmpty()
&& layout.getSegments().size() == 1, corfuRuntime);
} finally {
if (corfuRuntime != null) {
corfuRuntime.shutdown();
}
}
}
/**
* Add a new node with layout, sequencer and log unit components.
* The new log unit node is open to reads and writes only in the new segment and no
* catchup or replication of old data is performed.
*
* @throws Exception
*/
@Test
public void testAddNodeWithoutCatchup() throws Exception {
CorfuRuntime rt = null;
try {
addServer(SERVERS.PORT_0);
Layout l1 = new TestLayoutBuilder()
.setEpoch(0L)
.addLayoutServer(SERVERS.PORT_0)
.addSequencer(SERVERS.PORT_0)
.buildSegment()
.buildStripe()
.addLogUnit(SERVERS.PORT_0)
.addToSegment()
.addToLayout()
.build();
bootstrapAllServers(l1);
ServerContext sc1 = new ServerContextBuilder()
.setSingle(false)
.setServerRouter(new TestServerRouter(SERVERS.PORT_1))
.setPort(SERVERS.PORT_1)
.build();
addServer(SERVERS.PORT_1, sc1);
rt = getNewRuntime(getDefaultNode())
.connect();
// Write to address space 0
rt.getStreamsView().get(CorfuRuntime.getStreamID("test"))
.append("testPayload".getBytes());
rt.getLayoutManagementView().addNode(l1, SERVERS.ENDPOINT_1,
true,
true,
true,
false,
0);
rt.invalidateLayout();
Layout layoutPhase2 = rt.getLayoutView().getLayout();
Layout l2 = new TestLayoutBuilder()
.setEpoch(1L)
.addLayoutServer(SERVERS.PORT_0)
.addLayoutServer(SERVERS.PORT_1)
.addSequencer(SERVERS.PORT_0)
.addSequencer(SERVERS.PORT_1)
.buildSegment()
.setStart(0L)
.setEnd(1L)
.buildStripe()
.addLogUnit(SERVERS.PORT_0)
.addToSegment()
.addToLayout()
.buildSegment()
.setStart(1L)
.setEnd(-1L)
.buildStripe()
.addLogUnit(SERVERS.PORT_0)
.addLogUnit(SERVERS.PORT_1)
.addToSegment()
.addToLayout()
.build();
assertThat(l2.asJSONString()).isEqualTo(layoutPhase2.asJSONString());
} finally {
if (rt != null) {
rt.shutdown();
}
}
}
/**
* This test starts with a cluster of 3 at epoch 1 with PORT_0 as the primary sequencer.
* Now runtime_1 writes 5 entries to streams A and B each.
* The token count has increased from 0-9.
*
* The cluster now reconfigures to mark PORT_1 as the primary sequencer for epoch 2.
* A stale client still observing epoch 1 requests 10 tokens from PORT_0.
* However 2 tokens are requested from PORT_1.
*
* The cluster again reconfigures to mark PORT_0 as the primary sequencer for epoch 3.
* The state of the new primary sequencer should now be recreated using the FastObjectLoader
* and should NOT reflect the 10 invalid tokens requested by the stale client.
*/
@Test
public void regressTokenCountToValidDispatchedTokens() throws Exception {
final UUID streamA = CorfuRuntime.getStreamID("streamA");
final UUID streamB = CorfuRuntime.getStreamID("streamB");
byte[] payload = "test_payload".getBytes();
Layout layout_1 = new Layout(getManagementTestLayout());
// In case any management agent is capable of detecting a failure (one node shutdown) before all
// three nodes go down, we will drop all messages to prevent reporting failures which could move
// the epoch, before the client actually moves it (leading to a wrongEpochException)
TestRule mngtAgentDropAll = new TestRule().always().drop();
addClientRule(getManagementServer(SERVERS.PORT_0).getManagementAgent().getCorfuRuntime(),
mngtAgentDropAll);
addClientRule(getManagementServer(SERVERS.PORT_1).getManagementAgent().getCorfuRuntime(),
mngtAgentDropAll);
addClientRule(getManagementServer(SERVERS.PORT_2).getManagementAgent().getCorfuRuntime(),
mngtAgentDropAll);
// Shut down management servers to prevent auto-reconfiguration.
getManagementServer(SERVERS.PORT_0).shutdown();
getManagementServer(SERVERS.PORT_1).shutdown();
getManagementServer(SERVERS.PORT_2).shutdown();
SequencerServer server0 = getSequencer(SERVERS.PORT_0);
SequencerServer server1 = getSequencer(SERVERS.PORT_1);
CorfuRuntime runtime_1 = getNewRuntime(getDefaultNode()).connect();
CorfuRuntime runtime_2 = getNewRuntime(getDefaultNode()).connect();
IStreamView streamViewA = runtime_1.getStreamsView().get(streamA);
IStreamView streamViewB = runtime_1.getStreamsView().get(streamB);
// Write 10 entries to the log using runtime_1.
// Stream A 0-4
streamViewA.append(payload);
streamViewA.append(payload);
streamViewA.append(payload);
streamViewA.append(payload);
streamViewA.append(payload);
// Stream B 5-9
streamViewB.append(payload);
streamViewB.append(payload);
streamViewB.append(payload);
streamViewB.append(payload);
streamViewB.append(payload);
// Add a rule to drop Seal and Paxos messages on PORT_0 (the current primary sequencer).
addClientRule(runtime_1, SERVERS.ENDPOINT_0, new TestRule().drop().always());
// Trigger reconfiguration and failover the sequencer to PORT_1
Layout layout_2 = new LayoutBuilder(layout_1)
.assignResponsiveSequencerAsPrimary(Collections.singleton(SERVERS.ENDPOINT_0))
.build();
layout_2.setEpoch(layout_2.getEpoch() + 1);
runtime_1.getLayoutView().getRuntimeLayout(layout_2).sealMinServerSet();
runtime_1.getLayoutView().updateLayout(layout_2, 1L);
runtime_1.getLayoutManagementView().reconfigureSequencerServers(layout_1, layout_2, false);
waitForLayoutChange(layout -> layout.getEpoch() == layout_2.getEpoch(), runtime_1);
clearClientRules(runtime_1);
// Using the stale client with view of epoch 1, request 10 tokens.
final int tokenCount = 5;
for (int x = 0; x < tokenCount; x++) {
runtime_2.getSequencerView().next(streamA);
runtime_2.getSequencerView().next(streamB);
}
// Using the new client request 2 tokens and write to the log.
streamViewA.append(payload);
streamViewA.append(payload);
final int expectedServer0Tokens = 20;
final int expectedServer1Tokens = 12;
assertThat(server0.getSequencerEpoch()).isEqualTo(layout_1.getEpoch());
assertThat(server1.getSequencerEpoch()).isEqualTo(layout_2.getEpoch());
assertThat(server0.getGlobalLogTail()).isEqualTo(expectedServer0Tokens);
assertThat(server1.getGlobalLogTail()).isEqualTo(expectedServer1Tokens);
// Trigger reconfiguration to failover back to PORT_0.
Layout layout_3 = new LayoutBuilder(layout_2)
.assignResponsiveSequencerAsPrimary(Collections.singleton(SERVERS.ENDPOINT_1))
.build();
layout_3.setEpoch(layout_3.getEpoch() + 1);
runtime_1.getLayoutView().getRuntimeLayout(layout_3).sealMinServerSet();
runtime_1.getLayoutView().updateLayout(layout_3, 1L);
runtime_1.getLayoutManagementView().reconfigureSequencerServers(layout_2, layout_3, false);
// Assert that the token count does not reflect the 10 tokens requested by the stale
// client on PORT_0.
assertThat(server0.getSequencerEpoch()).isEqualTo(layout_3.getEpoch());
assertThat(server1.getSequencerEpoch()).isEqualTo(layout_2.getEpoch());
assertThat(server0.getGlobalLogTail()).isEqualTo(expectedServer1Tokens);
assertThat(server1.getGlobalLogTail()).isEqualTo(expectedServer1Tokens);
// Assert that the streamTailMap has been reset and returns the correct backpointer.
final long expectedBackpointerStreamA = 11;
TokenResponse tokenResponse = runtime_1.getSequencerView().next(streamA);
assertThat(tokenResponse.getBackpointerMap().get(streamA))
.isEqualTo(expectedBackpointerStreamA);
}
/**
* Starts a cluster with 3 nodes.
* The epoch is then incremented and a layout proposed and accepted for the new epoch.
* This leaves the sequencer un-bootstrapped causing token requests to hang.
* The heartbeats should convey this primary sequencer NOT_READY state to the failure
* detector which bootstraps the sequencer.
*/
@Test
public void handleUnBootstrappedSequencer() throws Exception {
Layout layout = new Layout(getManagementTestLayout());
final long highRank = 10L;
// We increment the epoch and propose the same layout for the new epoch.
// Due to the router and sequencer epoch mismatch, the sequencer becomes NOT_READY.
// Note that this reconfiguration is not followed by the explicit sequencer bootstrap step.
layout.setEpoch(layout.getEpoch() + 1);
corfuRuntime.getLayoutView().getRuntimeLayout(layout).sealMinServerSet();
// We increase to a higher rank to avoid being outranked. We could be outranked if the management
// agent attempts to fill in the epoch slot before we update.
corfuRuntime.getLayoutView().updateLayout(layout, highRank);
// Assert that the primary sequencer is not ready.
assertThatThrownBy(() -> corfuRuntime.getLayoutView().getRuntimeLayout()
.getPrimarySequencerClient()
.requestMetrics().get()).hasCauseInstanceOf(ServerNotReadyException.class);
// Wait for the management service to detect and bootstrap the sequencer.
corfuRuntime.getSequencerView().query();
// Assert that the primary sequencer is bootstrapped.
assertThat(corfuRuntime.getLayoutView().getRuntimeLayout().getPrimarySequencerClient()
.requestMetrics().get().getSequencerStatus()).isEqualTo(SequencerStatus.READY);
}
/**
* Tests the Cluster Status Query API.
* The test starts with setting up a 3 node cluster:
* Layout Servers = PORT_0, PORT_1, PORT_2.
* Sequencer Servers = PORT_0, PORT_1, PORT_2.
* LogUnit Servers = PORT_0, PORT_1, PORT_2.
*
* STEP 1: First status query:
* All nodes up. Cluster status: STABLE.
*
* STEP 2: In this step the client is partitioned from the 2 nodes in the cluster.
* The cluster however is healthy. Status query:
* PORT_0 and PORT_1 are UNRESPONSIVE. Cluster status: STABLE
* (Since the cluster is table it is just the client that cannot reach all healthy servers)
*
* A few entries are appended on a Stream. This data is written to PORT_0, PORT_1 and PORT_2.
*
* STEP 3: Client connections are restored from the previous step. PORT_0 is failed.
* This causes sequencer failover. The cluster is still reachable. Status query:
* PORT_0 is DOWN. Cluster status: DEGRADED.
*
* STEP 4: PORT_1 is failed. The cluster is non-operational now. Status query:
* PORT_0 and PORT_1 UNRESPONSIVE, however the Cluster status: DEGRADED, as layout cannot
* converge to a new layout (no consensus).
*
* STEP 5: All nodes are failed. The cluster is non-operational now. Status query:
* PORT_0, PORT_1 and PORT_2 DOWN/UNRESPONSIVE. Cluster status: UNAVAILABLE.
*
*/
@Test
public void queryClusterStatus() throws Exception {
get3NodeLayout();
getCorfuRuntime().getLayoutView().getLayout().getAllServers().forEach(endpoint ->
getCorfuRuntime().getRouter(endpoint)
.setTimeoutResponse(PARAMETERS.TIMEOUT_VERY_SHORT.toMillis()));
// STEP 1.
ClusterStatusReport clusterStatus = getCorfuRuntime().getManagementView().getClusterStatus();
Map<String, ConnectivityStatus> nodeConnectivityMap = clusterStatus.getClientServerConnectivityStatusMap();
Map<String, NodeStatus> nodeStatusMap = clusterStatus.getClusterNodeStatusMap();
ClusterStatusReport.ClusterStatusReliability clusterStatusReliability = clusterStatus.getClusterStatusReliability();
assertThat(nodeConnectivityMap.get(SERVERS.ENDPOINT_0)).isEqualTo(ConnectivityStatus.RESPONSIVE);
assertThat(nodeConnectivityMap.get(SERVERS.ENDPOINT_1)).isEqualTo(ConnectivityStatus.RESPONSIVE);
assertThat(nodeConnectivityMap.get(SERVERS.ENDPOINT_2)).isEqualTo(ConnectivityStatus.RESPONSIVE);
assertThat(nodeStatusMap.get(SERVERS.ENDPOINT_0)).isEqualTo(NodeStatus.UP);
assertThat(nodeStatusMap.get(SERVERS.ENDPOINT_1)).isEqualTo(NodeStatus.UP);
assertThat(nodeStatusMap.get(SERVERS.ENDPOINT_2)).isEqualTo(NodeStatus.UP);
assertThat(clusterStatusReliability).isEqualTo(ClusterStatusReport.ClusterStatusReliability.STRONG_QUORUM);
assertThat(clusterStatus.getClusterStatus()).isEqualTo(ClusterStatus.STABLE);
// STEP 2.
// Because we are explicitly dropping PING messages only (which are used to verify
// client's connectivity) on ENDPOINT_0 and ENDPOINT_1, this test will show both nodes
// unresponsive, despite of their actual node status being UP.
TestRule rule = new TestRule()
.requestMatches(msg -> msg.getPayload().getPayloadCase().equals(PayloadCase.PING_REQUEST))
.drop();
addClientRule(getCorfuRuntime(), SERVERS.ENDPOINT_0, rule);
addClientRule(getCorfuRuntime(), SERVERS.ENDPOINT_1, rule);
clusterStatus = getCorfuRuntime().getManagementView().getClusterStatus();
nodeConnectivityMap = clusterStatus.getClientServerConnectivityStatusMap();
nodeStatusMap = clusterStatus.getClusterNodeStatusMap();
clusterStatusReliability = clusterStatus.getClusterStatusReliability();
assertThat(nodeConnectivityMap.get(SERVERS.ENDPOINT_0)).isEqualTo(ConnectivityStatus.UNRESPONSIVE);
assertThat(nodeConnectivityMap.get(SERVERS.ENDPOINT_1)).isEqualTo(ConnectivityStatus.UNRESPONSIVE);
assertThat(nodeConnectivityMap.get(SERVERS.ENDPOINT_2)).isEqualTo(ConnectivityStatus.RESPONSIVE);
assertThat(nodeStatusMap.get(SERVERS.ENDPOINT_0)).isEqualTo(NodeStatus.UP);
assertThat(nodeStatusMap.get(SERVERS.ENDPOINT_1)).isEqualTo(NodeStatus.UP);
assertThat(nodeStatusMap.get(SERVERS.ENDPOINT_2)).isEqualTo(NodeStatus.UP);
assertThat(clusterStatusReliability).isEqualTo(ClusterStatusReport.ClusterStatusReliability.STRONG_QUORUM);
assertThat(clusterStatus.getClusterStatus()).isEqualTo(ClusterStatus.STABLE);
// Write 10 entries. 0-9.
IStreamView streamView = getCorfuRuntime().getStreamsView()
.get(CorfuRuntime.getStreamID("testStream"));
final int entriesCount = 10;
final byte[] payload = "payload".getBytes();
for (int i = 0; i < entriesCount; i++) {
streamView.append(payload);
}
// STEP 3.
clearClientRules(getCorfuRuntime());
addServerRule(SERVERS.PORT_0, new TestRule().drop().always());
waitForLayoutChange(layout -> layout.getUnresponsiveServers().size() == 1
&& layout.getUnresponsiveServers().contains(SERVERS.ENDPOINT_0)
&& layout.getSegments().size() == 1,
getCorfuRuntime());
clusterStatus = getCorfuRuntime().getManagementView().getClusterStatus();
nodeConnectivityMap = clusterStatus.getClientServerConnectivityStatusMap();
nodeStatusMap = clusterStatus.getClusterNodeStatusMap();
clusterStatusReliability = clusterStatus.getClusterStatusReliability();
assertThat(nodeConnectivityMap.get(SERVERS.ENDPOINT_0)).isEqualTo(ConnectivityStatus.UNRESPONSIVE);
assertThat(nodeConnectivityMap.get(SERVERS.ENDPOINT_1)).isEqualTo(ConnectivityStatus.RESPONSIVE);
assertThat(nodeConnectivityMap.get(SERVERS.ENDPOINT_2)).isEqualTo(ConnectivityStatus.RESPONSIVE);
assertThat(nodeStatusMap.get(SERVERS.ENDPOINT_0)).isEqualTo(NodeStatus.DOWN);
assertThat(nodeStatusMap.get(SERVERS.ENDPOINT_1)).isEqualTo(NodeStatus.UP);
assertThat(nodeStatusMap.get(SERVERS.ENDPOINT_2)).isEqualTo(NodeStatus.UP);
assertThat(clusterStatusReliability).isEqualTo(ClusterStatusReport.ClusterStatusReliability.STRONG_QUORUM);
assertThat(clusterStatus.getClusterStatus()).isEqualTo(ClusterStatus.DEGRADED);
// STEP 4.
// Since there will be no epoch change as majority of servers are down, we cannot obtain
// a reliable state of the cluster and report unavailable, still responsiveness to each node
// in the cluster is reported.
Semaphore latch1 = new Semaphore(1);
latch1.acquire();
addClientRule(getManagementServer(SERVERS.PORT_2).getManagementAgent().getCorfuRuntime(),
new TestRule().requestMatches(msg -> {
if (msg.getPayload().getPayloadCase().equals(PayloadCase.REPORT_FAILURE_REQUEST)) {
latch1.release();
}
return false;
}).drop());
addServerRule(SERVERS.PORT_1, new TestRule().drop().always());
addClientRule(getManagementServer(SERVERS.PORT_1).getManagementAgent().getCorfuRuntime(),
new TestRule().always().drop());
assertThat(latch1.tryAcquire(PARAMETERS.TIMEOUT_LONG.toMillis(), TimeUnit.MILLISECONDS))
.isTrue();
clusterStatus = getCorfuRuntime().getManagementView().getClusterStatus();
nodeConnectivityMap = clusterStatus.getClientServerConnectivityStatusMap();
nodeStatusMap = clusterStatus.getClusterNodeStatusMap();
clusterStatusReliability = clusterStatus.getClusterStatusReliability();
assertThat(nodeConnectivityMap.get(SERVERS.ENDPOINT_0)).isEqualTo(ConnectivityStatus.UNRESPONSIVE);
assertThat(nodeConnectivityMap.get(SERVERS.ENDPOINT_1)).isEqualTo(ConnectivityStatus.UNRESPONSIVE);
assertThat(nodeConnectivityMap.get(SERVERS.ENDPOINT_2)).isEqualTo(ConnectivityStatus.RESPONSIVE);
assertThat(nodeStatusMap.get(SERVERS.ENDPOINT_0)).isEqualTo(NodeStatus.NA);
assertThat(nodeStatusMap.get(SERVERS.ENDPOINT_1)).isEqualTo(NodeStatus.NA);
assertThat(nodeStatusMap.get(SERVERS.ENDPOINT_2)).isEqualTo(NodeStatus.NA);
assertThat(clusterStatusReliability).isEqualTo(ClusterStatusReport.ClusterStatusReliability.WEAK_NO_QUORUM);
assertThat(clusterStatus.getClusterStatus()).isEqualTo(ClusterStatus.UNAVAILABLE);
// STEP 5.
clearClientRules(getCorfuRuntime());
addServerRule(SERVERS.PORT_2, new TestRule().drop().always());
clusterStatus = getCorfuRuntime().getManagementView().getClusterStatus();
nodeConnectivityMap = clusterStatus.getClientServerConnectivityStatusMap();
nodeStatusMap = clusterStatus.getClusterNodeStatusMap();
clusterStatusReliability = clusterStatus.getClusterStatusReliability();
assertThat(nodeConnectivityMap.get(SERVERS.ENDPOINT_0)).isEqualTo(ConnectivityStatus.UNRESPONSIVE);
assertThat(nodeConnectivityMap.get(SERVERS.ENDPOINT_1)).isEqualTo(ConnectivityStatus.UNRESPONSIVE);
assertThat(nodeConnectivityMap.get(SERVERS.ENDPOINT_2)).isEqualTo(ConnectivityStatus.UNRESPONSIVE);
assertThat(nodeStatusMap.get(SERVERS.ENDPOINT_0)).isEqualTo(NodeStatus.NA);
assertThat(nodeStatusMap.get(SERVERS.ENDPOINT_1)).isEqualTo(NodeStatus.NA);
assertThat(nodeStatusMap.get(SERVERS.ENDPOINT_2)).isEqualTo(NodeStatus.NA);
assertThat(clusterStatusReliability).isEqualTo(ClusterStatusReport.ClusterStatusReliability.UNAVAILABLE);
assertThat(clusterStatus.getClusterStatus()).isEqualTo(ClusterStatus.UNAVAILABLE);
}
/**
* Tests that if the cluster gets stuck in a live-lock the systemDownHandler is invoked.
* Scenario: Cluster of 2 nodes - Nodes 0 and 1
* Some data (10 appends) is written into the cluster.
* Then rules are added on both the nodes' management agents so that they cannot reconfigure
* the system. Another rule is added to the tail of the chain to drop all READ_RESPONSES.
* The epoch is incremented and the new layout is pushed to both the nodes.
* NOTE: The sequencer is not bootstrapped for the new epoch.
* Now, both the management agents attempt to bootstrap the new sequencer but the
* FastObjectLoaders should stall due to the READ_RESPONSE drop rule.
* This triggers the systemDownHandler.
*/
@Test
public void triggerSystemDownHandlerInDeadlock() throws Exception {
// Cluster Setup.
addServer(SERVERS.PORT_0);
addServer(SERVERS.PORT_1);
Layout layout = new TestLayoutBuilder()
.setEpoch(1L)
.addLayoutServer(SERVERS.PORT_0)
.addLayoutServer(SERVERS.PORT_1)
.addSequencer(SERVERS.PORT_0)
.addSequencer(SERVERS.PORT_1)
.buildSegment()
.buildStripe()
.addLogUnit(SERVERS.PORT_0)
.addLogUnit(SERVERS.PORT_1)
.addToSegment()
.addToLayout()
.setClusterId(UUID.randomUUID())
.build();
bootstrapAllServers(layout);
corfuRuntime = getRuntime(layout).connect();
CorfuRuntime managementRuntime0 = getManagementServer(SERVERS.PORT_0)
.getManagementAgent().getCorfuRuntime();
CorfuRuntime managementRuntime1 = getManagementServer(SERVERS.PORT_1)
.getManagementAgent().getCorfuRuntime();
waitForSequencerToBootstrap(SERVERS.PORT_0);
// Setting aggressive timeouts
setAggressiveTimeouts(layout, corfuRuntime, managementRuntime0, managementRuntime1);
setAggressiveDetectorTimeouts(SERVERS.PORT_0, SERVERS.PORT_1);
// Append data.
IStreamView streamView = corfuRuntime.getStreamsView()
.get(CorfuRuntime.getStreamID("testStream"));
final byte[] payload = "test".getBytes();
final int num = 10;
for (int i = 0; i < num; i++) {
streamView.append(payload);
}
// Register custom systemDownHandler to detect live-lock.
final Semaphore semaphore = new Semaphore(2);
semaphore.acquire(2);
final int sysDownTriggerLimit = 3;
managementRuntime0.getParameters().setSystemDownHandlerTriggerLimit(sysDownTriggerLimit);
managementRuntime1.getParameters().setSystemDownHandlerTriggerLimit(sysDownTriggerLimit);
TestRule testRule = new TestRule()
.requestMatches(msg -> msg.getPayload().getPayloadCase().equals(PayloadCase.SEAL_REQUEST))
.drop();
addClientRule(managementRuntime0, testRule);
addClientRule(managementRuntime1, testRule);
// Since the fast loader will retrieve the tails from the head node,
// we need to drop all tail requests to hang the FastObjectLoaders
addServerRule(SERVERS.PORT_0, new TestRule().responseMatches(m -> {
if (m.getPayload().getPayloadCase().equals(ResponsePayloadMsg.PayloadCase.LOG_ADDRESS_SPACE_RESPONSE)) {
semaphore.release();
return true;
}
return false;
}).drop());
// Trigger an epoch change to trigger FastObjectLoader to run for sequencer bootstrap.
Layout layout1 = new Layout(layout);
layout1.setEpoch(layout1.getEpoch() + 1);
corfuRuntime.getLayoutView().getRuntimeLayout(layout1).sealMinServerSet();
corfuRuntime.getLayoutView().updateLayout(layout1, 1L);
assertThat(semaphore
.tryAcquire(2, PARAMETERS.TIMEOUT_LONG.toMillis(), TimeUnit.MILLISECONDS))
.isTrue();
// Create a fault - Epoch instability by just sealing the cluster but not filling the
// layout slot.
corfuRuntime.invalidateLayout();
Layout layout2 = new Layout(corfuRuntime.getLayoutView().getLayout());
layout2.setEpoch(layout2.getEpoch() + 1);
corfuRuntime.getLayoutView().getRuntimeLayout(layout2).sealMinServerSet();
clearClientRules(managementRuntime0);
clearClientRules(managementRuntime1);
for (int i = 0; i < PARAMETERS.NUM_ITERATIONS_MODERATE; i++) {
if (corfuRuntime.getLayoutView().getLayout().getEpoch() == layout2.getEpoch()) {
break;
}
corfuRuntime.invalidateLayout();
TimeUnit.MILLISECONDS.sleep(PARAMETERS.TIMEOUT_SHORT.toMillis());
}
// Assert that the DetectionWorker threads are freed from the deadlock and are able to fill
// up the layout slot and stabilize the cluster.
assertThat(corfuRuntime.getLayoutView().getLayout().getEpoch())
.isEqualTo(layout2.getEpoch());
clearServerRules(SERVERS.PORT_0);
// Once the rules are cleared, the detectors should resolve the epoch instability,
// bootstrap the sequencer and fetch a new token.
assertThat(corfuRuntime.getSequencerView().query()).isNotNull();
}
/**
* Tests the triggerSequencerReconfiguration method. The READ_RESPONSE messages are blocked by
* adding a rule to drop these. The reconfiguration task unblocks with the help of the
* systemDownHandler.
*/
@Test
public void unblockSequencerRecoveryOnDeadlock() throws Exception {
CorfuRuntime corfuRuntime = getDefaultRuntime();
final Layout layout = corfuRuntime.getLayoutView().getLayout();
// Setting aggressive timeouts
setAggressiveTimeouts(layout, corfuRuntime,
getManagementServer(SERVERS.PORT_0).getManagementAgent().getCorfuRuntime());
setAggressiveDetectorTimeouts(SERVERS.PORT_0);
final int sysDownTriggerLimit = 3;
getManagementServer(SERVERS.PORT_0).getManagementAgent().getCorfuRuntime().getParameters()
.setSystemDownHandlerTriggerLimit(sysDownTriggerLimit);
// Add rule to drop all read responses to hang the FastObjectLoaders.
addServerRule(SERVERS.PORT_0, new TestRule().responseMatches(m -> m.getPayload().getPayloadCase()
.equals(ResponsePayloadMsg.PayloadCase.READ_LOG_RESPONSE)).drop());
getManagementServer(SERVERS.PORT_0).getManagementAgent()
.getCorfuRuntime().getLayoutManagementView()
.asyncSequencerBootstrap(layout,
getManagementServer(SERVERS.PORT_0).getManagementAgent()
.getRemoteMonitoringService().getFailureDetectorWorker())
.get();
}
/**
* Tests that a degraded cluster heals a sealed cluster.
* NOTE: A sealed cluster without a layout causes the system to halt as none of the clients can
* perform data operations until the new epoch is filled in with a layout.
* Scenario: 3 nodes - PORT_0, PORT_1 and PORT_2.
* A server rule is added to simulate PORT_2 as unresponsive.
* First, the degraded cluster moves from epoch 1 to epoch 2 to mark PORT_2 unresponsive.
* Now, PORT_0 and PORT_1 are sealed to epoch 3.
* The fault detectors detect this and fills the epoch 3 with a layout.
*/
@Test
public void testSealedDegradedClusterHealing() throws Exception {
get3NodeLayout();
CorfuRuntime corfuRuntime = getDefaultRuntime();
addServerRule(SERVERS.PORT_2, new TestRule().always().drop());
for (int i = 0; i < PARAMETERS.NUM_ITERATIONS_MODERATE; i++) {
corfuRuntime.invalidateLayout();
if (!corfuRuntime.getLayoutView().getLayout().getUnresponsiveServers().isEmpty()) {
break;
}
TimeUnit.MILLISECONDS.sleep(PARAMETERS.TIMEOUT_VERY_SHORT.toMillis());
}
Layout layout = new Layout(corfuRuntime.getLayoutView().getLayout());
layout.setEpoch(layout.getEpoch() + 1);
corfuRuntime.getLayoutView().getRuntimeLayout(layout).sealMinServerSet();
for (int i = 0; i < PARAMETERS.NUM_ITERATIONS_MODERATE; i++) {
corfuRuntime.invalidateLayout();
if (corfuRuntime.getLayoutView().getLayout().getEpoch() == layout.getEpoch()) {
break;
}
TimeUnit.MILLISECONDS.sleep(PARAMETERS.TIMEOUT_VERY_SHORT.toMillis());
}
assertThat(corfuRuntime.getLayoutView().getLayout()).isEqualTo(layout);
}
/**
* Write a random entry to the specified CorfuTable.
*
* @param table CorfuTable to populate.
*/
private void writeRandomEntryToTable(CorfuTable table) {
Random r = new Random();
corfuRuntime.getObjectsView().TXBegin();
table.put(r.nextInt(), r.nextInt());
corfuRuntime.getObjectsView().TXEnd();
}
/**
* Test scenario where the sequencer bootstrap triggers cache cleanup causing maxConflictWildcard to be reset.
* The runtime requests for 2 tokens but persists only 1 log entry. On an epoch change, the failover sequencer
* (in this case, itself) is bootstrapped by running the fastObjectLoader.
* This bootstrap sets the token to 1 and maxConflictWildcard to 0. This test asserts that the maxConflictWildcard
* stays 0 even after the cache eviction and does not abort transactions with SEQUENCER_OVERFLOW cause.
*/
@Test
public void testSequencerCacheOverflowOnFailover() throws Exception {
corfuRuntime = getDefaultRuntime();
CorfuTable<String, String> table = corfuRuntime.getObjectsView().build()
.setTypeToken(new TypeToken<CorfuTable<String, String>>() {
})
.setStreamName("test")
.open();
writeRandomEntryToTable(table);
// Block the writes so that we only fetch a sequencer token but not persist the entry on the LogUnit.
addClientRule(corfuRuntime, new TestRule().requestMatches(m ->
m.getPayload().getPayloadCase().equals(PayloadCase.WRITE_LOG_REQUEST)).drop());
CompletableFuture<Boolean> future = CompletableFuture.supplyAsync(() -> {
writeRandomEntryToTable(table);
return true;
});
// Block any sequencer bootstrap attempts.
addClientRule(getManagementServer(SERVERS.PORT_0).getManagementAgent().getCorfuRuntime(), new TestRule()
.requestMatches(msg ->
msg.getPayload().getPayloadCase().equals(PayloadCase.BOOTSTRAP_SEQUENCER_REQUEST)).drop());
// Increment the sequencer epoch twice so that a full sequencer bootstrap is required.
incrementClusterEpoch(corfuRuntime);
Layout layout = incrementClusterEpoch(corfuRuntime);
// Clear rules to now allow sequencer bootstrap.
clearClientRules(getManagementServer(SERVERS.PORT_0).getManagementAgent().getCorfuRuntime());
while (getSequencer(SERVERS.PORT_0).getSequencerEpoch() != layout.getEpoch()) {
TimeUnit.MILLISECONDS.sleep(PARAMETERS.TIMEOUT_VERY_SHORT.toMillis());
}
clearClientRules(corfuRuntime);
// Attempt data operation.
// The data operation should fail if the maxConflictWildcard is updated on cache invalidation causing the
// the value to change.
writeRandomEntryToTable(table);
future.cancel(true);
}
/**
* Tests the partial bootstrap scenario while adding a new node.
* Starts with cluster of 1 node: PORT_0.
* We then bootstrap the layout server of PORT_1 with a layout.
* Then the bootstrapNewNode is triggered. This should detect the same layout and complete the bootstrap.
*/
@Test
public void testPartialBootstrapNodeSuccess() throws ExecutionException, InterruptedException {
corfuRuntime = getDefaultRuntime();
addServer(SERVERS.PORT_1);
Layout layout = corfuRuntime.getLayoutView().getLayout();
// Bootstrap the layout server.
corfuRuntime.getLayoutView().getRuntimeLayout().getLayoutClient(SERVERS.ENDPOINT_1).bootstrapLayout(layout);
// Attempt bootstrapping the node. The node should attempt bootstrapping both the components Layout Server and
// Management Server.
assertThat(corfuRuntime.getLayoutManagementView().bootstrapNewNode(SERVERS.ENDPOINT_1).get()).isTrue();
}
/**
* Tests the partial bootstrap scenario while adding a new node.
* Starts with cluster of 1 node: PORT_0.
* We then bootstrap the layout server of PORT_1 with a layout.
* A rule is added to prevent the management server from being bootstrapped. Then the bootstrapNewNode is
* triggered. This should pass, since the bootstrap new node function is a part of an add node workflow, that
* requires a management server to be bootstrapped.
*/
@Test
public void testPartialBootstrapNodeFailure() {
corfuRuntime = getDefaultRuntime();
addServer(SERVERS.PORT_1);
Layout layout = corfuRuntime.getLayoutView().getLayout();
// Bootstrap the layout server.
corfuRuntime.getLayoutView().getRuntimeLayout().getLayoutClient(SERVERS.ENDPOINT_1).bootstrapLayout(layout);
addClientRule(corfuRuntime, new TestRule().requestMatches(msg ->
msg.getPayload().getPayloadCase().equals(PayloadCase.BOOTSTRAP_MANAGEMENT_REQUEST)).drop());
assertThat(corfuRuntime.getLayoutManagementView().bootstrapNewNode(SERVERS.ENDPOINT_1).join()).isTrue();
}
}
| 45.655542 | 124 | 0.652722 |
40e73441bc58a0a144d45de67a4039178f5d73b6 | 421 | package com.miao.android.pictures.app;
import android.app.Application;
/**
* Created by Administrator on 2016/12/7.
*/
public class MyApplication extends Application {
private static MyApplication sMyApplication;
private static MyApplication getInstance(){
return sMyApplication;
}
@Override
public void onCreate() {
super.onCreate();
sMyApplication = this;
}
}
| 16.192308 | 48 | 0.679335 |
a6fa85e3203f657c8d9efec30a451c034af43071 | 862 | package org.github.xfactory;
class InfrastructureManager {
private static ThreadLocal<InfrastructureProvider> infrastructureProviderThreadLocal = new ThreadLocal<InfrastructureProvider>();
static void setInfrastructureProvider(InfrastructureProvider infrastructureProvider) {
infrastructureProviderThreadLocal.set(infrastructureProvider);
}
static void resetInfrastructureProvider() {
infrastructureProviderThreadLocal.set(null);
}
public static InfrastructureProvider getInfrastructureProvider() {
InfrastructureProvider infrastructureProvider = infrastructureProviderThreadLocal.get();
if (infrastructureProvider == null) {
throw new XFactoryException("InfrastructureProvider not set. Use XFactory.initTest() method to provide your implementation of the InfrastructureProvider to the XFactory");
}
return infrastructureProvider;
}
}
| 37.478261 | 174 | 0.834107 |
4a47f087307a5ec4d3dd0d12d89578a46d6db2b6 | 9,146 | /*
* Copyright 2017 Anton Mykolaienko.
*
* 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.fs.xml2json.core;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.stream.Stream;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.BDDMockito;
import org.mockito.Mockito;
/**
* Test for ApplicationProperties.
*
* @author Anton Mykolaienko
* @since 1.2.0
*/
public class ApplicationPropertiesTest {
private static final String DESTINATION_FOLDER = "ApplicationPropertiesFolder";
private static final String TEST_FILE = "testProps.txt";
private final List<File> filesToDelete = new ArrayList<>();
@Before
public void setUp() throws IOException {
File dir = getDestinationDirectory();
if (!dir.exists()) {
dir.mkdirs();
}
filesToDelete.add(dir);
Properties props = new Properties();
props.put("IntegerKey", String.valueOf(124545));
props.put("StringKey", "StringValue");
props.put("ShortKey", String.valueOf(127));
props.put("BinaryKey", String.valueOf(0b1111_1100));
try (OutputStream os = new FileOutputStream(new File(dir, TEST_FILE))) {
props.store(os, "");
}
}
@After
public void tearDown() {
filesToDelete.forEach(this::deleteFilesAndDirs);
}
void deleteFilesAndDirs(File file) {
if (file.isDirectory()) {
// delete from directory all files
Stream.of(file.listFiles()).forEach(f -> deleteFilesAndDirs(f));
file.delete();
} else {
file.delete();
}
}
@Test(expected = IllegalArgumentException.class)
public void testApplicationPropertiesWithNullLoader() {
ApplicationProperties props = new ApplicationProperties(null);
Assert.assertNull(props);
}
@Test(expected = IllegalArgumentException.class)
public void testApplicationPropertiesSetNullLoader() {
File propsFile = new File(getDestinationDirectory(), TEST_FILE);
ApplicationProperties props = new ApplicationProperties(new PropertiesLoader(propsFile));
Assert.assertNotNull(props);
props.setPropertiesLoader(null);
}
@Test
public void testApplicationPropertiesSetNotNullLoader() {
File propsFile = new File(getDestinationDirectory(), TEST_FILE);
PropertiesLoader loader = new PropertiesLoader(propsFile);
ApplicationProperties props = new ApplicationProperties(new PropertiesLoader(propsFile));
Assert.assertNotNull(props);
props.setPropertiesLoader(loader);
}
@Test
public void testGetPropertiesAndPathNotExists() {
File propsFile = new File(getDestinationDirectory(), TEST_FILE);
ApplicationProperties props = new ApplicationProperties(new PropertiesLoader(propsFile));
Assert.assertNotNull(props);
String path = props.getLastOpenedPath();
Assert.assertNull(path);
path = props.getLastOpenedPath();
Assert.assertNull(path);
}
@Test
public void testGetPropertiesAndPathIsEmpty() throws IOException {
File propsFile = new File(getDestinationDirectory(), TEST_FILE);
PropertiesLoader loader = new PropertiesLoader(propsFile);
ApplicationProperties appProps = new ApplicationProperties(loader);
Properties props = loader.load();
props.put(Config.LAST_DIRECTORY, "");
loader.saveProperties(props);
String path = appProps.getLastOpenedPath();
Assert.assertNull(path);
}
@Test
public void testGetPropertiesAndPathWithOnlySpaces() throws IOException {
File propsFile = new File(getDestinationDirectory(), TEST_FILE);
PropertiesLoader loader = new PropertiesLoader(propsFile);
ApplicationProperties appProps = new ApplicationProperties(loader);
Properties props = loader.load();
props.put(Config.LAST_DIRECTORY, " ");
loader.saveProperties(props);
String path = appProps.getLastOpenedPath();
Assert.assertNull(path);
}
@Test
public void testGetPropertiesAndPathIsNotExist() throws IOException {
File propsFile = new File(getDestinationDirectory(), TEST_FILE);
PropertiesLoader loader = new PropertiesLoader(propsFile);
ApplicationProperties appProps = new ApplicationProperties(loader);
Properties props = loader.load();
props.put(Config.LAST_DIRECTORY,
new File(propsFile.getParentFile(), "someNameFolder/file.txt").getAbsolutePath());
loader.saveProperties(props);
String path = appProps.getLastOpenedPath();
Assert.assertNull(path);
}
@Test
public void testGetPropertiesAndCorrectPath() throws IOException {
File propsFile = new File(getDestinationDirectory(), TEST_FILE);
PropertiesLoader loader = new PropertiesLoader(propsFile);
ApplicationProperties appProps = new ApplicationProperties(loader);
appProps.saveLastOpenedPath(propsFile);
String path = appProps.getLastOpenedPath();
Assert.assertEquals(propsFile.getParentFile().getAbsolutePath(), path);
}
@Test
public void testSaveLastPathTwice() throws IOException {
File propsFile = new File(getDestinationDirectory(), TEST_FILE);
PropertiesLoader loader = new PropertiesLoader(propsFile);
ApplicationProperties appProps = new ApplicationProperties(loader);
appProps.saveLastOpenedPath(new File(propsFile.getParentFile(), "someNameFolder/file.txt"));
String path = appProps.getLastOpenedPath();
Assert.assertNull(path);
appProps.saveLastOpenedPath(propsFile);
path = appProps.getLastOpenedPath();
Assert.assertEquals(propsFile.getParentFile().getAbsolutePath(), path);
}
@Test
public void testSaveLastPathTwiceSameValue() throws IOException {
File propsFile = new File(getDestinationDirectory(), TEST_FILE);
PropertiesLoader loader = new PropertiesLoader(propsFile);
ApplicationProperties appProps = new ApplicationProperties(loader);
appProps.saveLastOpenedPath(new File(propsFile.getParentFile(), "someNameFolder/file.txt"));
String path = appProps.getLastOpenedPath();
Assert.assertNull(path);
appProps.saveLastOpenedPath(propsFile);
// second save
appProps.saveLastOpenedPath(propsFile);
path = appProps.getLastOpenedPath();
Assert.assertEquals(propsFile.getParentFile().getAbsolutePath(), path);
}
@Test
public void testGetLastPathWithTabCharacter() throws IOException {
File propsFile = new File(getDestinationDirectory(), TEST_FILE);
PropertiesLoader loader = new PropertiesLoader(propsFile);
ApplicationProperties appProps = new ApplicationProperties(loader);
File lastOpenedFile = new File(propsFile.getParentFile(), File.separator + "newFolder"
+ File.separator + "testfile.txt");
if (!lastOpenedFile.getParentFile().exists()) {
lastOpenedFile.getParentFile().mkdirs();
filesToDelete.add(lastOpenedFile.getParentFile());
}
appProps.saveLastOpenedPath(lastOpenedFile.getAbsoluteFile());
String path = appProps.getLastOpenedPath();
Assert.assertNotNull(path);
Assert.assertEquals(lastOpenedFile.getParentFile().getAbsolutePath(), path);
}
@Test
public void testLoadWithException() throws IOException {
PropertiesLoader loader = Mockito.mock(PropertiesLoader.class);
BDDMockito.when(loader.load()).thenThrow(new IOException());
ApplicationProperties appProps = Mockito.spy(new ApplicationProperties(loader));
String path = appProps.getLastOpenedPath();
Assert.assertNull(path);
}
private File getDestinationDirectory() {
return new File(getTempDirectory(), DESTINATION_FOLDER);
}
private File getTempDirectory() {
return new File(System.getProperty("java.io.tmpdir"));
}
}
| 35.449612 | 100 | 0.669036 |
cf6b0b680df3ac2a431a51ad6587bc5122f8501c | 6,105 | package com.github.fujiyamakazan.zabuton.rakutenquest;
import java.awt.Color;
import java.io.Serializable;
import java.util.List;
import javax.swing.JFrame;
import org.apache.wicket.model.Model;
import org.apache.wicket.util.lang.Generics;
import com.github.fujiyamakazan.zabuton.util.jframe.JChoice;
import com.github.fujiyamakazan.zabuton.util.jframe.JChoiceElement;
import com.github.fujiyamakazan.zabuton.util.jframe.JChoicePage;
import com.github.fujiyamakazan.zabuton.util.jframe.JPage;
import com.github.fujiyamakazan.zabuton.util.jframe.component.JPageButton;
import com.github.fujiyamakazan.zabuton.util.jframe.component.JPageDelayLabel;
import com.github.fujiyamakazan.zabuton.util.jframe.component.JPageLink;
public class GameWindow<T extends Serializable> implements Serializable {
private static final long serialVersionUID = 1L;
@SuppressWarnings("unused")
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(GameWindow.class);
private String[] messages;
private final List<JChoiceElement<T>> choices = Generics.newArrayList();
private JChoiceElement<T> selected;
private RSounds sound;
public GameWindow(RSounds sound) {
this.sound = sound;
}
public void setMessage(String... messages) {
this.messages = messages;
}
public void addChoice(String label, T obj) {
choices.add(new JChoiceElement<T>(label, obj));
}
/**
* UIを表示します。
*/
public void show() {
JPage msgWindow = new RPage() {
private static final long serialVersionUID = 1L;
private JFrame msgWindowFrame;
@Override
protected JFrame createFrame() {
msgWindowFrame = super.createFrame();
return msgWindowFrame;
}
@Override
protected void onInitialize() {
super.onInitialize();
for (String msg : messages) {
addLine(new JPageDelayLabel(msg) {
private static final long serialVersionUID = 1L;
@Override
protected void sound() {
super.sound();
sound.soundClick();
}
});
}
}
@Override
protected void onAfterShow() {
super.onAfterShow();
JChoice<T> choice = new JChoice<T>("") {
private static final long serialVersionUID = 1L;
@Override
protected JPageButton createChoice(String label, Model<Boolean> model) {
return new JPageLink(label, model) {
private static final long serialVersionUID = 1L;
@Override
protected String getColor() {
return "#ffffff";
}
};
}
@Override
protected JPage createPage(String message, List<JPageButton> choices) {
JChoicePage choicePage = new JChoicePage("", choices) {
private static final long serialVersionUID = 1L;
// TODO カーソルキーが押されたら仮選択を移動する
// TODO Enterキーが押されたら仮選択をクリックとみなす
@Override
protected void settings() {
backgroundColor = Color.BLACK;
foregroundColer = Color.WHITE;
borderWidth = 0;
baseFont = RPage.FONT;
}
@Override
protected void onAfterShow() {
super.onAfterShow();
/* メッセージウィンドウ下部に表示します。 */
frame.setLocation(
msgWindowFrame.getLocation().x,
msgWindowFrame.getLocation().y
+ msgWindowFrame.getSize().height
+ 20);
// TODO 初期一番上を選択し、アンダーラインを入れる。
// TODO カーソルで選択可能とする
// TODO カーソル移動時にエフェクトを入れる
}
};
choicePage.setHorizonal(false);
return choicePage;
}
};
choice.addAllChoice(choices);
/* 表示 */
choice.showDialog();
/* 選択されたものを取得 */
selected = choice.getSelectedOne();
}
};
// AbstractAction myActionUpOrLeft = new AbstractAction() {
// private static final long serialVersionUID = 1L;
//
// @Override
// public void actionPerformed(ActionEvent e) {
// System.out.println("UPが押されました");
// }
// };
//
// KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
// choicePage.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ks, "VK_UP");
// choicePage.getRootPane().getActionMap().put("VK_UP", myActionUpOrLeft);
//
// msgWindow.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ks, "VK_UP");
// msgWindow.getRootPane().getActionMap().put("VK_UP", myActionUpOrLeft);
msgWindow.show();
msgWindow.dispose();
// // TODO マウスオーバーで仮選択とする
// // TODO 初期1件目を仮選択とする
// // TODO 仮選択されているときにアンダーラインを付ける
// // TODO 自身が選択されたら排他要素の仮選択を解除する
}
public T getSelected() {
if (this.selected != null) {
return this.selected.getObject();
}
return null;
}
}
| 33.916667 | 100 | 0.507617 |
f4904f6a10bf39e9f40389dce1081c55784ad62a | 408 | /**
* Written by Gideon Pfeffer
*/
package subUnits;
import Unit.Unit;
import javafx.scene.paint.Color;
public class Blank extends Unit{
private static final int BLANK_STATE = 2;
private static final Color COLOR = Color.WHITE;
/**
* sets the fill and state of the unit
*/
public Blank(Unit u){
super(u);
setFill(COLOR);
state = BLANK_STATE;
}
public Blank(){
this(new Unit());
}
}
| 15.692308 | 48 | 0.676471 |
c6fbccd770765a1a0f355602fa95e0bede33e2a3 | 1,043 | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
// buttom-up DP
public class Main {
public static void main(String[] args) throws IOException{
// set needed components
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] v = new int[n+1];
int[] a = new int[n+1];
// error-handling
if (n == 1) {
System.out.println(br.readLine());
br.close();
return;
}
if (n == 2){
System.out.println(Integer.parseInt(br.readLine())+Integer.parseInt(br.readLine()));
br.close();
return;
}
// get v
v[0] = 0;
for (int i = 1; i <= n; i++){
v[i] = Integer.parseInt(br.readLine());
}
// buttom-up DP
a[0] = 0; a[1] = v[1]; a[2] = v[1] + v[2];
for (int i = 3; i <= n; i++){
a[i] = Math.max(a[i-2], a[i-3]+v[i-1]) + v[i];
}
// print answer and end program
System.out.println(a[n]);
br.close();
return;
}
}
| 23.704545 | 90 | 0.552253 |
d2ee7c9a571ea37dc3214b573034727acba4030d | 373 | package ui;
import pieces.Piece;
/**
* maps a piece to the path of its icon
* @author jakobbussas
*
*/
public class IconMapper
{
public static String pieceToIcon(Piece piece) {
String path = piece.isColor() ? "white" : "black";
path += "_";
path += piece.getClass().getName().split("\\.")[1];
path += ".png";
path = path.toLowerCase();
return path;
}
}
| 17.761905 | 53 | 0.627346 |
7fbf98e0c4f27ca2661c2d9926f9755a9720693d | 7,238 | package nl.wernerdegroot.applicatives.processor.domain.typeconstructor;
import com.google.testing.compile.Compilation;
import com.google.testing.compile.Compiler;
import com.google.testing.compile.JavaFileObjects;
import nl.wernerdegroot.applicatives.processor.domain.FullyQualifiedName;
import nl.wernerdegroot.applicatives.processor.domain.TypeParameterName;
import nl.wernerdegroot.applicatives.processor.domain.type.ArrayType;
import nl.wernerdegroot.applicatives.processor.domain.type.GenericType;
import nl.wernerdegroot.applicatives.processor.domain.type.Type;
import nl.wernerdegroot.applicatives.processor.generator.TypeGenerator;
import org.junit.jupiter.api.Test;
import javax.tools.JavaFileObject;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
import java.util.stream.Stream;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.toList;
import static nl.wernerdegroot.applicatives.processor.domain.type.Type.LIST;
import static nl.wernerdegroot.applicatives.processor.domain.type.Type.STRING;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class TypeConstructorTest {
public static TypeParameterName T = TypeParameterName.of("T");
private final FullyQualifiedName ERUDITE = new FullyQualifiedName("nl.wernerdegroot.Erudite");
private final ConcreteTypeConstructor STRING_TYPE_CONSTRUCTOR = new ConcreteTypeConstructor(FullyQualifiedName.of("java.lang.String"), emptyList());
private final ConcreteTypeConstructor INTEGER_TYPE_CONSTRUCTOR = new ConcreteTypeConstructor(FullyQualifiedName.of("java.lang.Integer"), emptyList());
private final PlaceholderTypeConstructor placeholder = TypeConstructor.placeholder();
@Test
public void apply() {
Type expected = new ArrayType(new GenericType(T));
Type toVerify = new ArrayTypeConstructor(new PlaceholderTypeConstructor()).apply(T);
assertEquals(expected, toVerify);
}
@Test
public void array() {
ArrayTypeConstructor expected = new ArrayTypeConstructor(new PlaceholderTypeConstructor());
ArrayTypeConstructor toVerify = new PlaceholderTypeConstructor().array();
assertEquals(expected, toVerify);
}
@Test
public void generic() {
GenericTypeConstructor expected = new GenericTypeConstructor(T);
GenericTypeConstructor toVerify = TypeConstructor.generic(T);
assertEquals(expected, toVerify);
}
@Test
public void concreteGivenFullyQualifiedNameAndListOfTypeArguments() {
ConcreteTypeConstructor expected = new ConcreteTypeConstructor(ERUDITE, asList(STRING_TYPE_CONSTRUCTOR.invariant(), TypeConstructor.placeholder().covariant(), INTEGER_TYPE_CONSTRUCTOR.contravariant()));
ConcreteTypeConstructor toVerify = TypeConstructor.concrete(ERUDITE, STRING_TYPE_CONSTRUCTOR.invariant(), TypeConstructor.placeholder().covariant(), INTEGER_TYPE_CONSTRUCTOR.contravariant());
assertEquals(expected, toVerify);
}
@Test
public void concreteGivenFullyQualifiedNameAndTypeArguments() {
ConcreteTypeConstructor expected = new ConcreteTypeConstructor(ERUDITE, asList(STRING_TYPE_CONSTRUCTOR.invariant(), TypeConstructor.placeholder().covariant(), INTEGER_TYPE_CONSTRUCTOR.contravariant()));
ConcreteTypeConstructor toVerify = TypeConstructor.concrete(ERUDITE, STRING_TYPE_CONSTRUCTOR.invariant(), TypeConstructor.placeholder().covariant(), INTEGER_TYPE_CONSTRUCTOR.contravariant());
assertEquals(expected, toVerify);
}
@Test
public void concreteGivenFullyQualifiedName() {
ConcreteTypeConstructor expected = new ConcreteTypeConstructor(ERUDITE, emptyList());
ConcreteTypeConstructor toVerify = TypeConstructor.concrete(ERUDITE);
assertEquals(expected, toVerify);
}
@Test
public void arrayGivenElementTypeConstructor() {
ArrayTypeConstructor expected = new ArrayTypeConstructor(STRING_TYPE_CONSTRUCTOR);
ArrayTypeConstructor toVerify = TypeConstructor.array(STRING_TYPE_CONSTRUCTOR);
assertEquals(expected, toVerify);
}
@Test
public void placeholder() {
PlaceholderTypeConstructor expected = new PlaceholderTypeConstructor();
PlaceholderTypeConstructor toVerify = TypeConstructor.placeholder();
assertEquals(expected, toVerify);
}
@Test
public void canAccept() {
// This test covers some interesting test cases that are not easily covered by
// a test in one of the subclasses of `TypeConstructor`. These test cases check
// if the subclasses work well together, and perform their function as expected.
List<TypeConstructor> sources = Stream.of(
withList(withVariance(withList(withVariance(placeholders())))),
withList(withVariance(withArray(placeholders()))),
withArray(withList(withVariance(placeholders())))
).reduce(Stream.empty(), Stream::concat).collect(toList());
List<TypeConstructor> targets = sources;
for (TypeConstructor source : sources) {
for (TypeConstructor target : targets) {
verify(target, source);
}
}
}
private Stream<TypeConstructor> placeholders() {
return Stream.of(TypeConstructor.placeholder());
}
private Stream<TypeConstructorArgument> withVariance(Stream<TypeConstructor> s) {
return s.flatMap(typeConstructor -> Stream.of(typeConstructor.invariant(), typeConstructor.covariant(), typeConstructor.contravariant()));
}
private Stream<TypeConstructor> withList(Stream<TypeConstructorArgument> s) {
return s.map(LIST::with);
}
private Stream<TypeConstructor> withArray(Stream<TypeConstructor> s) {
return s.map(typeConstructor -> typeConstructor.array());
}
private void verify(TypeConstructor target, TypeConstructor source) {
StringWriter writer = new StringWriter();
PrintWriter out = new PrintWriter(writer);
out.println("class Testing {");
out.println(" void testing() {");
out.println(" " + TypeGenerator.generateFrom(source.apply(STRING)) + " source = null;");
out.println(" " + TypeGenerator.generateFrom(target.apply(STRING)) + " target = source;");
out.println(" }");
out.println("}");
String classBody = writer.toString();
JavaFileObject javaFileObject = JavaFileObjects.forSourceString("Testing", classBody);
Compilation result = Compiler.javac().compile(javaFileObject);
boolean compiles = result.status() == Compilation.Status.SUCCESS;
boolean canAccept = target.canAccept(source);
assertEquals(compiles, canAccept, String.format("Assign %s to %s", typeConstructorToString(source), typeConstructorToString(target)));
}
private String typeConstructorToString(TypeConstructor typeConstructor) {
Type substituteForPlaceholder = FullyQualifiedName.of("*").asType();
Type typeConstructorAsType = typeConstructor.apply(substituteForPlaceholder);
return TypeGenerator.generateFrom(typeConstructorAsType);
}
}
| 44.404908 | 210 | 0.740398 |
0f65e3e710d283c03fb9de51c8e7da5585d7b7d2 | 2,120 | package cz.zcu.kiv.mobile.logger.devices;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.view.MenuItem;
import android.view.View;
import cz.zcu.kiv.mobile.logger.R;
import cz.zcu.kiv.mobile.logger.common.UserActivity;
import cz.zcu.kiv.mobile.logger.data.types.NamedClass;
public abstract class APagerActivity extends UserActivity {
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link android.support.v4.app.FragmentPagerAdapter} derivative, which will
* keep every loaded fragment in memory. If this becomes too memory intensive,
* it may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private UserPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
private View pagerTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activities_pager);
// Show the Up button in the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);
mViewPager = (ViewPager) findViewById(R.id.pager);
pagerTitle = findViewById(R.id.pager_title_strip);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new UserPagerAdapter(getSupportFragmentManager(), userProfile.getId(), getDataPages());
// Set up the ViewPager with the sections adapter.
mViewPager.setAdapter(mSectionsPagerAdapter);
if(mSectionsPagerAdapter.getCount() == 1) {
pagerTitle.setVisibility(View.GONE);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
protected abstract NamedClass[] getDataPages();
}
| 31.641791 | 115 | 0.733019 |
76349d5dc41156afc1047c58dd16de1e6bf3bc54 | 1,930 | package edu.teco.dustradarnonegame.sensorthings.geojson;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
abstract public class GeoEntity implements Serializable {
// private members
private String type = null;
private List coordinates = null;
// constructors
protected GeoEntity(String type) {
this.type = type;
}
protected GeoEntity(GeoEntity old) {
this.type = old.getType();
this.coordinates = (List) deepCopy(old.getCoordinates());
}
// public methods
public String getType() {
return type;
}
public List getCoordinates() {
return coordinates;
}
public void setCoordinates(List coordinates) {
this.coordinates = coordinates;
}
public String toJson() {
Gson gson = new Gson();
return gson.toJson(this);
}
// static methods
public static List<Double> createPoint(double longitude, double latitude) {
List<Double> list = new ArrayList<>();
list.add(longitude);
list.add(latitude);
return list;
}
public static List<Double> createPoint(double longitude, double latitude, double height) {
List<Double> list = createPoint(longitude, latitude);
list.add(height);
return list;
}
// protected methods
protected void insertCoordinate(Object element) {
if (coordinates == null) {
coordinates = new ArrayList();
}
coordinates.add(element);
}
protected Object deepCopy(Object old) {
if (old == null) {
return null;
}
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.serializeNulls();
Gson gson = gsonBuilder.create();
return gson.fromJson(gson.toJson(old), old.getClass());
}
}
| 20.752688 | 94 | 0.623316 |
19a92b29f7581dd2168dd9866048b8aaf9c3689f | 2,508 | package dev.vality.magista.dao.impl;
import dev.vality.magista.*;
import dev.vality.magista.config.PostgresqlSpringBootITest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.jdbc.Sql;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
@PostgresqlSpringBootITest
@Sql("classpath:data/sql/search/payouts_search_data.sql")
public class PayoutsSearchDaoImplTest {
@Autowired
private SearchDaoImpl searchDao;
@Test
public void testPayouts() {
PayoutSearchQuery payoutSearchQuery = buildPayoutSearchQuery();
List<StatPayout> payouts = searchDao.getPayouts(payoutSearchQuery);
assertEquals(4, payouts.size());
}
@Test
public void shouldFilterByBankAccount() {
PayoutSearchQuery payoutSearchQuery = buildPayoutSearchQuery();
payoutSearchQuery.setPayoutType(PayoutToolType.payout_account);
List<StatPayout> payouts = searchDao.getPayouts(payoutSearchQuery);
assertEquals(2, payouts.size());
}
@Test
public void shouldFilterByWalletInfo() {
PayoutSearchQuery payoutSearchQuery = buildPayoutSearchQuery();
payoutSearchQuery.setPayoutType(PayoutToolType.wallet);
List<StatPayout> payouts = searchDao.getPayouts(payoutSearchQuery);
assertEquals(1, payouts.size());
}
@Test
public void shouldFilterByPaymentInstitutionAccount() {
PayoutSearchQuery payoutSearchQuery = buildPayoutSearchQuery();
payoutSearchQuery.setPayoutType(PayoutToolType.payment_institution_account);
List<StatPayout> payouts = searchDao.getPayouts(payoutSearchQuery);
assertEquals(1, payouts.size());
}
@Test
public void shouldFilterByUnpaid() {
PayoutSearchQuery payoutSearchQuery = buildPayoutSearchQuery();
payoutSearchQuery.setPayoutStatusTypes(List.of(PayoutStatusType.unpaid));
List<StatPayout> payouts = searchDao.getPayouts(payoutSearchQuery);
assertEquals(2, payouts.size());
}
private PayoutSearchQuery buildPayoutSearchQuery() {
return new PayoutSearchQuery()
.setCommonSearchQueryParams(new CommonSearchQueryParams()
.setPartyId("PARTY_ID_1")
.setShopIds(List.of("SHOP_ID_1"))
.setFromTime("2016-10-25T15:45:20Z")
.setToTime("3018-10-25T18:10:10Z"));
}
}
| 35.828571 | 84 | 0.711324 |
0a007d163f7c2f0c48eda5433cfd610e0bb96acc | 3,723 | /*
* Copyright © 2019 admin ([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 org.infrastructurebuilder.deployment.tf;
import static java.util.Objects.requireNonNull;
import java.util.Optional;
import javax.inject.Inject;
import javax.inject.Named;
import org.json.JSONArray;
@Named
public class DefaultTFFormatter implements TFFormatter {
private static final String INDENT = " ";
private final StringBuffer sb = new StringBuffer();
private int currentIndent = 0;
private final TFObject<?> resource;
private final TFFormatter specificFormatter;
@Inject
public DefaultTFFormatter(TFObject<?> resource, TFFormatterFactory rf) {
this.resource = requireNonNull(resource);
this.specificFormatter = requireNonNull(rf).getSpecificFormatterFor(Optional.of(this), this.resource);
}
@Override
public String specificFormat() {
return sb.toString();
}
@Override
public TFFormatter addQuotedString(final String str) {
indent().append("\"").append("" + str).append("\"");
return this;
}
@Override
public TFFormatter addString(final String str) {
indent().append(str);
return this;
}
@Override
public TFFormatter addNamedArray(final String name, final JSONArray array) {
indent();
addString(name).addString(" = ");
for (String str : (requireNonNull(array)).toString(2).split("\n")) {
addString(str);
}
return this;
}
@Override
public TFFormatter addComment(final String comment) {
indent().append("#").append(" " + comment).append("\n");
return this;
}
@Override
public int getCurrentIndent() {
return currentIndent;
}
@Override
public TFFormatter incrementIndent() {
this.currentIndent++;
return this;
}
@Override
public TFFormatter decrementIndent() {
this.currentIndent--;
return this;
}
@Override
public TFFormatter addHereDoc(final String hereDoc) {
//we might not need someting so unique per-instance, EOF might work but would cause the generated code to be different each time
String hdStringHeader = "EOF"; // FIXME UUID.randomUUID().toString().replace("-", "_");
sb.append("<<").append(hdStringHeader).append("\n")
// add hereDoc unformatted
.append(hereDoc)
// Close it
.append("\n").append(hdStringHeader).append("\n");
return this;
}
private StringBuffer indent() {
for (int i = 0; i < this.currentIndent; ++i)
sb.append(INDENT);
return sb;
}
@Override
public final TFFormatter resource() {
return addString("resource ")
// Std format for a resource is "type" "name"
.addQuotedString(this.resource.getType().toString()).addString(" ").addQuotedString(this.resource.getName())
// Open the specific parts for this resource
.addString(" {\n")
// First increment the indentation
.incrementIndent()
// Format this specific resource
.addString(this.specificFormatter.specificFormat())
// the decrement the indentation
.decrementIndent()
// Close out the resource
.addString("\n}\n").addComment("### " + this.resource.getName());
}
}
| 29.314961 | 132 | 0.683857 |
7fcd9f9b4c51fa6faef44bc80921efb48694a498 | 2,918 | /*
* JasperReports - Free Java Reporting Library.
* Copyright (C) 2001 - 2019 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is part of JasperReports.
*
* JasperReports 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.
*
* JasperReports 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with JasperReports. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.jasperreports.export;
import net.sf.jasperreports.annotations.properties.Property;
import net.sf.jasperreports.annotations.properties.PropertyScope;
import net.sf.jasperreports.engine.JRPropertiesUtil;
import net.sf.jasperreports.export.annotations.ExporterProperty;
import net.sf.jasperreports.properties.PropertyConstants;
/**
* Interface containing settings used by the JSON Metadata exporter.
*
* @see net.sf.jasperreports.engine.export.JsonMetadataExporter
*
* @author Narcis Marcu ([email protected])
*/
public interface JsonMetadataReportConfiguration extends JsonReportConfiguration {
/**
* Property whose value is used as default for the {@link #isEscapeMembers()} export configuration setting.
* <p>
* The property itself defaults to <code>true</code>.
* </p>
*
* @see net.sf.jasperreports.engine.JRPropertiesUtil
*/
@Property(
category = PropertyConstants.CATEGORY_EXPORT,
defaultValue = PropertyConstants.BOOLEAN_TRUE,
scopes = {PropertyScope.REPORT},
sinceVersion = PropertyConstants.VERSION_6_0_0,
valueType = Boolean.class
)
public static final String JSON_EXPORTER_ESCAPE_MEMBERS = JRPropertiesUtil.PROPERTY_PREFIX + "export.json.escape.members";
/**
* Property whose value is used as default for the {@link #getJsonSchemaResource()} export configuration setting.
*
* @see net.sf.jasperreports.engine.JRPropertiesUtil
*/
@Property(
category = PropertyConstants.CATEGORY_EXPORT,
scopes = {PropertyScope.REPORT},
sinceVersion = PropertyConstants.VERSION_6_0_0
)
public static final String JSON_EXPORTER_JSON_SCHEMA = JRPropertiesUtil.PROPERTY_PREFIX + "export.json.schema";
/**
*
*/
@ExporterProperty(
value=JSON_EXPORTER_ESCAPE_MEMBERS,
booleanDefault=true
)
public Boolean isEscapeMembers();
/**
*
*/
@ExporterProperty(value=JSON_EXPORTER_JSON_SCHEMA)
public String getJsonSchemaResource();
}
| 32.786517 | 123 | 0.76525 |
df0fb9128edc33f17328d240a463db1e8a6f7733 | 1,047 | /*****************************************************************************
* Copyright (C) The Apache Software Foundation. All rights reserved. *
* ------------------------------------------------------------------------- *
* This software is published under the terms of the Apache Software License *
* version 1.1, a copy of which has been included with this distribution in *
* the LICENSE file. *
*****************************************************************************/
package org.apache.cocoon.selection;
import org.apache.avalon.framework.activity.Initializable;
/**
* @version CVS $Revision: 1.2 $ $Date: 2002/01/11 17:07:06 $
* @deprecated Replaced by RequestParameterSelector - code factories should no longer be used
*/
public class RequestSelectorFactory extends RequestSelector implements Initializable {
public void initialize() {
getLogger().warn("RequestSelectorFactory is deprecated. Please use RequestParameterSelector");
}
}
| 45.521739 | 102 | 0.537727 |
8c243cb6dfade516d37a4f16bca84ed41b948298 | 1,485 | /*
* Copyright 2021 ICON Foundation
*
* 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 example.util;
import score.ObjectReader;
import score.ObjectWriter;
import java.math.BigInteger;
public class IntSet {
private final String id;
private final EnumerableSet<BigInteger> set;
public IntSet(String id) {
this.id = id;
this.set = new EnumerableSet<>(id, BigInteger.class);
}
// for serialize
public static void writeObject(ObjectWriter w, IntSet e) {
w.write(e.id);
}
// for de-serialize
public static IntSet readObject(ObjectReader r) {
return new IntSet(
r.readString()
);
}
public int length() {
return set.length();
}
public BigInteger at(int index) {
return set.at(index);
}
public void add(BigInteger value) {
set.add(value);
}
public void remove(BigInteger value) {
set.remove(value);
}
}
| 24.344262 | 75 | 0.659259 |
22e957a1ced8c801ec6a5c3ca97d4e124c6b06d4 | 182 | package sqlite.feature.relations.error5;
import com.abubusoft.kripton.android.annotation.BindDao;
@BindDao(Channel.class)
public interface DaoChannel extends DaoBase<Channel> {
}
| 20.222222 | 56 | 0.818681 |
3ac9a1721d85cbea4291e1c172bef96900d51b8e | 1,891 | package contest.usaco_other;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
/*
ID: jeffrey40
LANG: JAVA
TASK: friday
*/
import java.util.StringTokenizer;
public class friday {
static BufferedReader br;
static PrintWriter pr;
static StringTokenizer st;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new FileReader("friday.in"));
pr = new PrintWriter(new BufferedWriter(new FileWriter("friday.out")));
int year = 1900;
int month = 1;
int day = 0;
int n = readInt();
int[] freq = new int[7];
while (year != 1900 + n - 1 || month != 13) {
day %= 7;
freq[day]++;
if (month > 12) {
year++;
month = 1;
}
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
day += 31;
else if (month == 4 || month == 6 || month == 9 || month == 11)
day += 30;
else if (month == 2 && year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))
day += 29;
else
day += 28;
month++;
}
for (int x = 0; x < 7; x++) {
pr.print(freq[x] + (x == 6 ? "" : " "));
}
pr.println();
pr.close();
System.exit(0);
}
static String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine().trim());
return st.nextToken();
}
static long readLong() throws IOException {
return Long.parseLong(next());
}
static int readInt() throws IOException {
return Integer.parseInt(next());
}
static double readDouble() throws IOException {
return Double.parseDouble(next());
}
static String readLine() throws IOException {
return br.readLine().trim();
}
}
| 24.24359 | 107 | 0.578001 |
228a67950d436cc6a2bfa119d66ad9319d51ef1a | 1,488 | /**
* @Company 青鸟软通
* @Title: UserSimpleListParam.java
* @Package org.bana.wechat.qy.user.param
* @author Liu Wenjie
* @date 2015-5-11 下午9:16:05
* @version V1.0
*/
package org.bana.wechat.qy.user.param;
import org.bana.wechat.qy.common.WeChatParam;
/**
* @ClassName: UserSimpleListParam
* @Description: 获取简单集合对象的参数
*
*/
public class UserListParam extends WeChatParam {
private Integer department_id;//获取的部门id
private String fetch_child;//1/0:是否递归获取子部门下面的成员
private String status;//0获取全部成员,1获取已关注成员列表,2获取禁用成员列表,4获取未关注成员列表。status可叠加
/**
* @Description: 属性 department_id 的get方法
* @return department_id
*/
public Integer getDepartment_id() {
return department_id;
}
/**
* @Description: 属性 department_id 的set方法
* @param department_id
*/
public void setDepartment_id(Integer department_id) {
this.department_id = department_id;
}
/**
* @Description: 属性 fetch_child 的get方法
* @return fetch_child
*/
public String getFetch_child() {
return fetch_child;
}
/**
* @Description: 属性 fetch_child 的set方法
* @param fetch_child
*/
public void setFetch_child(String fetch_child) {
this.fetch_child = fetch_child;
}
/**
* @Description: 属性 status 的get方法
* @return status
*/
public String getStatus() {
return status;
}
/**
* @Description: 属性 status 的set方法
* @param status
*/
public void setStatus(String status) {
this.status = status;
}
}
| 22.208955 | 75 | 0.667339 |
2edda3ab9ae57d88d454db0936ccb04d8550d883 | 260 | package be.yannickdeturck.lagomshop.item.impl;
import com.lightbend.lagom.javadsl.persistence.AggregateEventTag;
public class ItemEventTag {
public static final AggregateEventTag<ItemEvent> INSTANCE =
AggregateEventTag.of(ItemEvent.class);
}
| 28.888889 | 65 | 0.788462 |
944a1baf54201b5a7d2a83b8c819782c56ac229a | 2,003 | /*
* Copyright 2007-2021, CIIC Guanaitong, Co., Ltd.
* All rights reserved.
*/
package com.gat.open.sdk.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.math.BigDecimal;
/**
* @author xin.hua
* date 2017/7/18
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class EnterpriseAccount {
/**
* account_openid : suw7l4W82D7+Eni2T7K+kw==
* balance : 77540391
* is_basic : 1
* name : 基本户
* status : 1
* type : 1
*/
@JsonProperty("account_openid")
private String accountOpenid;
private BigDecimal balance;
@JsonProperty("is_basic")
private int basic;
private String name;
private int status;
private int type;
public String getAccountOpenid() {
return accountOpenid;
}
public void setAccountOpenid(String accountOpenid) {
this.accountOpenid = accountOpenid;
}
public BigDecimal getBalance() {
return balance;
}
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
public int getBasic() {
return basic;
}
public void setBasic(int basic) {
this.basic = basic;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
@Override
public String toString() {
return "EnterpriseAccount{" +
"accountOpenid='" + accountOpenid + '\'' +
", balance=" + balance +
", basic=" + basic +
", name='" + name + '\'' +
", status=" + status +
", type=" + type +
'}';
}
}
| 20.438776 | 61 | 0.571143 |
6e9513b1a41ed6c3ceb172af8e5002e8100e5b34 | 2,051 | package crazypants.enderio.machine.power;
import java.text.NumberFormat;
import crazypants.enderio.Config;
import crazypants.util.Lang;
public class PowerDisplayUtil {
public static enum PowerType {
MJ(1, "power.mj"),
RF(10, "power.rf");
private final double ratio;
private final String abr;
private PowerType(double ratio, String abr) {
this.ratio = ratio;
this.abr = abr;
}
String abr() {
return Lang.localize(abr);
}
double toDisplayValue(double powerMJ) {
return powerMJ * ratio;
}
double fromDisplayValue(double powerDisplayed) {
return powerDisplayed / ratio;
}
}
private static final NumberFormat INT_NF = NumberFormat.getIntegerInstance();
private static final NumberFormat FLOAT_NF = NumberFormat.getInstance();
private static PowerType currentPowerType = Config.useRfAsDefault ? PowerType.RF : PowerType.MJ;
public static String perTickStr() {
return Lang.localize("power.tick");
}
public static String ofStr() {
return Lang.localize("gui.powerMonitor.of");
}
static {
FLOAT_NF.setMinimumFractionDigits(1);
FLOAT_NF.setMaximumFractionDigits(1);
}
public static String formatPower(double powerMJ) {
return INT_NF.format(currentPowerType.toDisplayValue(powerMJ));
}
public static Float parsePower(String power) {
if(power == null) {
return null;
}
try {
Number d = FLOAT_NF.parse(power);
if(d == null) {
return null;
}
return (float) currentPowerType.fromDisplayValue(d.doubleValue());
} catch (Exception e) {
return null;
}
}
public static String formatPowerFloat(double powerMJ) {
if(currentPowerType == PowerType.RF) {
return formatPower(powerMJ);
}
return FLOAT_NF.format(currentPowerType.toDisplayValue(powerMJ));
}
public static String abrevation() {
return currentPowerType.abr();
}
public static int fromDisplay(int input) {
return (int) currentPowerType.fromDisplayValue(input);
}
}
| 23.044944 | 98 | 0.684057 |
7e3d5f9a6ab0a5295f7bcf095685314ba495738d | 5,132 | package com.tomtom.gradsoundcloud.domain.profile.datasource;
import android.support.annotation.NonNull;
import com.tomtom.gradsoundcloud.domain.profile.model.User;
import com.tomtom.gradsoundcloud.view.profile.ProfileErrors;
import com.tomtom.gradsoundcloud.util.StringUtil;
import java.util.ArrayList;
import java.util.List;
import static com.google.gson.internal.$Gson$Preconditions.checkNotNull;
/**
* Repository layer that decides whether to get data from a cache or from network
* Implements UserDataSource which allows it to delegate the operations to the actual implementations
*
* @see UserDataSource
* @see com.tomtom.gradsoundcloud.domain.profile.datasource.local.UserLocalDataSource
* @see UserRemoteDataSource
*/
public class UserRepo implements UserDataSource {
private static final String TAG = UserRepo.class.getSimpleName();
private static UserRepo INSTANCE = null;
private final UserDataSource mUserLocalDataSource;
private final UserRemoteDataSource mUserRemoteDataSource;
private String selectedUserId;
private List<UserRepoObserver> mObservers = new ArrayList<UserRepoObserver>();
/**
* Gets single instance of class.
*
* @param localDataSource the tasks local data source
* @param remoteDataSource the remote data source
* @param selectedUserId the selected user id
* @return the instance
*/
public static UserRepo getInstance(UserDataSource localDataSource, UserRemoteDataSource remoteDataSource, String selectedUserId) {
if (INSTANCE == null) {
INSTANCE = new UserRepo(localDataSource, remoteDataSource, selectedUserId);
}
return INSTANCE;
}
private UserRepo(@NonNull UserDataSource userDataSource, UserRemoteDataSource mUserRemoteDataSource, String selectedUserId) {
this.mUserRemoteDataSource = mUserRemoteDataSource;
this.selectedUserId = selectedUserId;
mUserLocalDataSource = checkNotNull(userDataSource);
}
/**
* Add observers to the repo, used for ui updates
*
* @param observer the observer
*/
public void addContentObserver(UserRepoObserver observer) {
if (!mObservers.contains(observer)) {
mObservers.add(observer);
}
}
/**
* Removes Content observers from repo
*
* @param observer the observer
*/
public void removeContentObserver(UserRepoObserver observer) {
if (mObservers.contains(observer)) {
mObservers.remove(observer);
}
}
/**
* Notifies a observers a change has occured
* Allows UI to be updated
*/
private void notifyContentObserver() {
for (UserRepoObserver observer : mObservers) {
observer.onUserInfoChange();
}
}
@Override
public User getUser(@NonNull String userId) {
checkNotNull(userId);
User user = mUserLocalDataSource.getUser(userId);
if (user == null) {
user = mUserRemoteDataSource.getUser(userId);
if (user != null && user.getError() != null) {
return user;
} else if (user != null) {
//user isnt null, lets make a local copy
mUserLocalDataSource.deleteUser(userId);//delete if exists
mUserLocalDataSource.saveUser(user);//save new
}
}
if (user == null) {
return new User(ProfileErrors.NULL_USER);
}
//change the user to selected user
if (StringUtil.isNullorEmpty(selectedUserId)) {
selectedUserId = userId;
}
return user;
}
@Override
public User getSelectedUser() {
if (StringUtil.isNullorEmpty(selectedUserId)) {
return new User(ProfileErrors.NO_USER_SELECTED);
}
return getUser(selectedUserId);
}
@Override
public void saveUser(@NonNull User user) {
checkNotNull(user);
mUserLocalDataSource.saveUser(user);
notifyContentObserver();
}
@Override
public void deleteUser(@NonNull String userId) {
checkNotNull(userId);
mUserLocalDataSource.deleteUser(userId);
notifyContentObserver();
}
@Override
public void deleteSelectedUser() {
if (StringUtil.isNullorEmpty(selectedUserId)) {
return;
}
deleteUser(selectedUserId);
selectedUserId = null;
}
@Override
public void refreshUser() {
notifyContentObserver();
}
@Override
public void changeSelectedUser(String id) {
if (StringUtil.isNotNullAndNotEmpty(id)) {
selectedUserId = id;
}
}
public static void destroyInstance() {
INSTANCE = null;
}
/**
* The interface User repo observer.
*/
public interface UserRepoObserver {
/**
* On tasks changed.
*/
void onUserInfoChange();
}
}
| 30.188235 | 135 | 0.630553 |
96bd5d41ad4a3a73b4975e8c1c4e530b95bd7d9b | 12,677 | package com.gbsofts.gbcrypt.crypto;
import com.gbsofts.gbcrypt.util.FileUtil;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Random;
import java.util.UUID;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import org.streetjava.exception.SJErrorCode;
import org.streetjava.exception.SJException;
/**
* This class describes the sequence of crypto operators which have combined.
*
* @author Luong Dang Dung
*/
public class MixedCryptography implements Cryptographal {
private final AsymCryptographal crypto;
public MixedCryptography(AsymCryptographal _crypto) {
crypto = _crypto;
}
/**
* EncryptFile process <br/>
* 0.1 Generate SHA1 checksum bytes of Input <br/>
* 1. Generate params of Blowfish <br/>
* 2. Encrypte params of Blowfish --> params1 <br/>
* 3. Generate params of AES <br/>
* 4. Encrypt params of AES --> params2 <br/>
* 5. Encrypt content using Blowfish --> content1 <br/>
* 6. Get Blowfish IV bytes <br/>
* 7. Encrypt Bloswfish IV bytes <br/>
* 8. Encrypt content1 using AES --> content2 <br/>
* 9. Get AES IV bytes <br/>
* 10. Encrypt AES IV bytes <br/>
* 10.1 Write SHA1 checksum length to outputfile <br/>
* 10.2 Write SHA1 checksym bytes to output file <br/>
* 11. Write params1(s) length to outputfile <br/>
* 12. Write params2(s) length to outputfile <br/>
* 13. Write params1(s) to outputfile <br/>
* 14. Write params2(s) to outputfile <br/>
* 15. Write content2 to outputfile <br/>
* 16. Flush and close outfile <br/>
*
*
* @param inputFile
* @param outputFile
* @throws SJException
*/
public byte[] encrypt(byte[] inputBytes) throws SJException {
try {
//0.1 Generate SHA1 checksum bytes of Input
byte[] sha1checksum = FileUtil.CHECKSUM_BYTE_SHA1(inputBytes);
//1. Generate params of Blowfish
KeyGenerator keygenerator = KeyGenerator.getInstance("Blowfish");
SecretKey secretkey = keygenerator.generateKey();
//2. Encrypte params of Blowfish --> params1
byte[] blowfishKeyBytes = secretkey.getEncoded();
byte[] blowfishKeyEncryptedBytes = crypto.encrypt(blowfishKeyBytes);
//3. Generate params of AES
String randomAESPass = UUID.randomUUID().toString();
byte[] randomAESSalt = new byte[16];
new Random().nextBytes(randomAESSalt);
//4. Encrypt params of AES --> params2
byte[] aesPassBytes = randomAESPass.getBytes();
byte[] aesPassEncryptedBytes = crypto.encrypt(aesPassBytes);
byte[] randomAESSaltEncyptedBytes = crypto.encrypt(randomAESSalt);
//5. Encrypt content using Blowfish --> content1
SymCryptographal blowfishCrypto = new BlowfishCryptography(blowfishKeyBytes);
byte[] content1 = blowfishCrypto.encrypt(inputBytes);
//6. Get Blowfish IV bytes
byte[] blowfishIVBytes = blowfishCrypto.getIV();
//7. Encrypt Bloswfish IV bytes
byte[] blowfishIVEncryptedBytes = crypto.encrypt(blowfishIVBytes);
//8. Encrypt content1 using AES --> content2
SymCryptographal aesCrypto = new AESCryptography(randomAESPass.toCharArray(), randomAESSalt);
byte[] content2 = aesCrypto.encrypt(content1);
//9. Get AES IV bytes
byte[] aesIVBytes = aesCrypto.getIV();
//10. Encrypt AES IV bytes
byte[] aesIVEncryptedBytes = crypto.encrypt(aesIVBytes);
//10.1 Write SHA1 checksum length to outputfile
byte[] outputBytes = FileUtil.concat(new byte[0], FileUtil.INT_TO_BYTE_ARRAY(sha1checksum.length));
//10.2 Write SHA1 checksym bytes to output file
outputBytes = FileUtil.concat(outputBytes, sha1checksum);
//11. Write params1(s) length to outputfile
int blowfishKeyEncryptedBytesSize = blowfishKeyEncryptedBytes.length;
int blowfishIVEncryptedBytesSize = blowfishIVEncryptedBytes.length;
outputBytes = FileUtil.concat(outputBytes, FileUtil.INT_TO_BYTE_ARRAY(blowfishKeyEncryptedBytesSize));
outputBytes = FileUtil.concat(outputBytes, FileUtil.INT_TO_BYTE_ARRAY(blowfishIVEncryptedBytesSize));
//12. Write params2(s) length to outputfile
int aesPassEncryptedBytesSize = aesPassEncryptedBytes.length;
int randomAESSaltEncyptedBytesSize = randomAESSaltEncyptedBytes.length;
int aesIVEncryptedBytesSize = aesIVEncryptedBytes.length;
outputBytes = FileUtil.concat(outputBytes, FileUtil.INT_TO_BYTE_ARRAY(aesPassEncryptedBytesSize));
outputBytes = FileUtil.concat(outputBytes, FileUtil.INT_TO_BYTE_ARRAY(randomAESSaltEncyptedBytesSize));
outputBytes = FileUtil.concat(outputBytes, FileUtil.INT_TO_BYTE_ARRAY(aesIVEncryptedBytesSize));
//13. Write params1(s) to outputfile
outputBytes = FileUtil.concat(outputBytes, blowfishKeyEncryptedBytes);
outputBytes = FileUtil.concat(outputBytes, blowfishIVEncryptedBytes);
//14. Write params2(s) to outputfile
outputBytes = FileUtil.concat(outputBytes, aesPassEncryptedBytes);
outputBytes = FileUtil.concat(outputBytes, randomAESSaltEncyptedBytes);
outputBytes = FileUtil.concat(outputBytes, aesIVEncryptedBytes);
//15. Write content2 to outputfile
outputBytes = FileUtil.concat(outputBytes, content2);
return outputBytes;
} catch (Exception e) {
throw new SJException(e, SJErrorCode.TECHNICAL);
}
}
/**
* Decrypt File process <br/>
* 0.1 Read SHA1 checksum size, recalculate headerFixedSize <br/>
* 0.2 Read SHA1 checksum byte, recalculate headerFixedSize <br/>
* 1. Read blowfishKeyEncryptedBytesSize at headerFixedSize to
* (headerFixedSize+4) byte, recalculate headerFixedSize <br/>
* 2. Read blowfishIVEncryptedBytesSize at 4 - 8 byte --> num2 <br/>
* 3. Read aesPassEncryptedBytesSize at 8 - 12 byte --> num3 <br/>
* 4. Read randomAESSaltEncyptedBytesSize at 12 - 16 byte --> num4 <br/>
* 5. Read aesIVEncryptedBytes at 16 -20 byte --> num5 <br/>
* 6. Read bytes from 20 to num1 to get blowfishKeyEncryptedBytes and
* decrypt it using RSA <br/>
* 7. Read bytes from (20+num1) to num2 to get blowfishIVEncryptedBytesSize
* and decrypt it using RSA <br/>
* 8. Read bytes from (20+num1+num2) to num3 to get
* aesPassEncryptedBytesSize and decrypt it using RSA7 <br />
* 9. Read bytes from (20+num1+num2+num3) to num4 to get
* randomAESSaltEncyptedBytesSize and decrypt it using RSA <br/>
* 10. Read bytes from (20+num1+num2+num3+num4) to num5 to get
* aesIVEncryptedBytes and decrypt it using RSA <br/>
* 11. Get main content at (20 + num1 + num2 + num3 + num4 + num5) to file
* length --> content1 <br/>
* 12. Decrypt content1 using AES with params of (8), (9), (10) --> content2
* <br/>
* 13. Decrypt content2 using Blowfish with params of (6), (7) --> content3
* <br/>
* 14. Write content3 to outputfile <br/>
* 15. Compare outputfile checksum with SHA1 checksum <br/>
*
* @param inputFile
* @param outputFile
* @throws SJException
*/
public byte[] decrypt(byte[] fileContent) throws SJException {
try {
int headerFixedSize = 0;
//0.1 Read SHA1 checksum size at 0 - 4 byte
ByteBuffer wrapped = ByteBuffer.wrap(Arrays.copyOfRange(fileContent, headerFixedSize, headerFixedSize + 4));
int checkSumSize = wrapped.getInt();
headerFixedSize += 4;
//0.2 Read SHA1 checksum byte, recalculate headerFixedSize
byte[] checkSumBytes = Arrays.copyOfRange(fileContent, headerFixedSize, headerFixedSize + checkSumSize);
headerFixedSize += checkSumSize;
//1. Read blowfishKeyEncryptedBytesSize at 0 - 4 byte --> num1
wrapped = ByteBuffer.wrap(Arrays.copyOfRange(fileContent, headerFixedSize, headerFixedSize + 4));
int blowfishKeyEncryptedBytesSize = wrapped.getInt();
headerFixedSize += 4;
//2. Read blowfishIVEncryptedBytesSize at 4 - 8 byte --> num2
wrapped = ByteBuffer.wrap(Arrays.copyOfRange(fileContent, headerFixedSize, headerFixedSize + 4));
int blowfishIVEncryptedBytesSize = wrapped.getInt();
headerFixedSize += 4;
//3. Read aesPassEncryptedBytesSize at 8 - 12 byte --> num3
wrapped = ByteBuffer.wrap(Arrays.copyOfRange(fileContent, headerFixedSize, headerFixedSize + 4));
int aesPassEncryptedBytesSize = wrapped.getInt();
headerFixedSize += 4;
//4. Read randomAESSaltEncyptedBytesSize at 12 - 16 byte --> num4
wrapped = ByteBuffer.wrap(Arrays.copyOfRange(fileContent, headerFixedSize, headerFixedSize + 4));
int randomAESSaltEncyptedBytesSize = wrapped.getInt();
headerFixedSize += 4;
//5. Read aesIVEncryptedBytes at 16 -20 byte --> num5
wrapped = ByteBuffer.wrap(Arrays.copyOfRange(fileContent, headerFixedSize, headerFixedSize + 4));
int aesIVEncryptedBytesSize = wrapped.getInt();
headerFixedSize += 4;
//6. Read bytes from 20 to num1 to get blowfishKeyEncryptedBytes and decrypt it using RSA
byte[] blowfishKeyEncryptedBytes = Arrays.copyOfRange(fileContent, headerFixedSize, headerFixedSize + blowfishKeyEncryptedBytesSize);
byte[] blowfishKeyBytes = crypto.decrypt(blowfishKeyEncryptedBytes);
headerFixedSize += blowfishKeyEncryptedBytesSize;
//7. Read bytes from (20+num1) to num2 to get blowfishIVEncryptedBytesSize and decrypt it using RSA
byte[] blowfishIVEncryptedBytes = Arrays.copyOfRange(fileContent, headerFixedSize, headerFixedSize + blowfishIVEncryptedBytesSize);
byte[] blowfishIVBytes = crypto.decrypt(blowfishIVEncryptedBytes);
headerFixedSize += blowfishIVEncryptedBytesSize;
//8. Read bytes from (20+num1+num2) to num3 to get aesPassEncryptedBytesSize and decrypt it using RSA7
byte[] aesPassEncryptedBytes = Arrays.copyOfRange(fileContent, headerFixedSize, headerFixedSize + aesPassEncryptedBytesSize);
byte[] aesPassBytes = crypto.decrypt(aesPassEncryptedBytes);
headerFixedSize += aesPassEncryptedBytesSize;
//9. Read bytes from (20+num1+num2+num3) to num4 to get randomAESSaltEncyptedBytesSize and decrypt it using RSA
byte[] randomAESSaltEncyptedBytes = Arrays.copyOfRange(fileContent, headerFixedSize, headerFixedSize + randomAESSaltEncyptedBytesSize);
byte[] randomAESSaltBytes = crypto.decrypt(randomAESSaltEncyptedBytes);
headerFixedSize += randomAESSaltEncyptedBytesSize;
//10. Read bytes from (20+num1+num2+num3+num4) to num5 to get aesIVEncryptedBytesSize and decrypt it using RSA
byte[] aesIVEncryptedBytes = Arrays.copyOfRange(fileContent, headerFixedSize, headerFixedSize + aesIVEncryptedBytesSize);
byte[] aesIVBytes = crypto.decrypt(aesIVEncryptedBytes);
headerFixedSize += aesIVEncryptedBytesSize;
//11. Get main content at (20 + num1 + num2 + num3 + num4 + num5) to file length --> content1
byte[] content1 = Arrays.copyOfRange(fileContent, headerFixedSize, fileContent.length);
//12. Decrypt content1 using AES with params of (8), (9), (10) --> content2
String aesPass = new String(aesPassBytes);
SymCryptographal aesCrypto = new AESCryptography(aesPass.toCharArray(), randomAESSaltBytes);
aesCrypto.setIV(aesIVBytes);
byte[] content2 = aesCrypto.decrypt(content1);
//13. Decrypt content2 using Blowfish with params of (6), (7) --> content3
SymCryptographal blowfishCrypto = new BlowfishCryptography(blowfishKeyBytes);
blowfishCrypto.setIV(blowfishIVBytes);
byte[] content3 = blowfishCrypto.decrypt(content2);
if (Arrays.equals(FileUtil.CHECKSUM_BYTE_SHA1(content3), checkSumBytes)) {
return content3;
} else {
throw new SJException(SJErrorCode.SHA1_CHECKSUM_NOT_EQUAL);
}
} catch (Exception e) {
throw new SJException(e, SJErrorCode.TECHNICAL);
}
}
}
| 48.757692 | 147 | 0.666561 |
4ef3753105aef80e2ebc7d7f164c99d009ee5f24 | 18,195 | /**
* Personium
* Copyright 2014-2021 Personium Project Authors
* - FUJITSU 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 io.personium.test.jersey;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.ByteArrayInputStream;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.MediaType;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.json.simple.JSONObject;
import org.junit.Ignore;
import org.junit.runner.RunWith;
import io.personium.core.PersoniumUnitConfig;
import io.personium.core.model.Cell;
import io.personium.test.utils.Http;
import io.personium.test.utils.TResponse;
import io.personium.test.utils.UrlUtils;
/**
* JerseyTestFrameworkを利用したユニットテスト.
*/
@RunWith(PersoniumIntegTestRunner.class)
@Ignore
public class AbstractCase extends PersoniumTest {
/** ログオブジェクト. */
private Log log;
/** マスタートークン. */
public static final String MASTER_TOKEN_NAME = PersoniumUnitConfig.getMasterToken();
/** マスタートークン(Bearer + MASTER_TOKEN_NAME). */
public static final String BEARER_MASTER_TOKEN = "Bearer " + MASTER_TOKEN_NAME;
/** クエリフォーマット xml. */
public static final String QUERY_FORMAT_ATOM = "$format=atom";
/** クエリフォーマット json. */
public static final String QUERY_FORMAT_JSON = "$format=json";
/** __published. */
public static final String PUBLISHED = "__published";
/** __updated. */
public static final String UPDATED = "__updated";
/** __metadata. */
public static final String METADATA = "__metadata";
/** タイプ名Cell. */
public static final String TYPE_CELL = "UnitCtl.Cell";
/** 128文字の文字列. */
public static final String STRING_LENGTH_128 = "1234567890123456789012345678901234567890"
+ "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567x";
/** 128文字の文字列. */
public static final String STRING_LENGTH_129 = "1234567890123456789012345678901234567890"
+ "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678x";
/** XMLを操作するための名前空間. */
protected static final String MS_DS = "http://schemas.microsoft.com/ado/2007/08/dataservices";
/** XMLを操作するための名前空間. */
protected static final String MS_MD = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";
/** リクエストヘッダ. */
private HashMap<String, String> headers;
/**
* Constructor.
* @param application jax-rs application
*/
public AbstractCase(Application application) {
super(application);
log = LogFactory.getLog(AbstractCase.class);
log.debug("======================" + this.getClass().getName() + "======================");
}
/**
* リクエストヘッダをセットする.
* @param newHeaders 設定するヘッダのHashMapオブジェクト
*/
public final void setHeaders(final HashMap<String, String> newHeaders) {
this.headers = newHeaders;
}
/**
* Cell作成.
* @param cellName Cell名
* @return Cell作成時のレスポンスオブジェクト
*/
@SuppressWarnings("unchecked")
public final PersoniumResponse createCell(final String cellName) {
PersoniumRestAdapter rest = new PersoniumRestAdapter();
PersoniumResponse res = null;
// リクエストヘッダをセット
HashMap<String, String> requestheaders = new HashMap<String, String>();
requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN);
// リクエストボディを生成
JSONObject requestBody = new JSONObject();
requestBody.put("Name", cellName);
String data = requestBody.toJSONString();
// リクエスト
try {
res = rest.post(UrlUtils.unitCtl(Cell.EDM_TYPE_NAME), data, requestheaders);
} catch (Exception e) {
fail(e.getMessage());
}
return res;
}
/**
* Create box.
* @param cellName Cell name
* @param boxName Box name
* @return API response
*/
public TResponse createBox(String cellName, String boxName) {
return createBox(cellName, boxName, null);
}
/**
* Create box.
* @param cellName Cell name
* @param boxName Box name
* @param boxSchema Box schema
* @return API response
*/
public TResponse createBox(String cellName, String boxName, String boxSchema) {
if (boxSchema != null) {
return Http.request("cell/box-create-with-scheme.txt")
.with("cellPath", cellName)
.with("token", AbstractCase.MASTER_TOKEN_NAME)
.with("boxPath", boxName)
.with("schema", boxSchema)
.returns().debug().statusCode(HttpStatus.SC_CREATED);
} else {
return Http.request("cell/box-create.txt")
.with("cellPath", cellName)
.with("token", AbstractCase.MASTER_TOKEN_NAME)
.with("boxPath", boxName)
.returns().debug().statusCode(HttpStatus.SC_CREATED);
}
}
/**
* Create account.
* Type is basic.
* @param cellName Cell name
* @param accountName Account name
* @param password Password
* @return API response
*/
public TResponse createAccount(String cellName, String accountName, String password) {
return Http.request("account-create.txt")
.with("cellPath", cellName)
.with("token", AbstractCase.MASTER_TOKEN_NAME)
.with("password", password)
.with("username", accountName)
.returns().debug().statusCode(HttpStatus.SC_CREATED);
}
/**
* Create role.
* @param cellName Cell name
* @param roleName Role name
* @return API response
*/
public TResponse createRole(String cellName, String roleName) {
return createRole(cellName, roleName, null);
}
/**
* Create role.
* @param cellName Cell name
* @param roleName Role name
* @param boxName Box name
* @return API response
*/
@SuppressWarnings("unchecked")
public TResponse createRole(String cellName, String roleName, String boxName) {
JSONObject jsonBody = new JSONObject();
jsonBody.put("Name", roleName);
jsonBody.put("_Box.Name", boxName);
return Http.request("role-create.txt")
.with("cellPath", cellName)
.with("token", AbstractCase.MASTER_TOKEN_NAME)
.with("body", jsonBody.toJSONString())
.returns().debug().statusCode(HttpStatus.SC_CREATED);
}
/**
* Link account and role.
* @param cellName Cell name
* @param accountName Account name
* @param roleUrl Role url
* @return API response
*/
public TResponse linkAccountAndRole(String cellName, String accountName, String roleUrl) {
return Http.request("cell/link-account-role.txt")
.with("cellPath", cellName)
.with("username", accountName)
.with("token", AbstractCase.MASTER_TOKEN_NAME)
.with("roleUrl", roleUrl)
.returns().debug().statusCode(HttpStatus.SC_NO_CONTENT);
}
/**
* Create service collection.
* @param cellName Cell name
* @param boxName Box name
* @param path Path
* @return API response
*/
public TResponse createServiceCollection(String cellName, String boxName, String path) {
return Http.request("box/mkcol-service-fullpath.txt")
.with("cell", cellName)
.with("box", boxName)
.with("path", path)
.with("token", AbstractCase.BEARER_MASTER_TOKEN)
.returns().debug().statusCode(HttpStatus.SC_CREATED);
}
/**
* Create webdav collection.
* @param cellName Cell name
* @param boxName Box name
* @param path Path
* @return API response
*/
public TResponse createWebdavCollection(String cellName, String boxName, String path) {
return Http.request("box/mkcol-normal-fullpath.txt")
.with("cell", cellName)
.with("box", boxName)
.with("path", path)
.with("token", AbstractCase.BEARER_MASTER_TOKEN)
.returns().debug().statusCode(HttpStatus.SC_CREATED);
}
/**
* Create odata collection.
* @param cellName Cell name
* @param boxName Box name
* @param path Path
* @return API response
*/
public TResponse createOdataCollection(String cellName, String boxName, String path) {
return Http.request("box/mkcol-odata.txt")
.with("cellPath", cellName)
.with("boxPath", boxName)
.with("path", path)
.with("token", AbstractCase.MASTER_TOKEN_NAME)
.returns().debug().statusCode(HttpStatus.SC_CREATED);
}
/**
* URLを指定してGETを行う汎用メンバ.
* @param url リクエスト先のURL
* @return レスポンスオブジェクト
*/
public final PersoniumResponse restGet(final String url) {
PersoniumRestAdapter rest = new PersoniumRestAdapter();
PersoniumResponse res = null;
if (this.headers == null) {
// setHeadersで設定されていない場合、リクエストヘッダをセット
this.headers = new HashMap<String, String>();
this.headers.put(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
this.headers.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN);
}
try {
// リクエスト
res = rest.getAcceptEncodingGzip(url, this.headers);
// res = rest.get(url, headers);
} catch (Exception e) {
fail(e.getMessage());
}
return res;
}
/**
* URLを指定してPOSTを行う汎用メンバ.
* @param url リクエスト先のURL
* @param data postデータ
* @return レスポンスオブジェクト
*/
public final PersoniumResponse restPost(final String url, final String data) {
PersoniumRestAdapter rest = new PersoniumRestAdapter();
PersoniumResponse res = null;
// リクエストヘッダをセット
HashMap<String, String> requestheaders = new HashMap<String, String>();
requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN);
try {
// リクエスト
res = rest.post(url, data, requestheaders);
} catch (Exception e) {
fail(e.getMessage());
}
return res;
}
/**
* URLを指定してPUTを行う汎用メンバ.
* @param url リクエスト先のURL
* @param data リクエストデータ
* @return レスポンスオブジェクト
*/
public final PersoniumResponse restPut(final String url, final String data) {
PersoniumRestAdapter rest = new PersoniumRestAdapter();
PersoniumResponse res = null;
// リクエストヘッダをセット
HashMap<String, String> requestheaders = new HashMap<String, String>();
requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN);
try {
// リクエスト
res = rest.put(url, requestheaders, new ByteArrayInputStream(data.getBytes()));
} catch (Exception e) {
fail(e.getMessage());
}
return res;
}
/**
* URLを指定してDELETEを行う汎用メンバ.
* @param url リクエスト先のURL
* @return レスポンスオブジェクト
*/
public final PersoniumResponse restDelete(final String url) {
PersoniumRestAdapter rest = new PersoniumRestAdapter();
PersoniumResponse res = null;
// リクエストヘッダをセット
HashMap<String, String> requestheaders = new HashMap<String, String>();
requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN);
requestheaders.put(HttpHeaders.IF_MATCH, "*");
try {
// リクエスト
res = rest.del(url, requestheaders);
} catch (Exception e) {
fail(e.getMessage());
}
return res;
}
/**
* DcRequestオブジェクトを使用してリクエスト実行.
* @param req リクエストパラメータ
* @return res
*/
public static PersoniumResponse request(PersoniumRequest req) {
PersoniumRestAdapter rest = new PersoniumRestAdapter();
PersoniumResponse res = null;
String method = req.getMethod();
try {
// リクエスト
if (method.equals(HttpMethod.GET)) {
res = rest.getAcceptEncodingGzip(req.getUrl(), req.getHeaders());
} else if (method.equals(HttpMethod.PUT)) {
res = rest.put(req.getUrl(), req.getBody(), req.getHeaders());
} else if (method.equals(HttpMethod.POST)) {
res = rest.post(req.getUrl(), req.getBody(), req.getHeaders());
} else if (method.equals(HttpMethod.DELETE)) {
res = rest.del(req.getUrl(), req.getHeaders());
} else {
res = rest.request(method, req.getUrl(), req.getBody(), req.getHeaders());
}
} catch (Exception e) {
fail(e.getMessage());
}
return res;
}
/**
* CellのURL文字列を生成.
* @param curCellId cellのid
* @return cellを取得するURL
*/
public String getUrl(final String curCellId) {
return getUrl(curCellId, null);
}
/**
* CellのURL文字列を生成.
* @param curCellId cellのid
* @param reqQuery query
* @return cellを取得するURL
*/
public String getUrl(final String curCellId, final String reqQuery) {
StringBuilder url = new StringBuilder(UrlUtils.unitCtl(Cell.EDM_TYPE_NAME));
url.append("('");
url.append(curCellId);
url.append("')");
if (reqQuery != null) {
url.append("?");
url.append(reqQuery);
}
return url.toString();
}
/**
* CellのURL文字列を生成.
* @param curCellId cellのid
* @param reqQuery query
* @return cellを取得するURL
*/
public String getUrlWithOutQuote(final String curCellId, final String reqQuery) {
StringBuilder url = new StringBuilder(UrlUtils.unitCtl(Cell.EDM_TYPE_NAME));
url.append("(");
url.append(curCellId);
url.append(")");
if (reqQuery != null) {
url.append("?");
url.append(reqQuery);
}
return url.toString();
}
/**
* CellのJson形式のフォーマットチェック.
* @param doc JSONObjectオブジェクト
* @param locationHeader LOCATIONヘッダ
*/
public void checkCellResponse(final JSONObject doc, final String locationHeader) {
JSONObject results = (JSONObject) ((JSONObject) doc.get("d")).get("results");
validateCellResponse(results, locationHeader);
}
/**
* エラーレスポンスチェック.
* @param doc JSONObjectオブジェクト
* @param code エラーコード
*/
public void checkErrorResponse(JSONObject doc, String code) {
checkErrorResponse(doc, code, null);
}
/**
* エラーレスポンスチェック.
* @param doc JSONObjectオブジェクト
* @param code エラーコード
* @param message エラーメッセージ
*/
public void checkErrorResponse(JSONObject doc, String code, String message) {
String value;
JSONObject error = doc;
// code要素
value = (String) error.get("code");
assertNotNull(value);
// code値が引数と一致するかチェック
assertEquals(code, value);
// __metadata要素
JSONObject metadata = (JSONObject) error.get("message");
// lang要素
value = (String) metadata.get("lang");
assertNotNull(value);
// value要素
value = (String) metadata.get("value");
if (message == null) {
assertNotNull(value);
} else {
assertEquals(message, value);
}
}
/**
* 日付のフォーマットが正しいかチェックする.
* @param date レスポンスの日付
* @return boolean フォーマットの判定
*/
protected static Boolean validDate(final String date) {
String dateformat = "Date\\([0-9]+\\)";
Pattern pattern = Pattern.compile(dateformat);
Matcher dateformatmatch = pattern.matcher(date);
return dateformatmatch.find();
}
/**
* CellのJson形式のフォーマットチェック.
* @param results JSONObjectオブジェクト
* @param locationHeader LOCATIONヘッダ
*/
protected void validateCellResponse(final JSONObject results, final String locationHeader) {
String value;
// d:Name要素
value = (String) results.get("Name");
assertNotNull(value);
// Name値が空かどうかチェック
assertTrue(value.length() > 0);
// d:__published要素
value = (String) results.get("__published");
assertNotNull(value);
// __published要素の値が日付形式かどうかチェック
assertTrue(validDate(value));
// d:__updated要素
value = (String) results.get("__updated");
assertNotNull(value);
// __updated要素の値が日付形式かどうかチェック
assertTrue(validDate(value));
// __metadata要素
JSONObject metadata = (JSONObject) results.get("__metadata");
// uri要素
value = (String) metadata.get("uri");
assertNotNull(value);
if (locationHeader != null) {
// LOCATIONヘッダと等しいかチェック
assertEquals(value, locationHeader);
}
// type要素
value = (String) metadata.get("type");
assertNotNull(value);
assertEquals(value, TYPE_CELL);
// etag要素
value = (String) metadata.get("etag");
assertNotNull(value);
// etag値が空かどうかチェック
assertTrue(value.length() > 0);
}
}
| 32.20354 | 107 | 0.612366 |
3b9d5c2b872b6d846a67c1f273e94a5ff8ed6784 | 4,174 | //给定一棵树的前序遍历 preorder 与中序遍历 inorder。请构造二叉树并返回其根节点。
//
//
//
// 示例 1:
//
//
//Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
//Output: [3,9,20,null,null,15,7]
//
//
// 示例 2:
//
//
//Input: preorder = [-1], inorder = [-1]
//Output: [-1]
//
//
//
//
// 提示:
//
//
// 1 <= preorder.length <= 3000
// inorder.length == preorder.length
// -3000 <= preorder[i], inorder[i] <= 3000
// preorder 和 inorder 均无重复元素
// inorder 均出现在 preorder
// preorder 保证为二叉树的前序遍历序列
// inorder 保证为二叉树的中序遍历序列
//
// Related Topics 树 数组 哈希表 分治 二叉树 👍 1339 👎 0
package leetcode.editor.cn;
import java.util.Stack;
//java:从前序与中序遍历序列构造二叉树
class ConstructBinaryTreeFromPreorderAndInorderTraversal{
public static void main(String[] args){
Solution solution = new ConstructBinaryTreeFromPreorderAndInorderTraversal().new Solution();
}
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
/*
递归法实现
前序遍历数组的第一个数就是根节点,可以在中序遍历数组中找到把其分割开(左边是左子树中序遍历数组,右边是右子树中序遍历数组)
然后前序遍历可以分成两个部分(根据中序遍历分割点),左边是左子树前序遍历数组,右边是右子树前序遍历数组
然后分治+递归就可以得出答案
*/
public TreeNode buildTree(int[] preorder, int[] inorder) {
int preLen = preorder.length;;
int inLen = inorder.length;
return build(preorder, 0, preLen-1, inorder, 0, inLen-1);
}
TreeNode build(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart, int inEnd) {
if (preStart > preEnd) {
return null;
}
// root 节点对应的值就是前序遍历数组的第⼀个元素
int rootVal = preorder[preStart];
// rootVal 在中序遍历数组中的索引
int index = 0;
for (int i = inStart; i <= inEnd; i++) {
if (inorder[i] == rootVal) {
index = i;
break;
}
}
int leftSize = index - inStart;
// 先构造出当前根节点
TreeNode root = new TreeNode(rootVal);
// 递归构造左右⼦树
root.left = build(preorder, preStart + 1, preStart + leftSize, inorder, inStart, index - 1);
root.right = build(preorder, preStart + leftSize + 1, preEnd, inorder, index + 1, inEnd);
return root;
}
/*
迭代法
*/
public TreeNode _buildTree(int[] preorder, int[] inorder) {
if (preorder.length == 0) {
return null;
}
Stack<TreeNode> roots = new Stack<TreeNode>();
int pre = 0;
int in = 0;
//先序遍历第一个值作为根节点
TreeNode curRoot = new TreeNode(preorder[pre]);
TreeNode root = curRoot;
roots.push(curRoot);
pre++;
//遍历前序遍历的数组
while (pre < preorder.length) {
//出现了当前节点的值和中序遍历数组的值相等,寻找是谁的右子树
if (curRoot.val == inorder[in]) {
//每次进行出栈,实现倒着遍历
while (!roots.isEmpty() && roots.peek().val == inorder[in]) {
curRoot = roots.peek();
roots.pop();
in++;
}
//设为当前的右孩子
curRoot.right = new TreeNode(preorder[pre]);
//更新 curRoot
curRoot = curRoot.right;
roots.push(curRoot);
pre++;
} else {
//否则的话就一直作为左子树
curRoot.left = new TreeNode(preorder[pre]);
curRoot = curRoot.left;
roots.push(curRoot);
pre++;
}
}
return root;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
| 30.246377 | 105 | 0.499281 |
01e2519d26f7eb50f77096233dd38a6f750eef50 | 13,373 | /*
* Copyright 2006-2012 The Scriptella Project Team.
*
* 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 scriptella.jdbc;
import scriptella.configuration.ConfigurationException;
import scriptella.spi.AbstractConnection;
import scriptella.spi.ConnectionParameters;
import scriptella.spi.DialectIdentifier;
import scriptella.spi.NativeConnectionProvider;
import scriptella.spi.ParametersCallback;
import scriptella.spi.ProviderException;
import scriptella.spi.QueryCallback;
import scriptella.spi.Resource;
import scriptella.util.StringUtils;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Represents a JDBC connection.
* TODO Extract JDBCConnectionParameters class and JDBCStatementFactory as described in statement cache
*
* @author Fyodor Kupolov
* @version 1.0
*/
public class JdbcConnection extends AbstractConnection implements NativeConnectionProvider {
public static final String STATEMENT_CACHE_KEY = "statement.cache";
public static final String STATEMENT_SEPARATOR_KEY = "statement.separator";
public static final String STATEMENT_SEPARATOR_SINGLELINE_KEY = "statement.separator.singleline";
public static final String STATEMENT_BATCH_SIZE = "statement.batchSize";
public static final String STATEMENT_FETCH_SIZE = "statement.fetchSize";
public static final String KEEPFORMAT_KEY = "keepformat";
public static final String AUTOCOMMIT_KEY = "autocommit";
public static final String AUTOCOMMIT_SIZE_KEY = "autocommit.size";
public static final String FLUSH_BEFORE_QUERY = "flushBeforeQuery";
public static final String TRANSACTION_ISOLATION_KEY = "transaction.isolation";
public static final String TRANSACTION_ISOLATION_READ_UNCOMMITTED = "READ_UNCOMMITTED";
public static final String TRANSACTION_ISOLATION_READ_COMMITTED = "READ_COMMITTED";
public static final String TRANSACTION_ISOLATION_REPEATABLE_READ = "REPEATABLE_READ";
public static final String TRANSACTION_ISOLATION_SERIALIZABLE = "SERIALIZABLE";
private Connection con;
private static final Logger LOG = Logger.getLogger(JdbcConnection.class.getName());
private boolean transactable;
private boolean autocommit;
private ParametersParser parametersParser;
protected int statementCacheSize;
protected int statementBatchSize;
protected int statementFetchSize;
protected boolean flushBeforeQuery;
protected String separator = ";";
protected boolean separatorSingleLine;
protected boolean keepformat;
protected int autocommitSize;
private Integer txIsolation;
private final Map<Resource, SqlExecutor> resourcesMap = new IdentityHashMap<Resource, SqlExecutor>();
public JdbcConnection(Connection con, ConnectionParameters parameters) {
super(parameters);
if (con == null) {
throw new IllegalArgumentException("Connection cannot be null");
}
this.con = con;
init(parameters);
if (txIsolation != null) {
try {
con.setTransactionIsolation(txIsolation);
} catch (SQLException e) {
throw new JdbcException("Unable to set transaction isolation level for " + toString(), e);
}
}
try {
//Several drivers return -1 which is illegal, but means no TX
transactable = con.getTransactionIsolation() > Connection.TRANSACTION_NONE;
} catch (SQLException e) {
LOG.log(Level.WARNING, "Unable to determine transaction isolation level for connection " + toString(), e);
}
if (transactable) { //only effective for transactable connections
try {
con.setAutoCommit(autocommit);
} catch (Exception e) {
throw new JdbcException("Unable to set autocommit=false for " + toString(), e);
}
}
}
/**
* Called in constructor
*
* @param parameters connection parameters.
*/
protected void init(ConnectionParameters parameters) {
StringBuilder statusMsg = new StringBuilder();
if (!StringUtils.isAsciiWhitespacesOnly(parameters.getUrl())) {
statusMsg.append(parameters.getUrl()).append(": ");
}
statementCacheSize = parameters.getIntegerProperty(STATEMENT_CACHE_KEY, 64);
if (statementCacheSize > 0) {
statusMsg.append("Statement cache is enabled (cache size ").append(statementCacheSize).append("). ");
}
statementBatchSize = parameters.getIntegerProperty(STATEMENT_BATCH_SIZE, 0);
if (statementBatchSize > 0) {
statusMsg.append("Statement batching is enabled (batch size ").append(statementBatchSize).append("). ");
}
statementFetchSize = parameters.getIntegerProperty(STATEMENT_FETCH_SIZE, 0);
if (statementFetchSize != 0) {
statusMsg.append("Query statement fetching is enabled (fetch size ").append(statementFetchSize).append("). ");
}
String separatorStr = parameters.getStringProperty(STATEMENT_SEPARATOR_KEY);
if (!StringUtils.isEmpty(separatorStr)) {
separator = separatorStr.trim();
}
statusMsg.append("Statement separator '").append(separator).append('\'');
separatorSingleLine = parameters.getBooleanProperty(STATEMENT_SEPARATOR_SINGLELINE_KEY, false);
statusMsg.append(separatorSingleLine ? " on a single line. " : ". ");
keepformat = parameters.getBooleanProperty(KEEPFORMAT_KEY, false);
String isolationStr = parameters.getStringProperty(TRANSACTION_ISOLATION_KEY);
if (isolationStr != null) {
isolationStr = isolationStr.trim();
if (TRANSACTION_ISOLATION_READ_COMMITTED.equalsIgnoreCase(isolationStr)) {
txIsolation = Connection.TRANSACTION_READ_COMMITTED;
} else if (TRANSACTION_ISOLATION_READ_UNCOMMITTED.equalsIgnoreCase(isolationStr)) {
txIsolation = Connection.TRANSACTION_READ_UNCOMMITTED;
} else if (TRANSACTION_ISOLATION_REPEATABLE_READ.equalsIgnoreCase(isolationStr)) {
txIsolation = Connection.TRANSACTION_REPEATABLE_READ;
} else if (TRANSACTION_ISOLATION_SERIALIZABLE.equalsIgnoreCase(isolationStr)) {
txIsolation = Connection.TRANSACTION_SERIALIZABLE;
} else if (StringUtils.isDecimalInt(isolationStr)) {
txIsolation = parameters.getIntegerProperty(TRANSACTION_ISOLATION_KEY);
} else {
throw new ConfigurationException(
"Invalid " + TRANSACTION_ISOLATION_KEY + " connection property value: " + isolationStr +
". Valid values are: " + TRANSACTION_ISOLATION_READ_COMMITTED + ", " +
TRANSACTION_ISOLATION_READ_UNCOMMITTED + ", " + TRANSACTION_ISOLATION_REPEATABLE_READ +
", " + TRANSACTION_ISOLATION_SERIALIZABLE +
" or a numeric value according to java.sql.Connection transaction isolation constants");
}
}
if (isolationStr != null) {
statusMsg.append("Transaction isolation level: ").append(txIsolation).
append('(').append(isolationStr).append("). ");
}
autocommit = parameters.getBooleanProperty(AUTOCOMMIT_KEY);
autocommitSize = parameters.getIntegerProperty(AUTOCOMMIT_SIZE_KEY, 0);
statusMsg.append("Autocommit: ").append(autocommit);
if (autocommitSize > 0) {
statusMsg.append("(size ").append(autocommitSize).append(")");
}
statusMsg.append(".");
flushBeforeQuery = parameters.getBooleanProperty(FLUSH_BEFORE_QUERY, false);
if (flushBeforeQuery) {
statusMsg.append("Flushing before query execution is enabled.");
}
LOG.fine(statusMsg.toString());
parametersParser = new ParametersParser(parameters.getContext());
initDialectIdentifier();
}
StatementCounter getStatementCounter() {
return counter;
}
/**
* Initializes dialect identifier for connection.
* If driver doesn't support DatabaseMetaData or other problem occurs,
* {@link DialectIdentifier#NULL_DIALECT} is used.
* <p>May be overriden by subclasses.
*/
protected void initDialectIdentifier() {
try {
final DatabaseMetaData metaData = con.getMetaData();
if (metaData != null) { //Several drivers violate spec and return null
setDialectIdentifier(new DialectIdentifier(metaData.getDatabaseProductName(),
metaData.getDatabaseProductVersion()));
}
} catch (Exception e) {
setDialectIdentifier(DialectIdentifier.NULL_DIALECT);
LOG.log(Level.WARNING, "Failed to obtain meta data for connection. No dialect checking for " + con, e);
}
}
public void executeScript(Resource scriptContent, ParametersCallback parametersCallback) {
SqlExecutor s = resourcesMap.get(scriptContent);
if (s == null) {
resourcesMap.put(scriptContent, s = new SqlExecutor(scriptContent, this));
}
s.execute(parametersCallback);
}
public void executeQuery(Resource queryContent, ParametersCallback parametersCallback, QueryCallback queryCallback) {
SqlExecutor q = resourcesMap.get(queryContent);
if (q == null) {
resourcesMap.put(queryContent, q = new SqlExecutor(queryContent, this));
}
if (flushBeforeQuery) {
flush();
}
q.execute(parametersCallback, queryCallback);
if (q.getUpdateCount() < 0) {
throw new JdbcException("SQL query cannot make updates");
}
}
/**
* Creates an instance of statement cache.
*
* @return new instance of statement cache.
*/
protected StatementCache newStatementCache() {
return new StatementCache(getNativeConnection(), statementCacheSize, statementBatchSize, statementFetchSize);
}
ParametersParser getParametersParser() {
return parametersParser;
}
public void commit() {
if (con == null) {
throw new IllegalStateException("Attempt to commit a transaction on a closed connection");
}
flush();
if (!transactable) {
LOG.log(Level.INFO, "Connection " + toString() + " doesn't support transactions. Commit ignored.");
} else {
try {
con.commit();
} catch (Exception e) {
throw new JdbcException("Unable to commit transaction", e);
}
}
}
public void rollback() {
if (con == null) {
throw new IllegalStateException("Attempt to roll back a transaction on a closed connection");
}
if (!transactable) {
LOG.log(Level.INFO, "Connection " + toString() + " doesn't support transactions. Rollback ignored.");
} else {
try {
con.rollback();
} catch (Exception e) {
throw new JdbcException("Unable to roll back transaction", e);
}
}
}
public void flush() throws ProviderException {
//Caches for ETL element executors are flushed
if (resourcesMap != null) {
for (SqlExecutor executor : resourcesMap.values()) {
try {
executor.cache.flush();
} catch (SQLException e) {
throw new JdbcException("Unable to commit transaction - cannot flush cache", e);
}
}
}
}
public void close() {
if (con != null) {
//Closing resources
for (SqlExecutor element : resourcesMap.values()) {
element.close();
}
resourcesMap.clear();
try {
con.close();
con = null;
} catch (SQLException e) {
throw new JdbcException("Unable to close a connection", e);
}
}
}
@Override
public Connection getNativeConnection() {
return con;
}
public String toString() {
return "JdbcConnection{" + (con == null ? "" : con.getClass().getName()) + '}';
}
}
| 42.453968 | 123 | 0.636806 |
be224e2045b517f1106db7ea494cd40a072a6b6f | 512 | package com.google.android.gms.internal.ads;
import java.util.List;
import org.json.JSONObject;
/* compiled from: com.google.android.gms:play-services-ads@@19.4.0 */
final /* synthetic */ class zzcgx implements zzdvu {
private final JSONObject zzfnx;
private final zzcgw zzgdo;
zzcgx(zzcgw zzcgw, JSONObject jSONObject) {
this.zzgdo = zzcgw;
this.zzfnx = jSONObject;
}
public final Object apply(Object obj) {
return this.zzgdo.zza(this.zzfnx, (List) obj);
}
}
| 25.6 | 69 | 0.681641 |
e53a7dfc5d3b5e9411b7ff54c59676fb4fa1e9f7 | 412 | package com.bluroc.cloud.microservicescloudsleuthzipkinmiya;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MicroservicesCloudSleuthZipkinMiyaApplication {
public static void main(String[] args) {
SpringApplication.run(MicroservicesCloudSleuthZipkinMiyaApplication.class, args);
}
}
| 29.428571 | 89 | 0.832524 |
90dab3ed721e5dcb4f8327e6aad63a03096219bc | 1,518 | package us.potatoboy.worldborderfix.mixin;
import net.minecraft.network.packet.s2c.play.WorldBorderCenterChangedS2CPacket;
import net.minecraft.world.World;
import net.minecraft.world.border.WorldBorder;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
import us.potatoboy.worldborderfix.BorderWithWorld;
@Mixin(WorldBorderCenterChangedS2CPacket.class)
public abstract class WorldBorderCenterChangePacketMixin {
@Redirect(
method = "<init>(Lnet/minecraft/world/border/WorldBorder;)V",
at = @At(value = "INVOKE", target = "Lnet/minecraft/world/border/WorldBorder;getCenterX()D")
)
private double scaleCenterX(WorldBorder worldBorder) {
World world = ((BorderWithWorld) worldBorder).getWorld();
if (world != null) {
return worldBorder.getCenterX() * world.getDimension().getCoordinateScale();
}
return worldBorder.getCenterX();
}
@Redirect(
method = "<init>(Lnet/minecraft/world/border/WorldBorder;)V",
at = @At(value = "INVOKE", target = "Lnet/minecraft/world/border/WorldBorder;getCenterZ()D")
)
private double scaleCenterZ(WorldBorder worldBorder) {
World world = ((BorderWithWorld) worldBorder).getWorld();
if (world != null) {
return worldBorder.getCenterZ() * world.getDimension().getCoordinateScale();
}
return worldBorder.getCenterZ();
}
}
| 37.02439 | 104 | 0.701581 |
c72e5851a0b151f048703d4fdb469ef48223329e | 2,365 | package com.ynov.android.gluciddiab.dataUtils;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
/**
* Created by admin on 31/03/17.
*/
public class ProtocoleGlucidesDbHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "glucides.db";
private static final int DATABASE_VERSION = 1;
public ProtocoleGlucidesDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase sqLiteDatabase) {
final String SQL_CREATE_STAFFLIST_TABLE = "CREATE TABLE " +
ProtocoleGlucidesContract.ProtocoleGlucidesEntry.TABLE_NAME + " (" +
ProtocoleGlucidesContract.ProtocoleGlucidesEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
ProtocoleGlucidesContract.ProtocoleGlucidesEntry.GLU_LENT + " STRING, " +
ProtocoleGlucidesContract.ProtocoleGlucidesEntry.GLU_RAPIDE + " STRING, " +
ProtocoleGlucidesContract.ProtocoleGlucidesEntry.COLUMN_TIMESTAMP + " TIMESTAMP DEFAULT CURRENT_TIMESTAMP " +
");";
sqLiteDatabase.execSQL(SQL_CREATE_STAFFLIST_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + ProtocoleGlucidesContract.ProtocoleGlucidesEntry.TABLE_NAME);
onCreate(sqLiteDatabase);
}
// Getting single contact
public List<String> getProtocole(int id) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM protocoleglucidesdata", null);
if (cursor != null)
cursor.move(id);
List<String> proto = new ArrayList<String>();
proto.add((String)cursor.getString(0));
proto.add(cursor.getString(cursor.getColumnIndex(ProtocoleGlucidesContract.ProtocoleGlucidesEntry.GLU_LENT)));
proto.add(cursor.getString(cursor.getColumnIndex(ProtocoleGlucidesContract.ProtocoleGlucidesEntry.GLU_RAPIDE)));
proto.add((String)cursor.getString(3));
// return contact
return proto;
}
}
| 36.953125 | 129 | 0.694292 |
c1657c21d82d40202c6412ad638ea57e6f782b69 | 4,436 | package no.nav.familie.ks.sak.app.behandling;
import no.nav.familie.kontrakter.ks.søknad.Søknad;
import no.nav.familie.ks.sak.app.behandling.domene.Behandling;
import no.nav.familie.ks.sak.app.behandling.domene.BehandlingRepository;
import no.nav.familie.ks.sak.app.behandling.domene.Fagsak;
import no.nav.familie.ks.sak.app.behandling.domene.FagsakRepository;
import no.nav.familie.ks.sak.app.behandling.domene.grunnlag.SøknadTilGrunnlagMapper;
import no.nav.familie.ks.sak.app.behandling.domene.grunnlag.barnehagebarn.Barn;
import no.nav.familie.ks.sak.app.behandling.domene.grunnlag.barnehagebarn.BarnehageBarnGrunnlag;
import no.nav.familie.ks.sak.app.behandling.domene.grunnlag.barnehagebarn.BarnehageBarnGrunnlagRepository;
import no.nav.familie.ks.sak.app.behandling.domene.grunnlag.barnehagebarn.OppgittFamilieforhold;
import no.nav.familie.ks.sak.app.behandling.domene.grunnlag.søknad.OppgittErklæring;
import no.nav.familie.ks.sak.app.behandling.domene.grunnlag.søknad.SøknadGrunnlag;
import no.nav.familie.ks.sak.app.behandling.domene.grunnlag.søknad.SøknadGrunnlagRepository;
import no.nav.familie.ks.sak.app.integrasjon.IntegrasjonTjeneste;
import no.nav.familie.ks.sak.app.integrasjon.personopplysning.domene.PersonIdent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Set;
@Service
public class BehandlingslagerService {
private FagsakRepository fagsakRepository;
private BehandlingRepository behandlingRepository;
private SøknadGrunnlagRepository søknadGrunnlagRepository;
private BarnehageBarnGrunnlagRepository barnehageBarnGrunnlagRepository;
private IntegrasjonTjeneste integrasjonTjeneste;
@Autowired
public BehandlingslagerService(FagsakRepository fagsakRepository,
BehandlingRepository behandlingRepository,
SøknadGrunnlagRepository søknadGrunnlagRepository,
BarnehageBarnGrunnlagRepository barnehageBarnGrunnlagRepository,
IntegrasjonTjeneste integrasjonTjeneste) {
this.fagsakRepository = fagsakRepository;
this.behandlingRepository = behandlingRepository;
this.søknadGrunnlagRepository = søknadGrunnlagRepository;
this.barnehageBarnGrunnlagRepository = barnehageBarnGrunnlagRepository;
this.integrasjonTjeneste = integrasjonTjeneste;
}
public Behandling nyBehandling(Søknad søknad, String saksnummer, String journalpostID) {
final var søkerAktørId = integrasjonTjeneste.hentAktørId(søknad.getSøkerFødselsnummer());
final var fagsak = Fagsak.opprettNy(søkerAktørId, new PersonIdent(søknad.getSøkerFødselsnummer()), saksnummer);
fagsakRepository.save(fagsak);
final var behandling = Behandling.forFørstegangssøknad(fagsak, journalpostID).build();
behandlingRepository.save(behandling);
return behandling;
}
void trekkUtOgPersisterSøknad(Behandling behandling, Søknad søknad) {
final var familieforholdBuilder = new OppgittFamilieforhold.Builder();
familieforholdBuilder.setBarna(mapOgHentBarna(søknad));
familieforholdBuilder.setBorBeggeForeldreSammen(søknad.getOppgittFamilieforhold().getBorBeggeForeldreSammen());
barnehageBarnGrunnlagRepository.save(new BarnehageBarnGrunnlag(behandling, familieforholdBuilder.build()));
final var kravTilSoker = søknad.getOppgittErklæring();
final var erklæring = new OppgittErklæring(kravTilSoker.isBarnetHjemmeværendeOgIkkeAdoptert(),
kravTilSoker.isBorSammenMedBarnet(),
kravTilSoker.isIkkeAvtaltDeltBosted(),
kravTilSoker.isBarnINorgeNeste12Måneder());
final var oppgittUtlandsTilknytning = SøknadTilGrunnlagMapper.mapUtenlandsTilknytning(søknad);
søknadGrunnlagRepository.save(new SøknadGrunnlag(behandling,
new no.nav.familie.ks.sak.app.behandling.domene.grunnlag.søknad.Søknad(søknad.getInnsendtTidspunkt(), søknad.getSøkerFødselsnummer(), søknad.getOppgittAnnenPartFødselsnummer(), oppgittUtlandsTilknytning, erklæring)));
}
private Set<Barn> mapOgHentBarna(Søknad søknad) {
Set<Barn> barna = SøknadTilGrunnlagMapper.mapSøknadBarn(søknad);
for (Barn barn : barna) {
barn.setFødselsnummer(barn.getFødselsnummer());
}
return barna;
}
}
| 54.097561 | 229 | 0.773219 |
1484eff9f8d6a517f9ba6ce96b0e4d34341bac2c | 1,668 | package models.apostas.odd.resultados.dupla;
import models.apostas.Calculadora;
import models.apostas.Odd;
import models.apostas.Taxa;
import models.apostas.mercado.ApostaDuplaMercado;
import models.apostas.mercado.Mercado;
import models.eventos.futebol.ResultadoFutebol;
import javax.persistence.Entity;
@Entity
public class EmpateForaApostaDuplaOdd extends Odd<ApostaDuplaMercado.Posicao> {
private static final String DESCRICAO = "Ganha quando casa empata ou perde";
private static final String NOME = "ForaEmpate";
private static final String ABREVIACAO = "FE";
public EmpateForaApostaDuplaOdd() {
}
public EmpateForaApostaDuplaOdd(String codigo) {
super(codigo);
}
@Override
public String getNome() {
return NOME;
}
@Override
public Mercado getMercado() {
return Mercado.ApostaDupla;
}
@Override
public String getAbreviacao() {
return ABREVIACAO;
}
@Override
public String getDescricao() {
return DESCRICAO;
}
@Override
public ApostaDuplaMercado.Posicao getPosicao() {
return ApostaDuplaMercado.Posicao.EMPATE_FORA;
}
@Override
public Calculadora getCalculadora(Taxa taxa) {
return new CalculadoraM();
}
public class CalculadoraM implements Calculadora<ResultadoFutebol> {
@Override
public boolean calcular(ResultadoFutebol resultado) {
Long pontosCasa = resultado.casaSegundoTempo.getPontos();
Long pontosFora = resultado.foraSegundoTempo.getPontos();
return (pontosCasa < pontosFora) || (pontosCasa == pontosFora);
}
}
}
| 24.529412 | 80 | 0.693645 |
556b3dcb7588ad58c9375574f88f0b2a00c6ed4b | 2,415 | package com.workflowfm.composer.exceptions;
import java.awt.Component;
import com.workflowfm.composer.processes.CProcess;
import com.workflowfm.composer.prover.response.ExceptionResponse;
import com.workflowfm.composer.ui.dialogs.ExceptionDialog;
import com.workflowfm.composer.ui.dialogs.ProverExceptionResponseDialog;
import com.workflowfm.composer.utils.validate.ValidationException;
public class ComponentExceptionHandler implements ExceptionHandler {
private Component component;
public ComponentExceptionHandler(Component component) {
this.component = component;
}
public Component getComponent() {
return this.component;
}
// @Override
// public void handleException(String title, String message) {
// ExceptionDialog dialog = new ExceptionDialog(title, message);
// dialog.show(component);
// }
@Override
public void handleException(String message, Throwable exception) {
ExceptionDialog dialog = new ExceptionDialog("Error", message, exception);
dialog.show(component);
}
@Override
public void handleException(ExceptionResponse response) {
new ProverExceptionResponseDialog(response).show(component);
}
@Override
public void handleException(UserError error) {
ExceptionDialog dialog = new ExceptionDialog(error);
dialog.show(component);
}
@Override
public void handleException(Throwable exception) {
ExceptionDialog dialog = new ExceptionDialog(exception);
dialog.show(component);
}
@Override
public void uncheckedProcess(CProcess process) {
ExceptionDialog dialog = new ExceptionDialog("Error", "Unable to use unchecked process '" + process.getName() + "'.\nPlease verify the process first.");
dialog.show(component);
}
@Override
public void invalidProcess(CProcess process) {
ExceptionDialog dialog = new ExceptionDialog("Error", "Unable to use invalid process '" + process.getName() + "'.\nPlease verify the process first.");
dialog.show(component);
}
@Override
public void handleException(NotFoundException exception) {
ExceptionDialog dialog = new ExceptionDialog("Error finding " + exception.getType(), exception.getMessage());
dialog.show(component);
}
@Override
public void handleException(ValidationException exception) {
ExceptionDialog dialog = new ExceptionDialog("Invalid " + exception.getFieldType() + " '" + exception.getField() + "': " + exception.getValidationMessage());
dialog.show(component);
}
}
| 31.776316 | 159 | 0.772257 |
013d414e226dc9dc80dad8ca21615493add0891a | 470 | //package test.com.jd.blockchain.binaryproto.contract;
//
//import com.jd.blockchain.binaryproto.DataContract;
//import com.jd.blockchain.binaryproto.DataField;
//import com.jd.blockchain.binaryproto.ValueType;
//
//@DataContract(code=0x02, name="Address" , description="")
//public interface Address {
//
// @DataField(order=1, primitiveType=ValueType.TEXT)
// String getStreet();
//
// @DataField(order=2, primitiveType=ValueType.INT32)
// int getNumber();
//
//}
| 27.647059 | 60 | 0.734043 |
9c48882815ac434919f2c8aa5a0be3721418c31c | 440 | package ru.otus.spring.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import ru.otus.spring.dao.PersonDao;
import ru.otus.spring.service.PersonService;
import ru.otus.spring.service.PersonServiceImpl;
@Configuration
public class ServicesConfig {
@Bean
public PersonService personService(PersonDao dao) {
return new PersonServiceImpl(dao);
}
}
| 25.882353 | 60 | 0.793182 |
91777d6bf12f8a0c759c985e56e877a7c7c501bc | 2,826 | package ru.stqa.pft.addressbook1.tests;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ru.stqa.pft.addressbook1.tests.model.GroupData1;
import java.util.concurrent.TimeUnit;
public class GroupCreation2Tests {
FirefoxDriver wd;
@BeforeMethod
public void setUp() throws Exception {
wd = new FirefoxDriver();
wd.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
wd.get("http://localhost/addressbook/group.php");
login("admin", "secret");
}
private void login(String username, String password) {
wd.findElement(By.name("user")).click();
wd.findElement(By.name("user")).clear();
wd.findElement(By.name("user")).sendKeys(username);
wd.findElement(By.name("pass")).click();
wd.findElement(By.name("pass")).clear();
wd.findElement(By.name("pass")).sendKeys(password);
wd.findElement(By.xpath("//form[@id='LoginForm']/input[3]")).click();
}
@Test
public void testsGroupCreation2() {
gotoGroupPage1();
initGroupCreation1();
fillGroupForm1(new GroupData1("task41", "task42", "task43"));
submitGroupCreation1();
returnToGroupPage1();
}
private void returnToGroupPage1() {
wd.findElement(By.linkText("group page")).click();
}
private void fillGroupForm1(GroupData1 groupData1) {
wd.findElement(By.name("group_name")).click();
wd.findElement(By.name("group_name")).click();
wd.findElement(By.name("group_name")).clear();
wd.findElement(By.name("group_name")).sendKeys(groupData1.getName());
wd.findElement(By.name("group_header")).click();
wd.findElement(By.name("group_header")).clear();
wd.findElement(By.name("group_header")).sendKeys(groupData1.getHeader());
wd.findElement(By.name("group_footer")).click();
wd.findElement(By.name("group_footer")).clear();
wd.findElement(By.name("group_footer")).sendKeys(groupData1.getFooter());
}
private void submitGroupCreation1() {
wd.findElement(By.name("submit")).click();
}
private void initGroupCreation1() {
wd.findElement(By.name("new")).click();
}
private void gotoGroupPage1() {
wd.findElement(By.linkText("groups")).click();
}
@AfterMethod
public void tearDown() {
wd.quit();
}
public static boolean isAlertPresent(FirefoxDriver wd) {
try {
wd.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
}
| 31.4 | 81 | 0.643312 |
485a1b2c9b424eabf46bff644b84aa897bd0c61f | 4,222 | /*******************************************************************************
* Copyright (c) 2014 Luaj.org. All rights reserved.
*
* 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 org.luaj.vm2;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.ByteArrayInputStream;
import org.junit.jupiter.api.Test;
import org.luaj.vm2.Globals.BufferedStream;
class BufferedStreamTest {
private BufferedStream NewBufferedStream(int buflen, String contents) {
return new BufferedStream(buflen, new ByteArrayInputStream(contents.getBytes()));
}
@Test
void testReadEmptyStream() throws java.io.IOException {
BufferedStream bs = NewBufferedStream(4, "");
assertEquals(-1, bs.read());
assertEquals(-1, bs.read(new byte[10]));
assertEquals(-1, bs.read(new byte[10], 0, 10));
}
@Test
void testReadByte() throws java.io.IOException {
BufferedStream bs = NewBufferedStream(2, "abc");
assertEquals('a', bs.read());
assertEquals('b', bs.read());
assertEquals('c', bs.read());
assertEquals(-1, bs.read());
}
@Test
void testReadByteArray() throws java.io.IOException {
byte[] array = new byte[3];
BufferedStream bs = NewBufferedStream(4, "abcdef");
assertEquals(3, bs.read(array));
assertEquals("abc", new String(array));
assertEquals(1, bs.read(array));
assertEquals("d", new String(array, 0, 1));
assertEquals(2, bs.read(array));
assertEquals("ef", new String(array, 0, 2));
assertEquals(-1, bs.read());
}
@Test
void testReadByteArrayOffsetLength() throws java.io.IOException {
byte[] array = new byte[10];
BufferedStream bs = NewBufferedStream(8, "abcdefghijklmn");
assertEquals(4, bs.read(array, 0, 4));
assertEquals("abcd", new String(array, 0, 4));
assertEquals(4, bs.read(array, 2, 8));
assertEquals("efgh", new String(array, 2, 4));
assertEquals(6, bs.read(array, 0, 10));
assertEquals("ijklmn", new String(array, 0, 6));
assertEquals(-1, bs.read());
}
@Test
void testMarkOffsetBeginningOfStream() throws java.io.IOException {
byte[] array = new byte[4];
BufferedStream bs = NewBufferedStream(8, "abcdefghijkl");
assertEquals(true, bs.markSupported());
bs.mark(4);
assertEquals(4, bs.read(array));
assertEquals("abcd", new String(array));
bs.reset();
assertEquals(4, bs.read(array));
assertEquals("abcd", new String(array));
assertEquals(4, bs.read(array));
assertEquals("efgh", new String(array));
assertEquals(4, bs.read(array));
assertEquals("ijkl", new String(array));
assertEquals(-1, bs.read());
}
@Test
void testMarkOffsetMiddleOfStream() throws java.io.IOException {
byte[] array = new byte[4];
BufferedStream bs = NewBufferedStream(8, "abcdefghijkl");
assertEquals(true, bs.markSupported());
assertEquals(4, bs.read(array));
assertEquals("abcd", new String(array));
bs.mark(4);
assertEquals(4, bs.read(array));
assertEquals("efgh", new String(array));
bs.reset();
assertEquals(4, bs.read(array));
assertEquals("efgh", new String(array));
assertEquals(4, bs.read(array));
assertEquals("ijkl", new String(array));
assertEquals(-1, bs.read());
}
}
| 36.396552 | 83 | 0.689957 |
bd8bac66e8eaf69f945d8499661b4d3410a38312 | 582 | package ru.stqa.pft.sandbox;
public class FirstProgramm {
public static void main(String[] args) {
hello("QA");
hello("Developer");
Square s = new Square(25);
double l=5;
System.out.println("Площадь квадрата со стороной "+s.l+" = "+s.area());
Rectangle r = new Rectangle(22,24);
double a=4;
double b=6;
System.out.println("Площадь прямоугольника со сторонами "+r.a+" и "+r.b+" = "+r.area());
}
public static void hello(String wazza){
System.out.println("Hello, "+wazza+"!");
}
} | 23.28 | 96 | 0.56701 |
a1255c313f270bd91074f4797358f9575253bee9 | 3,322 | package org.antonakospanos.iot.atlas.web.api.v1;
import io.swagger.annotations.*;
import org.antonakospanos.iot.atlas.service.EventsService;
import org.antonakospanos.iot.atlas.web.api.BaseAtlasController;
import org.antonakospanos.iot.atlas.web.dto.events.HeartbeatFailureResponse;
import org.antonakospanos.iot.atlas.web.dto.events.HeartbeatRequest;
import org.antonakospanos.iot.atlas.web.dto.events.HeartbeatResponseData;
import org.antonakospanos.iot.atlas.web.dto.events.HeartbeatSuccessResponse;
import org.antonakospanos.iot.atlas.web.dto.response.ResponseBase;
import org.antonakospanos.iot.atlas.web.enums.Result;
import org.antonakospanos.iot.atlas.web.validator.EventsValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
@RestController
@Deprecated
@Api(value = "Events API", tags = "events", position = 0 , description = "Event Management of integrated IoT devices")
@RequestMapping(value = "/api/events")
public class EventsController extends BaseAtlasController {
private final static Logger logger = LoggerFactory.getLogger(EventsController.class);
@Autowired
EventsService service;
/**
* Backwards compatibility of PUT /devices/{deviceId} API
*
* @param heartbeat The device's heartbeat event
* @return The actions to be executed by the device
* @deprecated Replaced by PUT /devices/{deviceId} API
*/
@Deprecated
@ApiOperation(value = "Consumes state events that are published by IoT devices", response = HeartbeatSuccessResponse.class,
notes = "Backwards compatibility of PUT /devices/{deviceId} API")
@ApiResponses(value = {
@ApiResponse(code = 201, message = "The event is created!", response = HeartbeatSuccessResponse.class),
@ApiResponse(code = 400, message = "The request is invalid!"),
@ApiResponse(code = 500, message = "Server Error")})
@ResponseStatus(HttpStatus.CREATED)
@RequestMapping(value = "/heartbeat",
produces = {"application/json"},
consumes = {"application/json"},
method = RequestMethod.POST)
public ResponseEntity<ResponseBase> heartbeat(@ApiParam(value = "Inventory item") @Valid @RequestBody HeartbeatRequest heartbeat) {
ResponseEntity<ResponseBase> response;
EventsValidator.validateHeartBeat(heartbeat);
try {
HeartbeatResponseData data = service.create(heartbeat);
HeartbeatSuccessResponse heartbeatSuccessResponse = HeartbeatSuccessResponse.Builder().build(Result.SUCCESS).data(data);
response = ResponseEntity.status(HttpStatus.CREATED).body(heartbeatSuccessResponse);
} catch (Exception e) {
logger.error(e.getClass() + " Cause: " + e.getCause() + " Message: " + e.getMessage() + ". Heartbeat request: " + heartbeat, e);
HeartbeatFailureResponse heartbeatFailureResponse = HeartbeatFailureResponse.Builder().build(Result.GENERIC_ERROR);
response = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(heartbeatFailureResponse);
}
return response;
}
}
| 48.144928 | 140 | 0.742324 |
d843c7b0b3921dbf023fd2a4b3fbfc66a519a8b2 | 23,765 | /*
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @run testng/othervm -Djava.lang.invoke.VarHandle.VAR_HANDLE_GUARDS=true -Djava.lang.invoke.VarHandle.VAR_HANDLE_IDENTITY_ADAPT=false -Xverify:all TestMemoryAccess
* @run testng/othervm -Djava.lang.invoke.VarHandle.VAR_HANDLE_GUARDS=true -Djava.lang.invoke.VarHandle.VAR_HANDLE_IDENTITY_ADAPT=true -Xverify:all TestMemoryAccess
* @run testng/othervm -Djava.lang.invoke.VarHandle.VAR_HANDLE_GUARDS=false -Djava.lang.invoke.VarHandle.VAR_HANDLE_IDENTITY_ADAPT=false -Xverify:all TestMemoryAccess
* @run testng/othervm -Djava.lang.invoke.VarHandle.VAR_HANDLE_GUARDS=false -Djava.lang.invoke.VarHandle.VAR_HANDLE_IDENTITY_ADAPT=true -Xverify:all TestMemoryAccess
*/
import jdk.incubator.foreign.GroupLayout;
import jdk.incubator.foreign.MemoryLayouts;
import jdk.incubator.foreign.MemoryLayout;
import jdk.incubator.foreign.MemoryLayout.PathElement;
import jdk.incubator.foreign.MemorySegment;
import jdk.incubator.foreign.ResourceScope;
import jdk.incubator.foreign.SequenceLayout;
import jdk.incubator.foreign.ValueLayout;
import java.lang.invoke.VarHandle;
import java.util.function.Function;
import org.testng.annotations.*;
import static org.testng.Assert.*;
public class TestMemoryAccess {
@Test(dataProvider = "elements")
public void testAccess(Function<MemorySegment, MemorySegment> viewFactory, ValueLayout elemLayout, Class<?> carrier, Checker checker) {
ValueLayout layout = elemLayout.withName("elem");
testAccessInternal(viewFactory, layout, layout.varHandle(carrier), checker);
}
@Test(dataProvider = "elements")
public void testPaddedAccessByName(Function<MemorySegment, MemorySegment> viewFactory, MemoryLayout elemLayout, Class<?> carrier, Checker checker) {
GroupLayout layout = MemoryLayout.structLayout(MemoryLayout.paddingLayout(elemLayout.bitSize()), elemLayout.withName("elem"));
testAccessInternal(viewFactory, layout, layout.varHandle(carrier, PathElement.groupElement("elem")), checker);
}
@Test(dataProvider = "elements")
public void testPaddedAccessByIndexSeq(Function<MemorySegment, MemorySegment> viewFactory, MemoryLayout elemLayout, Class<?> carrier, Checker checker) {
SequenceLayout layout = MemoryLayout.sequenceLayout(2, elemLayout);
testAccessInternal(viewFactory, layout, layout.varHandle(carrier, PathElement.sequenceElement(1)), checker);
}
@Test(dataProvider = "arrayElements")
public void testArrayAccess(Function<MemorySegment, MemorySegment> viewFactory, MemoryLayout elemLayout, Class<?> carrier, ArrayChecker checker) {
SequenceLayout seq = MemoryLayout.sequenceLayout(10, elemLayout.withName("elem"));
testArrayAccessInternal(viewFactory, seq, seq.varHandle(carrier, PathElement.sequenceElement()), checker);
}
@Test(dataProvider = "arrayElements")
public void testPaddedArrayAccessByName(Function<MemorySegment, MemorySegment> viewFactory, MemoryLayout elemLayout, Class<?> carrier, ArrayChecker checker) {
SequenceLayout seq = MemoryLayout.sequenceLayout(10, MemoryLayout.structLayout(MemoryLayout.paddingLayout(elemLayout.bitSize()), elemLayout.withName("elem")));
testArrayAccessInternal(viewFactory, seq, seq.varHandle(carrier, MemoryLayout.PathElement.sequenceElement(), MemoryLayout.PathElement.groupElement("elem")), checker);
}
@Test(dataProvider = "arrayElements")
public void testPaddedArrayAccessByIndexSeq(Function<MemorySegment, MemorySegment> viewFactory, MemoryLayout elemLayout, Class<?> carrier, ArrayChecker checker) {
SequenceLayout seq = MemoryLayout.sequenceLayout(10, MemoryLayout.sequenceLayout(2, elemLayout));
testArrayAccessInternal(viewFactory, seq, seq.varHandle(carrier, PathElement.sequenceElement(), MemoryLayout.PathElement.sequenceElement(1)), checker);
}
private void testAccessInternal(Function<MemorySegment, MemorySegment> viewFactory, MemoryLayout layout, VarHandle handle, Checker checker) {
MemorySegment outer_segment;
try (ResourceScope scope = ResourceScope.newConfinedScope()) {
MemorySegment segment = viewFactory.apply(MemorySegment.allocateNative(layout, scope));
boolean isRO = segment.isReadOnly();
try {
checker.check(handle, segment);
if (isRO) {
throw new AssertionError(); //not ok, memory should be immutable
}
} catch (UnsupportedOperationException ex) {
if (!isRO) {
throw new AssertionError(); //we should not have failed!
}
return;
}
try {
checker.check(handle, segment.asSlice(layout.byteSize()));
throw new AssertionError(); //not ok, out of bounds
} catch (IndexOutOfBoundsException ex) {
//ok, should fail (out of bounds)
}
outer_segment = segment; //leak!
}
try {
checker.check(handle, outer_segment);
throw new AssertionError(); //not ok, scope is closed
} catch (IllegalStateException ex) {
//ok, should fail (scope is closed)
}
}
private void testArrayAccessInternal(Function<MemorySegment, MemorySegment> viewFactory, SequenceLayout seq, VarHandle handle, ArrayChecker checker) {
MemorySegment outer_segment;
try (ResourceScope scope = ResourceScope.newConfinedScope()) {
MemorySegment segment = viewFactory.apply(MemorySegment.allocateNative(seq, scope));
boolean isRO = segment.isReadOnly();
try {
for (int i = 0; i < seq.elementCount().getAsLong(); i++) {
checker.check(handle, segment, i);
}
if (isRO) {
throw new AssertionError(); //not ok, memory should be immutable
}
} catch (UnsupportedOperationException ex) {
if (!isRO) {
throw new AssertionError(); //we should not have failed!
}
return;
}
try {
checker.check(handle, segment, seq.elementCount().getAsLong());
throw new AssertionError(); //not ok, out of bounds
} catch (IndexOutOfBoundsException ex) {
//ok, should fail (out of bounds)
}
outer_segment = segment; //leak!
}
try {
checker.check(handle, outer_segment, 0);
throw new AssertionError(); //not ok, scope is closed
} catch (IllegalStateException ex) {
//ok, should fail (scope is closed)
}
}
@Test(dataProvider = "matrixElements")
public void testMatrixAccess(Function<MemorySegment, MemorySegment> viewFactory, MemoryLayout elemLayout, Class<?> carrier, MatrixChecker checker) {
SequenceLayout seq = MemoryLayout.sequenceLayout(20,
MemoryLayout.sequenceLayout(10, elemLayout.withName("elem")));
testMatrixAccessInternal(viewFactory, seq, seq.varHandle(carrier,
PathElement.sequenceElement(), PathElement.sequenceElement()), checker);
}
@Test(dataProvider = "matrixElements")
public void testPaddedMatrixAccessByName(Function<MemorySegment, MemorySegment> viewFactory, MemoryLayout elemLayout, Class<?> carrier, MatrixChecker checker) {
SequenceLayout seq = MemoryLayout.sequenceLayout(20,
MemoryLayout.sequenceLayout(10, MemoryLayout.structLayout(MemoryLayout.paddingLayout(elemLayout.bitSize()), elemLayout.withName("elem"))));
testMatrixAccessInternal(viewFactory, seq,
seq.varHandle(carrier,
PathElement.sequenceElement(), PathElement.sequenceElement(), PathElement.groupElement("elem")),
checker);
}
@Test(dataProvider = "matrixElements")
public void testPaddedMatrixAccessByIndexSeq(Function<MemorySegment, MemorySegment> viewFactory, MemoryLayout elemLayout, Class<?> carrier, MatrixChecker checker) {
SequenceLayout seq = MemoryLayout.sequenceLayout(20,
MemoryLayout.sequenceLayout(10, MemoryLayout.sequenceLayout(2, elemLayout)));
testMatrixAccessInternal(viewFactory, seq,
seq.varHandle(carrier,
PathElement.sequenceElement(), PathElement.sequenceElement(), PathElement.sequenceElement(1)),
checker);
}
@Test(dataProvider = "badCarriers",
expectedExceptions = IllegalArgumentException.class)
public void testBadCarriers(Class<?> carrier) {
ValueLayout l = MemoryLayouts.BITS_32_LE.withName("elem");
l.varHandle(carrier);
}
private void testMatrixAccessInternal(Function<MemorySegment, MemorySegment> viewFactory, SequenceLayout seq, VarHandle handle, MatrixChecker checker) {
MemorySegment outer_segment;
try (ResourceScope scope = ResourceScope.newConfinedScope()) {
MemorySegment segment = viewFactory.apply(MemorySegment.allocateNative(seq, scope));
boolean isRO = segment.isReadOnly();
try {
for (int i = 0; i < seq.elementCount().getAsLong(); i++) {
for (int j = 0; j < ((SequenceLayout) seq.elementLayout()).elementCount().getAsLong(); j++) {
checker.check(handle, segment, i, j);
}
}
if (isRO) {
throw new AssertionError(); //not ok, memory should be immutable
}
} catch (UnsupportedOperationException ex) {
if (!isRO) {
throw new AssertionError(); //we should not have failed!
}
return;
}
try {
checker.check(handle, segment, seq.elementCount().getAsLong(),
((SequenceLayout)seq.elementLayout()).elementCount().getAsLong());
throw new AssertionError(); //not ok, out of bounds
} catch (IndexOutOfBoundsException ex) {
//ok, should fail (out of bounds)
}
outer_segment = segment; //leak!
}
try {
checker.check(handle, outer_segment, 0, 0);
throw new AssertionError(); //not ok, scope is closed
} catch (IllegalStateException ex) {
//ok, should fail (scope is closed)
}
}
static Function<MemorySegment, MemorySegment> ID = Function.identity();
static Function<MemorySegment, MemorySegment> IMMUTABLE = MemorySegment::asReadOnly;
@DataProvider(name = "elements")
public Object[][] createData() {
return new Object[][] {
//BE, RW
{ ID, MemoryLayouts.BITS_8_BE, byte.class, Checker.BYTE },
{ ID, MemoryLayouts.BITS_16_BE, short.class, Checker.SHORT },
{ ID, MemoryLayouts.BITS_16_BE, char.class, Checker.CHAR },
{ ID, MemoryLayouts.BITS_32_BE, int.class, Checker.INT },
{ ID, MemoryLayouts.BITS_64_BE, long.class, Checker.LONG },
{ ID, MemoryLayouts.BITS_32_BE, float.class, Checker.FLOAT },
{ ID, MemoryLayouts.BITS_64_BE, double.class, Checker.DOUBLE },
//BE, RO
{ IMMUTABLE, MemoryLayouts.BITS_8_BE, byte.class, Checker.BYTE },
{ IMMUTABLE, MemoryLayouts.BITS_16_BE, short.class, Checker.SHORT },
{ IMMUTABLE, MemoryLayouts.BITS_16_BE, char.class, Checker.CHAR },
{ IMMUTABLE, MemoryLayouts.BITS_32_BE, int.class, Checker.INT },
{ IMMUTABLE, MemoryLayouts.BITS_64_BE, long.class, Checker.LONG },
{ IMMUTABLE, MemoryLayouts.BITS_32_BE, float.class, Checker.FLOAT },
{ IMMUTABLE, MemoryLayouts.BITS_64_BE, double.class, Checker.DOUBLE },
//LE, RW
{ ID, MemoryLayouts.BITS_8_LE, byte.class, Checker.BYTE },
{ ID, MemoryLayouts.BITS_16_LE, short.class, Checker.SHORT },
{ ID, MemoryLayouts.BITS_16_LE, char.class, Checker.CHAR },
{ ID, MemoryLayouts.BITS_32_LE, int.class, Checker.INT },
{ ID, MemoryLayouts.BITS_64_LE, long.class, Checker.LONG },
{ ID, MemoryLayouts.BITS_32_LE, float.class, Checker.FLOAT },
{ ID, MemoryLayouts.BITS_64_LE, double.class, Checker.DOUBLE },
//LE, RO
{ IMMUTABLE, MemoryLayouts.BITS_8_LE, byte.class, Checker.BYTE },
{ IMMUTABLE, MemoryLayouts.BITS_16_LE, short.class, Checker.SHORT },
{ IMMUTABLE, MemoryLayouts.BITS_16_LE, char.class, Checker.CHAR },
{ IMMUTABLE, MemoryLayouts.BITS_32_LE, int.class, Checker.INT },
{ IMMUTABLE, MemoryLayouts.BITS_64_LE, long.class, Checker.LONG },
{ IMMUTABLE, MemoryLayouts.BITS_32_LE, float.class, Checker.FLOAT },
{ IMMUTABLE, MemoryLayouts.BITS_64_LE, double.class, Checker.DOUBLE },
};
}
interface Checker {
void check(VarHandle handle, MemorySegment segment);
Checker BYTE = (handle, segment) -> {
handle.set(segment, (byte)42);
assertEquals(42, (byte)handle.get(segment));
};
Checker SHORT = (handle, segment) -> {
handle.set(segment, (short)42);
assertEquals(42, (short)handle.get(segment));
};
Checker CHAR = (handle, segment) -> {
handle.set(segment, (char)42);
assertEquals(42, (char)handle.get(segment));
};
Checker INT = (handle, segment) -> {
handle.set(segment, 42);
assertEquals(42, (int)handle.get(segment));
};
Checker LONG = (handle, segment) -> {
handle.set(segment, (long)42);
assertEquals(42, (long)handle.get(segment));
};
Checker FLOAT = (handle, segment) -> {
handle.set(segment, (float)42);
assertEquals((float)42, (float)handle.get(segment));
};
Checker DOUBLE = (handle, segment) -> {
handle.set(segment, (double)42);
assertEquals((double)42, (double)handle.get(segment));
};
}
@DataProvider(name = "arrayElements")
public Object[][] createArrayData() {
return new Object[][] {
//BE, RW
{ ID, MemoryLayouts.BITS_8_BE, byte.class, ArrayChecker.BYTE },
{ ID, MemoryLayouts.BITS_16_BE, short.class, ArrayChecker.SHORT },
{ ID, MemoryLayouts.BITS_16_BE, char.class, ArrayChecker.CHAR },
{ ID, MemoryLayouts.BITS_32_BE, int.class, ArrayChecker.INT },
{ ID, MemoryLayouts.BITS_64_BE, long.class, ArrayChecker.LONG },
{ ID, MemoryLayouts.BITS_32_BE, float.class, ArrayChecker.FLOAT },
{ ID, MemoryLayouts.BITS_64_BE, double.class, ArrayChecker.DOUBLE },
//BE, RO
{ IMMUTABLE, MemoryLayouts.BITS_8_BE, byte.class, ArrayChecker.BYTE },
{ IMMUTABLE, MemoryLayouts.BITS_16_BE, short.class, ArrayChecker.SHORT },
{ IMMUTABLE, MemoryLayouts.BITS_16_BE, char.class, ArrayChecker.CHAR },
{ IMMUTABLE, MemoryLayouts.BITS_32_BE, int.class, ArrayChecker.INT },
{ IMMUTABLE, MemoryLayouts.BITS_64_BE, long.class, ArrayChecker.LONG },
{ IMMUTABLE, MemoryLayouts.BITS_32_BE, float.class, ArrayChecker.FLOAT },
{ IMMUTABLE, MemoryLayouts.BITS_64_BE, double.class, ArrayChecker.DOUBLE },
//LE, RW
{ ID, MemoryLayouts.BITS_8_LE, byte.class, ArrayChecker.BYTE },
{ ID, MemoryLayouts.BITS_16_LE, short.class, ArrayChecker.SHORT },
{ ID, MemoryLayouts.BITS_16_LE, char.class, ArrayChecker.CHAR },
{ ID, MemoryLayouts.BITS_32_LE, int.class, ArrayChecker.INT },
{ ID, MemoryLayouts.BITS_64_LE, long.class, ArrayChecker.LONG },
{ ID, MemoryLayouts.BITS_32_LE, float.class, ArrayChecker.FLOAT },
{ ID, MemoryLayouts.BITS_64_LE, double.class, ArrayChecker.DOUBLE },
//LE, RO
{ IMMUTABLE, MemoryLayouts.BITS_8_LE, byte.class, ArrayChecker.BYTE },
{ IMMUTABLE, MemoryLayouts.BITS_16_LE, short.class, ArrayChecker.SHORT },
{ IMMUTABLE, MemoryLayouts.BITS_16_LE, char.class, ArrayChecker.CHAR },
{ IMMUTABLE, MemoryLayouts.BITS_32_LE, int.class, ArrayChecker.INT },
{ IMMUTABLE, MemoryLayouts.BITS_64_LE, long.class, ArrayChecker.LONG },
{ IMMUTABLE, MemoryLayouts.BITS_32_LE, float.class, ArrayChecker.FLOAT },
{ IMMUTABLE, MemoryLayouts.BITS_64_LE, double.class, ArrayChecker.DOUBLE },
};
}
interface ArrayChecker {
void check(VarHandle handle, MemorySegment segment, long index);
ArrayChecker BYTE = (handle, segment, i) -> {
handle.set(segment, i, (byte)i);
assertEquals(i, (byte)handle.get(segment, i));
};
ArrayChecker SHORT = (handle, segment, i) -> {
handle.set(segment, i, (short)i);
assertEquals(i, (short)handle.get(segment, i));
};
ArrayChecker CHAR = (handle, segment, i) -> {
handle.set(segment, i, (char)i);
assertEquals(i, (char)handle.get(segment, i));
};
ArrayChecker INT = (handle, segment, i) -> {
handle.set(segment, i, (int)i);
assertEquals(i, (int)handle.get(segment, i));
};
ArrayChecker LONG = (handle, segment, i) -> {
handle.set(segment, i, (long)i);
assertEquals(i, (long)handle.get(segment, i));
};
ArrayChecker FLOAT = (handle, segment, i) -> {
handle.set(segment, i, (float)i);
assertEquals((float)i, (float)handle.get(segment, i));
};
ArrayChecker DOUBLE = (handle, segment, i) -> {
handle.set(segment, i, (double)i);
assertEquals((double)i, (double)handle.get(segment, i));
};
}
@DataProvider(name = "matrixElements")
public Object[][] createMatrixData() {
return new Object[][] {
//BE, RW
{ ID, MemoryLayouts.BITS_8_BE, byte.class, MatrixChecker.BYTE },
{ ID, MemoryLayouts.BITS_16_BE, short.class, MatrixChecker.SHORT },
{ ID, MemoryLayouts.BITS_16_BE, char.class, MatrixChecker.CHAR },
{ ID, MemoryLayouts.BITS_32_BE, int.class, MatrixChecker.INT },
{ ID, MemoryLayouts.BITS_64_BE, long.class, MatrixChecker.LONG },
{ ID, MemoryLayouts.BITS_32_BE, float.class, MatrixChecker.FLOAT },
{ ID, MemoryLayouts.BITS_64_BE, double.class, MatrixChecker.DOUBLE },
//BE, RO
{ IMMUTABLE, MemoryLayouts.BITS_8_BE, byte.class, MatrixChecker.BYTE },
{ IMMUTABLE, MemoryLayouts.BITS_16_BE, short.class, MatrixChecker.SHORT },
{ IMMUTABLE, MemoryLayouts.BITS_16_BE, char.class, MatrixChecker.CHAR },
{ IMMUTABLE, MemoryLayouts.BITS_32_BE, int.class, MatrixChecker.INT },
{ IMMUTABLE, MemoryLayouts.BITS_64_BE, long.class, MatrixChecker.LONG },
{ IMMUTABLE, MemoryLayouts.BITS_32_BE, float.class, MatrixChecker.FLOAT },
{ IMMUTABLE, MemoryLayouts.BITS_64_BE, double.class, MatrixChecker.DOUBLE },
//LE, RW
{ ID, MemoryLayouts.BITS_8_LE, byte.class, MatrixChecker.BYTE },
{ ID, MemoryLayouts.BITS_16_LE, short.class, MatrixChecker.SHORT },
{ ID, MemoryLayouts.BITS_16_LE, char.class, MatrixChecker.CHAR },
{ ID, MemoryLayouts.BITS_32_LE, int.class, MatrixChecker.INT },
{ ID, MemoryLayouts.BITS_64_LE, long.class, MatrixChecker.LONG },
{ ID, MemoryLayouts.BITS_32_LE, float.class, MatrixChecker.FLOAT },
{ ID, MemoryLayouts.BITS_64_LE, double.class, MatrixChecker.DOUBLE },
//LE, RO
{ IMMUTABLE, MemoryLayouts.BITS_8_LE, byte.class, MatrixChecker.BYTE },
{ IMMUTABLE, MemoryLayouts.BITS_16_LE, short.class, MatrixChecker.SHORT },
{ IMMUTABLE, MemoryLayouts.BITS_16_LE, char.class, MatrixChecker.CHAR },
{ IMMUTABLE, MemoryLayouts.BITS_32_LE, int.class, MatrixChecker.INT },
{ IMMUTABLE, MemoryLayouts.BITS_64_LE, long.class, MatrixChecker.LONG },
{ IMMUTABLE, MemoryLayouts.BITS_32_LE, float.class, MatrixChecker.FLOAT },
{ IMMUTABLE, MemoryLayouts.BITS_64_LE, double.class, MatrixChecker.DOUBLE },
};
}
interface MatrixChecker {
void check(VarHandle handle, MemorySegment segment, long row, long col);
MatrixChecker BYTE = (handle, segment, r, c) -> {
handle.set(segment, r, c, (byte)(r + c));
assertEquals(r + c, (byte)handle.get(segment, r, c));
};
MatrixChecker SHORT = (handle, segment, r, c) -> {
handle.set(segment, r, c, (short)(r + c));
assertEquals(r + c, (short)handle.get(segment, r, c));
};
MatrixChecker CHAR = (handle, segment, r, c) -> {
handle.set(segment, r, c, (char)(r + c));
assertEquals(r + c, (char)handle.get(segment, r, c));
};
MatrixChecker INT = (handle, segment, r, c) -> {
handle.set(segment, r, c, (int)(r + c));
assertEquals(r + c, (int)handle.get(segment, r, c));
};
MatrixChecker LONG = (handle, segment, r, c) -> {
handle.set(segment, r, c, r + c);
assertEquals(r + c, (long)handle.get(segment, r, c));
};
MatrixChecker FLOAT = (handle, segment, r, c) -> {
handle.set(segment, r, c, (float)(r + c));
assertEquals((float)(r + c), (float)handle.get(segment, r, c));
};
MatrixChecker DOUBLE = (handle, segment, r, c) -> {
handle.set(segment, r, c, (double)(r + c));
assertEquals((double)(r + c), (double)handle.get(segment, r, c));
};
}
@DataProvider(name = "badCarriers")
public Object[][] createBadCarriers() {
return new Object[][] {
{ void.class },
{ boolean.class },
{ Object.class },
{ int[].class }
};
}
}
| 50.888651 | 174 | 0.62125 |
7e97cfe408a22d2881ea92fd459431c812688fdc | 180 | package club.extendz.spring.keycloak.exceptions;
public class UserDeletionFailedException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
}
| 16.363636 | 60 | 0.755556 |
7bc651d916c8ff5ff485e5fd95d2e3a851b3e5a3 | 447 | package com.claudio.contexto;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Contexto {
protected static ApplicationContext contexto;
static {
contexto = new ClassPathXmlApplicationContext(
"Spring-Module.xml");
}
public static Object getBean(String beanName) {
return contexto.getBean(beanName);
}
}
| 20.318182 | 75 | 0.742729 |
4a69300a0dd3a8da2dd14cfe0cea6f1942ada692 | 10,843 | // ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataquality.semantic.recognizer;
import static org.talend.dataquality.semantic.classifier.SemanticCategoryEnum.UNKNOWN;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.talend.dataquality.record.linkage.attribute.AbstractAttributeMatcher;
import org.talend.dataquality.record.linkage.attribute.LevenshteinMatcher;
import org.talend.dataquality.record.linkage.constant.TokenizedResolutionMethod;
import org.talend.dataquality.semantic.classifier.custom.UserDefinedClassifier;
import org.talend.dataquality.semantic.classifier.impl.DataDictFieldClassifier;
import org.talend.dataquality.semantic.index.Index;
import org.talend.dataquality.semantic.model.DQCategory;
import org.talend.dataquality.semantic.model.MainCategory;
import org.talend.dataquality.semantic.snapshot.DictionarySnapshot;
/**
* created by talend on 2015-07-28 Detailled comment.
*
*/
public class DefaultCategoryRecognizer implements CategoryRecognizer {
private final List<CategoryFrequency> catList = new ArrayList<>();
private final Map<String, CategoryFrequency> categoryToFrequency = new HashMap<>();
private final DataDictFieldClassifier dataDictFieldClassifier;
private final UserDefinedClassifier userDefineClassifier;
private final Map<String, DQCategory> metadata;
private final LFUCache<String, Set<String>> knownCategoryCache = new LFUCache<String, Set<String>>(10, 1000, 0.01f);
private long emptyCount = 0;
private long total = 0;
private AbstractAttributeMatcher defaultMatcher = new LevenshteinMatcher();
private boolean fingerPrintApply = true;
private boolean tokenizedApply = true;
public DefaultCategoryRecognizer(DictionarySnapshot dictionarySnapshot) throws IOException {
this(dictionarySnapshot.getSharedDataDict(), dictionarySnapshot.getCustomDataDict(), dictionarySnapshot.getKeyword(),
dictionarySnapshot.getRegexClassifier(), dictionarySnapshot.getMetadata());
}
public DefaultCategoryRecognizer(final Index sharedDictionary, Index customDictionary, Index keyword,
UserDefinedClassifier regex, Map<String, DQCategory> metadata) throws IOException {
this.userDefineClassifier = regex;
this.userDefineClassifier.getClassifiers().removeIf(classifier -> metadata.get(classifier.getId()) != null
&& Boolean.TRUE.equals(metadata.get(classifier.getId()).getDeleted()));
this.metadata = metadata;
final List<String> sharedCategories = new ArrayList<>();
final List<String> customCategories = new ArrayList<>();
for (DQCategory cat : metadata.values()) {
if (!cat.getDeleted()) {
if (cat.getModified()) {
customCategories.add(cat.getId());
} else {
sharedCategories.add(cat.getId());
}
}
}
sharedDictionary.setCategoriesToSearch(sharedCategories);
if (customDictionary != null) {
customDictionary.setCategoriesToSearch(customCategories);
}
dataDictFieldClassifier = new DataDictFieldClassifier(sharedDictionary, customDictionary, keyword);
}
@Override
public DataDictFieldClassifier getDataDictFieldClassifier() {
return dataDictFieldClassifier;
}
@Override
public UserDefinedClassifier getUserDefineClassifier() {
return userDefineClassifier;
}
/**
* @param data the input value
* @return the set of its semantic categories
*/
public Set<String> getSubCategorySet(String data) {
if (data == null || StringUtils.EMPTY.equals(data.trim())) {
emptyCount++;
return new HashSet<>();
}
final Set<String> knownCategory = knownCategoryCache.get(data);
if (knownCategory != null) {
return knownCategory;
}
MainCategory mainCategory = MainCategory.getMainCategory(data);
Set<String> subCategorySet = new HashSet<>();
switch (mainCategory) {
case Alpha:
case Numeric:
case AlphaNumeric:
subCategorySet.addAll(dataDictFieldClassifier.classify(data));
if (userDefineClassifier != null) {
subCategorySet.addAll(userDefineClassifier.classify(data, mainCategory));
}
knownCategoryCache.put(data, subCategorySet);
break;
case NULL:
case BLANK:
emptyCount++;
break;
}
return subCategorySet;
}
@Override
public void prepare() {
// dictionary.initIndex();
// keyword.initIndex();
}
@Override
public void reset() {
catList.clear();
categoryToFrequency.clear();
total = 0;
emptyCount = 0;
knownCategoryCache.clear();
}
/*
* (non-Javadoc)
*
* @see org.talend.dataquality.semantic.recognizer.CategoryRecognizer#process(java.lang.String)
*/
@Override
public String[] process(String data) {
Set<String> ids = getSubCategorySet(data);
Map<String, Integer> categoryToLevel = new HashMap<>();
List<String> categories = new ArrayList<>();
if (!ids.isEmpty()) {
for (String id : ids) {
categoryToLevel.put(id, 0);
DQCategory meta = metadata.get(id);
if (meta != null) {
if (!CollectionUtils.isEmpty(meta.getParents()))
incrementAncestorsCategories(categoryToLevel, id);
}
}
for (Map.Entry<String, Integer> entry : categoryToLevel.entrySet()) {
DQCategory meta = metadata.get(entry.getKey());
if (meta != null) {
categories.add(meta.getName());
incrementCategory(meta.getName(), meta.getLabel(), entry.getValue());
}
}
} else {
incrementCategory(StringUtils.EMPTY);
}
total++;
return categories.toArray(new String[categories.size()]);
}
/**
* For the discovery, if a category c matches with the data,
* it means all the ancestor categories of c have to match too.
* This method increments the ancestor categories of c.
*
* @param categoryToLevel, the category result
* @param id, the category ID of the matched category c
* @param categoryToLevel
*
*/
private void incrementAncestorsCategories(Map<String, Integer> categoryToLevel, String id) {
Deque<String> catToSee = new ArrayDeque<>();
catToSee.add(id);
String currentCategory;
while (!catToSee.isEmpty()) {
currentCategory = catToSee.pop();
DQCategory dqCategory = metadata.get(currentCategory);
Integer categoryLevel = categoryToLevel.get(currentCategory);
if (dqCategory != null && !CollectionUtils.isEmpty(dqCategory.getParents())) {
for (DQCategory parent : dqCategory.getParents()) {
String parentId = parent.getId();
Integer level = categoryToLevel.get(parentId);
if (level == null || level < categoryLevel + 1) {
categoryToLevel.put(parentId, categoryLevel + 1);
catToSee.add(parentId);
}
}
}
}
}
private void incrementCategory(String categoryName) {
incrementCategory(categoryName, categoryName);
}
private void incrementCategory(String categoryName, String categoryLabel) {
incrementCategory(categoryName, categoryLabel, 0);
}
private void incrementCategory(String categoryName, String categoryLabel, int categoryLevel) {
CategoryFrequency c = categoryToFrequency.get(categoryName);
if (c == null) {
c = new CategoryFrequency(categoryName, categoryLabel, categoryLevel);
categoryToFrequency.put(categoryName, c);
catList.add(c);
}
c.count++;
}
@Deprecated
public Collection<CategoryFrequency> getResult() {
for (CategoryFrequency category : categoryToFrequency.values()) {
category.score = Math.round(category.count * 10000 / total) / 100F;
}
Collections.sort(catList, Collections.reverseOrder());
return catList;
}
@Override
public Collection<CategoryFrequency> getResult(String columnName, float weight) {
for (CategoryFrequency category : categoryToFrequency.values()) {
category.score = category.count * 100F / total;
if (tokenizedApply) {
defaultMatcher.setTokenMethod(TokenizedResolutionMethod.ANYORDER);
}
defaultMatcher.setFingerPrintApply(fingerPrintApply);
float scoreOnHeader = 0;
if (columnName != null && !UNKNOWN.getDisplayName().equals(category.getCategoryName()))
scoreOnHeader = Double.valueOf(defaultMatcher.getMatchingWeight(columnName, category.getCategoryName()))
.floatValue();
if (scoreOnHeader > 0.7)
category.score += scoreOnHeader * weight * 100;
category.score = Math.min(Math.round(category.score * 100) / 100F, 100);
}
Collections.sort(catList, Collections.reverseOrder());
return catList;
}
@Override
public void end() {
dataDictFieldClassifier.closeIndex();
knownCategoryCache.clear();
}
public void setDefaultMatcher(AbstractAttributeMatcher defaultMatcher) {
this.defaultMatcher = defaultMatcher;
}
public void setFingerPrintApply(boolean fingerPrintApply) {
this.fingerPrintApply = fingerPrintApply;
}
public void setTokenizedApply(boolean tokenizedApply) {
this.tokenizedApply = tokenizedApply;
}
}
| 36.755932 | 125 | 0.642258 |
38c2e0ad96f187cce565b3bd2c368502c42b0d5b | 2,674 | /*
* Copyright (C) 2015 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.setupwizardlib.test;
import android.test.AndroidTestCase;
import android.test.suitebuilder.annotation.SmallTest;
import com.android.setupwizardlib.items.Item;
import com.android.setupwizardlib.items.ItemAdapter;
import com.android.setupwizardlib.items.ItemGroup;
import com.android.setupwizardlib.items.ItemHierarchy;
import java.util.Arrays;
import java.util.HashSet;
public class ItemAdapterTest extends AndroidTestCase {
private Item[] mItems = new Item[5];
private ItemGroup mItemGroup = new ItemGroup();
@Override
protected void setUp() throws Exception {
super.setUp();
for (int i = 0; i < 5; i++) {
Item item = new Item();
item.setTitle("TestTitle" + i);
item.setId(i);
item.setLayoutResource(((i % 3) + 1) * 10);
mItems[i] = item;
mItemGroup.addChild(item);
}
}
@SmallTest
public void testAdapter() {
ItemAdapter adapter = new ItemAdapter(mItemGroup);
assertEquals("Adapter should have 5 items", 5, adapter.getCount());
assertEquals("Adapter should return the first item", mItems[0], adapter.getItem(0));
assertEquals("ID should be same as position", 2, adapter.getItemId(2));
// Each test item has its own layout resource, and therefore its own view type
assertEquals("Should have 3 different view types", 3, adapter.getViewTypeCount());
HashSet<Integer> viewTypes = new HashSet<>(3);
viewTypes.add(adapter.getItemViewType(0));
viewTypes.add(adapter.getItemViewType(1));
viewTypes.add(adapter.getItemViewType(2));
assertEquals("View types should be 0, 1, 2",
new HashSet<>(Arrays.asList(0, 1, 2)), viewTypes);
}
@SmallTest
public void testGetRootItemHierarchy() {
ItemAdapter adapter = new ItemAdapter(mItemGroup);
ItemHierarchy root = adapter.getRootItemHierarchy();
assertSame("Root item hierarchy should be mItemGroup", mItemGroup, root);
}
}
| 36.630137 | 92 | 0.684368 |
9288b1b85b63d38912ed9220a99d7e469d708e49 | 11,369 | package io.ketill.awt;
import io.ketill.FeatureAdapter;
import io.ketill.IoDeviceAdapter;
import io.ketill.MappedFeatureRegistry;
import io.ketill.MappingMethod;
import io.ketill.pc.KeyPressZ;
import io.ketill.pc.Keyboard;
import io.ketill.pc.KeyboardKey;
import org.jetbrains.annotations.MustBeInvokedByOverriders;
import org.jetbrains.annotations.NotNull;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.Objects;
import static io.ketill.pc.Keyboard.*;
import static java.awt.event.KeyEvent.*;
/**
* A {@link Keyboard} adapter using Java AWT.
* <p>
* <b>Adapter quirks:</b> Unlike the {@code glfw-pc} module, this
* adapter uses virtual key codes to map keyboard keys. This means
* the physical location of a key will change based on the current
* keyboard layout of the system (such as QWERTY, AZERTY, etc.)
* <p>
* <b>Thread safety:</b> This adapter is <i>thread-safe.</i>
*/
public class AwtKeyboardAdapter extends IoDeviceAdapter<Keyboard> {
private static final int VK_F25 = VK_F24 + 1;
/**
* Captures the keyboard from a Java AWT component.
* <p>
* <b>Thread safety:</b> The returned keyboard can be shared among
* multiple threads. Its adapter is an {@link AwtKeyboardAdapter},
* which is <i>thread-safe.</i>
*
* @param component the AWT component.
* @return the captured keyboard.
* @throws NullPointerException if {@code component} is {@code null}.
*/
@CapturingMethod
public static @NotNull Keyboard capture(@NotNull Component component) {
Objects.requireNonNull(component, "component cannot be null");
return new Keyboard((d, r) -> new AwtKeyboardAdapter(d, r, component));
}
/**
* Captures the keyboard from a Java AWT component.
* <p>
* <b>Similar to:</b> {@link #capture(Component)}, with the difference
* being that the returned {@code Keyboard} will be polled automatically
* in a background thread managed by Ketill's Java AWT module.
* <p>
* <b>Thread safety:</b> The returned worker can be shared among multiple
* threads. It is an {@link AwtPollWorker}, which is <i>thread-safe.</i>
* Furthermore, the keyboard this worker manages can also be shared among
* multiple threads. Its adapter is an {@link AwtKeyboardAdapter}, which
* is also <i>thread-safe.</i>
*
* @param component the AWT component.
* @return the captured keyboard.
* @throws NullPointerException if {@code component} is {@code null}.
* @see AwtPollWorker#getDevice()
* @see AwtPollWorker#close()
*/
/* @formatter:off */
@CapturingMethod
public static @NotNull AwtPollWorker<Keyboard>
captureBackground(@NotNull Component component) {
Objects.requireNonNull(component, "component cannot be null");
Keyboard keyboard = capture(component);
return AwtPollWorker.pollInBackground(keyboard);
}
/* @formatter:on */
private final @NotNull AwtKeyboardListener keyboardListener;
/**
* Constructs a new {@code AwtKeyboardAdapter}.
*
* @param keyboard the keyboard which owns this adapter.
* @param registry the keyboard's mapped feature registry.
* @param component the AWT component.
* @throws NullPointerException if {@code device}, {@code registry},
* or {@code component} are {@code null}.
*/
public AwtKeyboardAdapter(@NotNull Keyboard keyboard,
@NotNull MappedFeatureRegistry registry,
@NotNull Component component) {
super(keyboard, registry);
Objects.requireNonNull(component, "component cannot be null");
this.keyboardListener = new AwtKeyboardListener(component);
}
/**
* Maps a {@link KeyboardKey} to a virtual keycode at a given location
* on the keyboard.
*
* @param key the keyboard key to map.
* @param keyCode the keycode to map {@code key} to.
* @param keyLocation the location of the key.
* @throws NullPointerException if {@code key} is {@code null}.
* @see #updateKey(KeyPressZ, AwtKeyMapping)
*/
@MappingMethod
protected void mapKey(@NotNull KeyboardKey key, int keyCode,
int keyLocation) {
Objects.requireNonNull(key, "key cannot be null");
registry.mapFeature(key, new AwtKeyMapping(keyCode, keyLocation),
this::updateKey);
}
/**
* Maps a {@link KeyboardKey} to a virtual keycode.
* <p>
* <b>Shorthand for:</b> {@link #mapKey(KeyboardKey, int, int)},
* with the argument for {@code keyLocation} being
* {@link KeyEvent#KEY_LOCATION_STANDARD}.
*
* @param key the keyboard key to map.
* @param keyCode the keycode to map {@code key} to.
* @throws NullPointerException if {@code key} is {@code null}.
* @see #updateKey(KeyPressZ, AwtKeyMapping)
*/
@MappingMethod
protected final void mapKey(@NotNull KeyboardKey key, int keyCode) {
this.mapKey(key, keyCode, KEY_LOCATION_STANDARD);
}
private void mapPrintableKeys() {
this.mapKey(KEY_SPACE, VK_SPACE);
this.mapKey(KEY_APOSTROPHE, VK_QUOTE);
this.mapKey(KEY_COMMA, VK_COMMA);
this.mapKey(KEY_MINUS, VK_MINUS);
this.mapKey(KEY_PERIOD, VK_PERIOD);
this.mapKey(KEY_SLASH, VK_SLASH);
this.mapKey(KEY_ZERO, VK_0);
this.mapKey(KEY_ONE, VK_1);
this.mapKey(KEY_TWO, VK_2);
this.mapKey(KEY_THREE, VK_3);
this.mapKey(KEY_FOUR, VK_4);
this.mapKey(KEY_FIVE, VK_5);
this.mapKey(KEY_SIX, VK_6);
this.mapKey(KEY_SEVEN, VK_7);
this.mapKey(KEY_EIGHT, VK_8);
this.mapKey(KEY_NINE, VK_9);
this.mapKey(KEY_SEMICOLON, VK_SEMICOLON);
this.mapKey(KEY_EQUAL, VK_EQUALS);
this.mapKey(KEY_A, VK_A);
this.mapKey(KEY_B, VK_B);
this.mapKey(KEY_C, VK_C);
this.mapKey(KEY_D, VK_D);
this.mapKey(KEY_E, VK_E);
this.mapKey(KEY_F, VK_F);
this.mapKey(KEY_G, VK_G);
this.mapKey(KEY_H, VK_H);
this.mapKey(KEY_I, VK_I);
this.mapKey(KEY_J, VK_J);
this.mapKey(KEY_K, VK_K);
this.mapKey(KEY_L, VK_L);
this.mapKey(KEY_M, VK_M);
this.mapKey(KEY_N, VK_N);
this.mapKey(KEY_O, VK_O);
this.mapKey(KEY_P, VK_P);
this.mapKey(KEY_Q, VK_Q);
this.mapKey(KEY_R, VK_R);
this.mapKey(KEY_S, VK_S);
this.mapKey(KEY_T, VK_T);
this.mapKey(KEY_U, VK_U);
this.mapKey(KEY_V, VK_V);
this.mapKey(KEY_W, VK_W);
this.mapKey(KEY_X, VK_X);
this.mapKey(KEY_Y, VK_Y);
this.mapKey(KEY_Z, VK_Z);
this.mapKey(KEY_LEFT_BRACKET, VK_OPEN_BRACKET);
this.mapKey(KEY_BACKSLASH, VK_BACK_SLASH);
this.mapKey(KEY_RIGHT_BRACKET, VK_CLOSE_BRACKET);
this.mapKey(KEY_GRAVE_ACCENT, VK_BACK_QUOTE);
}
private void mapMethodKeys() {
this.mapKey(KEY_ESCAPE, VK_ESCAPE);
this.mapKey(KEY_ENTER, VK_ENTER);
this.mapKey(KEY_TAB, VK_TAB);
this.mapKey(KEY_BACKSPACE, VK_BACK_SPACE);
this.mapKey(KEY_INSERT, VK_INSERT);
this.mapKey(KEY_DELETE, VK_DELETE);
this.mapKey(KEY_RIGHT, VK_RIGHT);
this.mapKey(KEY_LEFT, VK_LEFT);
this.mapKey(KEY_DOWN, VK_DOWN);
this.mapKey(KEY_UP, VK_UP);
this.mapKey(KEY_PAGE_UP, VK_PAGE_UP);
this.mapKey(KEY_PAGE_DOWN, VK_PAGE_DOWN);
this.mapKey(KEY_HOME, VK_HOME);
this.mapKey(KEY_END, VK_END);
this.mapKey(KEY_CAPS_LOCK, VK_CAPS_LOCK);
this.mapKey(KEY_SCROLL_LOCK, VK_SCROLL_LOCK);
this.mapKey(KEY_NUM_LOCK, VK_NUM_LOCK);
this.mapKey(KEY_PRINT_SCREEN, VK_PRINTSCREEN);
this.mapKey(KEY_PAUSE, VK_PAUSE);
this.mapKey(KEY_F1, VK_F1);
this.mapKey(KEY_F2, VK_F2);
this.mapKey(KEY_F3, VK_F3);
this.mapKey(KEY_F4, VK_F4);
this.mapKey(KEY_F5, VK_F5);
this.mapKey(KEY_F6, VK_F6);
this.mapKey(KEY_F7, VK_F7);
this.mapKey(KEY_F8, VK_F8);
this.mapKey(KEY_F9, VK_F9);
this.mapKey(KEY_F10, VK_F10);
this.mapKey(KEY_F11, VK_F11);
this.mapKey(KEY_F12, VK_F12);
this.mapKey(KEY_F13, VK_F13);
this.mapKey(KEY_F14, VK_F14);
this.mapKey(KEY_F15, VK_F15);
this.mapKey(KEY_F16, VK_F16);
this.mapKey(KEY_F17, VK_F17);
this.mapKey(KEY_F18, VK_F18);
this.mapKey(KEY_F19, VK_F19);
this.mapKey(KEY_F20, VK_F20);
this.mapKey(KEY_F21, VK_F21);
this.mapKey(KEY_F22, VK_F22);
this.mapKey(KEY_F23, VK_F23);
this.mapKey(KEY_F24, VK_F24);
this.mapKey(KEY_F25, VK_F25);
this.mapKey(KEY_KP_0, VK_NUMPAD0, KEY_LOCATION_NUMPAD);
this.mapKey(KEY_KP_1, VK_NUMPAD1, KEY_LOCATION_NUMPAD);
this.mapKey(KEY_KP_2, VK_NUMPAD2, KEY_LOCATION_NUMPAD);
this.mapKey(KEY_KP_3, VK_NUMPAD3, KEY_LOCATION_NUMPAD);
this.mapKey(KEY_KP_4, VK_NUMPAD4, KEY_LOCATION_NUMPAD);
this.mapKey(KEY_KP_5, VK_NUMPAD5, KEY_LOCATION_NUMPAD);
this.mapKey(KEY_KP_6, VK_NUMPAD6, KEY_LOCATION_NUMPAD);
this.mapKey(KEY_KP_7, VK_NUMPAD7, KEY_LOCATION_NUMPAD);
this.mapKey(KEY_KP_8, VK_NUMPAD8, KEY_LOCATION_NUMPAD);
this.mapKey(KEY_KP_9, VK_NUMPAD9, KEY_LOCATION_NUMPAD);
this.mapKey(KEY_KP_DOT, VK_DECIMAL, KEY_LOCATION_NUMPAD);
this.mapKey(KEY_KP_DIV, VK_DIVIDE, KEY_LOCATION_NUMPAD);
this.mapKey(KEY_KP_MUL, VK_MULTIPLY, KEY_LOCATION_NUMPAD);
this.mapKey(KEY_KP_SUB, VK_SUBTRACT, KEY_LOCATION_NUMPAD);
this.mapKey(KEY_KP_ADD, VK_ADD, KEY_LOCATION_NUMPAD);
this.mapKey(KEY_KP_ENTER, VK_ENTER, KEY_LOCATION_NUMPAD);
this.mapKey(KEY_KP_EQUAL, VK_EQUALS, KEY_LOCATION_NUMPAD);
this.mapKey(KEY_LEFT_SHIFT, VK_SHIFT, KEY_LOCATION_LEFT);
this.mapKey(KEY_LEFT_CTRL, VK_CONTROL, KEY_LOCATION_LEFT);
this.mapKey(KEY_LEFT_ALT, VK_ALT, KEY_LOCATION_LEFT);
this.mapKey(KEY_LEFT_SUPER, VK_WINDOWS, KEY_LOCATION_LEFT);
this.mapKey(KEY_RIGHT_SHIFT, VK_SHIFT, KEY_LOCATION_RIGHT);
this.mapKey(KEY_RIGHT_CTRL, VK_CONTROL, KEY_LOCATION_RIGHT);
this.mapKey(KEY_RIGHT_ALT, VK_ALT, KEY_LOCATION_RIGHT);
this.mapKey(KEY_RIGHT_SUPER, VK_WINDOWS, KEY_LOCATION_RIGHT);
this.mapKey(KEY_MENU, VK_CONTEXT_MENU);
}
@Override
@MustBeInvokedByOverriders
protected void initAdapter() {
this.mapPrintableKeys();
this.mapMethodKeys();
}
/**
* Updater for keyboard keys mapped via
* {@link #mapKey(KeyboardKey, int, int)}.
*
* @param state the key state.
* @param mapping the key mapping.
*/
@FeatureAdapter
protected void updateKey(@NotNull KeyPressZ state,
@NotNull AwtKeyMapping mapping) {
state.pressed = keyboardListener.isPressed(mapping);
}
@Override
@MustBeInvokedByOverriders
protected void pollDevice() {
if (!keyboardListener.isInitialized()) {
keyboardListener.init();
}
}
@Override
protected final boolean isDeviceConnected() {
return true; /* keyboard is always connected */
}
}
| 38.934932 | 79 | 0.653268 |
110ca94f088142310c7b420ea9949d093b1a79b6 | 4,346 | /*
* Copyright 2017 dmfs GmbH
*
* 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.dmfs.rfc3986.encoding;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* @author marten
*/
public class PrecodedTest
{
@Test
public void decoded() throws Exception
{
}
@Test
public void length() throws Exception
{
}
@Test
public void charAt() throws Exception
{
}
@Test
public void subSequence() throws Exception
{
assertEquals(new Precoded("123"), new Precoded("abc123xyz").subSequence(3, 6));
assertEquals("123", new Precoded("abc123xyz").subSequence(3, 6).toString());
}
@Test
public void testHashCode() throws Exception
{
}
@Test
public void equals() throws Exception
{
}
@Test
public void normalized() throws Exception
{
assertEquals("", new Precoded("").normalized().toString());
assertEquals("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
new Precoded("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ").normalized().toString());
assertEquals(".-_~", new Precoded(".-_~").normalized().toString());
assertEquals("%25%2F%22%26%3D%C3%9C%C3%96%C3%84a%C2%B9%C2%B2%C2%B3%C2%BC%C2%BD%C2%AC%40" +
"%C3%A6%C5%BF%C3%B0%C4%91%C5%8B%C4%A7%C5%82%C5%82%E2%82%AC%C2%B6%C5" +
"%A7%E2%86%90%E2%86%93%E2%86%92%C3%B8%C3%BE%C2%AB%C2%A2%E2%80%9E%E2" +
"%80%9C%E2%80%9D%C2%B5%E2%80%A6%C2%B7%C3%A2%C3%B4%C3%AA%C3%A0%C3%A8%C3%B2%C3%B9%C3%A2%20+",
new Precoded("%25%2F%22%26%3D%C3%9C%C3%96%C3%84a%C2%B9%C2%B2%C2%B3%C2%BC%C2%BD%C2%AC%40" +
"%C3%A6%C5%BF%C3%B0%C4%91%C5%8B%C4%A7%C5%82%C5%82%E2%82%AC%C2%B6%C5" +
"%A7%E2%86%90%E2%86%93%E2%86%92%C3%B8%C3%BE%C2%AB%C2%A2%E2%80%9E%E2" +
"%80%9C%E2%80%9D%C2%B5%E2%80%A6%C2%B7%C3%A2%C3%B4%C3%AA%C3%A0%C3%A8%C3%B2%C3%B9%C3%A2%20+").normalized().toString());
assertEquals("%25%2F%22%26%3D%C3%9C%C3%96%C3%84a%C2%B9%C2%B2%C2%B3%C2%BC%C2%BD%C2%AC%40" +
"%C3%A6%C5%BF%C3%B0%C4%91%C5%8B%C4%A7%C5%82%C5%82%E2%82%AC%C2%B6%C5" +
"%A7%E2%86%90%E2%86%93%E2%86%92%C3%B8%C3%BE%C2%AB%C2%A2%E2%80%9E%E2" +
"%80%9C%E2%80%9D%C2%B5%E2%80%A6%C2%B7%C3%A2%C3%B4%C3%AA%C3%A0%C3%A8%C3%B2%C3%B9%C3%A2%20+ab0",
new Precoded("%25%2f%22%26%3D%c3%9C%C3%96%C3%84a%C2%B9%C2%B2%C2%B3%C2%BC%C2%BD%C2%AC%40" +
"%C3%A6%C5%BF%C3%B0%C4%91%C5%8B%C4%A7%C5%82%C5%82%E2%82%ac%C2%B6%C5" +
"%A7%E2%86%90%E2%86%93%E2%86%92%C3%B8%C3%BE%C2%AB%C2%A2%E2%80%9E%E2" +
"%80%9C%E2%80%9D%C2%B5%E2%80%A6%C2%B7%C3%A2%C3%B4%C3%AA%c3%A0%C3%A8%C3%b2%C3%b9%c3%a2%20+%61%62%30").normalized().toString());
}
@Test
public void testDecoded() throws Exception
{
assertEquals("", new Precoded("").decoded());
assertEquals("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
new Precoded("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ").decoded());
assertEquals(".-_~", new Precoded(".-_~").decoded());
assertEquals("%/\"&=ÜÖÄa¹²³¼½¬@æſðđŋħłł€¶ŧ←↓→øþ«¢„“”µ…·âôêàèòùâ +",
new Precoded("%25%2F%22%26%3D%C3%9C%C3%96%C3%84a%C2%B9%C2%B2%C2%B3%C2%BC%C2%BD%C2%AC%40" +
"%C3%A6%C5%BF%C3%B0%C4%91%C5%8B%C4%A7%C5%82%C5%82%E2%82%AC%C2%B6%C5" +
"%A7%E2%86%90%E2%86%93%E2%86%92%C3%B8%C3%BE%C2%AB%C2%A2%E2%80%9E%E2" +
"%80%9C%E2%80%9D%C2%B5%E2%80%A6%C2%B7%C3%A2%C3%B4%C3%AA%C3%A0%C3%A8%C3%B2%C3%B9%C3%A2%20+").decoded());
}
} | 38.460177 | 150 | 0.589738 |
245792f91a03f85878727759ee069dad75e1d83d | 933 | package org.deletethis.hardcode;
import org.junit.Test;
import java.io.Serializable;
import java.util.Objects;
public class Data implements Serializable {
private final String foo;
private final int bar;
private final Long lng;
public Data(String foo, int bar, Long lng) {
this.foo = foo;
this.bar = bar;
this.lng = lng;
}
public String getFoo() {
return foo;
}
public int getBar() {
return bar;
}
public Long getLng() {
return lng;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Data)) return false;
Data data = (Data) o;
return bar == data.bar &&
Objects.equals(foo, data.foo) &&
Objects.equals(lng, data.lng);
}
@Override
public int hashCode() {
return Objects.hash(foo, bar, lng);
}
}
| 19.851064 | 48 | 0.566988 |
d501525b7eb919accc2bcf52120d54248ee37dce | 4,348 | package com.jatpeo.yard.common.util;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
/*
* springboot整合阿里云OSS
* */
@Slf4j
public class AliyunOSSUtil {
private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
private static final String endpoint = "oss-cn-beijing.aliyuncs.com";
private static final String accessKeyId = "LTAI4GCpQD6z4PviNhRLgFGv";
private static final String accessKeySecret = "Z8w6UjESq3p8OIeUCnWDc3Z2zfs1eC";
private static final String bucketName = "jiatp-blog";
private static final String fileHost = "jpps";
/*
* 上传
* */
public static String upload(File file) {
log.info("=========>OSS文件上传开始:" + file.getName());
System.out.println(endpoint + "endpoint");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = format.format(new Date());
if (null == file) {
return null;
}
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
try {
//容器不存在,就创建
if (!ossClient.doesBucketExist(bucketName)) {
ossClient.createBucket(bucketName);
CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
ossClient.createBucket(createBucketRequest);
}
//创建文件路径
String fileUrl = fileHost + "/" + (dateStr + "/" + UUID.randomUUID().toString().replace("-", "") + "-" + file.getName());
//上传文件
PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, file));
//设置权限 这里是公开读
ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
if (null != result) {
log.info("==========>OSS文件上传成功,OSS地址:" + fileUrl);
return fileUrl;
}
} catch (OSSException oe) {
log.error(oe.getMessage());
} catch (ClientException ce) {
log.error(ce.getMessage());
} finally {
//关闭
ossClient.shutdown();
}
return null;
}
/**
* 删除
*
* @param fileKey
* @return
*/
public static String deleteBlog(String fileKey) {
log.info("=========>OSS文件删除开始");
try {
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
if (!ossClient.doesBucketExist(bucketName)) {
log.info("==============>您的Bucket不存在");
return "您的Bucket不存在";
} else {
log.info("==============>开始删除Object");
ossClient.deleteObject(bucketName, fileKey);
log.info("==============>Object删除成功:" + fileKey);
return "==============>Object删除成功:" + fileKey;
}
} catch (Exception ex) {
log.info("删除Object失败", ex);
return "删除Object失败";
}
}
/**
* 查询文件名列表
*
* @param bucketName
* @return
*/
public static List<String> getObjectList(String bucketName) {
List<String> listRe = new ArrayList<String>();
try {
log.info("===========>查询文件名列表");
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
//列出11111目录下今天所有文件
listObjectsRequest.setPrefix("11111/" + format.format(new Date()) + "/");
ObjectListing list = ossClient.listObjects(listObjectsRequest);
for (OSSObjectSummary objectSummary : list.getObjectSummaries()) {
System.out.println(objectSummary.getKey());
listRe.add(objectSummary.getKey());
}
return listRe;
} catch (Exception ex) {
log.info("==========>查询列表失败", ex);
return new ArrayList<String>();
}
}
}
| 33.96875 | 133 | 0.578427 |
22a56a11d57797e0c58efc7bae1dbebdb3f5740e | 2,680 | package dk.alexandra.fresco.suite.spdz2k.datatypes;
import dk.alexandra.fresco.framework.value.SInt;
/**
* Represents an authenticated, secret-share element.
*
* @param <PlainT> type of underlying plain value, i.e., the value type we use for arithmetic.
*/
public class Spdz2kSInt<PlainT extends CompUInt<?, ?, PlainT>> implements SInt {
private final PlainT share;
private final PlainT macShare;
/**
* Creates a {@link Spdz2kSInt}.
*/
public Spdz2kSInt(PlainT share, PlainT macShare) {
this.share = share;
this.macShare = macShare;
}
/**
* Creates a {@link Spdz2kSInt} from a public value. <p>All parties compute the mac share of the
* value but only party one (by convention) stores the public value as the share, the others store
* 0.</p>
*/
public Spdz2kSInt(PlainT share, PlainT macKeyShare, PlainT zero, boolean isPartyOne) {
this(isPartyOne ? share : zero, share.multiply(macKeyShare));
}
/**
* Compute sum of this and other.
*/
public Spdz2kSInt<PlainT> add(Spdz2kSInt<PlainT> other) {
return new Spdz2kSInt<>(share.add(other.share), macShare.add(other.macShare));
}
/**
* Compute difference of this and other.
*/
public Spdz2kSInt<PlainT> subtract(Spdz2kSInt<PlainT> other) {
return new Spdz2kSInt<>(share.subtract(other.share), macShare.subtract(other.macShare));
}
/**
* Compute product of this and constant (open) value.
*/
public Spdz2kSInt<PlainT> multiply(PlainT other) {
return new Spdz2kSInt<>(share.multiply(other), macShare.multiply(other));
}
@Override
public String toString() {
return "Spdz2kSInt{" +
"share=" + share +
", macShare=" + macShare +
'}';
}
/**
* Compute sum of this and constant (open) value. <p>All parties compute their mac share of the
* public value and add it to the mac share of the authenticated value, however only party 1 adds
* the public value to is value share.</p>
*
* @param other constant, open value
* @param macKeyShare mac key share for maccing open value
* @param zero zero value
* @param isPartyOne used to ensure that only one party adds value to share
* @return result of sum
*/
public Spdz2kSInt<PlainT> addConstant(
PlainT other, PlainT macKeyShare, PlainT zero, boolean isPartyOne) {
Spdz2kSInt<PlainT> wrapped = new Spdz2kSInt<>(other, macKeyShare, zero, isPartyOne);
return add(wrapped);
}
/**
* Return share.
*/
public PlainT getShare() {
return share;
}
/**
* Return mac share.
*/
public PlainT getMacShare() {
return macShare;
}
@Override
public SInt out() {
return this;
}
}
| 27.346939 | 100 | 0.673134 |
a1ca627dc9131f36f596421e050a59134eda019f | 1,498 | /*
* Copyright 2021 Haulmont.
*
* 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.jmix.ui.app;
import io.jmix.core.security.event.UserSubstitutedEvent;
import io.jmix.ui.App;
import org.springframework.context.event.EventListener;
import org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent;
import org.springframework.stereotype.Component;
/**
* Listener that handles different sources of user changes, e.g. interactive authentication or user substitution.
*/
@Component("ui_UserChangedListener")
public class UserChangedListener {
@EventListener
public void onAuthenticationSuccess(InteractiveAuthenticationSuccessEvent event) {
forceRefreshUI();
}
@EventListener
public void onUserSubstituted(UserSubstitutedEvent event) {
forceRefreshUI();
}
protected void forceRefreshUI() {
if (App.isBound()) {
App.getInstance().forceRefreshUIsExceptCurrent();
}
}
}
| 31.87234 | 113 | 0.745661 |
9473d71d4945f921c90710f988dba9a142c4b5b9 | 12,120 | package org.opendocumentformat.tester;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.ValidationEvent;
import javax.xml.bind.util.ValidationEventCollector;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.example.documenttests.DocumenttestsType;
import org.example.documenttests.DocumenttestsconfigType;
import org.example.documenttests.DocumenttestsreportType;
import org.example.documenttests.FiletypeType;
import org.example.documenttests.TargetOutputType;
import org.example.documenttests.TargetType;
import org.example.documenttests.TestType;
import org.opendocumentformat.tester.validator.OdfChecker;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
public class Main {
class Loader {
final JAXBContext jaxbContext;
final Unmarshaller unmarshaller;
final Marshaller marshaller;
final Handler handler;
private final DocumentBuilder documentBuilder;
class Handler extends ValidationEventCollector {
public int linenumber;
public int offset;
public ValidationEvent lastEvent = null;
@Override
public boolean handleEvent(ValidationEvent event) {
linenumber = event.getLocator().getLineNumber();
offset = event.getLocator().getOffset();
lastEvent = event;
return false;
}
}
Loader() throws JAXBException {
final SchemaFactory schemaFactory = SchemaFactory
.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
File f = new File("documenttests.xsd");
Source source;
if (!f.exists()) {
source = new StreamSource(Loader.class.getClassLoader()
.getResourceAsStream("documenttests.xsd"));
} else {
source = new StreamSource(f);
}
Schema schema = null;
try {
schema = schemaFactory.newSchema(source);
} catch (SAXException e) {
e.printStackTrace();
}
jaxbContext = JAXBContext.newInstance(DocumenttestsType.class);
unmarshaller = jaxbContext.createUnmarshaller();
handler = new Handler();
unmarshaller.setEventHandler(handler);
unmarshaller.setSchema(schema);
marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
Boolean.TRUE);
documentBuilder = OdfChecker.createDocumentBuilder();
}
void getNSPrefixMap(NamedNodeMap atts, Map<String, String> nsmap) {
nsmap.clear();
for (int i = 0; i < atts.getLength(); ++i) {
Node n = atts.item(i);
if ("http://www.w3.org/2000/xmlns/".equals(n.getNamespaceURI())) {
if ("xmlns".equals(n.getLocalName())) {
nsmap.put("", n.getNodeValue());
} else {
nsmap.put(n.getLocalName(), n.getNodeValue());
}
}
}
}
DocumenttestsType loadTests(File testFile, Map<String, String> nsmap)
throws JAXBException, SAXException, IOException {
Document doc = documentBuilder.parse(testFile);
getNSPrefixMap(doc.getDocumentElement().getAttributes(), nsmap);
JAXBElement<DocumenttestsType> root;
root = unmarshaller.unmarshal(new StreamSource(testFile),
DocumenttestsType.class);
return root.getValue();
}
DocumenttestsconfigType loadConfig(File runConfFile)
throws JAXBException {
JAXBElement<DocumenttestsconfigType> root;
root = unmarshaller.unmarshal(new StreamSource(runConfFile),
DocumenttestsconfigType.class);
return root.getValue();
}
void writeReport(DocumenttestsreportType report, String path) {
JAXBElement<DocumenttestsreportType> root = new JAXBElement<DocumenttestsreportType>(
new QName("http://www.example.org/documenttests",
"documenttestsreport"),
DocumenttestsreportType.class, report);
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
marshaller.marshal(root, out);
unmarshaller.unmarshal(new StreamSource(
new ByteArrayInputStream(out.toByteArray())),
DocumenttestsreportType.class);
} catch (JAXBException e) {
e.printStackTrace();
}
try {
FileOutputStream f = new FileOutputStream(path);
f.write(out.toByteArray());
f.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void writeHTML(String inpath, String outpath) {
Source source;
File f = new File("report2html.xsl");
if (!f.exists()) {
source = new StreamSource(Loader.class.getClassLoader()
.getResourceAsStream("report2html.xsl"));
} else {
source = new StreamSource(f);
}
TransformerFactory transFact = TransformerFactory.newInstance();
try {
Transformer trans = transFact.newTransformer(source);
source = new StreamSource(new FileInputStream(inpath));
Result result = new StreamResult(new FileOutputStream(outpath));
trans.transform(source, result);
} catch (Exception e) {
e.printStackTrace();
}
}
static private void fatalFileError(int linenumber, Throwable t, File file) {
while (t.getMessage() == null & t.getCause() != null) {
t = t.getCause();
}
System.err.println("Could not load " + file.getPath() + " line "
+ linenumber + ": " + t.getMessage());
System.exit(1);
}
/**
* Return the suffix as used in OdfAutoTests. PDF has suffix .pdf. The ODF
* types have more complicated suffixes that encodes the file type into the
* name. For example, and ODF 1.0 text file in package format (enumeration
* value ODT_1_0) has suffix '-1.0.odt' and the single xml version has
* (enumeration value ODT_1_0_XML) has suffix '-1.0xml.odt'.
*
* @param type
* @return
*/
static String getSuffixForFileType(FiletypeType type) {
if (type.equals(FiletypeType.PDF)) {
return ".pdf";
}
String value = type.value();
String subtype = value.substring(3);
String ext = value.substring(0, 3);
return "_" + subtype + "." + ext;
}
// derive the file type from the file suffix. see getSuffix()
static FiletypeType getFileType(String name) {
if (name.endsWith(".pdf")) {
return FiletypeType.PDF;
}
String ext = name.substring(name.length() - 3);
int pos = name.lastIndexOf('_');
if (pos == -1) {
return null;
}
String subtype = name.substring(pos + 1, name.length() - 4);
FiletypeType type;
try {
type = FiletypeType.fromValue(ext + subtype);
} catch (IllegalArgumentException e) {
type = null;
}
return type;
}
static String getTestName(String filename) {
int end = filename.lastIndexOf('_');
if (end == -1) {
end = filename.length();
}
return filename.substring(0, end);
}
private static void createInputFiles(RunConfiguration conf,
DocumenttestsType tests) {
for (TestType test : tests.getTest()) {
File target = new File(conf.inputDir, test.getName()
+ getSuffixForFileType(test.getInput().getType()));
InputCreator creator = new InputCreator(test.getInput().getType());
creator.createInput(target, test.getInput());
}
}
static private DocumenttestsconfigType inferConfig(RunConfiguration rc,
DocumenttestsType tests) {
Map<String, InferredTest> testNames = new HashMap<String, InferredTest>();
for (TestType test : tests.getTest()) {
InferredTest i = new InferredTest(test.getInput().getType());
testNames.put(test.getName(), i);
}
DocumenttestsconfigType conf = new DocumenttestsconfigType();
// look through the output directory
for (File targetDir : rc.resultDir.listFiles()) {
if (targetDir.isDirectory()) {
// if at least one test result is in the directory, the dir
// name is the name of a configuration
TargetType target = null;
Map<FiletypeType, TargetOutputType> t = new HashMap<FiletypeType, TargetOutputType>();
for (File output : targetDir.listFiles()) {
String filename = output.getName();
String testname = Main.getTestName(filename);
FiletypeType type = getFileType(filename);
InferredTest test = testNames.get(testname);
if (test != null && type != null && output.canRead()) {
if (target == null) {
target = new TargetType();
target.setName(targetDir.getName());
}
TargetOutputType out = t.get(type);
if (out == null) {
out = new TargetOutputType();
out.setOutputType(type);
t.put(type, out);
target.getOutput().add(out);
}
out.getInputTypes().add(test.input);
}
}
if (target != null) {
conf.getTarget().add(target);
}
}
}
return conf;
}
public static void removeMissingTargets(DocumenttestsconfigType config) {
List<TargetType> targets = config.getTarget();
SortedSet<String> neededExecutables = new TreeSet<String>();
SortedSet<String> missingExecutables = new TreeSet<String>();
for (TargetType t : config.getTarget()) {
for (TargetOutputType o : t.getOutput()) {
neededExecutables.add(o.getCommand().getExe());
}
}
for (String exe : neededExecutables) {
String fullexe = Tester.resolveExe(exe);
if (exe == fullexe && !new File(exe).exists()) {
System.err.println("Executable " + exe
+ " was not found in PATH.");
missingExecutables.add(exe);
}
}
int i = 0;
while (i < targets.size()) {
TargetType t = targets.get(i);
List<TargetOutputType> outputs = t.getOutput();
int j = 0;
while (j < outputs.size()) {
TargetOutputType o = outputs.get(j);
String exe = o.getCommand().getExe();
if (missingExecutables.contains(exe)) {
outputs.remove(j);
} else {
j++;
}
}
if (outputs.size() == 0) {
targets.remove(i);
} else {
i++;
}
}
}
/**
* The main entry point for the application.
*
* @param args
*/
public static void main(String[] args) {
// parse the command-line arguments or exit if they make no sense
RunConfiguration conf;
try {
conf = RunConfiguration.parseArguments(args);
} catch (ArgumentException e) {
return;
}
Loader loader;
try {
loader = (new Main()).new Loader();
} catch (JAXBException e) {
throw new RuntimeException(e);
}
// load the tests file
DocumenttestsType tests = null;
Map<String, String> nsmap = new HashMap<String, String>();
try {
tests = loader.loadTests(conf.tests, nsmap);
} catch (Throwable t) {
fatalFileError(loader.handler.linenumber, t, conf.tests);
}
// create any missing input files
createInputFiles(conf, tests);
// if a run configuration is assigned, run the files through the
// configured applications
DocumenttestsconfigType config = null;
if (conf.runConfiguration != null) {
try {
config = loader.loadConfig(conf.runConfiguration);
} catch (Throwable t) {
fatalFileError(loader.handler.linenumber, t,
conf.runConfiguration);
}
removeMissingTargets(config);
}
Tester tester = null;
DocumenttestsreportType report = null;
if (config != null) {
tester = new Tester(conf, config, tests, nsmap);
report = tester.runAllTests();
} else {
config = inferConfig(conf, tests);
tester = new Tester(conf, config, tests, nsmap);
report = new DocumenttestsreportType();
}
tester.evaluateAllTests(report);
loader.writeReport(report, "report.xml");
writeHTML("report.xml", "report.html");
}
}
class InferredTest {
public final FiletypeType input;
public final Set<FiletypeType> outputs = new HashSet<FiletypeType>();
InferredTest(FiletypeType input) {
this.input = input;
}
} | 30.839695 | 90 | 0.702558 |
665b86db5b8965ce497e3605ebb748f0f37aa8e2 | 2,765 | /*
Copyright (C) GridGain Systems. 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.gridgain.grid.kernal.processors.service;
import org.gridgain.grid.kernal.processors.cache.*;
import org.gridgain.grid.service.*;
import org.gridgain.grid.util.typedef.internal.*;
import java.io.*;
import java.util.*;
/**
* Service deployment.
*/
public class GridServiceDeployment implements GridCacheInternal, Serializable {
/** */
private static final long serialVersionUID = 0L;
/** Node ID. */
private UUID nodeId;
/** Service configuration. */
private GridServiceConfiguration cfg;
/**
* @param nodeId Node ID.
* @param cfg Service configuration.
*/
public GridServiceDeployment(UUID nodeId, GridServiceConfiguration cfg) {
this.nodeId = nodeId;
this.cfg = cfg;
}
/**
* @return Node ID.
*/
public UUID nodeId() {
return nodeId;
}
/**
* @return Service configuration.
*/
public GridServiceConfiguration configuration() {
return cfg;
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
GridServiceDeployment that = (GridServiceDeployment)o;
if (cfg != null ? !cfg.equals(that.cfg) : that.cfg != null)
return false;
if (nodeId != null ? !nodeId.equals(that.nodeId) : that.nodeId != null)
return false;
return true;
}
/** {@inheritDoc} */
@Override public int hashCode() {
int res = nodeId != null ? nodeId.hashCode() : 0;
res = 31 * res + (cfg != null ? cfg.hashCode() : 0);
return res;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(GridServiceDeployment.class, this);
}
}
| 27.107843 | 79 | 0.606872 |
ca8fb821556b2e2cc6013477c1e1724e11d2cde7 | 37,539 | package it.polimi.ingsw.client.view;
import it.polimi.ingsw.client.clientNetwork.ActionFactory;
import it.polimi.ingsw.client.clientNetwork.ClientConnectionSocket;
import it.polimi.ingsw.constants.Constants;
import it.polimi.ingsw.messages.clientMessages.JoinLobby;
import it.polimi.ingsw.client.clientNetwork.MessageHandler;
import it.polimi.ingsw.messages.Message;
import it.polimi.ingsw.messages.clientMessages.LeaderCardSelection;
import it.polimi.ingsw.messages.clientMessages.ResourceSelection;
import it.polimi.ingsw.messages.clientMessages.SetPlayersNumber;
import it.polimi.ingsw.messages.clientMessages.internal.*;
import it.polimi.ingsw.server.controller.Place;
import it.polimi.ingsw.server.model.Resource;
import it.polimi.ingsw.server.model.ResourcePosition;
import it.polimi.ingsw.server.model.ResourceQuantity;
import it.polimi.ingsw.server.model.gameboard.NumOfShelf;
import it.polimi.ingsw.server.observer.Observer;
import java.io.IOException;
import java.io.PrintStream;
import java.util.*;
/**
* Class Cli it's the main class which manages the game if the player decides to
* play with the command line interface.
*
*/
public class Cli implements Observer {
private final PrintStream output;
private final Scanner input;
private final ClientView clientView;
private final MessageHandler messageHandler;
private boolean active;
private final ActionFactory actionFactory;
private ClientConnectionSocket connectionSocket;
/**
* Creates a new Cli instance.
*
*/
public Cli() {
input = new Scanner(System.in);
output = new PrintStream(System.out);
clientView = new ClientView(this);
messageHandler = new MessageHandler(clientView);
active = true;
actionFactory = new ActionFactory(output, input, this);
}
/**
* Asks for the server ip address and port, then it creates a new Cli object and calls
* the {@link #setup()} method on it.
*
* @param args the main args
*/
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Insert the server IP address\n>");
String ip = scanner.nextLine();
System.out.print("Insert the server port\n>");
try {
int port = scanner.nextInt();
Constants.setAddress(ip);
Constants.setPort(port);
Cli cli = new Cli();
cli.setup();
}
catch (InputMismatchException e){
System.out.println("Numeric format requested for the port. Application will now close.");
System.exit(0);
}
}
/**
* Returns the active attribute.
*
* @return the active attribute
*/
public boolean isActive() {
return active;
}
/**
* Sets up the connection with the server, asking if the player wants to join a new game
* or reconnect to a previous one. Tries to register the player with a provided nickname
* and start a thread that will contain the ClientConnectionSocket object used to send and
* receive messages from the server.
*
*/
private void setup() {
connectionSocket = new ClientConnectionSocket(this, messageHandler);
try {
while (!connectionSocket.setupConnection()) {
output.println("The entered IP/port doesn't match any active server. Please try again!");
output.print("Insert the server IP address\n>");
Constants.setAddress(readInputString());
output.print("Insert the server port\n>");
Constants.setPort(readInputInt(false));
}
System.out.println("Socket Connection setup completed!");
} catch (IOException e) {
System.err.println("Error during socket configuration! Application will now close.");
System.exit(0);
}
String nickname = null;
boolean confirmation = false;
boolean newPlayer = true;
while (!confirmation) {
boolean ok = false;
while (!ok) {
output.print("Would you like to start a new match or resume an existing one? [start/resume]\n>");
String answer = readInputString().toUpperCase();
switch (answer) {
case "START" -> {
newPlayer = true;
ok = true;
}
case "RESUME" -> {
newPlayer = false;
ok = true;
}
default -> output.println("Please select one of the two options.");
}
}
output.print("Insert your nickname:\n>");
nickname = readInputString();
if (nickname != null && !nickname.isEmpty() && connectionSocket.setupNickname(nickname, newPlayer))
confirmation = true;
}
clientView.setNickname(nickname);
clientView.getOwnGameBoard().setOwner(nickname);
Thread thread = new Thread(connectionSocket);
thread.start();
}
/**
* Acts based on the {@link ViewMessage} received, asking different things to player,
* printing updated view elements and sending different messages to the server.
*
* @param message the ViewMessage received
*/
@Override
public void update(Message message) {
ViewMessage m = (ViewMessage) message;
boolean request = true;
if (m instanceof DisplayMessage) {
output.println(m.getMessage());
} else if (m instanceof RequestPlayersNumber) {
RequestPlayersNumber r = (RequestPlayersNumber) m;
if(r.getInfoLobbies().isEmpty())
output.println(r.getMessage()+ " Please type start to begin: [start]");
else
output.println(r.getMessage());
for(int i = 0; i < r.getInfoLobbies().size(); i++){
output.println((i+1) + ". " +r.getInfoLobbies().get(i));
}
if(!r.getInfoLobbies().isEmpty())
output.println("Please type start if you want to create a new lobby, " +
"or join if you want to join an existing one: [start/join]");
output.print(">");
String answer = null;
while (request) {
answer = readInputString();
if (answer.equalsIgnoreCase("join")) {
if(r.getInfoLobbies().isEmpty())
output.print("There is no lobby available at the moment, please type start.\n>");
else {
output.print("Type the number of the lobby you want to join: \n>");
boolean lobbySel = true;
int l = 0;
while (lobbySel) {
l = readInputInt(false);
if (l >= 1 && l <= r.getInfoLobbies().size()) lobbySel = false;
else output.print("Please choose a number between 1 and " + r.getInfoLobbies().size() + ":\n>");
}
connectionSocket.send(new JoinLobby(r.getOwners().get(l - 1)));
request = false;
}
} else if (answer.equalsIgnoreCase("start")) {
Integer number = 0;
output.print("Please choose a number of players : [1/2/3/4]\n>");
while (request) {
number = readInputInt(false);
if (number >= 1 && number <= 4) request = false;
else output.print("Please choose a number between 1 and 4:\n>");
}
connectionSocket.send(new SetPlayersNumber(number));
request = false;
} else {
if (r.getInfoLobbies().isEmpty())
output.print("Invalid input. There is no lobby available at the moment, please type start.\n>");
else
output.print("Invalid input. Please select a valid option: [start/join]\n>");
}
}
} else if (m instanceof SetupDiscard) {
output.print(m.getMessage());
int index1 = 0;
int index2 = 0;
while (request) {
index1 = readInputInt(false);
output.print(">");
index2 = readInputInt(false);
if (index1 < 1 || index1 > 4 || index2 < 1 || index2 > 4 || index1 == index2)
output.print("Please choose two distinct numbers between 1 and 4:\n>");
else request = false;
}
connectionSocket.send(new LeaderCardSelection(new int[]{index1, index2}));
} else if (m instanceof SetupResources) {
output.print(m.getMessage());
List<ResourcePosition> rp;
List<String> s = new ArrayList<>();
if (clientView.getOwnGameBoard().getIndex() == 1 || clientView.getOwnGameBoard().getIndex() == 2) {
Resource r = askForResource();
s.add(r.toString());
} else if (clientView.getOwnGameBoard().getIndex() == 3) {
for (int i = 0; i < 2; i++) {
Resource r = askForResource();
if(i == 0)
output.print(">");
s.add(r.toString());
}
}
rp = (askForLocation(s, true, false, true));
connectionSocket.send(new ResourceSelection(rp));
} else if (m instanceof ChooseAction) {
output.print(m.getMessage()+ " (select a number between 0 and 11):\n" +
Constants.getChooseAction() + "\n>");
Integer n;
while (request) {
Message toSend;
n = readInputInt(false);
if (n < 0 || n > 11) {
output.print("Please choose a number between 0 and 11:\n>");
} else if (n > 5 && n < 11) {
showElements(n);
} else {
if ((n == 3 || n == 4) && getClientView().getHand().size() == 0) {
output.print("You don't have any leader card in your hand, " +
"please select a different action.\n>");
} else{
toSend = actionFactory.createAction(n);
if(toSend == null)
output.print(Constants.getChooseAction()+ "\n>");
else{
request = false;
connectionSocket.send(toSend);
}
}
}
}
} else if (m instanceof PrintChest) {
printChest(printGameBoardElem(m.getMessage()));
} else if (m instanceof PrintDevDecks){
printDevDecks();
} else if (m instanceof PrintDevSpace){
printDevSpace(printGameBoardElem(m.getMessage()));
} else if (m instanceof PrintHandCards){
printHandCards();
} else if (m instanceof PrintItinerary){
printItinerary(printGameBoardElem(m.getMessage()));
} else if (m instanceof PrintMarket){
printMarket();
} else if (m instanceof PrintPlayedCards){
printPlayedLeadCards(printGameBoardElem(m.getMessage()));
} else if (m instanceof PrintWarehouse){
printWarehouse(printGameBoardElem(m.getMessage()));
} else if (m instanceof NewView){
printMarket();
printDevDecks();
} else if (m instanceof PrintEndGame){
output.println(m.getMessage());
output.print("Please press any key to close the game: \n>");
input.next();
}
}
/**
* Used when printing an updated game board element. Prints the nickname of the owner of the
* element and returns the owner of the game board.
*
* @param owner the owner of the game board
* @return the game board of the specified player, {@code null} if no game board is found
*/
private GameBoardInfo printGameBoardElem(String owner){
if (owner.equals(clientView.getNickname())){
output.print("YOUR ");
return clientView.getOwnGameBoard();
}
else {
output.print(owner.toUpperCase() + "'S ");
for (GameBoardInfo g : getClientView().getOtherGameBoards()){
if (g.getOwner().equalsIgnoreCase(owner)){
return g;
}
}
}
return null;
}
/**
* Prints some view elements based on the input provided by the player.
*
* @param n the number chosen by the player
*/
private void showElements(int n) {
switch (n) {
case 6 -> printGameBoard(clientView.getOwnGameBoard());
case 7 -> askForGameBoard();
case 8 -> printMarket();
case 9 -> printDevDecks();
case 10 -> printHandCards();
}
output.print("Please choose an action (select a number between 0 and 11):\n" +
Constants.getChooseAction() + "\n>");
}
/**
* Asks the player whose game board he wants to see printed in the terminal and prints it. If the player is
* in a single player game it prints Lorenzo de Medici's position on the itinerary.
*
*/
private void askForGameBoard() {
if (clientView.getOwnGameBoard().getBlackCrossPosition() != null)
output.println("Lorenzo De Medici's position: " + clientView.getOwnGameBoard().getBlackCrossPosition() + "/24\n");
else {
while (true) {
StringBuilder names = new StringBuilder();
for (GameBoardInfo gbi : clientView.getOtherGameBoards()){
if (clientView.getOtherGameBoards().indexOf(gbi) != 0) names.append("/");
names.append(gbi.getOwner().toUpperCase());
}
output.print("Whose game board would you like to view? [" + names + "]\n>");
String s = readInputString().toUpperCase();
if(s.equalsIgnoreCase("back")) return;
for (GameBoardInfo g : clientView.getOtherGameBoards()) {
if (g.getOwner().equalsIgnoreCase(s)) {
printGameBoard(g);
return;
}
}
output.print("Please select the nickname of a player in the match. ");
}
}
}
/**
* Asks the player for a resource.
*
* @return the resource chosen by the player
*/
private Resource askForResource() {
boolean request = true;
Resource r = null;
while (request) {
String s = readInputString().toUpperCase();
try {
r = Resource.valueOf(s);
request = false;
} catch (IllegalArgumentException e) {
output.print("Please select a valid resource:\n>");
}
}
return r;
}
/**
* Used when the player has to store resources or when he has to expend them. Returns the
* list of ResourcePosition objects needed to perform the action.
*
* @param stringList the list of strings which represents the resources that need to be stored or expended
* @param deposit {@code true} if the resources are meant to be stored, {@code false} otherwise
* @param canDiscard {@code true} if the player can discard the resources, {@code false} otherwise
* @param setupResources {@code true} when selecting resources in the setup phase, {@code false} otherwise
* @return the list of ResourcePosition objects needed to perform the action
*/
public List<ResourcePosition> askForLocation(List<String> stringList, boolean deposit, boolean canDiscard, boolean setupResources) {
List<ResourceQuantity> req = new ArrayList<>();
List<ResourcePosition> result = new ArrayList<>();
for (Resource r : Resource.values())
req.add(new ResourceQuantity((int) stringList.
stream().filter(s -> s.equalsIgnoreCase(r.toString())).count(), r));
String order = "";
Place place;
NumOfShelf shelf;
for (ResourceQuantity r : req) {
for (int i = 0; i < r.getQuantity(); i++) {
if (r.getResource() != Resource.EMPTY && r.getResource() != Resource.FAITHPOINT) {
switch (i) {
case 0 -> order = "first ";
case 1 -> order = "second ";
case 2 -> order = "third ";
case 3 -> order = "fourth ";
case 4 -> order = "fifth ";
}
while (true) {
String s;
if (!deposit)
output.print("Where would you like to take your " + order +
r.getResource().toString().toLowerCase() + " from? [Warehouse/Chest]\n>");
else {
if(!setupResources)
output.print("Where would you like to store your " + order +
r.getResource().toString().toLowerCase() + " in? [Warehouse/Discard]\n>");
else
output.print("Where would you like to store your " + order +
r.getResource().toString().toLowerCase() + " in? [Warehouse]\n>");
}
s = readInputString().toUpperCase();
if(s.equalsIgnoreCase("back") && !setupResources) return null;
if (s.equalsIgnoreCase("DISCARD"))
s = "TRASH_CAN";
try {
place = Place.valueOf(s);
if (place == Place.WAREHOUSE) {
Integer loc = inWarehouse(r.getResource().toString());
if (deposit){
if (clientView.getOwnGameBoard().getWarehouse().size() > 3) loc = null;
if (loc == null){
if(clientView.getOwnGameBoard().getWarehouse().size() == 3)
output.print("Which shelf would you like to store it in? " +
"[1/2/3]\n>");
else if(clientView.getOwnGameBoard().getWarehouse().size() == 4)
output.print("Which shelf would you like to store it in? " +
"[1/2/3/4] (4 is the first depot)\n>");
else
output.print("Which shelf would you like to store it in? " +
"[1/2/3/4/5] (4, 5 are the depots)\n>");
while (true) {
Integer n;
if(setupResources)
n = readInputInt(false);
else
n = readInputInt(true);
if(n == null) return null;
int size = getClientView().getOwnGameBoard().getWarehouse().size();
if (n < 1 || n > size)
output.print("Please select a number between 1 and " + size + " :\n>");
else {
shelf = NumOfShelf.values()[n - 1];
break;
}
}
}
else shelf = NumOfShelf.values()[loc];
result.add(new ResourcePosition(r.getResource(), place, shelf));
break;
} else {
if (loc == null){
output.print("You don't have this resource in the warehouse, please try again:\n");
}
else {
shelf = NumOfShelf.values()[loc];
result.add(new ResourcePosition(r.getResource(), place, shelf));
break;
}
}
} else if (place == Place.TRASH_CAN) {
if (!deposit)
output.print("You cannot take resources that have been discarded.\n");
else {
if (!canDiscard)
output.print("You cannot discard this resource.\n");
else {
result.add(new ResourcePosition(r.getResource(), place, null));
break;
}
}
} else if (place == Place.CHEST) {
if (deposit)
output.print("This resource cannot be stored in the chest.\n");
else{
result.add(new ResourcePosition(r.getResource(), place, null));
break;
}
}
} catch (IllegalArgumentException e) {
output.print("Please select a valid source. ");
}
}
} else result.add(new ResourcePosition(r.getResource(), null, null));
}
}
return result;
}
/**
* Returns a integer which represents the warehouse shelf that contains a
* specified resource.
*
* @param res the resource
* @return the integer representing the warehouse shelf that contains the resource, {@code null} if no shelf
* contains that resource
*/
private Integer inWarehouse (String res){
for (int i = 0; i < 3; i++){
List<String> l = clientView.getOwnGameBoard().getWarehouse().get(i);
if (l != null && !l.isEmpty() && l.get(0).equalsIgnoreCase(res)) return i;
}
return null;
}
/**
* Prints the market disposition and the external marble.
*
*/
private void printMarket() {
String[][] market = clientView.getMarket();
output.print("MARKET: \n\n");
output.println("EXTERNAL MARBLE = " + clientView.getExternalMarble() + "\n");
for (int n = 0; n < 3; n++) {
for (int i = 0; i < 36; i++)
output.print("*");
output.print("*\n");
for (int i = 0; i < 4; i++)
output.print("* ");
output.print("*\n");
for (int i = 0; i < 4; i++) {
output.print("* ");
output.print(market[n][i]);
for (int j = 0; j < 7 - market[n][i].length(); j++)
output.print(" ");
}
output.print("*\n");
for (int i = 0; i < 4; i++)
output.print("* ");
output.print("*\n");
}
for (int i = 0; i < 36; i++)
output.print("*");
output.print("*\n\n");
}
/**
* Prints the development decks.
*
*/
private void printDevDecks() {
output.println("DEVELOPMENT DECKS:\n");
for (DevCardInfo[] a : clientView.getDevDecks()) {
for (int i = 0; i < 4; i++)
output.print(Constants.devCardBorder + " ");
output.print("\n");
for (int i = 0; i < 4; i++) {
if (a[i] == null)
output.print(Constants.emptyDevCardBorder);
else
printCardElement("* COL: " + a[i].getColour(), true);
}
output.print("\n");
for (int i = 0; i < 4; i++) {
if (a[i] == null)
output.print(Constants.emptyDevCardBorder);
else
printCardElement("* LVL: " + a[i].getLevel(), true);
}
output.print("\n");
for (int i = 0; i < 4; i++) {
if (a[i] == null)
output.print(Constants.emptyDevCardBorder);
else
printCardElement("* VP: " + a[i].getVictoryPoints(), true);
}
output.print("\n");
for (int i = 0; i < 4; i++) {
if (a[i] == null)
output.print(Constants.emptyDevCardBorder);
else
printCardElement("* REQ: " + buildResourceString(a[i].getResourceRequirements()), true);
}
output.print("\n");
for (int i = 0; i < 4; i++) {
if (a[i] == null)
output.print(Constants.emptyDevCardBorder);
else
printCardElement("* IN: " + buildResourceString(a[i].getProductionInput()), true);
}
output.print("\n");
for (int i = 0; i < 4; i++) {
if (a[i] == null)
output.print(Constants.emptyDevCardBorder);
else
printCardElement("* OUT: " + buildResourceString(a[i].getProductionOutput()), true);
}
output.print("\n");
for (int i = 0; i < 4; i++)
output.print(Constants.devCardBorder + " ");
output.print("\n\n");
}
}
/**
* Prints an attribute of a card, used when printing cards in the terminal.
*
* @param s the attribute to print
* @param isDevCard {@code true} if the card is a development card, {@code false} if the card is a leader card
*/
private void printCardElement(String s, boolean isDevCard) {
output.print(s);
if (isDevCard) {
for (int i = 0; i < 34 - s.length(); i++)
output.print(" ");
} else {
for (int i = 0; i < 38 - s.length(); i++)
output.print(" ");
}
output.print("* ");
}
/**
* Returns a string which represents a list of resources that can be either
* the input, output or the requirements of a card.
*
* @param list the list of resources
* @return the built string
*/
public String buildResourceString(List<String> list) {
int[] quantity = {0, 0, 0, 0, 0};
StringBuilder result = new StringBuilder();
for (String s : list) {
switch (s.toUpperCase()) {
case "COIN" -> quantity[0]++;
case "STONE" -> quantity[1]++;
case "SERVANT" -> quantity[2]++;
case "SHIELD" -> quantity[3]++;
case "FAITHPOINT" -> quantity[4]++;
}
}
int firstNotNull = 0;
for (int n = 0; n < 5; n++) {
String resType = switch (n) {
case 0 -> " CO";
case 1 -> " ST";
case 2 -> " SE";
case 3 -> " SH";
case 4 -> " FP";
default -> "";
};
if (quantity[n] != 0) {
if (n != firstNotNull) {
result.append(" + ");
}
result.append(quantity[n]).append(resType);
} else
firstNotNull++;
}
return result.toString();
}
/**
* Prints the hand leader cards.
*
*/
private void printHandCards() {
output.println("HAND LEADER CARDS:\n");
printLeadCards(clientView.getHand());
}
/**
* Returns a string which represents a list of cards needed to play
* a leader card.
*
* @param list the list of development cards
* @return the built string
*/
private String buildDevCardString(List<DevCardInfo> list) {
StringBuilder result = new StringBuilder();
for (DevCardInfo d : list) {
result.append(d.getColour());
if (d.getLevel() != 0)
result.append(" LVL ").append(d.getLevel());
if (list.indexOf(d) != list.size() - 1)
result.append(" + ");
}
return result.toString();
}
/**
* Prints all the game board elements of a player's game board.
*
* @param g the game board to print
*/
private void printGameBoard(GameBoardInfo g) {
printItinerary(g);
printChest(g);
printWarehouse(g);
printDevSpace(g);
printPlayedLeadCards(g);
}
/**
* Prints the itinerary of a player.
*
* @param g the game board that contains the itinerary
*/
private void printItinerary(GameBoardInfo g) {
if (g != null){
output.println("ITINERARY:\n\n" +
"Position: " + g.getPosition() + "/24");
if (g.getBlackCrossPosition() != null)
output.println("Lorenzo De Medici's position: " + g.getBlackCrossPosition() + "/24");
output.println("Papal cards status: ");
for (int i = 0; i < g.getPapalCards().size(); i++)
output.println(i + " -> " + g.getPapalCards().get(i) + " (value: " + (i + 2) + ")");
output.println("\n");
}
}
/**
* Prints a player's chest.
*
* @param g the game board that contains the chest
*/
private void printChest(GameBoardInfo g) {
if (g != null){
output.print("CHEST:\n\n| ");
List<String> resources = new ArrayList<>(g.getChest().keySet());
for (String res : resources) {
output.print(res + ": " + g.getChest().get(res) + " | ");
}
output.println("\n");
}
}
/**
* Prints a player's warehouse.
*
* @param g the game board that contains the warehouse
*/
private void printWarehouse(GameBoardInfo g) {
if (g != null){
output.print("WAREHOUSE: \n\n");
for (int i = 0; i < g.getWarehouse().size(); i++) {
if (i < 3)
output.print("Shelf number " + (i + 1) + ": ");
else
output.print("Depot number " + (i - 2) + ": ");
for (String s : g.getWarehouse().get(i))
output.print(s + " ");
output.println();
}
output.println("\n");
}
}
/**
* Prints the development space of a player.
*
* @param g the game board that contains the development space
*/
private void printDevSpace(GameBoardInfo g) {
if (g != null){
output.print("DEVELOPMENT SPACE: \n\n");
for (int i = 0; i < 3; i++)
output.print(Constants.devCardBorder + " ");
output.print("\n");
for (int i = 0; i < 3; i++) {
if (g.getDevSpace().get(i).isEmpty())
output.print(Constants.emptyDevCardBorder);
else
printCardElement("* COL: " + g.getDevSpace().get(i).get(0).getColour(), true);
}
output.print("\n");
for (int i = 0; i < 3; i++) {
if (g.getDevSpace().get(i).isEmpty())
output.print(Constants.emptyDevCardBorder);
else
printCardElement("* LVL: " + g.getDevSpace().get(i).get(0).getLevel(), true);
}
output.print("\n");
for (int i = 0; i < 3; i++) {
if (g.getDevSpace().get(i).isEmpty())
output.print(Constants.emptyDevCardBorder);
else
printCardElement("* VP: " + g.getDevSpace().get(i).get(0).getVictoryPoints(), true);
}
output.print("\n");
for (int i = 0; i < 3; i++) {
if (g.getDevSpace().get(i).isEmpty())
output.print(Constants.emptyDevCardBorder);
else
printCardElement("* REQ: " + buildResourceString(g.getDevSpace().get(i).get(0).getResourceRequirements()), true);
}
output.print("\n");
for (int i = 0; i < 3; i++) {
if (g.getDevSpace().get(i).isEmpty())
output.print(Constants.emptyDevCardBorder);
else
printCardElement("* IN: " + buildResourceString(g.getDevSpace().get(i).get(0).getProductionInput()), true);
}
output.print("\n");
for (int i = 0; i < 3; i++) {
if (g.getDevSpace().get(i).isEmpty())
output.print(Constants.emptyDevCardBorder);
else
printCardElement("* OUT: " + buildResourceString(g.getDevSpace().get(i).get(0).getProductionOutput()), true);
}
output.print("\n");
for (int i = 0; i < 3; i++)
output.print(Constants.devCardBorder + " ");
output.print("\n\n");
}
}
/**
* Prints the player's played leader cards.
*
* @param g the game board that contains the played leader cards
*/
private void printPlayedLeadCards(GameBoardInfo g) {
if (g != null){
output.println("PLAYED LEADER CARDS:\n");
printLeadCards(g.getPlayedCards());
}
}
/**
* Prints leader cards.
*
* @param cards the list of leader cards to print
*/
private void printLeadCards(List<LeadCardInfo> cards) {
if (!(cards.isEmpty())) {
for (int i = 0; i < cards.size(); i++) {
output.print(Constants.leadCardBorder + " ");
}
output.print("\n");
for (LeadCardInfo card : cards) {
printCardElement("* VP: " + card.getVictoryPoints(), false);
}
output.print("\n");
for (LeadCardInfo card : cards) {
if (card.getCardRequirements() == null)
printCardElement("* RES REQ: " + buildResourceString(card.getResourceRequirements()), false);
else
printCardElement("* CARD REQ: " + buildDevCardString(card.getCardRequirements()), false);
}
output.print("\n");
for (LeadCardInfo card : cards) {
printCardElement("* TYPE: " + card.getType(), false);
}
output.print("\n");
for (LeadCardInfo card : cards) {
printCardElement("* RES: " + card.getResource(), false);
}
output.print("\n");
for (int i = 0; i < cards.size(); i++) {
output.print(Constants.leadCardBorder + " ");
}
output.print("\n\n");
}
}
/**
* Reads input from the player, expecting a string.
*
* @return the string inserted by the player
*/
private String readInputString() {
String inputString;
do {
try {
inputString = input.nextLine();
break;
} catch (InputMismatchException e) {
output.print("Please insert a valid input.\n>");
}
} while (true);
return inputString;
}
/**
* Reads input from the player, expecting an int.
*
* @return the int inserted by the player
*/
private Integer readInputInt(boolean canQuit) {
int inputInt;
String line;
do {
try {
line = input.nextLine();
if(line.equalsIgnoreCase("back") && canQuit) return null;
inputInt = Integer.parseInt(line);
break;
} catch (InputMismatchException | NumberFormatException e) {
output.print("Please insert a valid input.\n>");
}
} while (true);
return inputInt;
}
/**
* Returns the ClientView object associated with this cli.
*
* @return the ClientView object associated with this cli
*/
public ClientView getClientView() {
return clientView;
}
} | 41.525442 | 136 | 0.482725 |
e4bbc84672fa74c13729573abf9024245cb3b4f3 | 1,503 | package com.spring.auth.client.infrastructure.repositories;
import com.spring.auth.client.domain.Client;
import com.spring.auth.client.domain.ClientJpa;
import com.spring.auth.client.domain.ClientMapper;
import com.spring.auth.client.infrastructure.repositories.jpa.ClientRepositoryJpa;
import com.spring.auth.client.infrastructure.repositories.ports.CheckClientsConstraintsPort;
import com.spring.auth.client.infrastructure.repositories.ports.UpdateClientPort;
import com.spring.auth.exceptions.application.DuplicatedKeyException;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
@AllArgsConstructor
public class UpdateClientRepository implements UpdateClientPort {
private final ClientRepositoryJpa clientRepositoryJpa;
private final CheckClientsConstraintsPort checkClientsConstraintsPort;
@Override
public Client update(Client client) throws DuplicatedKeyException {
checkClientsConstraintsPort.check(List.of(client));
return getFirstFromList(saveClients(List.of(client)));
}
private Client getFirstFromList(List<Client> clients) {
return clients.stream().findFirst().get();
}
private List<Client> saveClients(List<Client> clients) {
List<ClientJpa> clientsJpa = ClientMapper.parseClientList(clients);
List<ClientJpa> savedClientsJpa = clientRepositoryJpa.saveAll(clientsJpa);
return ClientMapper.parseClientJpaList(savedClientsJpa);
}
}
| 39.552632 | 92 | 0.802395 |
bf00606556025c6e6dceeff2a8cbfd9f50cd3771 | 9,446 | /**
* Copyright (C) 2015 Stubhub.
*/
package io.bigdime.validation;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
/**
* RecordCountValidator class is to perform whether hdfs record count matches source record count or not
*
* record count mismatches --- validation fail
* otherwise, validation success
*
* @author Rita Liu
*/
import io.bigdime.alert.Logger;
import io.bigdime.alert.LoggerFactory;
import io.bigdime.core.ActionEvent;
import io.bigdime.core.commons.DataConstants;
import io.bigdime.core.config.AdaptorConfig;
import io.bigdime.core.constants.ActionEventHeaderConstants;
import io.bigdime.core.validation.DataValidationException;
import io.bigdime.core.validation.Factory;
import io.bigdime.core.validation.ValidationResponse;
import io.bigdime.core.validation.Validator;
import io.bigdime.core.validation.ValidationResponse.ValidationResult;
import io.bigdime.libs.hdfs.WebHdfs;
import io.bigdime.libs.hdfs.WebHDFSConstants;
import io.bigdime.validation.common.AbstractValidator;
@Factory(id = "record_count", type = RecordCountValidator.class)
/**
* Performs validation by comparing comparing expected(from event header) and actual
* record count(from hdfs).
*
* @author Rita Liu
*
*/
public class RecordCountValidator implements Validator {
private WebHdfs webHdfs;
private static final Logger logger = LoggerFactory.getLogger(RecordCountValidator.class);
private String name;
/**
* This validate method will compare Hdfs record count and source record
* count
*
* @param actionEvent
* @return true if Hdfs record count is same as source record count,
* otherwise return false
*
*/
@Override
public ValidationResponse validate(ActionEvent actionEvent) throws DataValidationException {
ValidationResponse validationPassed = new ValidationResponse();
AbstractValidator commonCheckValidator = new AbstractValidator();
validationPassed.setValidationResult(ValidationResult.FAILED);
String host = actionEvent.getHeaders().get(ActionEventHeaderConstants.HOST_NAMES);
String portString = actionEvent.getHeaders().get(ActionEventHeaderConstants.PORT);
String userName = actionEvent.getHeaders().get(ActionEventHeaderConstants.USER_NAME);
String srcRCString = actionEvent.getHeaders().get(ActionEventHeaderConstants.SOURCE_RECORD_COUNT);
String hdfsBasePath = actionEvent.getHeaders().get(ActionEventHeaderConstants.HDFS_PATH);
String hdfsFileName = actionEvent.getHeaders().get(ActionEventHeaderConstants.HDFS_FILE_NAME);
String hivePartitionValues = actionEvent.getHeaders().get(ActionEventHeaderConstants.HIVE_PARTITION_VALUES);
String partitionPath = "";
String hdfsCompletedPath = "";
int sourceRecordCount = 0;
commonCheckValidator.checkNullStrings(ActionEventHeaderConstants.HOST_NAMES, host);
commonCheckValidator.checkNullStrings(ActionEventHeaderConstants.PORT, portString);
commonCheckValidator.checkNullStrings(ActionEventHeaderConstants.USER_NAME, userName);
try {
int port = Integer.parseInt(portString);
if (webHdfs == null) {
webHdfs = WebHdfs.getInstance(host, port)
.addHeader(WebHDFSConstants.CONTENT_TYPE,WebHDFSConstants.APPLICATION_OCTET_STREAM)
.addParameter(WebHDFSConstants.USER_NAME, userName)
.addParameter("overwrite", "false");
}
} catch (NumberFormatException e) {
logger.warn(AdaptorConfig.getInstance().getAdaptorContext().getAdaptorName(), "NumberFormatException",
"Illegal port number input while parsing string to integer");
throw new NumberFormatException();
}
commonCheckValidator.checkNullStrings(ActionEventHeaderConstants.SOURCE_RECORD_COUNT, srcRCString);
try {
sourceRecordCount = Integer.parseInt(srcRCString);
} catch (NumberFormatException e) {
logger.warn(AdaptorConfig.getInstance().getAdaptorContext().getAdaptorName(), "NumberFormatException",
"Illegal source record count input while parsing string to integer");
throw new NumberFormatException();
}
commonCheckValidator.checkNullStrings(ActionEventHeaderConstants.HDFS_PATH, hdfsBasePath);
commonCheckValidator.checkNullStrings(ActionEventHeaderConstants.HDFS_FILE_NAME, hdfsFileName);
if (StringUtils.isNotBlank(hivePartitionValues)) {
String[] partitionList = hivePartitionValues.split(DataConstants.COMMA);
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < partitionList.length; i++) {
stringBuilder.append(partitionList[i].trim() + DataConstants.SLASH);
}
partitionPath = stringBuilder.toString();
hdfsCompletedPath = hdfsBasePath + partitionPath + hdfsFileName;
} else {
hdfsCompletedPath = hdfsBasePath + hdfsFileName;
}
int hdfsRecordCount = 0;
try {
hdfsRecordCount = getHdfsRecordCount(hdfsCompletedPath);
} catch (ClientProtocolException e) {
logger.warn(AdaptorConfig.getInstance().getAdaptorContext().getAdaptorName(), "ClientProtocolException",
"Exception occurred while getting hdfs record count, cause: " + e.getMessage());
} catch (IOException ex) {
logger.warn(AdaptorConfig.getInstance().getAdaptorContext().getAdaptorName(), "IOException",
"Exception occurred while getting hdfs record count, cause: " + ex.getMessage());
}
logger.debug(AdaptorConfig.getInstance().getName(), "performing validation",
"hdfsCompletedPath={} sourceRecordCount={} hdfsRecordCount={}", hdfsCompletedPath, sourceRecordCount,
hdfsRecordCount);
if (sourceRecordCount == hdfsRecordCount) {
logger.info(AdaptorConfig.getInstance().getAdaptorContext().getAdaptorName(), "Record count matches",
"Hdfs record count({}) is same as source record count({}).", hdfsRecordCount, sourceRecordCount);
validationPassed.setValidationResult(ValidationResult.PASSED);
} else {
String checksumErrorFilePath = "RCError" +DataConstants.SLASH + AdaptorConfig.getInstance().getAdaptorContext().getAdaptorName()
+ DataConstants.SLASH + partitionPath;
// Take out /webhdfs/v1 from hdfsBasePath
String hdfsDir = hdfsBasePath.substring(11);
logger.warn(AdaptorConfig.getInstance().getAdaptorContext().getAdaptorName(),
"Record count mismatches, Hdfs file moved",
"Hdfs record count({}) is not same as source record count({}) and hdfsCompletedPath ={}.errorFilePath ={}", hdfsRecordCount,
sourceRecordCount,hdfsCompletedPath,hdfsBasePath + checksumErrorFilePath);
try {
if (!checkErrorRecordCountDirExists(hdfsBasePath + checksumErrorFilePath)) {
if (makeErrorRecordCountDir(hdfsBasePath + checksumErrorFilePath)) {
moveErrorRecordCountFile(hdfsCompletedPath, hdfsDir + checksumErrorFilePath);
}
} else {
moveErrorRecordCountFile(hdfsCompletedPath, hdfsDir + checksumErrorFilePath);
}
} catch (IOException e) {
logger.warn(AdaptorConfig.getInstance().getAdaptorContext().getAdaptorName(), "Exception occurs",
"Failed to move to provided location: " + hdfsDir + checksumErrorFilePath);
}
validationPassed.setValidationResult(ValidationResult.FAILED);
}
return validationPassed;
}
/**
* This is for hdfs record count using WebHdfs
*
* @param fileName
* hdfs file name
* @throws IOException
* @throws ClientProtocolException
*
*/
private int getHdfsRecordCount(String fileName) throws ClientProtocolException, IOException {
HttpResponse response = webHdfs.openFile(fileName);
InputStream responseStream = response.getEntity().getContent();
StringWriter writer = new StringWriter();
IOUtils.copy(responseStream, writer);
String theString = writer.toString();
int hdfsRecordCount = (theString.split(System.getProperty("line.separator")).length);
webHdfs.releaseConnection();
responseStream.close();
writer.close();
return hdfsRecordCount;
}
/**
* This is to check errorRecordCountDir exists or not in hdfs
*
* @param filePath
* @return true if errorRecordCountDir exists else return false
* @throws IOException
*/
private boolean checkErrorRecordCountDirExists(String filePath) throws IOException {
HttpResponse response = webHdfs.fileStatus(filePath);
webHdfs.releaseConnection();
if (response.getStatusLine().getStatusCode() == 404) {
return false;
} else {
return true;
}
}
/**
* This is to make error record count directory in hdfs
*
* @param dirPath
* @return true if create directory successfully else return false
* @throws IOException
*/
private boolean makeErrorRecordCountDir(String dirPath) throws IOException {
HttpResponse response = webHdfs.mkdir(dirPath);
webHdfs.releaseConnection();
if (response.getStatusLine().getStatusCode() == 200) {
return true;
} else {
return false;
}
}
/**
* This method is move errorRecordCountFile to another location in hdfs
*
* @param source
* errorRecordCountFile path
* @param dest
* error record count directory
* @throws IOException
*/
private void moveErrorRecordCountFile(String source, String dest) throws IOException {
webHdfs.addParameter("destination", dest);
webHdfs.rename(source);
webHdfs.releaseConnection();
}
@Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| 35.378277 | 131 | 0.761592 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.