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
|
---|---|---|---|---|---|
ca4d13d31e5066990aaae60d92743f702ab9ac29 | 205 | package com.atlassian.db.replica.internal;
import java.sql.Connection;
import java.sql.SQLException;
public interface ConnectionOperation {
void accept(Connection connection) throws SQLException;
}
| 20.5 | 59 | 0.809756 |
f873dc7ac89caccfb49b04c55f063c0847ead6ad | 897 | package edu.kit.scc.dem.wapsrv.service;
import org.mockito.Mockito;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
/**
* Tests with container mockup.
*
* @author Matthias Dressel
* @author Michael Hitzker
* @author Markus Hoefler
* @author Andreas Loeffler
* @author Timo Schmidt
* @version 1.1
*/
@Configuration
@Profile("test")
public class ContainerServiceMock {
/**
* Gets a container Service mock object
*
* @return A container service mock object
*/
@Bean
@Primary
public ContainerService containerService() {
ContainerService containerServiceMock = Mockito.mock(ContainerService.class);
return containerServiceMock;
}
}
| 26.382353 | 84 | 0.716834 |
3b37ca826938b10a658f1070a0bfa047fa97ea1a | 126 | package client.service;
public class Service {
public Service() {
// TODO Auto-generated constructor stub
}
}
| 12.6 | 42 | 0.65873 |
eca84dbdf8eefe2756aa73895d8938075793ddd0 | 6,283 | package xin.cymall.service.impl;
import com.alibaba.fastjson.JSON;
import com.aliyun.oss.common.utils.LogUtils;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import xin.cymall.common.dadaexpress.DaDaExpressUtil;
import xin.cymall.common.enumresource.OrderStatusEnum;
import xin.cymall.common.utils.AppPush;
import xin.cymall.common.utils.OrderUtil;
import xin.cymall.common.utils.StringUtil;
import xin.cymall.common.utils.UUID;
import xin.cymall.dao.*;
import xin.cymall.entity.SrvOrder;
import xin.cymall.entity.SrvOrderFood;
import xin.cymall.entity.SrvRestaurant;
import xin.cymall.entity.wchart.OrderFood;
import xin.cymall.entity.wchart.SrvWxUser;
import xin.cymall.entity.wchart.WxOrder;
import xin.cymall.service.PushService;
import xin.cymall.service.SrvOrderService;
@Service("srvOrderService")
@Transactional
public class SrvOrderServiceImpl implements SrvOrderService {
@Autowired
private SrvOrderDao srvOrderDao;
@Autowired
private SrvWxUserDao srvWxUserDao;
@Autowired
private SrvOrderFoodDao srvOrderFoodDao;
@Autowired
private SrvRestaurantDao srvRestaurantDao;
@Autowired
private SrvCouponDao srvCouponDao;
@Override
public SrvOrder get(String id){
return srvOrderDao.get(id);
}
@Override
public List<SrvOrder> getList(Map<String, Object> map){
return srvOrderDao.getList(map);
}
@Override
public int getCount(Map<String, Object> map){
return srvOrderDao.getCount(map);
}
@Transactional
@Override
public String save(WxOrder wxOrder) throws IOException {
SrvOrder order = new SrvOrder();
order.setId(UUID.generateId());
SrvWxUser srvWxUser =srvWxUserDao.getByOpenId(wxOrder.getWxId());
order.setOrderNo(OrderUtil.generateOrderNo(wxOrder.getOrderType()));
order.setOrderType(wxOrder.getOrderType());
order.setUserId(srvWxUser.getId());
order.setRestaurantId(wxOrder.getRestaurantId());
order.setUserAddrId(wxOrder.getUserAddrId());
order.setCouponId(wxOrder.getCouponId());
if(wxOrder.getPackFee()!=null && wxOrder.getPackFee()>0)
order.setPackFee(wxOrder.getPackFee());
else
order.setPackFee(0);
if(wxOrder.getWayFee()!=null && wxOrder.getWayFee()>0) {
order.setWayFee(wxOrder.getWayFee());
order.setDadaOrder(wxOrder.getDadaOrder());
order.setExpressNum(wxOrder.getExpressNum());
order.setExpressCompnay("达达快递");
}
if(wxOrder.getCouponAmount()!=null && wxOrder.getCouponAmount() > 0)
order.setCouponAmount(wxOrder.getCouponAmount());
else
order.setCouponAmount(0);
order.setUserPayFee(wxOrder.getUserPayAmount()+ order.getPackFee());
order.setOrderTotal(wxOrder.getTotalAmount() + order.getPackFee());
order.setRestaurantTotal(wxOrder.getRestaurantTotal());
order.setRemark(wxOrder.getRemark());
ObjectMapper mapper = new ObjectMapper();
List<OrderFood> list = mapper.readValue(wxOrder.getFoodList(), new TypeReference<List<OrderFood>>() {});
list.stream().collect(Collectors.groupingBy(obj -> obj,Collectors.counting())).forEach((orderFood, num) -> {
SrvOrderFood srvOrderFood = new SrvOrderFood();
srvOrderFood.setId(UUID.generateId());
srvOrderFood.setFoodId(orderFood.getId());
srvOrderFood.setOrderId(order.getId());
srvOrderFood.setPrice(orderFood.getSysPrice());
srvOrderFood.setTotalPrice(num.intValue() * orderFood.getSysPrice());
srvOrderFood.setFoodName(orderFood.getName());
srvOrderFood.setNumber(num.intValue());
order.setRestaurantId(orderFood.getRid());
srvOrderFoodDao.save(srvOrderFood);
});
order.setStatus(OrderStatusEnum.ORDRT_STATUS1.getCode());
Map<String,Object> couponMap = new HashMap<>();
couponMap.put("id",order.getCouponId());
couponMap.put("userId",order.getUserId());
couponMap.put("isUse","1");
couponMap.put("userTime",new Date());
srvCouponDao.update(couponMap);
srvOrderDao.save(order);
return order.getOrderNo();
}
public void updateOrderSuccessCallback(String orderNo){
SrvOrder srvOrder = srvOrderDao.getByOderNo(orderNo);
if(srvOrder != null) {
srvOrder.setStatus(OrderStatusEnum.ORDRT_STATUS3.getCode());
//支付成功 推送给app
SrvRestaurant srvRestaurant = srvRestaurantDao.get(srvOrder.getRestaurantId());
HashMap<String, String> message = new HashMap();
message.put("title","你有一条新的订单");
message.put("titleText","你有一条新的订单");
message.put("transText", "你有一条新的订单");
System.out.println((AppPush.pushMsgToSingle(srvRestaurant.getClientId(), message).getResponse()));
if("1".equals(srvRestaurant.getAutoReceipt()) && "1".equals(srvOrder.getOrderType())){
//自动接单 需要订单类型为外卖
srvOrder.setStatus(OrderStatusEnum.ORDRT_STATUS4.getCode());
srvOrder.setReceiptTime(new Date());
//提交达达订单
DaDaExpressUtil.addAfterQuery(srvOrder.getExpressNum());
}
update(srvOrder);
}
}
@Override
@Transactional
public void updateOrderDada(String dadaOrder, String orderStatus,String expressName,String expressPhone) {
SrvOrder srvOrder = srvOrderDao.queryOrderByDada(dadaOrder);
srvOrder.setStatus(orderStatus);
if(!StringUtil.isEmpty(expressName))
srvOrder.setExpressName(expressName);
if(!StringUtil.isEmpty(expressPhone))
srvOrder.setExpressPhone(expressPhone);
if(orderStatus.equals(OrderStatusEnum.ORDRT_STATUS7.getCode())){
srvRestaurantDao.addBalance(srvOrder.getRestaurantTotal(), srvOrder.getRestaurantId());
}
srvOrderDao.update(srvOrder);
}
@Override
public void update(SrvOrder srvOrder){
srvOrderDao.update(srvOrder);
}
@Override
public void delete(String id){
srvOrderDao.delete(id);
}
@Override
public void deleteBatch(String[] ids){
srvOrderDao.deleteBatch(ids);
}
@Override
public void updateState(String[] ids,String stateValue) {
for (String id:ids){
SrvOrder srvOrder=get(id);
srvOrder.setStatus(stateValue);
update(srvOrder);
}
}
@Override
public SrvOrder receiptOrder(SrvOrder srvOrder) {
return srvOrderDao.receiptOrder(srvOrder);
}
}
| 33.243386 | 110 | 0.769378 |
37868fa6c70c726d068a675b34fa4f864e151fd5 | 3,027 | /*******************************************************************************
* Copyright 2017 Capital One Services, LLC and Bitwise, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package hydrograph.ui.propertywindow.property;
import java.util.LinkedHashMap;
// TODO: Auto-generated Javadoc
/**
*
* @author Bitwise
* Sep 29, 2015
*
*/
public class ELTComponenetProperties {
private LinkedHashMap<String, Object> componentConfigurationProperties;
private LinkedHashMap<String, Object> componentMiscellaneousProperties;
private ELTComponenetProperties(){
}
/**
* Instantiates a new ELT componenet properties.
*
* @param componentConfigurationProperties
* the component configuration properties
* @param componentMiscellaneousProperties
* the component miscellaneous properties
*/
public ELTComponenetProperties(
LinkedHashMap<String, Object> componentConfigurationProperties,
LinkedHashMap<String, Object> componentMiscellaneousProperties) {
super();
this.componentConfigurationProperties = componentConfigurationProperties;
this.componentMiscellaneousProperties = componentMiscellaneousProperties;
}
public LinkedHashMap<String, Object> getComponentConfigurationProperties() {
return componentConfigurationProperties;
}
/**
* Gets the component configuration property.
*
* @param propertyName
* the property name
* @return the component configuration property
*/
public Object getComponentConfigurationProperty(String propertyName) {
return componentConfigurationProperties.get(propertyName);
}
public void setComponentConfigurationProperties(
LinkedHashMap<String, Object> componentConfigurationProperties) {
this.componentConfigurationProperties = componentConfigurationProperties;
}
public LinkedHashMap<String, Object> getComponentMiscellaneousProperties() {
return componentMiscellaneousProperties;
}
/**
* Gets the component miscellaneous property.
*
* @param propertyName
* the property name
* @return the component miscellaneous property
*/
public Object getComponentMiscellaneousProperty(String propertyName) {
return componentMiscellaneousProperties.get(propertyName);
}
public void setComponentMiscellaneousProperties(
LinkedHashMap<String, Object> componentMiscellaneousProperties) {
this.componentMiscellaneousProperties = componentMiscellaneousProperties;
}
}
| 33.263736 | 81 | 0.737364 |
e2b39c58320da050e8b785950a9ad432819ec769 | 2,770 | import java.util.Scanner;
public class MyMain {
// Generates a random number between 10 and 20, inclusive
public static int randomTeen() {
int WillHarris = (int)(Math.random() * 11) + 10;
return WillHarris;
}
// Use your previous method to generate three random numbers between 10 and 20, inclusive.
// Your program should print out the three numbers, as well as the largest and smallest
// values of the three.
// Example of running your code:
// The three random numbers are 20, 14, and 10
// The largest number is 20
// The smallest number is 10
public static void main(String[] args) {
int m = randomTeen();
int o = randomTeen();
int p = randomTeen();
System.out.println(Mathey.max(m, Mathey.max(o, p)));
// pythag theorem
System.out.println(Mathey.sqrt(Mathey.pow(5 , 2) + Mathey.pow(12, 2)));
// My tests
System.out.println("Mathey.max tests");
System.out.println("Mathey max int 2");
System.out.println(Mathey.max(1, 2)); // 2
System.out.println(Mathey.max(2, 1)); // 2
System.out.println("Mathey max double 2");
System.out.println(Mathey.max(3.0,4.5)); // 4.5
System.out.println(Mathey.max(34.2,16.5)); // 34.2
System.out.println("Mathey max int 3");
System.out.println(Mathey.max(3, 7, 12)); // 12
System.out.println(Mathey.max(6, 1, 2)); // 6
System.out.println("Mathey max double 4");
System.out.println(Mathey.max(3, 55, 6,44)); // 55
System.out.println(Mathey.max(22, 5, 18,0)); // 22
System.out.println("Random int 2");
System.out.println(Mathey.randomInteger(4,12));
System.out.println(Mathey.randomInteger(32,120));
System.out.println("Random int 1");
System.out.println(Mathey.randomInteger(6));
System.out.println(Mathey.randomInteger(43));
System.out.println("pow test");
System.out.println(Mathey.pow(3,4));
System.out.println(Mathey.pow(2,6));
System.out.println("ABS test");
System.out.println(Mathey.abs(-5));
System.out.println(Mathey.abs(24));
System.out.println("Round test");
System.out.println(Mathey.round(3.4));
System.out.println(Mathey.round(7.6));
System.out.println("Floor test");
System.out.println(Mathey.floor(4.6));
System.out.println(Mathey.floor(43.9));
System.out.println("Ceiling test");
System.out.println(Mathey.ceil(3.01));
System.out.println(Mathey.ceil(65.999));
System.out.println("Sqrt test");
System.out.println(Mathey.sqrt(42.7));
System.out.println(Mathey.sqrt(144.0));
}
}
| 31.123596 | 94 | 0.606137 |
1301b34567ac49b1ef8f95421ff8cacb207bc236 | 1,344 | package com.example.alpha.tencentnewsclientdemo.JavaBean;
/**
* 新闻item实体类
* Created by Alpha on 2016/6/30.
*/
public class NewsItem {
private String title;
private String link;
private String author;
private int comments=0;
private String description;
private String date;
private String imageuri;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getComments() {
return comments;
}
public void setComments(int comments) {
this.comments = comments;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getImageuri() {
return imageuri;
}
public void setImageuri(String imageuri) {
this.imageuri = imageuri;
}
}
| 18.666667 | 57 | 0.606399 |
c0fe1086974a5d3614d2efac40a74538e2894298 | 143 | package Modele;
public class FantomeRouge extends Fantome{
public FantomeRouge(Salle salle ){
super.salle = salle;
}
}
| 17.875 | 43 | 0.65035 |
deccca1db26fa28130ef1165ac1f7a05e2b1bab0 | 7,728 | package com.mrbysco.structurevisualizer.keybinding;
import com.mrbysco.structurevisualizer.StructureVisualizer;
import com.mrbysco.structurevisualizer.render.RenderHandler;
import com.mrbysco.structurevisualizer.screen.TemplateSelectionScreen;
import com.mrbysco.structurevisualizer.util.StructureRenderHelper;
import net.minecraft.client.Minecraft;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.client.util.InputMappings;
import net.minecraft.client.util.InputMappings.Type;
import net.minecraft.util.Util;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraft.world.gen.feature.template.Template;
import net.minecraftforge.client.event.InputEvent.KeyInputEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.client.registry.ClientRegistry;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import org.lwjgl.glfw.GLFW;
public class KeyBinds {
public static KeyBinding KEY_TOGGLE = new KeyBinding(
"key." + StructureVisualizer.MOD_ID + ".open",
Type.KEYSYM,
GLFW.GLFW_KEY_KP_9,
"category." + StructureVisualizer.MOD_ID + ".main");
public static KeyBinding KEY_RENDER = new KeyBinding(
"key." + StructureVisualizer.MOD_ID + ".render",
Type.KEYSYM,
GLFW.GLFW_KEY_KP_3,
"category." + StructureVisualizer.MOD_ID + ".main");
public static KeyBinding KEY_X_DOWN = new KeyBinding(
"key." + StructureVisualizer.MOD_ID + ".x_down",
Type.KEYSYM,
GLFW.GLFW_KEY_KP_7,
"category." + StructureVisualizer.MOD_ID + ".main");
public static KeyBinding KEY_X_UP = new KeyBinding(
"key." + StructureVisualizer.MOD_ID + ".x_up",
Type.KEYSYM,
GLFW.GLFW_KEY_KP_8,
"category." + StructureVisualizer.MOD_ID + ".main");
public static KeyBinding KEY_Y_DOWN = new KeyBinding(
"key." + StructureVisualizer.MOD_ID + ".y_down",
Type.KEYSYM,
GLFW.GLFW_KEY_KP_4,
"category." + StructureVisualizer.MOD_ID + ".main");
public static KeyBinding KEY_Y_UP = new KeyBinding(
"key." + StructureVisualizer.MOD_ID + ".y_up",
Type.KEYSYM,
GLFW.GLFW_KEY_KP_5,
"category." + StructureVisualizer.MOD_ID + ".main");
public static KeyBinding KEY_Z_DOWN = new KeyBinding(
"key." + StructureVisualizer.MOD_ID + ".z_down",
Type.KEYSYM,
GLFW.GLFW_KEY_KP_1,
"category." + StructureVisualizer.MOD_ID + ".main");
public static KeyBinding KEY_Z_UP = new KeyBinding(
"key." + StructureVisualizer.MOD_ID + ".z_up",
Type.KEYSYM,
GLFW.GLFW_KEY_KP_2,
"category." + StructureVisualizer.MOD_ID + ".main");
public static KeyBinding KEY_COORDINATE = new KeyBinding(
"key." + StructureVisualizer.MOD_ID + ".coordinate",
Type.KEYSYM,
GLFW.GLFW_KEY_KP_6,
"category." + StructureVisualizer.MOD_ID + ".main");
public static KeyBinding KEY_LAYER_DOWN = new KeyBinding(
"key." + StructureVisualizer.MOD_ID + ".layer_down",
Type.KEYSYM,
GLFW.GLFW_KEY_KP_SUBTRACT,
"category." + StructureVisualizer.MOD_ID + ".main");
public static KeyBinding KEY_LAYER_UP = new KeyBinding(
"key." + StructureVisualizer.MOD_ID + ".layer_up",
Type.KEYSYM,
GLFW.GLFW_KEY_KP_ADD,
"category." + StructureVisualizer.MOD_ID + ".main");
public static void registerKeybinds(final FMLClientSetupEvent event) {
ClientRegistry.registerKeyBinding(KEY_TOGGLE);
ClientRegistry.registerKeyBinding(KEY_RENDER);
ClientRegistry.registerKeyBinding(KEY_X_DOWN);
ClientRegistry.registerKeyBinding(KEY_X_UP);
ClientRegistry.registerKeyBinding(KEY_Y_DOWN);
ClientRegistry.registerKeyBinding(KEY_Y_UP);
ClientRegistry.registerKeyBinding(KEY_Z_DOWN);
ClientRegistry.registerKeyBinding(KEY_Z_UP);
ClientRegistry.registerKeyBinding(KEY_COORDINATE);
ClientRegistry.registerKeyBinding(KEY_LAYER_DOWN);
ClientRegistry.registerKeyBinding(KEY_LAYER_UP);
}
@SubscribeEvent
public void onKeyInput(KeyInputEvent event) {
final Minecraft minecraft = Minecraft.getInstance();
if(minecraft.screen != null && event.getAction() != GLFW.GLFW_PRESS)
if (InputMappings.isKeyDown(minecraft.getWindow().getWindow(), 292)) { return; }
if (KEY_TOGGLE.consumeClick()) {
minecraft.setScreen(new TemplateSelectionScreen());
}
if (KEY_COORDINATE.consumeClick()) {
BlockPos pos = RenderHandler.position;
Template template = RenderHandler.cachedTemplate;
if(pos != null && template != null) {
pos = pos.offset((template.size.getX() / 2), 0, (template.size.getZ() / 2));
minecraft.player.sendMessage(new TranslationTextComponent("structurevisualizer.coordinates",
new StringTextComponent(String.valueOf(pos.getX())).withStyle(TextFormatting.RED),
new StringTextComponent(String.valueOf(pos.getY())).withStyle(TextFormatting.GREEN),
new StringTextComponent(String.valueOf(pos.getZ())).withStyle(TextFormatting.BLUE)), Util.NIL_UUID);
}
}
if (KEY_X_DOWN.consumeClick()){
changePosition(minecraft, -1, 0, 0);
}
if (KEY_X_UP.consumeClick())
changePosition(minecraft, 1, 0, 0);
if (KEY_Y_DOWN.consumeClick()) {
changePosition(minecraft, 0, -1, 0);
}
if (KEY_Y_UP.consumeClick())
changePosition(minecraft, 0, 1, 0);
if (KEY_Z_DOWN.consumeClick())
changePosition(minecraft, 0, 0, -1);
if (KEY_Z_UP.consumeClick())
changePosition(minecraft, 0, 0, 1);
if (KEY_RENDER.consumeClick()) {
if(RenderHandler.templateWorld == null) {
minecraft.player.sendMessage(new TranslationTextComponent("structurevisualizer.render.fail"), Util.NIL_UUID);
} else {
RenderHandler.renderStructure = !RenderHandler.renderStructure;
}
}
if (KEY_LAYER_DOWN.consumeClick()) {
layerDown(minecraft);
}
if (KEY_LAYER_UP.consumeClick()) {
layerUp(minecraft);
}
}
public void layerDown(Minecraft minecraft) {
if(RenderHandler.cachedTemplate != null) {
RenderHandler.renderBuffer = null;
RenderHandler.templateWorld = null;
int downLayer = RenderHandler.layer - 1;
if(downLayer == 0) {
RenderHandler.layer = RenderHandler.templateHeight;
} else {
RenderHandler.layer = downLayer;
}
minecraft.player.displayClientMessage(new TranslationTextComponent("structurevisualizer.layer", RenderHandler.layer, RenderHandler.templateHeight).withStyle(TextFormatting.YELLOW), true);
StructureRenderHelper.initializeTemplateWorld(RenderHandler.cachedTemplate, minecraft.level, RenderHandler.position, RenderHandler.position, RenderHandler.placementSettings, 2);
}
}
public void layerUp(Minecraft minecraft) {
if(RenderHandler.cachedTemplate != null) {
RenderHandler.renderBuffer = null;
RenderHandler.templateWorld = null;
int upLayer = RenderHandler.layer + 1;
if(upLayer > RenderHandler.templateHeight) {
RenderHandler.layer = 1;
} else {
RenderHandler.layer = upLayer;
}
minecraft.player.displayClientMessage(new TranslationTextComponent("structurevisualizer.layer", RenderHandler.layer, RenderHandler.templateHeight).withStyle(TextFormatting.YELLOW), true);
StructureRenderHelper.initializeTemplateWorld(RenderHandler.cachedTemplate, minecraft.level, RenderHandler.position, RenderHandler.position, RenderHandler.placementSettings, 2);
}
}
public void changePosition(Minecraft minecraft, int x, int y, int z) {
if(RenderHandler.cachedTemplate != null) {
RenderHandler.renderBuffer = null;
RenderHandler.templateWorld = null;
RenderHandler.position = RenderHandler.position.offset(x, y, z);
StructureRenderHelper.initializeTemplateWorld(RenderHandler.cachedTemplate, minecraft.level, RenderHandler.position, RenderHandler.position, RenderHandler.placementSettings, 2);
}
}
}
| 40.25 | 190 | 0.760999 |
abc13a147946a2e484c68e5a4923e107b8136bc5 | 494 | package it.unive.golisa.cfg.expression.literal;
import it.unive.golisa.cfg.type.GoStringType;
import it.unive.lisa.program.SourceCodeLocation;
import it.unive.lisa.program.cfg.CFG;
import it.unive.lisa.program.cfg.statement.literal.Literal;
public class GoRune extends Literal<String> {
public GoRune(CFG cfg, SourceCodeLocation location, String value) {
super(cfg, location, value, GoStringType.INSTANCE);
}
@Override
public String toString() {
return "'" + getValue() + "'";
}
}
| 26 | 68 | 0.759109 |
c98bb4a840433fc21f7d60139092cde10659c64e | 6,981 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.ilm;
import org.elasticsearch.action.admin.indices.alias.Alias;
import org.elasticsearch.action.admin.indices.template.put.PutComposableIndexTemplateAction;
import org.elasticsearch.cluster.metadata.ComposableIndexTemplate;
import org.elasticsearch.cluster.metadata.IndexMetadata;
import org.elasticsearch.cluster.metadata.Template;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.xpack.cluster.routing.allocation.DataTierAllocationDecider;
import org.elasticsearch.xpack.core.LocalStateCompositeXPackPlugin;
import org.elasticsearch.xpack.core.XPackSettings;
import org.elasticsearch.xpack.core.ilm.ExplainLifecycleRequest;
import org.elasticsearch.xpack.core.ilm.ExplainLifecycleResponse;
import org.elasticsearch.xpack.core.ilm.IndexLifecycleExplainResponse;
import org.elasticsearch.xpack.core.ilm.LifecyclePolicy;
import org.elasticsearch.xpack.core.ilm.LifecycleSettings;
import org.elasticsearch.xpack.core.ilm.Phase;
import org.elasticsearch.xpack.core.ilm.RolloverAction;
import org.elasticsearch.xpack.core.ilm.ShrinkAction;
import org.elasticsearch.xpack.core.ilm.action.ExplainLifecycleAction;
import org.elasticsearch.xpack.core.ilm.action.PutLifecycleAction;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static org.hamcrest.Matchers.equalTo;
@ESIntegTestCase.ClusterScope(scope = ESIntegTestCase.Scope.TEST, numDataNodes = 0, numClientNodes = 0)
public class ILMMultiNodeIT extends ESIntegTestCase {
private static final String index = "myindex";
@Override
protected Collection<Class<? extends Plugin>> nodePlugins() {
return Arrays.asList(LocalStateCompositeXPackPlugin.class, IndexLifecycle.class);
}
@Override
protected Collection<Class<? extends Plugin>> transportClientPlugins() {
return nodePlugins();
}
@Override
protected Settings nodeSettings(int nodeOrdinal) {
Settings.Builder settings = Settings.builder().put(super.nodeSettings(nodeOrdinal));
settings.put(XPackSettings.MACHINE_LEARNING_ENABLED.getKey(), false);
settings.put(XPackSettings.SECURITY_ENABLED.getKey(), false);
settings.put(XPackSettings.WATCHER_ENABLED.getKey(), false);
settings.put(XPackSettings.GRAPH_ENABLED.getKey(), false);
settings.put(LifecycleSettings.LIFECYCLE_POLL_INTERVAL, "1s");
// This is necessary to prevent ILM and SLM installing a lifecycle policy, these tests assume a blank slate
settings.put(LifecycleSettings.LIFECYCLE_HISTORY_INDEX_ENABLED, false);
settings.put(LifecycleSettings.SLM_HISTORY_INDEX_ENABLED_SETTING.getKey(), false);
return settings.build();
}
@Override
protected boolean ignoreExternalCluster() {
return true;
}
@Override
protected Settings transportClientSettings() {
Settings.Builder settings = Settings.builder().put(super.transportClientSettings());
settings.put(XPackSettings.MACHINE_LEARNING_ENABLED.getKey(), false);
settings.put(XPackSettings.SECURITY_ENABLED.getKey(), false);
settings.put(XPackSettings.WATCHER_ENABLED.getKey(), false);
settings.put(XPackSettings.GRAPH_ENABLED.getKey(), false);
return settings.build();
}
public void testShrinkOnTiers() throws Exception {
startHotOnlyNode();
startWarmOnlyNode();
ensureGreen();
RolloverAction rolloverAction = new RolloverAction(null, null, 1L);
Phase hotPhase = new Phase("hot", TimeValue.ZERO, Collections.singletonMap(rolloverAction.getWriteableName(), rolloverAction));
ShrinkAction shrinkAction = new ShrinkAction(1);
Phase warmPhase = new Phase("warm", TimeValue.ZERO, Collections.singletonMap(shrinkAction.getWriteableName(), shrinkAction));
Map<String, Phase> phases = new HashMap<>();
phases.put(hotPhase.getName(), hotPhase);
phases.put(warmPhase.getName(), warmPhase);
LifecyclePolicy lifecyclePolicy = new LifecyclePolicy("shrink-policy", phases);
client().execute(PutLifecycleAction.INSTANCE, new PutLifecycleAction.Request(lifecyclePolicy)).get();
Template t = new Template(Settings.builder()
.put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 2)
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0)
.put(LifecycleSettings.LIFECYCLE_NAME, "shrink-policy")
.put(RolloverAction.LIFECYCLE_ROLLOVER_ALIAS, "shrink-alias")
.put(DataTierAllocationDecider.INDEX_ROUTING_PREFER, "data_hot")
.build(), null, null);
ComposableIndexTemplate template = new ComposableIndexTemplate(
Collections.singletonList(index + "*"),
t,
null,
null,
null,
null
);
client().execute(
PutComposableIndexTemplateAction.INSTANCE,
new PutComposableIndexTemplateAction.Request("template").indexTemplate(template)
).actionGet();
client().admin().indices().prepareCreate(index + "-000001")
.addAlias(new Alias("shrink-alias").writeIndex(true)).get();
client().prepareIndex(index + "-000001", MapperService.SINGLE_MAPPING_NAME)
.setCreate(true).setId("1").setSource("@timestamp", "2020-09-09").get();
assertBusy(() -> {
String name = "shrink-" + index + "-000001";
ExplainLifecycleResponse explain =
client().execute(ExplainLifecycleAction.INSTANCE, new ExplainLifecycleRequest().indices("*")).get();
logger.info("--> explain: {}", Strings.toString(explain));
IndexLifecycleExplainResponse indexResp = explain.getIndexResponses().get(name);
assertNotNull(indexResp);
assertThat(indexResp.getPhase(), equalTo("warm"));
assertThat(indexResp.getStep(), equalTo("complete"));
}, 60, TimeUnit.SECONDS);
}
public void startHotOnlyNode() {
Settings nodeSettings = Settings.builder().putList("node.roles", Arrays.asList("master", "data_hot", "ingest")).build();
internalCluster().startNode(nodeSettings);
}
public void startWarmOnlyNode() {
Settings nodeSettings = Settings.builder().putList("node.roles", Arrays.asList("master", "data_warm", "ingest")).build();
internalCluster().startNode(nodeSettings);
}
}
| 46.54 | 135 | 0.724968 |
773f38639a11cc34b2481d5b8d570be73cfc0604 | 140 | package com.luwei.rxbus;
/**
* Created by Tomey at 2018/6/19
*/
public interface IEvent{
int getFlag();
<T> T getContent();
}
| 10.769231 | 32 | 0.614286 |
e6cbb425fbfa6611fabec51bb34f04edbf63c758 | 343 | package org.mikolamb.framework.sub.taskmachine.queue.function;
import java.util.Optional;
/**
* @Author WangGang
* @Description //TODO 任务机队列接口$
* Created by WangGang on 2019/4/18 0018 15:12
**/
public interface MikoLambTaskQueueUnBlockOperation<M> {
/*入队*/
public boolean push(M m);
/*出队*/
public Optional<M> pull();
}
| 19.055556 | 62 | 0.690962 |
703165954211966f6382f20e2bd9580d6f724d46 | 554 | package com.xmlmind.fo.converter.odt;
import com.xmlmind.fo.zip.ZipEntry;
public class OdtEntry extends ZipEntry {
public String type;
public OdtEntry(String var1, String var2) {
super(var1);
this.type = var2;
}
public OdtEntry(String var1, String var2, String var3) {
this(var1, var2);
this.setPath(var3);
}
public OdtEntry(String var1, String var2, String[] var3) {
this(var1, var2);
this.paths = var3;
}
public void setPath(String var1) {
this.paths = new String[]{var1};
}
}
| 20.518519 | 61 | 0.638989 |
13495e37d6995f8db546aa32f86e6d08e4a7081d | 1,274 | package com.im.imserver.convertor;
import com.im.imserver.domain.user.Role;
import com.im.imserver.domain.user.UserProfile;
import com.im.imserver.dto.clientobject.UserProfileCO;
import com.im.imserver.gatewayimpl.database.dataobject.UserProfileDO;
import org.springframework.beans.BeanUtils;
public class UserProfileConvertor{
public static UserProfile toEntity(UserProfileCO userProfileCO){
UserProfile userProfile = new UserProfile();
BeanUtils.copyProperties(userProfileCO, userProfile);
userProfile.setRole(Role.valueOf(userProfileCO.getRole()));
return userProfile;
}
public static UserProfileDO toDataObject(UserProfile userProfile){
UserProfileDO userProfileDO = new UserProfileDO();
BeanUtils.copyProperties(userProfile, userProfileDO);
userProfileDO.setRole(userProfile.getRole().name());
return userProfileDO;
}
public static UserProfileDO toDataObjectForCreate(UserProfile userProfile){
UserProfileDO userProfileDO = toDataObject(userProfile);
return userProfileDO;
}
public static UserProfileDO toDataObjectForUpdate(UserProfile userProfile){
UserProfileDO userProfileDO = toDataObject(userProfile);
return userProfileDO;
}
}
| 36.4 | 80 | 0.758242 |
62b305aebc206993a1b9edf1c02130c135bb699b | 2,291 | package com.web.server.webserver.config;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.info.BuildProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.Collections;
import java.util.Date;
@Configuration
@EnableSwagger2
@Import(springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration.class)
@RequiredArgsConstructor
public class SwaggerConfig {
private final BuildProperties buildProperties;
@Bean
public Docket api() {
return new Docket(DocumentationType.OAS_30)
.genericModelSubstitutes(ResponseEntity.class)
.ignoredParameterTypes(Pageable.class)
.ignoredParameterTypes(java.sql.Date.class)
.directModelSubstitute(java.time.LocalDate.class, java.sql.Date.class)
.directModelSubstitute(java.time.ZonedDateTime.class, Date.class)
.directModelSubstitute(java.time.LocalDateTime.class, Date.class)
.select()
.apis(RequestHandlerSelectors.basePackage("com.web.server.webserver.controller"))
.build()
.apiInfo(apiInfo())
.securitySchemes(Collections.singletonList(apiKey()));
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(" API")
.version(buildProperties.getVersion())
.build();
}
private ApiKey apiKey() {
return new ApiKey("Authorization", "Authorization", "header");
}
}
| 38.183333 | 98 | 0.715408 |
82f8654edc3868ced744f5c727227430b3f81de6 | 169 | import java.util.List;
public class Course {
String userID;
String password;
String courseID;
String courseName;
List<Student>selectedStudent;
}
| 13 | 33 | 0.692308 |
f64114062cd2b58fae154bcba056a2954b782d91 | 144 | package com.scart.dao;
import com.scart.entity.Account;
public interface AccountDAO {
public Account findAccount(String userName );
} | 18 | 49 | 0.75 |
20dae8c8eab4f71225103093291956dd085b08d7 | 193 | package exceptions;
public class HttpRequestException extends Exception {
public HttpRequestException(final String message, final Throwable cause) {
super(message, cause);
}
}
| 24.125 | 78 | 0.746114 |
8e3dcefba66fd182d9cc8d601ebead183a749203 | 3,576 | package blackbird.core.impl;
import java.io.IOException;
import blackbird.core.ComponentImplementation;
import blackbird.core.DInterface;
import blackbird.core.Device;
import blackbird.core.exception.ImplementationFailedException;
import blackbird.core.ports.ParentDevicePort;
import static blackbird.core.avr.DigitalPinValue.HIGH;
import static blackbird.core.avr.DigitalPinValue.LOW;
public class AukeyRemote extends Device {
private static final long serialVersionUID = -7567884786987932459L;
public AukeyRemote(String name) {
super(name);
getUIData().put("iconName", "ic_remote");
}
public interface Interface extends DInterface {
void switchSocket(int num, int state);
}
public static class Implementation extends ComponentImplementation<AukeyRemote, DInterface> implements Interface {
public static final MCP23017.Pin OFF_PIN = MCP23017.Pin.B7;
public static final MCP23017.Pin ON_PIN = MCP23017.Pin.B5;
public static final MCP23017.Pin SOCKET_1_PIN = MCP23017.Pin.B1;
public static final MCP23017.Pin SOCKET_2_PIN = MCP23017.Pin.B3;
public static final MCP23017.Pin STATE_LED_PIN = MCP23017.Pin.A7;
MCP23017.Interface mcp;
public Implementation(DInterface component, MCP23017.Interface mcp) throws ImplementationFailedException {
super(component);
this.mcp = mcp;
try {
mcp.pinMode(OFF_PIN, false);
mcp.pinMode(ON_PIN, false);
mcp.pinMode(SOCKET_1_PIN, false);
mcp.pinMode(SOCKET_2_PIN, false);
mcp.pinMode(STATE_LED_PIN, false);
mcp.digitalWrite(OFF_PIN, LOW);
mcp.digitalWrite(ON_PIN, LOW);
mcp.digitalWrite(SOCKET_1_PIN, LOW);
mcp.digitalWrite(SOCKET_2_PIN, LOW);
mcp.digitalWrite(STATE_LED_PIN, HIGH);
} catch (IOException e) {
throw new ImplementationFailedException("IO Exception during initializing aukey remote, " +
"system may be in inconsistent", e);
}
}
@Override
public synchronized void switchSocket(int num, int state) {
try {
MCP23017.Pin socketPin = null;
MCP23017.Pin statePin;
switch (num) {
case 1:
socketPin = SOCKET_1_PIN;
break;
case 2:
socketPin = SOCKET_2_PIN;
break;
}
if (state == Socket.ON)
statePin = ON_PIN;
else
statePin = OFF_PIN;
mcp.digitalWrite(statePin, HIGH);
mcp.digitalWrite(socketPin, HIGH);
Thread.sleep(200);
mcp.digitalWrite(statePin, LOW);
mcp.digitalWrite(socketPin, LOW);
Thread.sleep(1000);
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}
}
public static class Builder extends ParentDevicePort.Builder<AukeyRemote, Interface, MCP23017, MCP23017.Interface> {
@Override
public Interface assemble(DInterface component, MCP23017.Interface parentInterface)
throws ImplementationFailedException {
return new Implementation(component, parentInterface);
}
}
}
}
| 33.111111 | 124 | 0.595078 |
8dfaa9d1160b4bb4175501e8a7426ac72b14a803 | 9,261 | package general.common;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.inject.Guice;
import com.google.inject.Injector;
import general.TestHelper;
import models.common.*;
import models.common.workers.Worker;
import org.apache.commons.lang3.tuple.Pair;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import play.ApplicationLoader;
import play.Environment;
import play.inject.guice.GuiceApplicationBuilder;
import play.inject.guice.GuiceApplicationLoader;
import play.libs.Json;
import utils.common.HashUtils;
import javax.inject.Inject;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import static org.fest.assertions.Assertions.assertThat;
/**
* Tests StudyLogger
*
* @author Kristian Lange
*/
public class StudyLoggerTest {
private Injector injector;
@Inject
private TestHelper testHelper;
@Inject
private StudyLogger studyLogger;
@Before
public void startApp() throws Exception {
GuiceApplicationBuilder builder = new GuiceApplicationLoader()
.builder(new ApplicationLoader.Context(Environment.simple()));
injector = Guice.createInjector(builder.applicationModule());
injector.injectMembers(this);
}
@After
public void stopApp() throws Exception {
// Clean up
testHelper.removeAllStudies();
testHelper.removeStudyAssetsRootDir();
testHelper.removeAllStudyLogs();
}
@Test
public void simpleCheck() {
int a = 1 + 1;
assertThat(a).isEqualTo(2);
}
@Test
public void checkCreate() throws Exception {
Study study = testHelper.createAndPersistExampleStudyForAdmin(injector);
// Check that log is created
Path studyLogPath = Paths.get(studyLogger.getPath(study));
assertThat(Files.isReadable(studyLogPath)).isTrue();
checkInitEntry(study);
}
@Test
public void checkRecreate() throws Exception {
Study study = testHelper.createAndPersistExampleStudyForAdmin(injector);
// Check that log is created
Path studyLogPath = Paths.get(studyLogger.getPath(study));
assertThat(Files.isReadable(studyLogPath)).isTrue();
// Now delete the log
Files.delete(studyLogPath);
assertThat(Files.notExists(studyLogPath)).isTrue();
// Write something into the log
studyLogger.log(study, testHelper.getAdmin(), "bla bla bla");
// Check that the log is recreated
assertThat(Files.isReadable(studyLogPath)).isTrue();
checkInitEntry(study);
}
@Test
public void checkRetire() throws IOException {
Study study = testHelper.createAndPersistExampleStudyForAdmin(injector);
// Check that log is created
Path logPath = Paths.get(studyLogger.getPath(study));
assertThat(Files.isReadable(logPath)).isTrue();
String retiredLogFilename = studyLogger.retire(study);
// Check that the log is renamed
Path retiredLogPath = Paths.get(Common.getStudyLogsPath() + File.separator + retiredLogFilename);
assertThat(Files.notExists(logPath)).isTrue();
assertThat(Files.exists(retiredLogPath)).isTrue();
List<String> content = Files.readAllLines(retiredLogPath);
JsonNode json = Json.parse(content.get(content.size() - 1)); // get last line from log
assertThat(json.has("msg")).isTrue();
assertThat(json.has("timestamp")).isTrue();
assertThat(json.has("studyUuid")).isTrue();
}
@Test
public void checkLog() throws IOException {
Study study = testHelper.createAndPersistExampleStudyForAdmin(injector);
Path logPath = Paths.get(studyLogger.getPath(study));
User user = testHelper.getAdmin();
// Use all log() methods
studyLogger.log(study, user, "bla bla bla");
studyLogger.log(study, user, "foo foo foo", study.getDefaultBatch());
studyLogger.log(study, "bar bar bar", testHelper.getAdmin().getWorker());
studyLogger.log(study, "fuu fuu fuu", study.getDefaultBatch(), testHelper.getAdmin().getWorker());
studyLogger.log(study, user, "bir bir bir", Pair.of("birkey", "birvalue"));
// Check they wrote something into the log
List<String> content = Files.readAllLines(logPath);
// First line is always empty, second line is the initial msg, third line is study created, fourth line is
// study description
assertThat(content.get(4)).contains("bla bla bla");
assertThat(content.get(5)).contains("foo foo foo");
assertThat(content.get(5)).contains("\"batchId\":" + study.getDefaultBatch().getId());
assertThat(content.get(6)).contains("bar bar bar");
assertThat(content.get(6)).contains("\"workerId\":" + testHelper.getAdmin().getWorker().getId());
assertThat(content.get(7)).contains("fuu fuu fuu");
assertThat(content.get(7)).contains("\"batchId\":" + study.getDefaultBatch().getId());
assertThat(content.get(7)).contains("\"workerId\":" + testHelper.getAdmin().getWorker().getId());
assertThat(content.get(8)).contains("bir bir bir");
assertThat(content.get(8)).contains("\"birkey\":\"birvalue\"");
}
@Test
public void checkLogResultDataStoring() throws IOException {
Study study = testHelper.createAndPersistExampleStudyForAdmin(injector);
Worker worker = testHelper.getAdmin().getWorker();
Batch batch = study.getDefaultBatch();
StudyResult studyResult1 = new StudyResult(study, batch, worker);
ComponentResult componentResult = new ComponentResult(study.getFirstComponent().get());
componentResult.setStudyResult(studyResult1);
componentResult.setData("result data 1");
studyResult1.addComponentResult(componentResult);
studyLogger.logResultDataStoring(componentResult);
Path logPath = Paths.get(studyLogger.getPath(study));
List<String> content = Files.readAllLines(logPath);
JsonNode json = Json.parse(content.get(content.size() - 1)); // get last line from log
assertThat(json.has("msg")).isTrue();
assertThat(json.has("timestamp")).isTrue();
assertThat(json.has("componentUuid")).isTrue();
assertThat(json.get("componentUuid").asText()).isEqualTo(study.getFirstComponent().get().getUuid());
assertThat(json.has("workerId")).isTrue();
assertThat(json.get("workerId").asLong()).isEqualTo(worker.getId());
assertThat(json.has("dataHash")).isTrue();
assertThat(json.get("dataHash").asText()).isEqualTo(HashUtils.getHash("result data 1", HashUtils.SHA_256));
}
@Test
public void checkLogResultFileUploading() throws IOException {
Study study = testHelper.createAndPersistExampleStudyForAdmin(injector);
Worker worker = testHelper.getAdmin().getWorker();
Batch batch = study.getDefaultBatch();
StudyResult studyResult1 = new StudyResult(study, batch, worker);
ComponentResult componentResult = new ComponentResult(study.getFirstComponent().get());
componentResult.setStudyResult(studyResult1);
componentResult.setData("result data 1");
studyResult1.addComponentResult(componentResult);
Path uploadedFile = Paths.get("test/resources/example.png");
studyLogger.logResultUploading(uploadedFile, componentResult);
Path logPath = Paths.get(studyLogger.getPath(study));
List<String> content = Files.readAllLines(logPath);
JsonNode json = Json.parse(content.get(content.size() - 1)); // get last line from log
assertThat(json.has("msg")).isTrue();
assertThat(json.has("timestamp")).isTrue();
assertThat(json.has("componentUuid")).isTrue();
assertThat(json.get("componentUuid").asText()).isEqualTo(study.getFirstComponent().get().getUuid());
assertThat(json.has("workerId")).isTrue();
assertThat(json.get("workerId").asLong()).isEqualTo(worker.getId());
assertThat(json.has("fileName")).isTrue();
assertThat(json.get("fileName").asText()).isEqualTo(uploadedFile.getFileName().toString());
assertThat(json.has("fileHash")).isTrue();
assertThat(json.get("fileHash").asText()).isEqualTo(HashUtils.getHash(uploadedFile, HashUtils.SHA_256));
}
private void checkInitEntry(Study study) throws IOException {
Path logPath = Paths.get(studyLogger.getPath(study));
List<String> content = Files.readAllLines(logPath);
JsonNode json = Json.parse(content.get(1)); // First line is empty, second line is init msg
assertThat(json.has("msg")).isTrue();
assertThat(json.has("timestamp")).isTrue();
assertThat(json.has("studyUuid")).isTrue();
assertThat(json.get("studyUuid").asText()).isEqualTo(study.getUuid());
assertThat(json.has("serversMac")).isTrue();
assertThat(json.get("serversMac").asText()).isEqualTo(Common.getMac());
assertThat(json.has("hashFunction")).isTrue();
assertThat(json.get("hashFunction").asText()).isEqualTo(HashUtils.SHA_256);
}
}
| 41.529148 | 115 | 0.682648 |
f18908098fdd8bb82e6e2542486d7d0442a11c22 | 322 | package com.muhacha.bpm.demos.claims.delegates;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.JavaDelegate;
public class SendDeclinedEmail implements JavaDelegate {
@Override
public void execute(DelegateExecution delegateExecution) throws Exception {
}
}
| 24.769231 | 79 | 0.804348 |
80c189d22528b8954e9a5d5fbcf712b1a855dbb6 | 411 | package coneforest.cli;
public class OptionDouble
extends OptionHolder<Double>
{
public OptionDouble(final String names)
{
super(names);
}
@Override
public Double parseArg(final String arg)
throws ProcessingException
{
try
{
return Double.parseDouble(arg);
}
catch(final NumberFormatException e)
{
throw new ProcessingException(Messages.format("optProcExcpnBadArg", arg));
}
}
}
| 16.44 | 77 | 0.734793 |
ff3777f7ab4cb5cfab9591c60a17114c242386d7 | 1,305 | /*
Copyright [2013-2014] eBay Software 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 models.data;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
/**
* 20131213
* @author ypei
*
*/
public class HttpHeaderMetadata {
private String httpHeaderType;
private final Map<String, String> headerMap = new HashMap<String, String>();
public String getHttpHeaderType() {
return httpHeaderType;
}
public void setHttpHeaderType(String httpHeaderType) {
this.httpHeaderType = httpHeaderType;
}
public Map<String, String> getHeaderMap() {
return headerMap;
}
public HttpHeaderMetadata(String httpHeaderType, Map<String, String> headerMap) {
super();
this.httpHeaderType = httpHeaderType;
this.headerMap.putAll(headerMap);
}
}
| 22.894737 | 82 | 0.759387 |
d5a4b8ac968ca7c93bc52a6c6f316d906debaa18 | 11,088 | package uk.ac.ebi.gxa.loader.service;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.sdrf.node.attribute.CharacteristicsAttribute;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.sdrf.node.attribute.FactorValueAttribute;
import uk.ac.ebi.gxa.efo.Efo;
import uk.ac.ebi.gxa.efo.EfoTerm;
import uk.ac.ebi.gxa.loader.AtlasLoaderException;
import uk.ac.ebi.gxa.utils.Pair;
import uk.ac.ebi.gxa.utils.StringUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* This service class deals with cross-factor merging of factor values at experiment load time.
* It also deals with merging units into their corresponding factor values, if these units exist in EFO.
*
* @author Robert Petryszak
*/
public class PropertyValueMergeService {
private final static Logger log = LoggerFactory.getLogger(PropertyValueMergeService.class);
// Set containing all factors for which values need doses merged into them
private static final Set<String> FACTORS_NEEDING_DOSE = Sets.newHashSet();
static {
FACTORS_NEEDING_DOSE.add("compound");
FACTORS_NEEDING_DOSE.add("irradiate");
}
private static final String DOSE = "dose";
// Units containing the following values should never be pluralised when being joined to factor values
private static final List<String> NON_PLURALISED_UNITS = Lists.newArrayList();
static {
NON_PLURALISED_UNITS.add("other");
NON_PLURALISED_UNITS.add("percent");
NON_PLURALISED_UNITS.add("molar");
}
// Units that should end in 'es' rather than 's' in their plural form
private static final String INCH = "inch";
// separator in units in which only the first work should be pluralised (e.g. "micromole per kilogram")
private static final String PER = "per";
// The only case other than the above in which only the first word should be pluralised (e.g. "degree celsius")
private static final String DEGREE = "degree";
// A temporary mapping from MAGE-OM to EFO - for certain units that for operational reasons cannot for the time being arrive
// into Atlas as EFO units
private static final Map<String, String> TRANSLATED_UNITS = Maps.newHashMap();
static {
TRANSLATED_UNITS.put("K", "kelvin");
TRANSLATED_UNITS.put("degrees_C", "degree celsius");
TRANSLATED_UNITS.put("degrees_F", "degree fahrenheit");
}
private Efo efo;
public void setEfo(Efo efo) {
this.efo = efo;
}
/**
* @param unit
* @return true if unit should be pluralised; false otherwise
*/
private static boolean isPluralised(String unit) {
for (String unitVal : NON_PLURALISED_UNITS) {
if (unit.contains(unitVal))
return false;
}
return true;
}
/**
* Pluralise a unit only if:
* - unit is not empty
* - factor value it describes is not equal to 1
* - it is not equal to OTHER or contains PERCENT in it
* - it does not already end in "s"
* <p/>
* Pluralisation method is as follows:
* - if a unit contains PER, pluralise the term preceding it (unless that term ends in "s" already)
* - else if a unit starts with DEGREE, pluralise word DEGREE unless the unit starts with DEGREE + "s"
* - else unless the units already ends in "s", pluralise thh whole unit.
* <p/>
* See the junit test case of this method for the full list of test cases.
* <p/> c.f. examples of units in EFO in ticket 3356:
* MAGE-OM_to_EFO_Units.txt
* OtherUnitsMappedToEFO.txt
*
* @param unit
* @param factorValue
* @return
*/
public static String pluraliseUnitIfApplicable(String unit, String factorValue) {
try {
if (Strings.isNullOrEmpty(factorValue) || Integer.parseInt(factorValue) == 1)
return unit;
} catch (NumberFormatException nfe) {
// quiesce
}
if (!Strings.isNullOrEmpty(unit) && isPluralised(unit)) {
int idx = unit.indexOf(PER);
if (idx != -1)
return pluralise(unit.substring(0, idx - 1).trim()) + " " + unit.substring(idx);
else if (unit.startsWith(DEGREE) && !unit.equals(DEGREE + "s"))
return pluralise(DEGREE) + unit.substring(DEGREE.length());
else
return pluralise(unit);
}
return unit;
}
/**
* @param word
* @return Word pluralised according to a naive pluralisation definition - this method does not implement an exhaustive
* English language pluralisation method but is designed to cover the universe of units used in Atlas only.
*/
private static String pluralise(String word) {
if (!word.endsWith("s")) {
if (INCH.equals(word)) {
return word + "es";
} else
return word + "s";
}
return word;
}
/**
*
* @param unit
* @return an EFO term, corresponding to unit - if unit is a key in TRANSLATED_UNITS; else unit itself
*/
private static String translateUnitToEFOIfApplicable(String unit) {
if (TRANSLATED_UNITS.containsKey(unit.trim()))
return TRANSLATED_UNITS.get(unit.trim());
return unit;
}
/**
* @param characteristicsAttribute
* @return sample characteristic value contained in characteristicsAttribute (with an appended unit, if one exists)
* @throws AtlasLoaderException - if UnitAttribute within characteristicsAttribute exists but has not value or if unit value cannot be found in EFO
*/
public String getCharacteristicValueWithUnit(CharacteristicsAttribute characteristicsAttribute) throws AtlasLoaderException {
String scValue = StringUtil.removeSeparatorDuplicates(characteristicsAttribute.getNodeName()).trim();
if (!Strings.isNullOrEmpty(scValue) && characteristicsAttribute.unit != null) {
String unitValue = translateUnitToEFOIfApplicable(characteristicsAttribute.unit.getAttributeValue());
if (Strings.isNullOrEmpty(unitValue))
throw new AtlasLoaderException("Unable to find unit value for sample characteristic value: " + scValue);
if (!isEfoTerm(unitValue)) {
throw new AtlasLoaderException("Unit: " + unitValue + " not found in EFO");
}
return Joiner.on(" ").join(scValue, PropertyValueMergeService.pluraliseUnitIfApplicable(unitValue.trim(), scValue));
}
return scValue;
}
/**
* @param factorValueAttribute
* @return factorValue contained in factorValueAttribute (with an appended unit, if one exists)
* @throws AtlasLoaderException - if UnitAttribute within factorValueAttribute exists but has not value or if unit value cannot be found in EFO
*/
private String getFactorValueWithUnit(FactorValueAttribute factorValueAttribute) throws AtlasLoaderException {
String factorValueName = StringUtil.removeSeparatorDuplicates(factorValueAttribute.getNodeName()).trim();
if (!Strings.isNullOrEmpty(factorValueName) && factorValueAttribute.unit != null) {
String unitValue = translateUnitToEFOIfApplicable(factorValueAttribute.unit.getAttributeValue());
if (Strings.isNullOrEmpty(unitValue))
throw new AtlasLoaderException("Unable to find unit value for factor value: " + factorValueName);
if (!isEfoTerm(unitValue)) {
throw new AtlasLoaderException("Unit: " + unitValue + " not found in EFO");
}
return Joiner.on(" ").join(factorValueName, PropertyValueMergeService.pluraliseUnitIfApplicable(unitValue.trim(), factorValueName));
}
return factorValueName;
}
/**
*
* @param factorValueAttributes
* @return equivalent of factorValueAttributes, but with all the relevant merge operations performed.
* @throws AtlasLoaderException
*/
public List<Pair<String, String>> getMergedFactorValues(List<Pair<String, FactorValueAttribute>> factorValueAttributes)
throws AtlasLoaderException {
String mainFactorValue = null;
String mainFactor = null;
String doseFactorValue = null;
List<Pair<String, String>> factorValues = new ArrayList<Pair<String, String>>();
for (Pair<String, FactorValueAttribute> pv : factorValueAttributes) {
String ef = pv.getKey();
String efv = getFactorValueWithUnit(pv.getValue());
if (Strings.isNullOrEmpty(efv))
continue; // We don't load empty factor values
if (FACTORS_NEEDING_DOSE.contains(ef.toLowerCase())) {
mainFactorValue = efv;
mainFactor = ef;
} else if (DOSE.equalsIgnoreCase(ef))
doseFactorValue = efv;
if (FACTORS_NEEDING_DOSE.contains(ef.toLowerCase()) || DOSE.equalsIgnoreCase(ef)) {
if (!Strings.isNullOrEmpty(mainFactorValue) && !Strings.isNullOrEmpty(doseFactorValue)) {
ef = mainFactor;
efv = Joiner.on(" ").join(mainFactorValue, doseFactorValue);
mainFactor = null;
mainFactorValue = null;
doseFactorValue = null;
} else {
// Don't add either compound or dose factor values to assay on their own, until:
// - you have both of them, in which case merge them together and then add to assay
// - you know that either dose or compound values are missing, in which case add to assay that one
// (dose or compound) that is present
continue;
}
}
factorValues.add(Pair.create(ef, efv));
}
if (!Strings.isNullOrEmpty(mainFactorValue) && Strings.isNullOrEmpty(doseFactorValue)) {
factorValues.add(Pair.create(mainFactor, mainFactorValue));
log.warn("Adding " + mainFactor + " : " + mainFactorValue + " to assay with no corresponding value for factor: " + DOSE);
} else if (!Strings.isNullOrEmpty(doseFactorValue) && Strings.isNullOrEmpty(mainFactorValue)) {
throw new AtlasLoaderException(DOSE + " : " + doseFactorValue + " has no corresponding value for any of the following factors: " + FACTORS_NEEDING_DOSE);
}
return factorValues;
}
/**
* @param term
* @return true if term can be found in EFO; false otherwise
*/
private boolean isEfoTerm(String term) {
for (EfoTerm t : efo.searchTermPrefix(term)) {
if (term.equals(t.getTerm()))
return true;
}
return false;
}
}
| 42.320611 | 165 | 0.653229 |
3acf1e25f794688b1caeb78b0fd78ab30cabcee8 | 2,030 | package cn.quasar.blog.controller;
import cn.quasar.blog.domain.Categories;
import cn.quasar.blog.dto.MessageResult;
import cn.quasar.blog.dto.MessageStatus;
import cn.quasar.blog.service.CategoriesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping(value = "/categories")
public class CategoriesController {
@Autowired
private CategoriesService categoriesService;
@GetMapping(value = "/all")
public MessageResult queryCategories() {
List<Categories> categories = categoriesService.getAllCategories();
return new MessageResult(HttpStatus.OK.value(), MessageStatus.SUCCESS.getStatus(), categories, "");
}
@GetMapping(value = "/id/{categoriesId}")
public MessageResult queryCategoriesById(@PathVariable int categoriesId) {
Categories categories = categoriesService.getCategoriesById(categoriesId);
return new MessageResult(HttpStatus.OK.value(), MessageStatus.SUCCESS.getStatus(), categories, "");
}
@GetMapping(value = "/category_id/{categoryId}")
public MessageResult queryCategoriesByCategoryId(@PathVariable int categoryId) {
List<Categories> categories = categoriesService.getCategoriesByCategoryId(categoryId);
return new MessageResult(HttpStatus.OK.value(), MessageStatus.SUCCESS.getStatus(), categories, "");
}
@GetMapping(value = "/article_id/{articleId}")
public MessageResult queryCategoriesByArticleId(@PathVariable int articleId) {
List<Categories> categories = categoriesService.getCategoriesByArticleId(articleId);
return new MessageResult(HttpStatus.OK.value(), MessageStatus.SUCCESS.getStatus(), categories, "");
}
}
| 39.038462 | 107 | 0.769951 |
2751a5279614c69ea0b42237be89832070abdec4 | 4,382 | /*
* Copyright (C) 2021 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.launcher3.widget.picker.search;
import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageButton;
import com.android.launcher3.ExtendedEditText;
import com.android.launcher3.search.SearchAlgorithm;
import com.android.launcher3.search.SearchCallback;
import com.android.launcher3.widget.model.WidgetsListBaseEntry;
import java.util.ArrayList;
/**
* Controller for a search bar with an edit text and a cancel button.
*/
public class WidgetsSearchBarController implements TextWatcher,
SearchCallback<WidgetsListBaseEntry>, ExtendedEditText.OnBackKeyListener,
View.OnKeyListener {
private static final String TAG = "WidgetsSearchBarController";
private static final boolean DEBUG = false;
protected SearchAlgorithm<WidgetsListBaseEntry> mSearchAlgorithm;
protected ExtendedEditText mInput;
protected ImageButton mCancelButton;
protected SearchModeListener mSearchModeListener;
protected String mQuery;
public WidgetsSearchBarController(
SearchAlgorithm<WidgetsListBaseEntry> algo, ExtendedEditText editText,
ImageButton cancelButton, SearchModeListener searchModeListener) {
mSearchAlgorithm = algo;
mInput = editText;
mInput.addTextChangedListener(this);
mInput.setOnBackKeyListener(this);
mInput.setOnKeyListener(this);
mCancelButton = cancelButton;
mCancelButton.setOnClickListener(v -> clearSearchResult());
mSearchModeListener = searchModeListener;
}
@Override
public void afterTextChanged(final Editable s) {
mQuery = s.toString();
if (mQuery.isEmpty()) {
mSearchAlgorithm.cancel(/* interruptActiveRequests= */ true);
mSearchModeListener.exitSearchMode();
mCancelButton.setVisibility(GONE);
} else {
mSearchAlgorithm.cancel(/* interruptActiveRequests= */ false);
mSearchModeListener.enterSearchMode();
mSearchAlgorithm.doSearch(mQuery, this);
mCancelButton.setVisibility(VISIBLE);
}
}
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
// Do nothing.
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
// Do nothing.
}
@Override
public void onSearchResult(String query, ArrayList<WidgetsListBaseEntry> items) {
if (DEBUG) {
Log.d(TAG, "onSearchResult query: " + query + " items: " + items);
}
mSearchModeListener.onSearchResults(items);
}
@Override
public void onAppendSearchResult(String query, ArrayList<WidgetsListBaseEntry> items) {
// Not needed.
}
@Override
public void clearSearchResult() {
// Any existing search session will be cancelled by setting text to empty.
mInput.setText("");
}
/**
* Cleans up after search is no longer needed.
*/
public void onDestroy() {
mSearchAlgorithm.destroy();
}
@Override
public boolean onBackKey() {
clearFocus();
return true;
}
@Override
public boolean onKey(View view, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
clearFocus();
return true;
}
return false;
}
/**
* Clears focus from edit text.
*/
public void clearFocus() {
mInput.clearFocus();
mInput.hideKeyboard();
}
}
| 31.753623 | 91 | 0.686445 |
a0f5f51bde41f9fb0fc01e70836df9af57fe7c52 | 8,609 | package com.longbridge.greendemo.controller;
import java.util.Date;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.longbridge.greendemo.exception.PermissionNotMatchException;
import com.longbridge.greendemo.exception.ResourceNotFoundException;
import com.longbridge.greendemo.exception.RoleNotMatchException;
import com.longbridge.greendemo.jwt.DAOUser;
import com.longbridge.greendemo.jwt.UserDao;
import com.longbridge.greendemo.model.Merchant;
import com.longbridge.greendemo.model.Permission;
import com.longbridge.greendemo.repository.MerchantRepository;
import com.longbridge.greendemo.repository.PermissionRepository;
import com.longbridge.greendemo.settings.AppRolesListEnum;
import com.longbridge.greendemo.settings.PermissionsHashMap;
/**
* The type Merchant controller. Merchant api controller
*
* @author idisimagha dublin-green
*/
@RestController
@RequestMapping("/api/v1/merchant")
@CrossOrigin(origins = "http://localhost:8080")
public class MerchantController {
@Autowired
private UserDao userRepository;
@Autowired
private MerchantRepository merchantRepository;
@Autowired
private PermissionRepository permissionRepository;
/**
* Get all merchants list.
*
* @return the list
*/
@GetMapping("/getAllMerchants")
public List<Merchant> getAllMerchants() {
return merchantRepository.findAll();
}
/**
* Get approved merchants list.
*
* @return the list
*/
@GetMapping("/getApprovedMerchants")
public List<Merchant> getApprovedMerchants() {
return merchantRepository.findByStatus(true);
}
/**
* Get not approved permission list.
*
* @return the list
*/
@GetMapping("/getUnapprovedMerchants")
public List<Merchant> getUnapprovedMerchants() {
return merchantRepository.findByStatus(false);
}
/**
* Gets merchant by id.
*
* @param id
* @return the merchant
* @throws ResourceNotFoundException the resource not found exception
*/
@GetMapping("/getMerchantById/{id}")
public ResponseEntity<Merchant> getMerchantById(@PathVariable(value = "id") Long merchantId) throws ResourceNotFoundException {
Merchant merchant = merchantRepository.findById(merchantId)
.orElseThrow(() -> new ResourceNotFoundException("Merchant not found on :: " + merchantId));
return ResponseEntity.ok().body(merchant);
}
/**
* Create merchant.
*
* @param merchantObj
* @param userId
* @return the code
* @throws ResourceNotFoundException
* @throws PermissionNotMatchException
* @throws RoleNotMatchException
*/
@PostMapping("/createCode/{merchantObj}/{userId}")
public @Valid Merchant createMerchant(
@Valid @RequestBody Merchant merchantObj,
@PathVariable(value = "userId") Long userId)
throws ResourceNotFoundException, PermissionNotMatchException, RoleNotMatchException {
final String PERMISSION_KEY = "CAN_CREATE_MERCHANTS";
final String PERMISSION_NEEDED = PermissionsHashMap.getValueByKey(PERMISSION_KEY);
Permission permission;
if(PERMISSION_NEEDED == null){
throw new PermissionNotMatchException("Permission key is invalid not does not have permission (" + PERMISSION_KEY + ")");
}else {
permission = permissionRepository.findByStatusAndNameAndRoleName(true, PERMISSION_NEEDED, AppRolesListEnum.ROLE_ADMIN.toString());
System.out.println("permission.getName() : " + permission.getName());
}
DAOUser user = userRepository.findById(userId)
.orElseThrow(() -> new ResourceNotFoundException("User not found on :: " + userId));
if(!user.getRole().equalsIgnoreCase(AppRolesListEnum.ROLE_ADMIN.toString())) {
throw new RoleNotMatchException(user.getUsername() + " does not have " + AppRolesListEnum.ROLE_ADMIN.toString() + " role");
}else if(!permission.getStatus()) {
throw new PermissionNotMatchException("Permission not enabled (" + PERMISSION_NEEDED + ")");
}else {
merchantObj.setCreatedAt(new Date());
merchantObj.setCreatedBy(user.getUsername());
merchantObj.setUpdatedAt(new Date());
merchantObj.setUpdatedBy(user.getUsername());
}
return merchantRepository.save(merchantObj);
}
/**
* Approve merchant
*
* @param merchantId
* @param userId
* @return the response entity
* @throws ResourceNotFoundException the resource not found exception
* @throws PermissionNotMatchException
* @throws RoleNotMatchException
*/
@PutMapping("/approveMerchant/{id}/{userId}")
public ResponseEntity<Merchant> approveMerchant(@PathVariable(value = "id") Long merchantId,
@PathVariable(value = "userId") Long userId) throws ResourceNotFoundException, PermissionNotMatchException, RoleNotMatchException {
final String PERMISSION_KEY = "CAN_APPROVE_MERCHANTS";
final String PERMISSION_NEEDED = PermissionsHashMap.getValueByKey(PERMISSION_KEY);
Permission permission;
if(PERMISSION_NEEDED == null){
throw new PermissionNotMatchException("Permission key is invalid not does not have permission (" + PERMISSION_KEY + ")");
}else {
permission = permissionRepository.findByStatusAndNameAndRoleName(true, PERMISSION_NEEDED, AppRolesListEnum.ROLE_ADMIN.toString());
}
Merchant merchantToUpdate = merchantRepository.findById(merchantId)
.orElseThrow(() -> new ResourceNotFoundException("Merchant not found on :: " + merchantId));
Merchant updatedMerchant;
DAOUser user = userRepository.findById(userId)
.orElseThrow(() -> new ResourceNotFoundException("User not found on :: " + userId));
if(!user.getRole().equalsIgnoreCase(AppRolesListEnum.ROLE_ADMIN.toString())) {
throw new RoleNotMatchException(user.getUsername() + " does not have " + AppRolesListEnum.ROLE_ADMIN.toString() + " role");
}else if(!permission.getStatus()) {
throw new PermissionNotMatchException("Permission not enabled (" + PERMISSION_NEEDED + ")");
}else {
merchantToUpdate.setStatus(true);
merchantToUpdate.setUpdatedAt(new Date());
merchantToUpdate.setUpdatedBy(user.getUsername());
updatedMerchant = merchantRepository.save(merchantToUpdate);
}
return ResponseEntity.ok(updatedMerchant);
}
/**
* Disapprove merchant
*
* @param id
* @param userId
* @return the response entity
* @throws ResourceNotFoundException the resource not found exception
* @throws PermissionNotMatchException
* @throws RoleNotMatchException
*/
@PutMapping("/disapproveMerchant/{id}/{userId}")
public ResponseEntity<Merchant> disapproveMerchant(@PathVariable(value = "id") Long merchantId, @PathVariable(value = "userId") Long userId)
throws ResourceNotFoundException, PermissionNotMatchException, RoleNotMatchException {
final String PERMISSION_KEY = "CAN_DISAPPROVE_PERMISSIONS";
final String PERMISSION_NEEDED = PermissionsHashMap.getValueByKey(PERMISSION_KEY);
Permission permission;
if(PERMISSION_NEEDED == null){
throw new PermissionNotMatchException("Permission key is invalid not does not have permission (" + PERMISSION_KEY + ")");
}else {
permission = permissionRepository.findByStatusAndNameAndRoleName(true, PERMISSION_NEEDED, AppRolesListEnum.ROLE_ADMIN.toString());
}
Merchant merchantToUpdate = merchantRepository.findById(merchantId)
.orElseThrow(() -> new ResourceNotFoundException("Merchant not found on :: " + merchantId));
Merchant updatedMerchant;
DAOUser user = userRepository.findById(userId)
.orElseThrow(() -> new ResourceNotFoundException("User not found on :: " + userId));
if(!user.getRole().equalsIgnoreCase(AppRolesListEnum.ROLE_ADMIN.toString())) {
throw new RoleNotMatchException(user.getUsername() + " does not have " + AppRolesListEnum.ROLE_ADMIN.toString() + " role");
}else if(!permission.getStatus()) {
throw new PermissionNotMatchException("Permission not enabled (" + PERMISSION_NEEDED + ")");
}else {
merchantToUpdate.setStatus(false);
merchantToUpdate.setUpdatedAt(new Date());
merchantToUpdate.setUpdatedBy(user.getUsername());
updatedMerchant = merchantRepository.save(merchantToUpdate);
}
return ResponseEntity.ok(updatedMerchant);
}
}
| 36.948498 | 141 | 0.766756 |
f0fa15b7fffb42c1ef8de5aaaf7a972a4ab0e944 | 2,491 | package jr.dungeon.wishes;
import jr.dungeon.Dungeon;
import jr.dungeon.Level;
import jr.dungeon.entities.player.Player;
import jr.dungeon.tiles.Tile;
import jr.dungeon.tiles.TileFlag;
import jr.dungeon.tiles.TileType;
import jr.utils.Point;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicReference;
public class WishExplore implements Wish {
@Override
public void grant(Dungeon d, Player p, String... a) {
boolean isGod = p.isGodmode();
p.setGodmode(true);
Level firstLevel = d.getLevel();
Point firstLevelSpawn = p.getPosition();
AtomicReference<Tile> firstSewerDown = new AtomicReference<>();
for (int i = 0; i < 7; i++) {
if (firstSewerDown.get() == null) {
Arrays.stream(p.getLevel().tileStore.getTiles())
.filter(t -> t.getType() == TileType.TILE_LADDER_DOWN)
.findFirst().ifPresent(firstSewerDown::set);
}
Arrays.stream(p.getLevel().tileStore.getTiles())
.filter(t -> t.getType() == TileType.TILE_ROOM_STAIRS_DOWN)
.findFirst().ifPresent(t -> {
p.setPosition(t.position);
p.defaultVisitors.climbDown();
d.greenYou("traverse to [CYAN]%s[].", d.getLevel());
});
}
if (firstSewerDown.get() != null) {
Tile fsdt = firstSewerDown.get();
d.changeLevel(fsdt.getLevel(), fsdt.position);
Arrays.stream(p.getLevel().tileStore.getTiles())
.filter(t -> t.getType() == TileType.TILE_LADDER_DOWN)
.findFirst().ifPresent(t -> {
p.setPosition(t.position);
p.defaultVisitors.climbDown();
d.greenYou("traverse to [CYAN]%s[].", d.getLevel());
});
for (int i = 0; i < 7; i++) {
Arrays.stream(p.getLevel().tileStore.getTiles())
.filter(t -> (t.getType().getFlags() & TileFlag.DOWN) == TileFlag.DOWN)
.findFirst().ifPresent(t -> {
p.setPosition(t.position);
p.defaultVisitors.climbDown();
d.greenYou("traverse to [CYAN]%s[].", d.getLevel());
});
}
}
d.changeLevel(firstLevel, firstLevelSpawn);
p.setGodmode(isGod);
}
}
| 36.101449 | 91 | 0.529506 |
c7113ef56facd95fd245f34ae59c7492f9f70ce2 | 3,550 | package com.clock.systemui.activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import com.clock.systemui.R;
import com.clock.systemui.activity.bs.BottomSheetsDemoActivity;
import com.clock.systemui.activity.bt.BarTabDemoActivity;
import com.clock.systemui.activity.cardview.CardViewDemoActivity;
import com.clock.systemui.activity.collapsing.CollapsingDemoActivity;
import com.clock.systemui.activity.listview.ListViewDemoActivity;
import com.clock.systemui.activity.navigation.NavigationDemoActivity;
import com.clock.systemui.activity.recycler.RecyclerDemoActivity;
import com.clock.systemui.activity.snackbar.SnackBarDemoActivity;
import com.clock.systemui.activity.toolbar.ToolDemoActivity;
import com.clock.systemui.activity.translucent.TranslucentDemoActivity;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn_translucent_demo).setOnClickListener(this);
findViewById(R.id.btn_toolbar_demo).setOnClickListener(this);
findViewById(R.id.btn_navigation_demo).setOnClickListener(this);
findViewById(R.id.btn_listview_demo).setOnClickListener(this);
findViewById(R.id.btn_recycler_demo).setOnClickListener(this);
findViewById(R.id.btn_card_view).setOnClickListener(this);
findViewById(R.id.btn_snack_bar).setOnClickListener(this);
findViewById(R.id.btn_bar_tab).setOnClickListener(this);
findViewById(R.id.btn_collapsing).setOnClickListener(this);
findViewById(R.id.btn_bottom_sheets).setOnClickListener(this);
}
@Override
public void onClick(View v) {
int viewId = v.getId();
if (viewId == R.id.btn_translucent_demo) {
Intent intent = new Intent(this, TranslucentDemoActivity.class);
startActivity(intent);
} else if (viewId == R.id.btn_toolbar_demo) {
Intent intent = new Intent(this, ToolDemoActivity.class);
startActivity(intent);
} else if (viewId == R.id.btn_navigation_demo) {
Intent intent = new Intent(this, NavigationDemoActivity.class);
startActivity(intent);
} else if (viewId == R.id.btn_listview_demo) {
Intent intent = new Intent(this, ListViewDemoActivity.class);
startActivity(intent);
} else if (viewId == R.id.btn_recycler_demo) {
Intent intent = new Intent(this, RecyclerDemoActivity.class);
startActivity(intent);
} else if (viewId == R.id.btn_card_view) {
Intent intent = new Intent(this, CardViewDemoActivity.class);
startActivity(intent);
} else if (viewId == R.id.btn_snack_bar) {
Intent intent = new Intent(this, SnackBarDemoActivity.class);
startActivity(intent);
} else if (viewId == R.id.btn_bar_tab) {
Intent intent = new Intent(this, BarTabDemoActivity.class);
startActivity(intent);
} else if (viewId == R.id.btn_collapsing) {
Intent intent = new Intent(this, CollapsingDemoActivity.class);
startActivity(intent);
} else if (viewId == R.id.btn_bottom_sheets) {
Intent intent = new Intent(this, BottomSheetsDemoActivity.class);
startActivity(intent);
}
}
}
| 40.804598 | 85 | 0.706197 |
b6e048d6f5388ce5f063fce680673668c3935644 | 2,767 | package de.nevini.modules.util.unicode.obfuscate;
import org.apache.commons.lang3.ObjectUtils;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class Obfuscator {
private static final Map<Character, char[]> map;
private static final Map<Character, Character> pam;
static {
map = new HashMap<>();
// see: https://github.com/etanzapinsky/unicode-obfuscation/blob/master/main.py
map.put('a', new char[]{'ª', '∀', '⟑', 'α', '@'});
map.put('b', new char[]{'฿', 'В', 'ь', 'β'});
map.put('c', new char[]{'©', '∁', '⊂', '☪', '¢'});
map.put('d', new char[]{'∂', '⫒', 'ძ'});
map.put('e', new char[]{'ℇ', '℮', '∃', '∈', '∑', '⋿', '€', 'ϱ'});
map.put('f', new char[]{'⨍', '⨗', '⫭', '៛', 'ϝ'});
map.put('g', new char[]{'₲', 'ց', 'Ԍ'});
map.put('h', new char[]{'ℏ', '⫲', '⫳', '₶'});
map.put('i', new char[]{'ℹ', '⫯', 'ι', 'ї'});
map.put('j', new char[]{'⌡', 'ϳ', 'ј'});
map.put('k', new char[]{'₭', 'κ', 'Ϗ'});
map.put('l', new char[]{'∟', '₤', 'լ'});
map.put('m', new char[]{'≞', '⋔', '⨇', '⩋', '⫙', '₥'});
map.put('n', new char[]{'∏', '∩', 'η'});
map.put('o', new char[]{'º', '⦿', '☉', 'ο', 'օ'});
map.put('p', new char[]{'℗', '♇', '₱', 'ρ', 'բ'});
map.put('q', new char[]{'ԛ', 'զ', 'գ', '৭', 'ҩ'});
map.put('r', new char[]{'®', 'Я', 'Ւ'});
map.put('s', new char[]{'∫', '$', 'ѕ'});
map.put('t', new char[]{'⊺', '⟙', '✝', '♱', '♰', 'τ', 'է'});
map.put('u', new char[]{'µ', '∪', '∐', '⨃'});
map.put('v', new char[]{'∨', '√', '⩔'});
map.put('w', new char[]{'⨈', '⩊', '⫝', '₩', 'ω'});
map.put('x', new char[]{'×', '⨯', '☓', '✗'});
map.put('y', new char[]{'¥', '⑂', 'Ⴤ', 'ӱ'});
map.put('z', new char[]{'Ꙁ', 'Ⴠ', 'Հ'});
// reverse map
pam = new HashMap<>();
map.forEach((k, v) -> {
for (char c : v) {
pam.put(c, k);
}
});
}
public static String obfuscate(String input) {
Random rng = new Random();
StringBuilder output = new StringBuilder(input.length());
input.chars().map(c -> {
char[] choice = map.get((char) Character.toLowerCase(c));
if (choice == null) return c;
return choice[rng.nextInt(choice.length)];
}).forEach(c -> output.append((char) c));
return output.toString();
}
public static String deobfuscate(String input) {
StringBuilder output = new StringBuilder(input.length());
input.chars().forEach(c -> output.append(ObjectUtils.defaultIfNull(pam.get((char) c), (char) c)));
return output.toString();
}
}
| 39.528571 | 106 | 0.437297 |
8edbd4c6b8793803e9b906407b10ffad254a4149 | 46,553 | package net.minecraft.server;
import com.google.common.collect.Lists;
import java.util.Arrays;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
public class EntityFox extends EntityAnimal {
private static final DataWatcherObject<Integer> bo = DataWatcher.a(EntityFox.class, DataWatcherRegistry.b);
private static final DataWatcherObject<Byte> bp = DataWatcher.a(EntityFox.class, DataWatcherRegistry.a);
public static final DataWatcherObject<Optional<UUID>> FIRST_TRUSTED_PLAYER = DataWatcher.a(EntityFox.class, DataWatcherRegistry.o);
public static final DataWatcherObject<Optional<UUID>> SECOND_TRUSTED_PLAYER = DataWatcher.a(EntityFox.class, DataWatcherRegistry.o);
private static final Predicate<EntityItem> bs = (entityitem) -> {
return !entityitem.p() && entityitem.isAlive();
};
private static final Predicate<Entity> bt = (entity) -> {
if (!(entity instanceof EntityLiving)) {
return false;
} else {
EntityLiving entityliving = (EntityLiving) entity;
return entityliving.da() != null && entityliving.db() < entityliving.ticksLived + 600;
}
};
private static final Predicate<Entity> bu = (entity) -> {
return entity instanceof EntityChicken || entity instanceof EntityRabbit;
};
private static final Predicate<Entity> bv = (entity) -> {
return !entity.bw() && IEntitySelector.e.test(entity);
};
private PathfinderGoal bw;
private PathfinderGoal bx;
private PathfinderGoal by;
private float bz;
private float bA;
private float bB;
private float bC;
private int bD;
public EntityFox(EntityTypes<? extends EntityFox> entitytypes, World world) {
super(entitytypes, world);
this.lookController = new EntityFox.k();
this.moveController = new EntityFox.m();
this.a(PathType.DANGER_OTHER, 0.0F);
this.a(PathType.DAMAGE_OTHER, 0.0F);
this.setCanPickupLoot(true);
}
@Override
protected void initDatawatcher() {
super.initDatawatcher();
this.datawatcher.register(EntityFox.FIRST_TRUSTED_PLAYER, Optional.empty());
this.datawatcher.register(EntityFox.SECOND_TRUSTED_PLAYER, Optional.empty());
this.datawatcher.register(EntityFox.bo, 0);
this.datawatcher.register(EntityFox.bp, (byte) 0);
}
@Override
protected void initPathfinder() {
this.bw = new PathfinderGoalNearestAttackableTarget<>(this, EntityAnimal.class, 10, false, false, (entityliving) -> {
return entityliving instanceof EntityChicken || entityliving instanceof EntityRabbit;
});
this.bx = new PathfinderGoalNearestAttackableTarget<>(this, EntityTurtle.class, 10, false, false, EntityTurtle.bo);
this.by = new PathfinderGoalNearestAttackableTarget<>(this, EntityFish.class, 20, false, false, (entityliving) -> {
return entityliving instanceof EntityFishSchool;
});
this.goalSelector.a(0, new EntityFox.g());
this.goalSelector.a(1, new EntityFox.b());
this.goalSelector.a(2, new EntityFox.n(2.2D));
this.goalSelector.a(3, new EntityFox.e(1.0D));
this.goalSelector.a(4, new PathfinderGoalAvoidTarget<>(this, EntityHuman.class, 16.0F, 1.6D, 1.4D, (entityliving) -> {
return EntityFox.bv.test(entityliving) && !this.c(entityliving.getUniqueID()) && !this.fb();
}));
this.goalSelector.a(4, new PathfinderGoalAvoidTarget<>(this, EntityWolf.class, 8.0F, 1.6D, 1.4D, (entityliving) -> {
return !((EntityWolf) entityliving).isTamed() && !this.fb();
}));
this.goalSelector.a(4, new PathfinderGoalAvoidTarget<>(this, EntityPolarBear.class, 8.0F, 1.6D, 1.4D, (entityliving) -> {
return !this.fb();
}));
this.goalSelector.a(5, new EntityFox.u());
this.goalSelector.a(6, new EntityFox.o());
this.goalSelector.a(6, new EntityFox.s(1.25D));
this.goalSelector.a(7, new EntityFox.l(1.2000000476837158D, true));
this.goalSelector.a(7, new EntityFox.t());
this.goalSelector.a(8, new EntityFox.h(this, 1.25D));
this.goalSelector.a(9, new EntityFox.q(32, 200));
this.goalSelector.a(10, new EntityFox.f(1.2000000476837158D, 12, 2));
this.goalSelector.a(10, new PathfinderGoalLeapAtTarget(this, 0.4F));
this.goalSelector.a(11, new PathfinderGoalRandomStrollLand(this, 1.0D));
this.goalSelector.a(11, new EntityFox.p());
this.goalSelector.a(12, new EntityFox.j(this, EntityHuman.class, 24.0F));
this.goalSelector.a(13, new EntityFox.r());
this.targetSelector.a(3, new EntityFox.a(EntityLiving.class, false, false, (entityliving) -> {
return EntityFox.bt.test(entityliving) && !this.c(entityliving.getUniqueID());
}));
}
@Override
public SoundEffect d(ItemStack itemstack) {
return SoundEffects.ENTITY_FOX_EAT;
}
@Override
public void movementTick() {
if (!this.world.isClientSide && this.isAlive() && this.doAITick()) {
++this.bD;
ItemStack itemstack = this.getEquipment(EnumItemSlot.MAINHAND);
if (this.l(itemstack)) {
if (this.bD > 600) {
ItemStack itemstack1 = itemstack.a(this.world, (EntityLiving) this);
if (!itemstack1.isEmpty()) {
this.setSlot(EnumItemSlot.MAINHAND, itemstack1);
}
this.bD = 0;
} else if (this.bD > 560 && this.random.nextFloat() < 0.1F) {
this.playSound(this.d(itemstack), 1.0F, 1.0F);
this.world.broadcastEntityEffect(this, (byte) 45);
}
}
EntityLiving entityliving = this.getGoalTarget();
if (entityliving == null || !entityliving.isAlive()) {
this.setCrouching(false);
this.w(false);
}
}
if (this.isSleeping() || this.isFrozen()) {
this.jumping = false;
this.aR = 0.0F;
this.aT = 0.0F;
}
super.movementTick();
if (this.fb() && this.random.nextFloat() < 0.05F) {
this.playSound(SoundEffects.ENTITY_FOX_AGGRO, 1.0F, 1.0F);
}
}
@Override
protected boolean isFrozen() {
return this.dk();
}
private boolean l(ItemStack itemstack) {
return itemstack.getItem().isFood() && this.getGoalTarget() == null && this.onGround && !this.isSleeping();
}
@Override
protected void a(DifficultyDamageScaler difficultydamagescaler) {
if (this.random.nextFloat() < 0.2F) {
float f = this.random.nextFloat();
ItemStack itemstack;
if (f < 0.05F) {
itemstack = new ItemStack(Items.EMERALD);
} else if (f < 0.2F) {
itemstack = new ItemStack(Items.EGG);
} else if (f < 0.4F) {
itemstack = this.random.nextBoolean() ? new ItemStack(Items.RABBIT_FOOT) : new ItemStack(Items.RABBIT_HIDE);
} else if (f < 0.6F) {
itemstack = new ItemStack(Items.WHEAT);
} else if (f < 0.8F) {
itemstack = new ItemStack(Items.LEATHER);
} else {
itemstack = new ItemStack(Items.FEATHER);
}
this.setSlot(EnumItemSlot.MAINHAND, itemstack);
}
}
public static AttributeProvider.Builder eK() {
return EntityInsentient.p().a(GenericAttributes.MOVEMENT_SPEED, 0.30000001192092896D).a(GenericAttributes.MAX_HEALTH, 10.0D).a(GenericAttributes.FOLLOW_RANGE, 32.0D).a(GenericAttributes.ATTACK_DAMAGE, 2.0D);
}
@Override
public EntityFox createChild(WorldServer worldserver, EntityAgeable entityageable) {
EntityFox entityfox = (EntityFox) EntityTypes.FOX.a((World) worldserver);
entityfox.setFoxType(this.random.nextBoolean() ? this.getFoxType() : ((EntityFox) entityageable).getFoxType());
return entityfox;
}
@Nullable
@Override
public GroupDataEntity prepare(WorldAccess worldaccess, DifficultyDamageScaler difficultydamagescaler, EnumMobSpawn enummobspawn, @Nullable GroupDataEntity groupdataentity, @Nullable NBTTagCompound nbttagcompound) {
Optional<ResourceKey<BiomeBase>> optional = worldaccess.i(this.getChunkCoordinates());
EntityFox.Type entityfox_type = EntityFox.Type.a(optional);
boolean flag = false;
if (groupdataentity instanceof EntityFox.i) {
entityfox_type = ((EntityFox.i) groupdataentity).a;
if (((EntityFox.i) groupdataentity).a() >= 2) {
flag = true;
}
} else {
groupdataentity = new EntityFox.i(entityfox_type);
}
this.setFoxType(entityfox_type);
if (flag) {
this.setAgeRaw(-24000);
}
if (worldaccess instanceof WorldServer) {
this.initializePathFinderGoals();
}
this.a(difficultydamagescaler);
return super.prepare(worldaccess, difficultydamagescaler, enummobspawn, (GroupDataEntity) groupdataentity, nbttagcompound);
}
private void initializePathFinderGoals() {
if (this.getFoxType() == EntityFox.Type.RED) {
this.targetSelector.a(4, this.bw);
this.targetSelector.a(4, this.bx);
this.targetSelector.a(6, this.by);
} else {
this.targetSelector.a(4, this.by);
this.targetSelector.a(6, this.bw);
this.targetSelector.a(6, this.bx);
}
}
@Override
protected void a(EntityHuman entityhuman, ItemStack itemstack) {
if (this.k(itemstack)) {
this.playSound(this.d(itemstack), 1.0F, 1.0F);
}
super.a(entityhuman, itemstack);
}
@Override
protected float b(EntityPose entitypose, EntitySize entitysize) {
return this.isBaby() ? entitysize.height * 0.85F : 0.4F;
}
public EntityFox.Type getFoxType() {
return EntityFox.Type.a((Integer) this.datawatcher.get(EntityFox.bo));
}
public void setFoxType(EntityFox.Type entityfox_type) {
this.datawatcher.set(EntityFox.bo, entityfox_type.b());
}
private List<UUID> fa() {
List<UUID> list = Lists.newArrayList();
list.add(((Optional) this.datawatcher.get(EntityFox.FIRST_TRUSTED_PLAYER)).orElse((Object) null));
list.add(((Optional) this.datawatcher.get(EntityFox.SECOND_TRUSTED_PLAYER)).orElse((Object) null));
return list;
}
private void b(@Nullable UUID uuid) {
if (((Optional) this.datawatcher.get(EntityFox.FIRST_TRUSTED_PLAYER)).isPresent()) {
this.datawatcher.set(EntityFox.SECOND_TRUSTED_PLAYER, Optional.ofNullable(uuid));
} else {
this.datawatcher.set(EntityFox.FIRST_TRUSTED_PLAYER, Optional.ofNullable(uuid));
}
}
@Override
public void saveData(NBTTagCompound nbttagcompound) {
super.saveData(nbttagcompound);
List<UUID> list = this.fa();
NBTTagList nbttaglist = new NBTTagList();
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
UUID uuid = (UUID) iterator.next();
if (uuid != null) {
nbttaglist.add(GameProfileSerializer.a(uuid));
}
}
nbttagcompound.set("Trusted", nbttaglist);
nbttagcompound.setBoolean("Sleeping", this.isSleeping());
nbttagcompound.setString("Type", this.getFoxType().a());
nbttagcompound.setBoolean("Sitting", this.isSitting());
nbttagcompound.setBoolean("Crouching", this.isCrouching());
}
@Override
public void loadData(NBTTagCompound nbttagcompound) {
super.loadData(nbttagcompound);
NBTTagList nbttaglist = nbttagcompound.getList("Trusted", 11);
for (int i = 0; i < nbttaglist.size(); ++i) {
this.b(GameProfileSerializer.a(nbttaglist.get(i)));
}
this.setSleeping(nbttagcompound.getBoolean("Sleeping"));
this.setFoxType(EntityFox.Type.a(nbttagcompound.getString("Type")));
this.setSitting(nbttagcompound.getBoolean("Sitting"));
this.setCrouching(nbttagcompound.getBoolean("Crouching"));
if (this.world instanceof WorldServer) {
this.initializePathFinderGoals();
}
}
public boolean isSitting() {
return this.t(1);
}
public void setSitting(boolean flag) {
this.d(1, flag);
}
public boolean eN() {
return this.t(64);
}
private void x(boolean flag) {
this.d(64, flag);
}
private boolean fb() {
return this.t(128);
}
private void y(boolean flag) {
this.d(128, flag);
}
@Override
public boolean isSleeping() {
return this.t(32);
}
public void setSleeping(boolean flag) {
this.d(32, flag);
}
private void d(int i, boolean flag) {
if (flag) {
this.datawatcher.set(EntityFox.bp, (byte) ((Byte) this.datawatcher.get(EntityFox.bp) | i));
} else {
this.datawatcher.set(EntityFox.bp, (byte) ((Byte) this.datawatcher.get(EntityFox.bp) & ~i));
}
}
private boolean t(int i) {
return ((Byte) this.datawatcher.get(EntityFox.bp) & i) != 0;
}
@Override
public boolean e(ItemStack itemstack) {
EnumItemSlot enumitemslot = EntityInsentient.j(itemstack);
return !this.getEquipment(enumitemslot).isEmpty() ? false : enumitemslot == EnumItemSlot.MAINHAND && super.e(itemstack);
}
@Override
public boolean canPickup(ItemStack itemstack) {
Item item = itemstack.getItem();
ItemStack itemstack1 = this.getEquipment(EnumItemSlot.MAINHAND);
return itemstack1.isEmpty() || this.bD > 0 && item.isFood() && !itemstack1.getItem().isFood();
}
private void m(ItemStack itemstack) {
if (!itemstack.isEmpty() && !this.world.isClientSide) {
EntityItem entityitem = new EntityItem(this.world, this.locX() + this.getLookDirection().x, this.locY() + 1.0D, this.locZ() + this.getLookDirection().z, itemstack);
entityitem.setPickupDelay(40);
entityitem.setThrower(this.getUniqueID());
this.playSound(SoundEffects.ENTITY_FOX_SPIT, 1.0F, 1.0F);
this.world.addEntity(entityitem);
}
}
private void n(ItemStack itemstack) {
EntityItem entityitem = new EntityItem(this.world, this.locX(), this.locY(), this.locZ(), itemstack);
this.world.addEntity(entityitem);
}
@Override
protected void b(EntityItem entityitem) {
ItemStack itemstack = entityitem.getItemStack();
if (this.canPickup(itemstack)) {
int i = itemstack.getCount();
if (i > 1) {
this.n(itemstack.cloneAndSubtract(i - 1));
}
this.m(this.getEquipment(EnumItemSlot.MAINHAND));
this.a(entityitem);
this.setSlot(EnumItemSlot.MAINHAND, itemstack.cloneAndSubtract(1));
this.dropChanceHand[EnumItemSlot.MAINHAND.b()] = 2.0F;
this.receive(entityitem, itemstack.getCount());
entityitem.die();
this.bD = 0;
}
}
@Override
public void tick() {
super.tick();
if (this.doAITick()) {
boolean flag = this.isInWater();
if (flag || this.getGoalTarget() != null || this.world.V()) {
this.fc();
}
if (flag || this.isSleeping()) {
this.setSitting(false);
}
if (this.eN() && this.world.random.nextFloat() < 0.2F) {
BlockPosition blockposition = this.getChunkCoordinates();
IBlockData iblockdata = this.world.getType(blockposition);
this.world.triggerEffect(2001, blockposition, Block.getCombinedId(iblockdata));
}
}
this.bA = this.bz;
if (this.eW()) {
this.bz += (1.0F - this.bz) * 0.4F;
} else {
this.bz += (0.0F - this.bz) * 0.4F;
}
this.bC = this.bB;
if (this.isCrouching()) {
this.bB += 0.2F;
if (this.bB > 3.0F) {
this.bB = 3.0F;
}
} else {
this.bB = 0.0F;
}
}
@Override
public boolean k(ItemStack itemstack) {
return itemstack.getItem() == Items.SWEET_BERRIES;
}
@Override
protected void a(EntityHuman entityhuman, EntityInsentient entityinsentient) {
((EntityFox) entityinsentient).b(entityhuman.getUniqueID());
}
public boolean eO() {
return this.t(16);
}
public void u(boolean flag) {
this.d(16, flag);
}
public boolean eV() {
return this.bB == 3.0F;
}
public void setCrouching(boolean flag) {
this.d(4, flag);
}
public boolean isCrouching() {
return this.t(4);
}
public void w(boolean flag) {
this.d(8, flag);
}
public boolean eW() {
return this.t(8);
}
@Override
public void setGoalTarget(@Nullable EntityLiving entityliving) {
if (this.fb() && entityliving == null) {
this.y(false);
}
super.setGoalTarget(entityliving);
}
@Override
protected int e(float f, float f1) {
return MathHelper.f((f - 5.0F) * f1);
}
private void fc() {
this.setSleeping(false);
}
private void fd() {
this.w(false);
this.setCrouching(false);
this.setSitting(false);
this.setSleeping(false);
this.y(false);
this.x(false);
}
private boolean fe() {
return !this.isSleeping() && !this.isSitting() && !this.eN();
}
@Override
public void F() {
SoundEffect soundeffect = this.getSoundAmbient();
if (soundeffect == SoundEffects.ENTITY_FOX_SCREECH) {
this.playSound(soundeffect, 2.0F, this.dG());
} else {
super.F();
}
}
@Nullable
@Override
protected SoundEffect getSoundAmbient() {
if (this.isSleeping()) {
return SoundEffects.ENTITY_FOX_SLEEP;
} else {
if (!this.world.isDay() && this.random.nextFloat() < 0.1F) {
List<EntityHuman> list = this.world.a(EntityHuman.class, this.getBoundingBox().grow(16.0D, 16.0D, 16.0D), IEntitySelector.g);
if (list.isEmpty()) {
return SoundEffects.ENTITY_FOX_SCREECH;
}
}
return SoundEffects.ENTITY_FOX_AMBIENT;
}
}
@Nullable
@Override
protected SoundEffect getSoundHurt(DamageSource damagesource) {
return SoundEffects.ENTITY_FOX_HURT;
}
@Nullable
@Override
protected SoundEffect getSoundDeath() {
return SoundEffects.ENTITY_FOX_DEATH;
}
private boolean c(UUID uuid) {
return this.fa().contains(uuid);
}
@Override
protected void d(DamageSource damagesource) {
ItemStack itemstack = this.getEquipment(EnumItemSlot.MAINHAND);
if (!itemstack.isEmpty()) {
this.a(itemstack);
this.setSlot(EnumItemSlot.MAINHAND, ItemStack.b);
}
super.d(damagesource);
}
public static boolean a(EntityFox entityfox, EntityLiving entityliving) {
double d0 = entityliving.locZ() - entityfox.locZ();
double d1 = entityliving.locX() - entityfox.locX();
double d2 = d0 / d1;
boolean flag = true;
for (int i = 0; i < 6; ++i) {
double d3 = d2 == 0.0D ? 0.0D : d0 * (double) ((float) i / 6.0F);
double d4 = d2 == 0.0D ? d1 * (double) ((float) i / 6.0F) : d3 / d2;
for (int j = 1; j < 4; ++j) {
if (!entityfox.world.getType(new BlockPosition(entityfox.locX() + d4, entityfox.locY() + (double) j, entityfox.locZ() + d3)).getMaterial().isReplaceable()) {
return false;
}
}
}
return true;
}
class j extends PathfinderGoalLookAtPlayer {
public j(EntityInsentient entityinsentient, Class oclass, float f) {
super(entityinsentient, oclass, f);
}
@Override
public boolean a() {
return super.a() && !EntityFox.this.eN() && !EntityFox.this.eW();
}
@Override
public boolean b() {
return super.b() && !EntityFox.this.eN() && !EntityFox.this.eW();
}
}
class h extends PathfinderGoalFollowParent {
private final EntityFox b;
public h(EntityFox entityfox, double d0) {
super(entityfox, d0);
this.b = entityfox;
}
@Override
public boolean a() {
return !this.b.fb() && super.a();
}
@Override
public boolean b() {
return !this.b.fb() && super.b();
}
@Override
public void c() {
this.b.fd();
super.c();
}
}
public class k extends ControllerLook {
public k() {
super(EntityFox.this);
}
@Override
public void a() {
if (!EntityFox.this.isSleeping()) {
super.a();
}
}
@Override
protected boolean b() {
return !EntityFox.this.eO() && !EntityFox.this.isCrouching() && !EntityFox.this.eW() & !EntityFox.this.eN();
}
}
public class o extends PathfinderGoalWaterJumpAbstract {
public o() {}
@Override
public boolean a() {
if (!EntityFox.this.eV()) {
return false;
} else {
EntityLiving entityliving = EntityFox.this.getGoalTarget();
if (entityliving != null && entityliving.isAlive()) {
if (entityliving.getAdjustedDirection() != entityliving.getDirection()) {
return false;
} else {
boolean flag = EntityFox.a((EntityFox) EntityFox.this, entityliving);
if (!flag) {
EntityFox.this.getNavigation().a((Entity) entityliving, 0);
EntityFox.this.setCrouching(false);
EntityFox.this.w(false);
}
return flag;
}
} else {
return false;
}
}
}
@Override
public boolean b() {
EntityLiving entityliving = EntityFox.this.getGoalTarget();
if (entityliving != null && entityliving.isAlive()) {
double d0 = EntityFox.this.getMot().y;
return (d0 * d0 >= 0.05000000074505806D || Math.abs(EntityFox.this.pitch) >= 15.0F || !EntityFox.this.onGround) && !EntityFox.this.eN();
} else {
return false;
}
}
@Override
public boolean C_() {
return false;
}
@Override
public void c() {
EntityFox.this.setJumping(true);
EntityFox.this.u(true);
EntityFox.this.w(false);
EntityLiving entityliving = EntityFox.this.getGoalTarget();
EntityFox.this.getControllerLook().a(entityliving, 60.0F, 30.0F);
Vec3D vec3d = (new Vec3D(entityliving.locX() - EntityFox.this.locX(), entityliving.locY() - EntityFox.this.locY(), entityliving.locZ() - EntityFox.this.locZ())).d();
EntityFox.this.setMot(EntityFox.this.getMot().add(vec3d.x * 0.8D, 0.9D, vec3d.z * 0.8D));
EntityFox.this.getNavigation().o();
}
@Override
public void d() {
EntityFox.this.setCrouching(false);
EntityFox.this.bB = 0.0F;
EntityFox.this.bC = 0.0F;
EntityFox.this.w(false);
EntityFox.this.u(false);
}
@Override
public void e() {
EntityLiving entityliving = EntityFox.this.getGoalTarget();
if (entityliving != null) {
EntityFox.this.getControllerLook().a(entityliving, 60.0F, 30.0F);
}
if (!EntityFox.this.eN()) {
Vec3D vec3d = EntityFox.this.getMot();
if (vec3d.y * vec3d.y < 0.029999999329447746D && EntityFox.this.pitch != 0.0F) {
EntityFox.this.pitch = MathHelper.j(EntityFox.this.pitch, 0.0F, 0.2F);
} else {
double d0 = Math.sqrt(Entity.c(vec3d));
double d1 = Math.signum(-vec3d.y) * Math.acos(d0 / vec3d.f()) * 57.2957763671875D;
EntityFox.this.pitch = (float) d1;
}
}
if (entityliving != null && EntityFox.this.g((Entity) entityliving) <= 2.0F) {
EntityFox.this.attackEntity(entityliving);
} else if (EntityFox.this.pitch > 0.0F && EntityFox.this.onGround && (float) EntityFox.this.getMot().y != 0.0F && EntityFox.this.world.getType(EntityFox.this.getChunkCoordinates()).a(Blocks.SNOW)) {
EntityFox.this.pitch = 60.0F;
EntityFox.this.setGoalTarget((EntityLiving) null);
EntityFox.this.x(true);
}
}
}
class g extends PathfinderGoalFloat {
public g() {
super(EntityFox.this);
}
@Override
public void c() {
super.c();
EntityFox.this.fd();
}
@Override
public boolean a() {
return EntityFox.this.isInWater() && EntityFox.this.b((Tag) TagsFluid.WATER) > 0.25D || EntityFox.this.aP();
}
}
class q extends PathfinderGoalNearestVillage {
public q(int i, int j) {
super(EntityFox.this, j);
}
@Override
public void c() {
EntityFox.this.fd();
super.c();
}
@Override
public boolean a() {
return super.a() && this.g();
}
@Override
public boolean b() {
return super.b() && this.g();
}
private boolean g() {
return !EntityFox.this.isSleeping() && !EntityFox.this.isSitting() && !EntityFox.this.fb() && EntityFox.this.getGoalTarget() == null;
}
}
class n extends PathfinderGoalPanic {
public n(double d0) {
super(EntityFox.this, d0);
}
@Override
public boolean a() {
return !EntityFox.this.fb() && super.a();
}
}
class b extends PathfinderGoal {
int a;
public b() {
this.a(EnumSet.of(PathfinderGoal.Type.LOOK, PathfinderGoal.Type.JUMP, PathfinderGoal.Type.MOVE));
}
@Override
public boolean a() {
return EntityFox.this.eN();
}
@Override
public boolean b() {
return this.a() && this.a > 0;
}
@Override
public void c() {
this.a = 40;
}
@Override
public void d() {
EntityFox.this.x(false);
}
@Override
public void e() {
--this.a;
}
}
public static class i extends EntityAgeable.a {
public final EntityFox.Type a;
public i(EntityFox.Type entityfox_type) {
super(false);
this.a = entityfox_type;
}
}
public class f extends PathfinderGoalGotoTarget {
protected int g;
public f(double d0, int i, int j) {
super(EntityFox.this, d0, i, j);
}
@Override
public double h() {
return 2.0D;
}
@Override
public boolean k() {
return this.d % 100 == 0;
}
@Override
protected boolean a(IWorldReader iworldreader, BlockPosition blockposition) {
IBlockData iblockdata = iworldreader.getType(blockposition);
return iblockdata.a(Blocks.SWEET_BERRY_BUSH) && (Integer) iblockdata.get(BlockSweetBerryBush.a) >= 2;
}
@Override
public void e() {
if (this.l()) {
if (this.g >= 40) {
this.n();
} else {
++this.g;
}
} else if (!this.l() && EntityFox.this.random.nextFloat() < 0.05F) {
EntityFox.this.playSound(SoundEffects.ENTITY_FOX_SNIFF, 1.0F, 1.0F);
}
super.e();
}
protected void n() {
if (EntityFox.this.world.getGameRules().getBoolean(GameRules.MOB_GRIEFING)) {
IBlockData iblockdata = EntityFox.this.world.getType(this.e);
if (iblockdata.a(Blocks.SWEET_BERRY_BUSH)) {
int i = (Integer) iblockdata.get(BlockSweetBerryBush.a);
iblockdata.set(BlockSweetBerryBush.a, 1);
int j = 1 + EntityFox.this.world.random.nextInt(2) + (i == 3 ? 1 : 0);
ItemStack itemstack = EntityFox.this.getEquipment(EnumItemSlot.MAINHAND);
if (itemstack.isEmpty()) {
EntityFox.this.setSlot(EnumItemSlot.MAINHAND, new ItemStack(Items.SWEET_BERRIES));
--j;
}
if (j > 0) {
Block.a(EntityFox.this.world, this.e, new ItemStack(Items.SWEET_BERRIES, j));
}
EntityFox.this.playSound(SoundEffects.ITEM_SWEET_BERRIES_PICK_FROM_BUSH, 1.0F, 1.0F);
EntityFox.this.world.setTypeAndData(this.e, (IBlockData) iblockdata.set(BlockSweetBerryBush.a, 1), 2);
}
}
}
@Override
public boolean a() {
return !EntityFox.this.isSleeping() && super.a();
}
@Override
public void c() {
this.g = 0;
EntityFox.this.setSitting(false);
super.c();
}
}
class r extends EntityFox.d {
private double c;
private double d;
private int e;
private int f;
public r() {
super(null);
this.a(EnumSet.of(PathfinderGoal.Type.MOVE, PathfinderGoal.Type.LOOK));
}
@Override
public boolean a() {
return EntityFox.this.getLastDamager() == null && EntityFox.this.getRandom().nextFloat() < 0.02F && !EntityFox.this.isSleeping() && EntityFox.this.getGoalTarget() == null && EntityFox.this.getNavigation().m() && !this.h() && !EntityFox.this.eO() && !EntityFox.this.isCrouching();
}
@Override
public boolean b() {
return this.f > 0;
}
@Override
public void c() {
this.j();
this.f = 2 + EntityFox.this.getRandom().nextInt(3);
EntityFox.this.setSitting(true);
EntityFox.this.getNavigation().o();
}
@Override
public void d() {
EntityFox.this.setSitting(false);
}
@Override
public void e() {
--this.e;
if (this.e <= 0) {
--this.f;
this.j();
}
EntityFox.this.getControllerLook().a(EntityFox.this.locX() + this.c, EntityFox.this.getHeadY(), EntityFox.this.locZ() + this.d, (float) EntityFox.this.eo(), (float) EntityFox.this.O());
}
private void j() {
double d0 = 6.283185307179586D * EntityFox.this.getRandom().nextDouble();
this.c = Math.cos(d0);
this.d = Math.sin(d0);
this.e = 80 + EntityFox.this.getRandom().nextInt(20);
}
}
class t extends EntityFox.d {
private int c;
public t() {
super(null);
this.c = EntityFox.this.random.nextInt(140);
this.a(EnumSet.of(PathfinderGoal.Type.MOVE, PathfinderGoal.Type.LOOK, PathfinderGoal.Type.JUMP));
}
@Override
public boolean a() {
return EntityFox.this.aR == 0.0F && EntityFox.this.aS == 0.0F && EntityFox.this.aT == 0.0F ? this.j() || EntityFox.this.isSleeping() : false;
}
@Override
public boolean b() {
return this.j();
}
private boolean j() {
if (this.c > 0) {
--this.c;
return false;
} else {
return EntityFox.this.world.isDay() && this.g() && !this.h();
}
}
@Override
public void d() {
this.c = EntityFox.this.random.nextInt(140);
EntityFox.this.fd();
}
@Override
public void c() {
EntityFox.this.setSitting(false);
EntityFox.this.setCrouching(false);
EntityFox.this.w(false);
EntityFox.this.setJumping(false);
EntityFox.this.setSleeping(true);
EntityFox.this.getNavigation().o();
EntityFox.this.getControllerMove().a(EntityFox.this.locX(), EntityFox.this.locY(), EntityFox.this.locZ(), 0.0D);
}
}
abstract class d extends PathfinderGoal {
private final PathfinderTargetCondition b;
private d() {
this.b = (new PathfinderTargetCondition()).a(12.0D).c().a(EntityFox.this.new c());
}
protected boolean g() {
BlockPosition blockposition = new BlockPosition(EntityFox.this.locX(), EntityFox.this.getBoundingBox().maxY, EntityFox.this.locZ());
return !EntityFox.this.world.e(blockposition) && EntityFox.this.f(blockposition) >= 0.0F;
}
protected boolean h() {
return !EntityFox.this.world.a(EntityLiving.class, this.b, EntityFox.this, EntityFox.this.getBoundingBox().grow(12.0D, 6.0D, 12.0D)).isEmpty();
}
}
public class c implements Predicate<EntityLiving> {
public c() {}
public boolean test(EntityLiving entityliving) {
return entityliving instanceof EntityFox ? false : (!(entityliving instanceof EntityChicken) && !(entityliving instanceof EntityRabbit) && !(entityliving instanceof EntityMonster) ? (entityliving instanceof EntityTameableAnimal ? !((EntityTameableAnimal) entityliving).isTamed() : (entityliving instanceof EntityHuman && (entityliving.isSpectator() || ((EntityHuman) entityliving).isCreative()) ? false : (EntityFox.this.c(entityliving.getUniqueID()) ? false : !entityliving.isSleeping() && !entityliving.bw()))) : true);
}
}
class s extends PathfinderGoalFleeSun {
private int c = 100;
public s(double d0) {
super(EntityFox.this, d0);
}
@Override
public boolean a() {
if (!EntityFox.this.isSleeping() && this.a.getGoalTarget() == null) {
if (EntityFox.this.world.V()) {
return true;
} else if (this.c > 0) {
--this.c;
return false;
} else {
this.c = 100;
BlockPosition blockposition = this.a.getChunkCoordinates();
return EntityFox.this.world.isDay() && EntityFox.this.world.e(blockposition) && !((WorldServer) EntityFox.this.world).a_(blockposition) && this.g();
}
} else {
return false;
}
}
@Override
public void c() {
EntityFox.this.fd();
super.c();
}
}
class a extends PathfinderGoalNearestAttackableTarget<EntityLiving> {
@Nullable
private EntityLiving j;
private EntityLiving k;
private int l;
public a(Class oclass, boolean flag, boolean flag1, Predicate predicate) {
super(EntityFox.this, oclass, 10, flag, flag1, predicate);
}
@Override
public boolean a() {
if (this.b > 0 && this.e.getRandom().nextInt(this.b) != 0) {
return false;
} else {
Iterator iterator = EntityFox.this.fa().iterator();
while (iterator.hasNext()) {
UUID uuid = (UUID) iterator.next();
if (uuid != null && EntityFox.this.world instanceof WorldServer) {
Entity entity = ((WorldServer) EntityFox.this.world).getEntity(uuid);
if (entity instanceof EntityLiving) {
EntityLiving entityliving = (EntityLiving) entity;
this.k = entityliving;
this.j = entityliving.getLastDamager();
int i = entityliving.cZ();
return i != this.l && this.a(this.j, this.d);
}
}
}
return false;
}
}
@Override
public void c() {
this.a(this.j);
this.c = this.j;
if (this.k != null) {
this.l = this.k.cZ();
}
EntityFox.this.playSound(SoundEffects.ENTITY_FOX_AGGRO, 1.0F, 1.0F);
EntityFox.this.y(true);
EntityFox.this.fc();
super.c();
}
}
class e extends PathfinderGoalBreed {
public e(double d0) {
super(EntityFox.this, d0);
}
@Override
public void c() {
((EntityFox) this.animal).fd();
((EntityFox) this.partner).fd();
super.c();
}
@Override
protected void g() {
WorldServer worldserver = (WorldServer) this.b;
EntityFox entityfox = (EntityFox) this.animal.createChild(worldserver, this.partner);
if (entityfox != null) {
EntityPlayer entityplayer = this.animal.getBreedCause();
EntityPlayer entityplayer1 = this.partner.getBreedCause();
EntityPlayer entityplayer2 = entityplayer;
if (entityplayer != null) {
entityfox.b(entityplayer.getUniqueID());
} else {
entityplayer2 = entityplayer1;
}
if (entityplayer1 != null && entityplayer != entityplayer1) {
entityfox.b(entityplayer1.getUniqueID());
}
if (entityplayer2 != null) {
entityplayer2.a(StatisticList.ANIMALS_BRED);
CriterionTriggers.o.a(entityplayer2, this.animal, this.partner, (EntityAgeable) entityfox);
}
this.animal.setAgeRaw(6000);
this.partner.setAgeRaw(6000);
this.animal.resetLove();
this.partner.resetLove();
entityfox.setAgeRaw(-24000);
entityfox.setPositionRotation(this.animal.locX(), this.animal.locY(), this.animal.locZ(), 0.0F, 0.0F);
worldserver.addAllEntities(entityfox);
this.b.broadcastEntityEffect(this.animal, (byte) 18);
if (this.b.getGameRules().getBoolean(GameRules.DO_MOB_LOOT)) {
this.b.addEntity(new EntityExperienceOrb(this.b, this.animal.locX(), this.animal.locY(), this.animal.locZ(), this.animal.getRandom().nextInt(7) + 1));
}
}
}
}
class l extends PathfinderGoalMeleeAttack {
public l(double d0, boolean flag) {
super(EntityFox.this, d0, flag);
}
@Override
protected void a(EntityLiving entityliving, double d0) {
double d1 = this.a(entityliving);
if (d0 <= d1 && this.h()) {
this.g();
this.a.attackEntity(entityliving);
EntityFox.this.playSound(SoundEffects.ENTITY_FOX_BITE, 1.0F, 1.0F);
}
}
@Override
public void c() {
EntityFox.this.w(false);
super.c();
}
@Override
public boolean a() {
return !EntityFox.this.isSitting() && !EntityFox.this.isSleeping() && !EntityFox.this.isCrouching() && !EntityFox.this.eN() && super.a();
}
}
class u extends PathfinderGoal {
public u() {
this.a(EnumSet.of(PathfinderGoal.Type.MOVE, PathfinderGoal.Type.LOOK));
}
@Override
public boolean a() {
if (EntityFox.this.isSleeping()) {
return false;
} else {
EntityLiving entityliving = EntityFox.this.getGoalTarget();
return entityliving != null && entityliving.isAlive() && EntityFox.bu.test(entityliving) && EntityFox.this.h((Entity) entityliving) > 36.0D && !EntityFox.this.isCrouching() && !EntityFox.this.eW() && !EntityFox.this.jumping;
}
}
@Override
public void c() {
EntityFox.this.setSitting(false);
EntityFox.this.x(false);
}
@Override
public void d() {
EntityLiving entityliving = EntityFox.this.getGoalTarget();
if (entityliving != null && EntityFox.a((EntityFox) EntityFox.this, entityliving)) {
EntityFox.this.w(true);
EntityFox.this.setCrouching(true);
EntityFox.this.getNavigation().o();
EntityFox.this.getControllerLook().a(entityliving, (float) EntityFox.this.eo(), (float) EntityFox.this.O());
} else {
EntityFox.this.w(false);
EntityFox.this.setCrouching(false);
}
}
@Override
public void e() {
EntityLiving entityliving = EntityFox.this.getGoalTarget();
EntityFox.this.getControllerLook().a(entityliving, (float) EntityFox.this.eo(), (float) EntityFox.this.O());
if (EntityFox.this.h((Entity) entityliving) <= 36.0D) {
EntityFox.this.w(true);
EntityFox.this.setCrouching(true);
EntityFox.this.getNavigation().o();
} else {
EntityFox.this.getNavigation().a((Entity) entityliving, 1.5D);
}
}
}
class m extends ControllerMove {
public m() {
super(EntityFox.this);
}
@Override
public void a() {
if (EntityFox.this.fe()) {
super.a();
}
}
}
class p extends PathfinderGoal {
public p() {
this.a(EnumSet.of(PathfinderGoal.Type.MOVE));
}
@Override
public boolean a() {
if (!EntityFox.this.getEquipment(EnumItemSlot.MAINHAND).isEmpty()) {
return false;
} else if (EntityFox.this.getGoalTarget() == null && EntityFox.this.getLastDamager() == null) {
if (!EntityFox.this.fe()) {
return false;
} else if (EntityFox.this.getRandom().nextInt(10) != 0) {
return false;
} else {
List<EntityItem> list = EntityFox.this.world.a(EntityItem.class, EntityFox.this.getBoundingBox().grow(8.0D, 8.0D, 8.0D), EntityFox.bs);
return !list.isEmpty() && EntityFox.this.getEquipment(EnumItemSlot.MAINHAND).isEmpty();
}
} else {
return false;
}
}
@Override
public void e() {
List<EntityItem> list = EntityFox.this.world.a(EntityItem.class, EntityFox.this.getBoundingBox().grow(8.0D, 8.0D, 8.0D), EntityFox.bs);
ItemStack itemstack = EntityFox.this.getEquipment(EnumItemSlot.MAINHAND);
if (itemstack.isEmpty() && !list.isEmpty()) {
EntityFox.this.getNavigation().a((Entity) list.get(0), 1.2000000476837158D);
}
}
@Override
public void c() {
List<EntityItem> list = EntityFox.this.world.a(EntityItem.class, EntityFox.this.getBoundingBox().grow(8.0D, 8.0D, 8.0D), EntityFox.bs);
if (!list.isEmpty()) {
EntityFox.this.getNavigation().a((Entity) list.get(0), 1.2000000476837158D);
}
}
}
public static enum Type {
RED(0, "red", new ResourceKey[]{Biomes.TAIGA, Biomes.TAIGA_HILLS, Biomes.TAIGA_MOUNTAINS, Biomes.GIANT_TREE_TAIGA, Biomes.GIANT_SPRUCE_TAIGA, Biomes.GIANT_TREE_TAIGA_HILLS, Biomes.GIANT_SPRUCE_TAIGA_HILLS}), SNOW(1, "snow", new ResourceKey[]{Biomes.SNOWY_TAIGA, Biomes.SNOWY_TAIGA_HILLS, Biomes.SNOWY_TAIGA_MOUNTAINS});
private static final EntityFox.Type[] c = (EntityFox.Type[]) Arrays.stream(values()).sorted(Comparator.comparingInt(EntityFox.Type::b)).toArray((i) -> {
return new EntityFox.Type[i];
});
private static final Map<String, EntityFox.Type> d = (Map) Arrays.stream(values()).collect(Collectors.toMap(EntityFox.Type::a, (entityfox_type) -> {
return entityfox_type;
}));
private final int e;
private final String f;
private final List<ResourceKey<BiomeBase>> g;
private Type(int i, String s, ResourceKey... aresourcekey) {
this.e = i;
this.f = s;
this.g = Arrays.asList(aresourcekey);
}
public String a() {
return this.f;
}
public int b() {
return this.e;
}
public static EntityFox.Type a(String s) {
return (EntityFox.Type) EntityFox.Type.d.getOrDefault(s, EntityFox.Type.RED);
}
public static EntityFox.Type a(int i) {
if (i < 0 || i > EntityFox.Type.c.length) {
i = 0;
}
return EntityFox.Type.c[i];
}
public static EntityFox.Type a(Optional<ResourceKey<BiomeBase>> optional) {
return optional.isPresent() && EntityFox.Type.SNOW.g.contains(optional.get()) ? EntityFox.Type.SNOW : EntityFox.Type.RED;
}
}
}
| 32.737693 | 533 | 0.556312 |
af32d0bff33778f5b11ad8547dab55ceb6d35a8e | 331 | package HeiMa.a161_MaoHeGou;
/**
* @Author Miracle Liuce
* @Date 2021/11/4 19:20
* @Version 1.0
*/
public class Dog extends Animal{
public Dog() {
}
public Dog(String name, int age) {
super(name, age);
}
public void lookDoor(){
System.out.println("狗狗会看门");
}
}
| 15.045455 | 39 | 0.540785 |
1f56da62507ba731a56ee04198053f70d17c97a9 | 1,449 | /*
* #%L
* fujion
* %%
* Copyright (C) 2021 Fujion Framework
* %%
* 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.
*
* #L%
*/
package org.fujion.plotly.common;
/**
* Determines a formatting rule for the exponents.
*/
public enum ExponentFormatEnum {
/**
* Suppresses exponential form (e.g., 1,000,000,000).
*/
NONE("none"),
/**
* Lower case exponent character (e.g., 1e+9).
*/
LOWER_E("e"),
/**
* Upper case exponent character (e.g., 1E+9).
*/
UPPER_E("E"),
/**
* Show in power notation (e.g., 1x10^9, with 9 as a superscript).
*/
POWER("power"),
/**
* Use SI units (e.g., 1G)
*/
SI("SI"),
/**
* Use number units (e.g., 1B)
*/
B("B");
private final String value;
ExponentFormatEnum(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
}
| 22.640625 | 75 | 0.600414 |
d0d0d0ab0d5b3f5bd53640043ab4b4d2e7c569fb | 758 | package org.suggs.webapps.buildpipeline.concordion;
import org.suggs.webapps.buildpipeline.dsl.DSL;
import org.suggs.webapps.buildpipeline.pages.impl.SeleniumPages;
import org.agileinsider.concordion.junit.ConcordionPlus;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Concordion fixture class for the user access tests.
* <p/>
* User: suggitpe Date: 12/12/11 Time: 7:30 AM
*/
@RunWith(ConcordionPlus.class)
public class UserCanAccessApplicationScenario extends DSL {
@SuppressWarnings("unused")
private static final Logger LOG = LoggerFactory.getLogger( UserCanAccessApplicationScenario.class );
public UserCanAccessApplicationScenario() {
super( new SeleniumPages() );
}
}
| 28.074074 | 104 | 0.773087 |
d21832d7b70023dfc1bf6c0582454a9f6eb32134 | 6,042 | /*
* 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.
*
* Other licenses:
* -----------------------------------------------------------------------------
* Commercial licenses for this work are available. These replace the above
* ASL 2.0 and offer limited warranties, support, maintenance, and commercial
* database integrations.
*
* For more information, please visit: http://www.jooq.org/licenses
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package org.jooq.meta.h2.information_schema.tables;
import java.util.Arrays;
import java.util.List;
import org.jooq.Field;
import org.jooq.ForeignKey;
import org.jooq.Name;
import org.jooq.Record;
import org.jooq.Schema;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.TableOptions;
import org.jooq.UniqueKey;
import org.jooq.impl.DSL;
import org.jooq.impl.SQLDataType;
import org.jooq.impl.TableImpl;
import org.jooq.meta.h2.information_schema.InformationSchema;
import org.jooq.meta.h2.information_schema.Keys;
/** This class is generated by jOOQ. */
@SuppressWarnings({"all", "unchecked", "rawtypes"})
public class Tables extends TableImpl<Record> {
private static final long serialVersionUID = -1054465531;
/** The reference instance of <code>INFORMATION_SCHEMA.TABLES</code> */
public static final Tables TABLES = new Tables();
/** The class holding records for this type */
@Override
public Class<Record> getRecordType() {
return Record.class;
}
/** The column <code>INFORMATION_SCHEMA.TABLES.TABLE_CATALOG</code>. */
public final TableField<Record, String> TABLE_CATALOG =
createField(DSL.name("TABLE_CATALOG"), SQLDataType.VARCHAR(2147483647), this, "");
/** The column <code>INFORMATION_SCHEMA.TABLES.TABLE_SCHEMA</code>. */
public final TableField<Record, String> TABLE_SCHEMA =
createField(DSL.name("TABLE_SCHEMA"), SQLDataType.VARCHAR(2147483647), this, "");
/** The column <code>INFORMATION_SCHEMA.TABLES.TABLE_NAME</code>. */
public final TableField<Record, String> TABLE_NAME =
createField(DSL.name("TABLE_NAME"), SQLDataType.VARCHAR(2147483647), this, "");
/** The column <code>INFORMATION_SCHEMA.TABLES.TABLE_TYPE</code>. */
public final TableField<Record, String> TABLE_TYPE =
createField(DSL.name("TABLE_TYPE"), SQLDataType.VARCHAR(2147483647), this, "");
/** The column <code>INFORMATION_SCHEMA.TABLES.STORAGE_TYPE</code>. */
public final TableField<Record, String> STORAGE_TYPE =
createField(DSL.name("STORAGE_TYPE"), SQLDataType.VARCHAR(2147483647), this, "");
/** The column <code>INFORMATION_SCHEMA.TABLES.SQL</code>. */
public final TableField<Record, String> SQL =
createField(DSL.name("SQL"), SQLDataType.VARCHAR(2147483647), this, "");
/** The column <code>INFORMATION_SCHEMA.TABLES.REMARKS</code>. */
public final TableField<Record, String> REMARKS =
createField(DSL.name("REMARKS"), SQLDataType.VARCHAR(2147483647), this, "");
/** The column <code>INFORMATION_SCHEMA.TABLES.LAST_MODIFICATION</code>. */
public final TableField<Record, Long> LAST_MODIFICATION =
createField(DSL.name("LAST_MODIFICATION"), SQLDataType.BIGINT, this, "");
/** The column <code>INFORMATION_SCHEMA.TABLES.ID</code>. */
public final TableField<Record, Integer> ID =
createField(DSL.name("ID"), SQLDataType.INTEGER, this, "");
/** The column <code>INFORMATION_SCHEMA.TABLES.TYPE_NAME</code>. */
public final TableField<Record, String> TYPE_NAME =
createField(DSL.name("TYPE_NAME"), SQLDataType.VARCHAR(2147483647), this, "");
/** The column <code>INFORMATION_SCHEMA.TABLES.TABLE_CLASS</code>. */
public final TableField<Record, String> TABLE_CLASS =
createField(DSL.name("TABLE_CLASS"), SQLDataType.VARCHAR(2147483647), this, "");
/** The column <code>INFORMATION_SCHEMA.TABLES.ROW_COUNT_ESTIMATE</code>. */
public final TableField<Record, Long> ROW_COUNT_ESTIMATE =
createField(DSL.name("ROW_COUNT_ESTIMATE"), SQLDataType.BIGINT, this, "");
private Tables(Name alias, Table<Record> aliased) {
this(alias, aliased, null);
}
private Tables(Name alias, Table<Record> aliased, Field<?>[] parameters) {
super(alias, null, aliased, parameters, DSL.comment(""), TableOptions.table());
}
/** Create an aliased <code>INFORMATION_SCHEMA.TABLES</code> table reference */
public Tables(String alias) {
this(DSL.name(alias), TABLES);
}
/** Create an aliased <code>INFORMATION_SCHEMA.TABLES</code> table reference */
public Tables(Name alias) {
this(alias, TABLES);
}
/** Create a <code>INFORMATION_SCHEMA.TABLES</code> table reference */
public Tables() {
this(DSL.name("TABLES"), null);
}
public <O extends Record> Tables(Table<O> child, ForeignKey<O, Record> key) {
super(child, key, TABLES);
}
@Override
public Schema getSchema() {
return InformationSchema.INFORMATION_SCHEMA;
}
@Override
public UniqueKey<Record> getPrimaryKey() {
return Keys.SYNTHETIC_PK_TABLES;
}
@Override
public List<UniqueKey<Record>> getKeys() {
return Arrays.<UniqueKey<Record>>asList(Keys.SYNTHETIC_PK_TABLES);
}
@Override
public Tables as(String alias) {
return new Tables(DSL.name(alias), this);
}
@Override
public Tables as(Name alias) {
return new Tables(alias, this);
}
/** Rename this table */
@Override
public Tables rename(String name) {
return new Tables(DSL.name(name), null);
}
/** Rename this table */
@Override
public Tables rename(Name name) {
return new Tables(name, null);
}
}
| 32.836957 | 88 | 0.704734 |
17717b1c1652aef80aa37b35146ed868ee3ea947 | 2,123 | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.qpid.server.protocol.v0_10.transport.mimecontentconverter;
import java.nio.ByteBuffer;
import java.util.List;
import org.apache.qpid.server.message.mimecontentconverter.ObjectToMimeContentConverter;
import org.apache.qpid.server.plugin.PluggableService;
import org.apache.qpid.server.protocol.v0_10.transport.BBEncoder;
import org.apache.qpid.server.protocol.v0_10.transport.EncoderUtils;
@PluggableService
public class ListToAmqpListConverter implements ObjectToMimeContentConverter<List>
{
@Override
public String getType()
{
return getMimeType();
}
@Override
public Class<List> getObjectClass()
{
return List.class;
}
@Override
public int getRank()
{
return 0;
}
@Override
public String getMimeType()
{
return "amqp/list";
}
@Override
public boolean isAcceptable(final List list)
{
return EncoderUtils.isEncodable(list);
}
@Override
public byte[] toMimeContent(final List list)
{
BBEncoder encoder = new BBEncoder(1024);
encoder.writeList(list);
final ByteBuffer buf = encoder.buffer();
int remaining = buf.remaining();
byte[] data = new byte[remaining];
buf.get(data);
return data;
}
}
| 27.934211 | 88 | 0.704663 |
768f8bd052361dec96eae0ba09c19fbc517e65ae | 179 | package com.ttnn.business.cs.dbo;
import javax.inject.Named;
import com.ttnn.framework.support.CSDBOSupport;
@Named
/** 业务运行日志*/
public class CSSL01DBO extends CSDBOSupport
{
}
| 17.9 | 47 | 0.782123 |
965870a4419d0f73acb6bf39110369fb3c64e0a4 | 5,793 |
package it.polito.dp2.RNS.sol1.jaxb;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.datatype.XMLGregorianCalendar;
/**
* <p>Java class for VehicleType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="VehicleType">
* <complexContent>
* <extension base="{}IdentifiedEntity">
* <all>
* <element name="entryTime" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
* </all>
* <attribute name="type" use="required" type="{}VehicleTypeType" />
* <attribute name="state" use="required" type="{}VehicleState" />
* <attribute name="position" use="required" type="{http://www.w3.org/2001/XMLSchema}token" />
* <attribute name="origin" use="required" type="{http://www.w3.org/2001/XMLSchema}token" />
* <attribute name="destination" use="required" type="{http://www.w3.org/2001/XMLSchema}token" />
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "VehicleType", propOrder = {
"entryTime"
})
public class VehicleType
extends IdentifiedEntity
{
@XmlElement(required = true)
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar entryTime;
@XmlAttribute(name = "type", required = true)
protected VehicleTypeType type;
@XmlAttribute(name = "state", required = true)
protected VehicleState state;
@XmlAttribute(name = "position", required = true)
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "token")
protected String position;
@XmlAttribute(name = "origin", required = true)
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "token")
protected String origin;
@XmlAttribute(name = "destination", required = true)
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "token")
protected String destination;
/**
* Gets the value of the entryTime property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getEntryTime() {
return entryTime;
}
/**
* Sets the value of the entryTime property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setEntryTime(XMLGregorianCalendar value) {
this.entryTime = value;
}
public boolean isSetEntryTime() {
return (this.entryTime!= null);
}
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link VehicleTypeType }
*
*/
public VehicleTypeType getType() {
return type;
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link VehicleTypeType }
*
*/
public void setType(VehicleTypeType value) {
this.type = value;
}
public boolean isSetType() {
return (this.type!= null);
}
/**
* Gets the value of the state property.
*
* @return
* possible object is
* {@link VehicleState }
*
*/
public VehicleState getState() {
return state;
}
/**
* Sets the value of the state property.
*
* @param value
* allowed object is
* {@link VehicleState }
*
*/
public void setState(VehicleState value) {
this.state = value;
}
public boolean isSetState() {
return (this.state!= null);
}
/**
* Gets the value of the position property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPosition() {
return position;
}
/**
* Sets the value of the position property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPosition(String value) {
this.position = value;
}
public boolean isSetPosition() {
return (this.position!= null);
}
/**
* Gets the value of the origin property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOrigin() {
return origin;
}
/**
* Sets the value of the origin property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOrigin(String value) {
this.origin = value;
}
public boolean isSetOrigin() {
return (this.origin!= null);
}
/**
* Gets the value of the destination property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDestination() {
return destination;
}
/**
* Sets the value of the destination property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDestination(String value) {
this.destination = value;
}
public boolean isSetDestination() {
return (this.destination!= null);
}
}
| 24.54661 | 106 | 0.587778 |
ef707b4d119fd1e8b4e1cc0aef174965fc1df23f | 4,594 | /*
* Tencent is pleased to support the open source community by making BK-CI 蓝鲸持续集成平台 available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* BK-CI 蓝鲸持续集成平台 is licensed under the MIT license.
*
* A copy of the MIT License is included in this file.
*
*
* Terms of the MIT License:
* ---------------------------------------------------
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
* NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.tencent.bk.codecc.defect.common;
import com.tencent.bk.codecc.defect.vo.TreeNodeVO;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* @date 2016/9/20
*/
@Component
public class Tree
{
private Boolean expand;
private Boolean eliminate = true;
private void addChild(int index, String[] path, TreeNodeVO parent)
{
boolean isNewNode = true;
if (parent.getChildren() != null)
{
for (TreeNodeVO child : parent.getChildren())
{
if (child.getName().equals(path[index]))
{
isNewNode = false;
addChild(++index, path, child);
break;
}
}
}
if (isNewNode)
{
TreeNodeVO child = new TreeNodeVO(path[index], expand);
if (parent.getChildren() == null)
{
parent.setChildren(new ArrayList<>());
}
parent.getChildren().add(child);
if (++index < path.length)
{
addChild(index, path, child);
}
}
}
public TreeNodeVO buildTree(Set<String> paths, String streamName)
{
TreeNodeVO root = new TreeNodeVO(streamName, expand);
if (paths == null || paths.size() == 0)
{
return root;
}
int index = 0;
for (String path : paths)
{
String[] dirs = path.split("/");
if (dirs[0].length() == 0)
{
index = 1;
}
addChild(index, dirs, root);
}
for (int i = 0; i < root.getChildren().size(); i++)
{
TreeNodeVO treeNode = root.getChildren().get(i);
if ("usr".equals(treeNode.getName()) || treeNode.getName().contains("Program Files"))
{
continue;
}
if (eliminate)
{
// 把单节点的树去掉
treeNode = eliminateDepth(treeNode);
}
root.getChildren().set(i, treeNode);
}
// 对树节点按字母排序
sortTree(root);
return root;
}
public TreeNodeVO buildTree(Set<String> paths, String streamName, boolean expand, boolean eliminate)
{
this.expand = expand;
this.eliminate = eliminate;
return buildTree(paths, streamName);
}
private TreeNodeVO eliminateDepth(TreeNodeVO root)
{
while (root.getChildren() != null && root.getChildren().size() == 1)
{
root = root.getChildren().get(0);
}
return root;
}
public void sortTree(TreeNodeVO root)
{
List<TreeNodeVO> childs = root.getChildren();
if (CollectionUtils.isNotEmpty(childs))
{
for (TreeNodeVO node : childs)
{
sortTree(node);
}
childs.sort((o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName()));
}
}
}
| 31.465753 | 129 | 0.579016 |
90635b237643a0b660172d81002fa7ce1b60fdcd | 1,188 | package org.javacs;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import java.net.URI;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.logging.Logger;
import org.eclipse.lsp4j.*;
import org.junit.Test;
public class FindReferencesTest {
private static final Logger LOG = Logger.getLogger("main");
private static final JavaLanguageServer server = LanguageServerFixture.getJavaLanguageServer();
protected List<? extends Location> items(String file, int row, int column) {
URI uri = FindResource.uri(file);
ReferenceParams params = new ReferenceParams();
params.setTextDocument(new TextDocumentIdentifier(uri.toString()));
params.setUri(uri.toString());
params.setPosition(new Position(row - 1, column - 1));
try {
return server.getTextDocumentService().references(params).get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}
@Test
public void findAllReferences() {
assertThat(items("/org/javacs/example/GotoOther.java", 6, 30), not(empty()));
}
}
| 31.263158 | 99 | 0.695286 |
fc469065b2635aa7c89b684b71d32111776f57b2 | 94 | package com.volmit.react.util;
public class Ex
{
public static void t(Throwable e)
{
}
}
| 9.4 | 34 | 0.691489 |
9448a00a660ef0a6426a64599111acfc5dda495f | 1,069 | package uk.ac.ebi.pride.cluster.ws.modules.cluster.model;
import java.util.ArrayList;
import java.util.List;
/**
* Statistics
*
* @author Rui Wang
* @version $Id$
*/
public class SpectrumSimilarityStatistics {
// spectrum similarity to the consensus spectrum for the PSMs with the highest ratio peptide sequence in the cluster
private final List<Float> highRatioPeptideSpectrumSimilarities = new ArrayList<Float>();
// spectrum similarity for all the PSMs in the cluster
private final List<Float> clusterSpectrumSimilarities = new ArrayList<Float>();
public List<Float> getHighRatioPeptideSpectrumSimilarities() {
return highRatioPeptideSpectrumSimilarities;
}
public void addHighRatioPeptideSpectrumSimilarity(Float deltaMz) {
highRatioPeptideSpectrumSimilarities.add(deltaMz);
}
public List<Float> getClusterSpectrumSimilarities() {
return clusterSpectrumSimilarities;
}
public void addClusterSpectrumSimilarity(Float deltaMz) {
clusterSpectrumSimilarities.add(deltaMz);
}
}
| 30.542857 | 120 | 0.751169 |
06aa5d32c04f9c1aed0513884fe7497a1f750db6 | 14,110 | package com.bx.erp.test.staff;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.math.BigInteger;
import java.security.interfaces.RSAPublicKey;
import javax.servlet.http.HttpSession;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.util.StringUtils;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.bx.erp.action.BaseAction;
import com.bx.erp.action.BaseAction.EnumSession;
import com.bx.erp.cache.BaseCache;
import com.bx.erp.cache.CacheManager;
import com.bx.erp.model.BxStaff;
import com.bx.erp.model.Company;
import com.bx.erp.model.ErrorInfo;
import com.bx.erp.model.CacheType.EnumCacheType;
import com.bx.erp.model.ErrorInfo.EnumErrorCode;
import com.bx.erp.model.config.BxConfigGeneral;
import com.bx.erp.test.BaseActionTest;
import com.bx.erp.test.Shared;
import com.bx.erp.util.FieldFormat;
import com.bx.erp.util.RSAUtils;
import com.jayway.jsonpath.JsonPath;
import net.sf.json.JSONObject;
@WebAppConfiguration
public class BxStaffActionTest extends BaseActionTest {
private final String PHONE = "13185246281";
@BeforeClass
public void setup() {
super.setUp();
}
@AfterClass
public void tearDown() {
super.tearDown();
}
@Test
public void testRetrieve1Ex() throws Exception {
Shared.printTestMethodStartInfo();
System.out.println("-------------------case1: 根据ID查询-------------------");
MvcResult mr = mvc.perform(//
get("/bxStaff/retrieve1Ex.bx?" + BxStaff.field.getFIELD_NAME_ID() + "=1&" + BxStaff.field.getFIELD_NAME_mobile() + "=")//
.contentType(MediaType.APPLICATION_JSON)//
.session((MockHttpSession) Shared.getBXStaffLoginSession(mvc, PHONE))//
)//
.andExpect(status().isOk())//
.andDo(print())//
.andReturn();
Shared.checkJSONErrorCode(mr);
System.out.println("-------------------case2: 根据不存在ID查询-------------------");
MvcResult mr2 = mvc.perform(//
get("/bxStaff/retrieve1Ex.bx?" + BxStaff.field.getFIELD_NAME_ID() + "=-1&" + BxStaff.field.getFIELD_NAME_mobile() + "=")//
.contentType(MediaType.APPLICATION_JSON)//
.session((MockHttpSession) Shared.getBXStaffLoginSession(mvc, PHONE))//
)//
.andExpect(status().isOk())//
.andDo(print())//
.andReturn();
Shared.checkJSONErrorCode(mr2, EnumErrorCode.EC_WrongFormatForInputField);
Shared.checkJSONMsg(mr2, FieldFormat.FIELD_ERROR_ID, "错误信息与预期不相符");
// bxStaff暂时没有检查权限
// System.out.println("-------------------case3: 没有权限进行查询-------------------");
// MvcResult mr3 = mvc.perform(//
// get("/bxStaff/retrieve1Ex.bx?" + BxStaff.field.getFIELD_NAME_ID() + "=1&" +
// BxStaff.field.getFIELD_NAME_mobile() + "=")//
// .contentType(MediaType.APPLICATION_JSON)//
// .session((MockHttpSession) Shared.getStaffLoginSession(mvc,
// NoPermission_PHONE))//
// )//
// .andExpect(status().isOk())//
// .andDo(print())//
// .andReturn();
//
// Shared.checkJSONErrorCode(mr3, EnumErrorCode.EC_NoPermission);
System.out.println("-------------------case4: 用手机号码进行查询-------------------");
MvcResult mr4 = mvc.perform(//
get("/bxStaff/retrieve1Ex.bx?" + BxStaff.field.getFIELD_NAME_ID() + "=0&" + BxStaff.field.getFIELD_NAME_mobile() + "=13462346281")//
.contentType(MediaType.APPLICATION_JSON)//
.session((MockHttpSession) Shared.getBXStaffLoginSession(mvc, PHONE))//
)//
.andExpect(status().isOk())//
.andDo(print())//
.andReturn();
Shared.checkJSONErrorCode(mr4);
System.out.println("-------------------case5: 用不存在的手机号码进行查询-------------------");
MvcResult mr5 = mvc.perform(//
get("/bxStaff/retrieve1Ex.bx?" + BxStaff.field.getFIELD_NAME_ID() + "=0&" + BxStaff.field.getFIELD_NAME_mobile() + "=-99999")//
.contentType(MediaType.APPLICATION_JSON)//
.session((MockHttpSession) Shared.getBXStaffLoginSession(mvc, PHONE))//
)//
.andExpect(status().isOk())//
.andDo(print())//
.andReturn();
Shared.checkJSONErrorCode(mr5, EnumErrorCode.EC_WrongFormatForInputField);
Shared.checkJSONMsg(mr5, BxStaff.FIELD_ERROR_Mobile, "错误信息与预期不相符");
}
@Test
public void testLogout() throws Exception {
final String BxStaff_Phone = "13462346281";
BxStaff bxStaff = new BxStaff();
// ..拿到公钥
MvcResult ret = mvc.perform(post("/bxStaff/getTokenEx.bx").contentType(MediaType.APPLICATION_JSON).param(BxStaff.field.getFIELD_NAME_mobile(), BxStaff_Phone)).andExpect(status().isOk()).andDo(print()).andReturn();
String json = ret.getResponse().getContentAsString();
JSONObject o = JSONObject.fromObject(json);
String modulus = JsonPath.read(o, "$.rsa.modulus");
String exponent = JsonPath.read(o, "$.rsa.exponent");
modulus = new BigInteger(modulus, 16).toString();
exponent = new BigInteger(exponent, 16).toString();
RSAPublicKey publicKey = RSAUtils.getPublicKey(modulus, exponent);
final String pwd = Shared.PASSWORD_DEFAULT;
// ..加密密码
String pwdEncrypted = RSAUtils.encryptByPublicKey(pwd, publicKey);
bxStaff.setPwdEncrypted(pwdEncrypted);
MvcResult mr = mvc
.perform(post("/bxStaff/loginEx.bx").param(BxStaff.field.getFIELD_NAME_mobile(), BxStaff_Phone).param(BxStaff.field.getFIELD_NAME_pwdEncrypted(), pwdEncrypted)
.param(BxStaff.field.getFIELD_NAME_companySN(), Shared.DB_BXSN_Test).session((MockHttpSession) ret.getRequest().getSession()).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andDo(print()).andReturn();
Shared.checkJSONErrorCode(mr, EnumErrorCode.EC_NoError);
MvcResult mr2 = mvc.perform(get("/bxStaff/logoutEx.bx").session((MockHttpSession) mr.getRequest().getSession()).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andDo(print()).andReturn();
Shared.checkJSONErrorCode(mr2);
}
@Test
public void testLogin() throws Exception {
Shared.printTestMethodStartInfo();
// ------------------- 第一次测试:密码正确且密码格式正确 -------------------
// System.out.println("------------------- 第一次测试:密码正确且密码格式正确
// -------------------");
final String BxStaff_Phone = "13462346281";
BxStaff bs = new BxStaff();
// ..拿到公钥
MvcResult ret = mvc.perform(post("/bxStaff/getTokenEx.bx").contentType(MediaType.APPLICATION_JSON).param(BxStaff.field.getFIELD_NAME_mobile(), BxStaff_Phone)).andExpect(status().isOk()).andDo(print()).andReturn();
String json = ret.getResponse().getContentAsString();
JSONObject o = JSONObject.fromObject(json);
String modulus = JsonPath.read(o, "$.rsa.modulus");
String exponent = JsonPath.read(o, "$.rsa.exponent");
modulus = new BigInteger(modulus, 16).toString();
exponent = new BigInteger(exponent, 16).toString();
RSAPublicKey publicKey = RSAUtils.getPublicKey(modulus, exponent);
final String pwd = Shared.PASSWORD_DEFAULT;
// ..加密密码
String pwdEncrypted = RSAUtils.encryptByPublicKey(pwd, publicKey);
bs.setPwdEncrypted(pwdEncrypted);
MvcResult mr = mvc.perform(post//
("/bxStaff/loginEx.bx")//
.param(BxStaff.field.getFIELD_NAME_mobile(), BxStaff_Phone)//
.param(BxStaff.field.getFIELD_NAME_pwdEncrypted(), pwdEncrypted)//
.session((MockHttpSession) ret.getRequest().getSession())//
.contentType(MediaType.APPLICATION_JSON)//
)//
.andExpect(status().isOk()).andDo(print()).andReturn();
Shared.checkJSONErrorCode(mr, EnumErrorCode.EC_NoError);
}
@Test
public void testLogin2() throws Exception {
Shared.printTestMethodStartInfo();
Shared.caseLog("case2:用户登录超过当日限制次数");
//
ErrorInfo ec = new ErrorInfo();
BxConfigGeneral bxConfigGeneral = (BxConfigGeneral) CacheManager.getCache(BaseAction.DBName_Public, EnumCacheType.ECT_BXConfigGeneral).read1(BaseCache.MaxLoginCountIn1Day, STAFF_ID4, ec, BaseAction.DBName_Public);
String oldMaxLoginCountIn1Day = bxConfigGeneral.getValue();
//
int newMaxLoginCountIn1Day = 5;
BxConfigGeneral newBxConfigGeneral = (BxConfigGeneral) bxConfigGeneral.clone();
newBxConfigGeneral.setValue(String.valueOf(newMaxLoginCountIn1Day));
CacheManager.getCache(BaseAction.DBName_Public, EnumCacheType.ECT_BXConfigGeneral).write1(newBxConfigGeneral, BaseAction.DBName_Public, STAFF_ID4);
for (int i = 0; i < newMaxLoginCountIn1Day - 1; i++) {
login(Shared.BxStaff_Phone);
}
BxStaff bs = new BxStaff();
// ..拿到公钥
MvcResult ret = mvc.perform(post("/bxStaff/getTokenEx.bx").contentType(MediaType.APPLICATION_JSON).param(BxStaff.field.getFIELD_NAME_mobile(), Shared.BxStaff_Phone)).andExpect(status().isOk()).andDo(print()).andReturn();
String json = ret.getResponse().getContentAsString();
JSONObject o = JSONObject.fromObject(json);
String modulus = JsonPath.read(o, "$.rsa.modulus");
String exponent = JsonPath.read(o, "$.rsa.exponent");
modulus = new BigInteger(modulus, 16).toString();
exponent = new BigInteger(exponent, 16).toString();
RSAPublicKey publicKey = RSAUtils.getPublicKey(modulus, exponent);
final String pwd = Shared.PASSWORD_DEFAULT;
// ..加密密码
String pwdEncrypted = RSAUtils.encryptByPublicKey(pwd, publicKey);
bs.setPwdEncrypted(pwdEncrypted);
MvcResult mr = mvc.perform(post//
("/bxStaff/loginEx.bx")//
.param(BxStaff.field.getFIELD_NAME_mobile(), Shared.BxStaff_Phone)//
.param(BxStaff.field.getFIELD_NAME_pwdEncrypted(), pwdEncrypted)//
.session((MockHttpSession) ret.getRequest().getSession())//
.contentType(MediaType.APPLICATION_JSON)//
)//
.andExpect(status().isOk()).andDo(print()).andReturn();
newBxConfigGeneral.setValue(oldMaxLoginCountIn1Day);
CacheManager.getCache(BaseAction.DBName_Public, EnumCacheType.ECT_BXConfigGeneral).write1(newBxConfigGeneral, BaseAction.DBName_Public, STAFF_ID4);
Assert.assertTrue(StringUtils.isEmpty(mr.getResponse().getContentAsString()), "没有正常限制用户登录次数");
}
@Test
public void testLogin3() throws Exception {
Shared.printTestMethodStartInfo();
Shared.caseLog("case3:OP登录后,需要返回公司Logo的URL");
final String BxStaff_Phone = "13462346281";
BxStaff bs = new BxStaff();
// ..拿到公钥
MvcResult ret = mvc.perform(post("/bxStaff/getTokenEx.bx").contentType(MediaType.APPLICATION_JSON).param(BxStaff.field.getFIELD_NAME_mobile(), BxStaff_Phone)).andExpect(status().isOk()).andDo(print()).andReturn();
String json = ret.getResponse().getContentAsString();
JSONObject o = JSONObject.fromObject(json);
String modulus = JsonPath.read(o, "$.rsa.modulus");
String exponent = JsonPath.read(o, "$.rsa.exponent");
modulus = new BigInteger(modulus, 16).toString();
exponent = new BigInteger(exponent, 16).toString();
RSAPublicKey publicKey = RSAUtils.getPublicKey(modulus, exponent);
final String pwd = Shared.PASSWORD_DEFAULT;
// ..加密密码
String pwdEncrypted = RSAUtils.encryptByPublicKey(pwd, publicKey);
bs.setPwdEncrypted(pwdEncrypted);
MvcResult mr = mvc.perform(post//
("/bxStaff/loginEx.bx")//
.param(BxStaff.field.getFIELD_NAME_mobile(), BxStaff_Phone)//
.param(BxStaff.field.getFIELD_NAME_pwdEncrypted(), pwdEncrypted)//
.session((MockHttpSession) ret.getRequest().getSession())//
.contentType(MediaType.APPLICATION_JSON)//
)//
.andExpect(status().isOk()).andDo(print()).andReturn();
Shared.checkJSONErrorCode(mr, EnumErrorCode.EC_NoError);
HttpSession session = ret.getRequest().getSession();
Company company = (Company) session.getAttribute(EnumSession.SESSION_Company.getName());
Assert.assertTrue(company.getLogo() != null, "商家登录后,需要返回公司Logo的URL");
}
private void login(String phone) throws Exception {
BxStaff bs = new BxStaff();
// ..拿到公钥
MvcResult ret = mvc.perform(post("/bxStaff/getTokenEx.bx").contentType(MediaType.APPLICATION_JSON).param(BxStaff.field.getFIELD_NAME_mobile(), phone)).andExpect(status().isOk()).andDo(print()).andReturn();
String json = ret.getResponse().getContentAsString();
JSONObject o = JSONObject.fromObject(json);
String modulus = JsonPath.read(o, "$.rsa.modulus");
String exponent = JsonPath.read(o, "$.rsa.exponent");
modulus = new BigInteger(modulus, 16).toString();
exponent = new BigInteger(exponent, 16).toString();
RSAPublicKey publicKey = RSAUtils.getPublicKey(modulus, exponent);
final String pwd = Shared.PASSWORD_DEFAULT;
// ..加密密码
String pwdEncrypted = RSAUtils.encryptByPublicKey(pwd, publicKey);
bs.setPwdEncrypted(pwdEncrypted);
MvcResult mr = mvc.perform(post//
("/bxStaff/loginEx.bx")//
.param(BxStaff.field.getFIELD_NAME_mobile(), phone)//
.param(BxStaff.field.getFIELD_NAME_pwdEncrypted(), pwdEncrypted)//
.session((MockHttpSession) ret.getRequest().getSession())//
.contentType(MediaType.APPLICATION_JSON)//
)//
.andExpect(status().isOk()).andDo(print()).andReturn();
Shared.checkJSONErrorCode(mr, EnumErrorCode.EC_NoError);
}
@Test
public void testRetrieveNEx() throws Exception {
Shared.printTestMethodStartInfo();
System.out.println("-------------------case1:正常查询-------------------");
MvcResult mr = mvc.perform(//
get("/bxStaff/retrieveNEx.bx")//
.contentType(MediaType.APPLICATION_JSON)//
.session((MockHttpSession) Shared.getBXStaffLoginSession(mvc, PHONE))//
)//
.andExpect(status().isOk())//
.andDo(print())//
.andReturn();
Shared.checkJSONErrorCode(mr);
// bxStaff暂时没有检查权限
// System.out.println("-------------------case2: 没有权限进行查询-------------------");
// MvcResult mr2 = mvc.perform(//
// get("/bxStaff/retrieveNEx.bx")//
// .contentType(MediaType.APPLICATION_JSON)//
// .session((MockHttpSession) Shared.getStaffLoginSession(mvc,
// NoPermission_PHONE))//
// )//
// .andExpect(status().isOk())//
// .andDo(print())//
// .andReturn();
//
// Shared.checkJSONErrorCode(mr2, EnumErrorCode.EC_NoPermission);
}
} | 40.085227 | 222 | 0.719915 |
371c052500f54daa10c7995ace017bf58f62e011 | 892 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.javastore.dtos;
import java.io.Serializable;
/**
*
* @author
* Este objeto nos envia los datos del usuario o cliente que inicia sesion
*/
public class LoginDTO implements Serializable {
private String email;
private String password;
public LoginDTO() {
}
public LoginDTO(String email, String password) {
this.email = email;
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
| 19.822222 | 79 | 0.652466 |
f23a2335bf1a61811672b0f9393a0b9497992f54 | 528 | package p02_ferrari;
public class Ferrari implements Car{
private static String MODEL = "488-Spider";
private String driver;
public Ferrari(String driver) {
this.driver = driver;
}
@Override
public String toString() {
return String.format("%s/%s/%s/%s", MODEL, this.useBrakes(), this.pushTheGas(), this.driver);
}
@Override
public String useBrakes() {
return "Brakes!";
}
@Override
public String pushTheGas() {
return "Zadu6avam sA!";
}
}
| 20.307692 | 101 | 0.609848 |
42562193618f10a7210794aa1cb490f5f56170bd | 3,781 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.catalina.tribes.group.interceptors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.catalina.tribes.ChannelMessage;
import org.apache.catalina.tribes.Member;
import org.apache.catalina.tribes.group.InterceptorPayload;
import org.apache.catalina.tribes.transport.bio.util.LinkObject;
import org.apache.catalina.tribes.util.TcclThreadFactory;
/**
*
* Same implementation as the MessageDispatchInterceptor
* except it uses an atomic long for the currentSize calculation
* and uses a thread pool for message sending.
*
* @author Filip Hanik
* @version 1.0
*/
public class MessageDispatch15Interceptor extends MessageDispatchInterceptor {
protected AtomicLong currentSize = new AtomicLong(0);
protected ThreadPoolExecutor executor = null;
protected int maxThreads = 10;
protected int maxSpareThreads = 2;
protected long keepAliveTime = 5000;
protected LinkedBlockingQueue<Runnable> runnablequeue = new LinkedBlockingQueue<Runnable>();
@Override
public long getCurrentSize() {
return currentSize.get();
}
@Override
public long addAndGetCurrentSize(long inc) {
return currentSize.addAndGet(inc);
}
@Override
public long setAndGetCurrentSize(long value) {
currentSize.set(value);
return value;
}
@Override
public boolean addToQueue(ChannelMessage msg, Member[] destination, InterceptorPayload payload) {
final LinkObject obj = new LinkObject(msg,destination,payload);
Runnable r = new Runnable() {
@Override
public void run() {
sendAsyncData(obj);
}
};
executor.execute(r);
return true;
}
@Override
public LinkObject removeFromQueue() {
return null; //not used, thread pool contains its own queue.
}
@Override
public void startQueue() {
if ( run ) return;
executor = new ThreadPoolExecutor(maxSpareThreads, maxThreads,
keepAliveTime, TimeUnit.MILLISECONDS, runnablequeue,
new TcclThreadFactory());
run = true;
}
@Override
public void stopQueue() {
run = false;
executor.shutdownNow();
setAndGetCurrentSize(0);
runnablequeue.clear();
}
public long getKeepAliveTime() {
return keepAliveTime;
}
public int getMaxSpareThreads() {
return maxSpareThreads;
}
public int getMaxThreads() {
return maxThreads;
}
public void setKeepAliveTime(long keepAliveTime) {
this.keepAliveTime = keepAliveTime;
}
public void setMaxSpareThreads(int maxSpareThreads) {
this.maxSpareThreads = maxSpareThreads;
}
public void setMaxThreads(int maxThreads) {
this.maxThreads = maxThreads;
}
} | 30.491935 | 101 | 0.697964 |
7d9dcb3afe91a703cfd7335cce6e94d583f7a049 | 1,765 | /*
* copyright 2012, gash
*
* Gash licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package poke.debug;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
public class DebugFrameDecoder extends LengthFieldBasedFrameDecoder {
public DebugFrameDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment,
int initialBytesToStrip) {
super(maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip);
}
@Override
protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
Object rtn = null;
try {
rtn = super.decode(ctx, in);
System.err.println("----------------------------");
int readerIndex = in.readerIndex();
System.err.println("reader index: " + readerIndex);
if (rtn != null) {
byte[] arr = ((ByteBuf) rtn).array();
if (arr != null) {
for (byte b : arr)
System.err.println(b);
} else
System.err.println("buffer is empty");
}
System.err.println("----------------------------");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rtn;
}
}
| 32.090909 | 113 | 0.699717 |
e1ce193296027950bdea0daa2ee6f2a7615fbd7b | 124 | package io.quarkus.it.mockbean;
public class SuffixServiceSingleton {
String getSuffix() {
return "";
}
}
| 13.777778 | 37 | 0.645161 |
334b53504506902b041f45f03b232139a44a6fd9 | 6,842 | /*
* Copyright (C) 2013 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.omniburst.winetv.android.browser;
import android.net.Uri;
import android.util.Log;
import com.google.android.gms.cast.MediaInfo;
import com.google.android.gms.cast.MediaMetadata;
import com.google.android.gms.common.images.WebImage;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class VideoProvider {
private static final String TAG = "VideoProvider";
private static String TAG_MEDIA = "videos";
private static String THUMB_PREFIX_URL =
"http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/";
private static String TAG_CATEGORIES = "categories";
private static String TAG_NAME = "name";
private static String TAG_STUDIO = "studio";
private static String TAG_SOURCES = "sources";
private static String TAG_SUBTITLE = "subtitle";
private static String TAG_THUMB = "image-480x270"; // "thumb";
private static String TAG_IMG_780_1200 = "image-780x1200";
private static String TAG_TITLE = "title";
private static List<MediaInfo> mediaList;
protected JSONObject parseUrl(String urlString) {
InputStream is = null;
try {
java.net.URL url = new java.net.URL(urlString);
URLConnection urlConnection = url.openConnection();
is = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream(), "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
String xml = sb.toString();
JSONObject obj = XML.toJSONObject(xml);
return obj;
} catch (Exception e) {
Log.d(TAG, "Failed to parse the json for media list", e);
return null;
} finally {
if (null != is) {
try {
is.close();
} catch (IOException e) {
// ignore
}
}
}
}
public static List<MediaInfo> buildMedia(String url) throws JSONException {
if (null != mediaList) {
return mediaList;
}
mediaList = new ArrayList<MediaInfo>();
JSONObject jsonObj = new VideoProvider().parseUrl(url);
JSONObject wineSpotTVAppData = jsonObj.getJSONObject("WineSpotTVAppData");
JSONArray episodes = wineSpotTVAppData.getJSONArray("episode");
if (episodes != null) {
for (int i = 0; i < episodes.length(); i++) {
JSONObject episode = episodes.getJSONObject(i);
String subTitle = episode.getString("episodeDes");
String videoUrl = episode.getString("videoURL");
String imageurl = episode.getString("episodeImg");
String bigImageurl = episode.getString("episodeImg");
String title = episode.getString("episodeTitle");
String studio = episode.getString("episodeShow");
mediaList.add(buildMediaInfo(title, studio, subTitle, videoUrl, imageurl,
bigImageurl));
}
}
// JSONArray categories = jsonObj.getJSONArray(TAG_CATEGORIES);
// if (null != categories) {
// for (int i = 0; i < categories.length(); i++) {
// JSONObject category = categories.getJSONObject(i);
// category.getString(TAG_NAME);
// JSONArray videos = category.getJSONArray(getJsonMediaTag());
// if (null != videos) {
// for (int j = 0; j < videos.length(); j++) {
// JSONObject video = videos.getJSONObject(j);
// String subTitle = video.getString(TAG_SUBTITLE);
// JSONArray videoUrls = video.getJSONArray(TAG_SOURCES);
// if (null == videoUrls || videoUrls.length() == 0) {
// continue;
// }
// String videoUrl = videoUrls.getString(0);
// String imageurl = getThumbPrefix() + video.getString(TAG_THUMB);
// String bigImageurl = getThumbPrefix() + video.getString(TAG_IMG_780_1200);
// String title = video.getString(TAG_TITLE);
// String studio = video.getString(TAG_STUDIO);
// mediaList.add(buildMediaInfo(title, studio, subTitle, videoUrl, imageurl,
// bigImageurl));
// }
// }
// }
// }
Collections.reverse(mediaList);
return mediaList;
}
private static MediaInfo buildMediaInfo(String title,
String subTitle, String studio, String url, String imgUrl, String bigImageUrl) {
MediaMetadata movieMetadata = new MediaMetadata(MediaMetadata.MEDIA_TYPE_MOVIE);
movieMetadata.putString(MediaMetadata.KEY_SUBTITLE, subTitle);
movieMetadata.putString(MediaMetadata.KEY_TITLE, title);
movieMetadata.putString(MediaMetadata.KEY_STUDIO, studio);
movieMetadata.addImage(new WebImage(Uri.parse(imgUrl)));
movieMetadata.addImage(new WebImage(Uri.parse(bigImageUrl)));
return new MediaInfo.Builder(url)
.setStreamType(MediaInfo.STREAM_TYPE_BUFFERED)
.setContentType(getMediaType())
.setMetadata(movieMetadata)
.build();
}
private static String getMediaType() {
return "video/mp4";
}
private static String getJsonMediaTag() {
return TAG_MEDIA;
}
private static String getThumbPrefix() {
return THUMB_PREFIX_URL;
}
}
| 40.247059 | 124 | 0.607717 |
e864edccc6191dccffc5fd2b73a1438ddf0c84d6 | 671 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
package net.dot;
import android.app.AlertDialog;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("Use `adb shell am instrument -w " + getApplicationContext().getPackageName() + "net.dot.MonoRunner` to run the tests.");
dlgAlert.create().show();
}
}
| 30.5 | 149 | 0.725782 |
1639d7b41832d1a578d0e4c648bc7f2705eaf311 | 220 | package com.kk.api.service;
import com.kk.api.entity.ClazzStudent;
import com.kk.api.core.service.Service;
/**
* @author kk
* @date 2021/05/02
*/
public interface ClazzStudentService extends Service<ClazzStudent> {
}
| 16.923077 | 68 | 0.754545 |
a87a06dcdabc5fc9755e37c92b82025f15659d06 | 2,027 | /*
* Copyright 1&1 Internet AG, https://github.com/1and1/
*
* 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 net.oneandone.lavender.index;
import net.oneandone.sushi.fs.MkfileException;
import net.oneandone.sushi.fs.file.FileNode;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Util {
private static final MessageDigest DIGEST;
static {
try {
DIGEST = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e.getMessage());
}
}
public static synchronized byte[] md5(byte... data) {
return md5(data, data.length);
}
public static synchronized byte[] md5(byte[] data, int count) {
DIGEST.update(data, 0, count);
return DIGEST.digest();
}
//--
private static int tmpNo = 1;
// Java's tmp file mechanism is allowed to create files with rw- --- --- permission.
// Use this method if you want tmp files created with regular user permissions.
public static FileNode newTmpFile(FileNode parent) {
FileNode file;
while (true) {
file = parent.join("_tmp_" + tmpNo);
try {
file.mkfile();
file.getWorld().onShutdown().deleteAtExit(file);
return file;
} catch (MkfileException e) {
// continue
tmpNo++;
}
}
}
private Util() {
}
}
| 28.957143 | 88 | 0.633942 |
7c6e765b18eb86dc64615ba93fe820e3890fa647 | 542 | package app.service.bags;
import java.util.List;
import org.springframework.stereotype.Service;
import app.dto.BagDto;
import app.model.Bag;
import app.model.User;
@Service
public interface BagsService {
public List<Bag> getAllBagsByColour(String colour);
public List<Bag> getAllBagInStock();
public List<Bag> getAllBagsByBrand(String brandName);
public List<Bag> getAllBagsByDescription(String description);
public Bag saveBag(Bag b);
public void deleteBag(String uuid);
public void updateBag(BagDto dto, String uuid);
}
| 18.689655 | 62 | 0.780443 |
07090f9f0467fc0445b786c1702efb67a23cb5ef | 443 | package com.ewem.generator.mapper;
import com.ewem.common.core.mybatisplus.BaseMapperPlus;
import com.ewem.generator.domain.GenTableColumn;
import java.util.List;
/**
* 业务据层
*
* @author ewem
*/
public interface GenTableColumnMapper extends BaseMapperPlus<GenTableColumn> {
/**
* 根据表名称查询列信息
*
* @param tableName 表名称
* @return 列信息
*/
List<GenTableColumn> selectDbTableColumnsByName(String tableName);
}
| 18.458333 | 78 | 0.713318 |
dfe479c5afb460886fd39a21c8e0138496117a71 | 1,831 | /*
* 2007-2016 [PagSeguro Internet Ltda.]
*
* NOTICE OF LICENSE
*
* 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.
*
* Copyright: 2007-2016 PagSeguro Internet Ltda.
* Licence: http://www.apache.org/licenses/LICENSE-2.0
*/
package br.com.uol.pagseguro.api.common.domain.builder;
import br.com.uol.pagseguro.api.common.domain.Bank;
import br.com.uol.pagseguro.api.common.domain.BankName;
import br.com.uol.pagseguro.api.utils.Builder;
/**
* Builder for Bank
*
* @author PagSeguro Internet Ltda.
*/
public final class BankBuilder implements Builder<Bank> {
private BankName name;
/**
* Set name of bank
*
* @param name Name of bank
* @return Builder for Bank
* @see Bank#getBankName()
*/
public BankBuilder withName(BankName.Name name) {
this.name = new BankName(name);
return this;
}
/**
* Build the Bank
*
* @return Interface for bank
* @see Bank
*/
@Override
public Bank build() {
return new SimpleBank(this);
}
/**
* Implementation of {@code Bank}
*/
private static class SimpleBank implements Bank {
private final BankBuilder bankBuilder;
public SimpleBank(BankBuilder bankBuilder) {
this.bankBuilder = bankBuilder;
}
@Override
public BankName getBankName() {
return bankBuilder.name;
}
}
}
| 23.779221 | 75 | 0.691972 |
bbc6e6dde1a06d24890fbee15f8de75720002837 | 1,698 | package com.baerdev.ad.SW04_2.BucketHashSet;
import java.util.Iterator;
public class SingleLinkedList<T> implements Iterable<T> {
private Node start;
private int size = 0;
public void add(T value) {
if (start == null) {
start = new Node(value);
} else {
Node node = new Node(value);
node.setNext(start);
start = node;
}
size++;
}
public boolean contains(T value) {
if (start == null) {
return false;
}
Node tmp = start;
do {
if (tmp.getValue().equals(value)) {
return true;
}
tmp = tmp.getNext();
} while (tmp != null);
return false;
}
public int getSize() {
return size;
}
public boolean remove(T value) {
Node tmp = start;
Node last = null;
do {
if (tmp.getValue().equals(value)) {
if (last == null) {
start = tmp.getNext();
} else {
last.setNext(tmp.getNext());
}
tmp.setNext(null);
size--;
return true;
} else {
last = tmp;
}
tmp = tmp.getNext();
} while (tmp != null);
return false;
}
@Override
public Iterator<T> iterator() {
return null; //todo: add singlelinedlistiterator
}
} | 26.123077 | 61 | 0.393404 |
8514ae9b815853fb0d49772f0079fa11078281a5 | 722 | package de.thoughtgang.cloud;
import de.thoughtgang.cloud.customer.Customer;
import io.vertx.core.http.HttpServerRequest;
import org.jboss.logging.Logger;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/customer")
public class WebServiceCustomerResource {
private static final Logger LOG = Logger.getLogger(WebServiceCustomerResource.class);
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
public String submit(Customer customer) {
customer.toString();
LOG.info(customer + " ------ CUSTOMER xxxx-----> ");
return "Hello Customer!";
}
}
| 24.896552 | 89 | 0.725762 |
5a3e65ce93d54ff93d2d9bb1815f6f088d045b18 | 254 | /**
* Copyright (c) 2019 Yodlee, Inc. All Rights Reserved.
*
* Licensed under the MIT License. See LICENSE file in the project root for license information.
*/
package com.yodlee.api.model.documents.enums;
public enum DocType {
STMT, TAX, EBILL
}
| 21.166667 | 96 | 0.724409 |
736e5a9506c4b3c9cbb502e8c8b67373ba4602fb | 1,540 | package com.google.sps.servlets;
import com.google.sps.data.BigFootSighting;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Scanner;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/** Returns UFO data as a JSON array, e.g. [{"lat": 38.4404675, "lng": -122.7144313}] */
@WebServlet("/bf-data")
public class BigFootServlet extends HttpServlet {
private Collection<BigFootSighting> bfSightings;
@Override
public void init() {
bfSightings = new ArrayList<>();
Scanner scanner = new Scanner(getServletContext().getResourceAsStream("/WEB-INF/bf-data.csv"));
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] cells = line.split(",");
// check that we are past the first row
if(!cells[4].equals("latitude")){
double lat = Double.parseDouble(cells[cells.length - 2]);
double lng = Double.parseDouble(cells[cells.length - 1]);
bfSightings.add(new BigFootSighting(lat, lng));
}
}
scanner.close();
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("application/json");
Gson gson = new Gson();
String json = gson.toJson(bfSightings);
response.getWriter().println(json);
}
} | 32.083333 | 99 | 0.69026 |
8112612917157cca90f42a8f1b56d0694d0df81f | 1,399 | package fi.fmi.avi.converter.tac.lexer;
import java.util.List;
import java.util.Optional;
/**
* Used for constructing {@link LexemeSequence}s one or more {@link Lexeme} at a time.
*
* An instance of this class can be created using {@link LexingFactory#createLexemeSequenceBuilder()}.
*
* @author Ilkka Rinne / Spatineo 2017
*/
public interface LexemeSequenceBuilder {
/**
* Adds one {@link Lexeme} as the last one in the constructed sequence.
*
* @param lexeme
* to add
*
* @return the builder
*/
LexemeSequenceBuilder append(Lexeme lexeme);
/**
* Adds all the {@link Lexeme} contained in <code>lexemes</code> to the end
* of the constructed sequence in the given order.
*
* @param lexemes
* to add
*
* @return the builder
*/
LexemeSequenceBuilder appendAll(List<Lexeme> lexemes);
/**
* Removes the last Lexeme appended if one exists.
*
* @return the builder
*/
LexemeSequenceBuilder removeLast();
/**
* Returns the last lexeme in the sequence to build if one exists.
*
* @return the last lexeme in the sequence to build if one exists
*/
Optional<Lexeme> getLast();
boolean isEmpty();
/**
* Returns the complete {@link LexemeSequence}.
*
* @return the sequence
*/
LexemeSequence build();
}
| 23.711864 | 102 | 0.624017 |
493de5447a07573e1ca46dd213df4340b90e3cbd | 11,184 | package cc.duduhuo.simpler.base;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadSampleListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.umeng.analytics.MobclickAgent;
import java.io.File;
import java.util.ArrayList;
import cc.duduhuo.applicationtoast.AppToast;
import cc.duduhuo.simpler.config.BaseConfig;
import cc.duduhuo.simpler.config.BaseSettings;
import cc.duduhuo.simpler.config.Constants;
import cc.duduhuo.simpler.util.AccessTokenKeeper;
import cc.duduhuo.simpler.util.AccountUtil;
import cc.duduhuo.simpler.util.FileUtils;
import cc.duduhuo.simpler.util.PrefsUtils;
import cc.duduhuo.simpler.util.SettingsUtil;
/**
* =======================================================
* 作者:liying - [email protected]
* 日期:2017/3/2 23:17
* 版本:1.0
* 描述:
* 备注:
* =======================================================
*/
public class BaseActivity extends AppCompatActivity {
private static final String TAG = "BaseActivity";
/** 存储所有Activity中的异步任务,便于统一删除 */
private Multimap<Class<? extends BaseActivity>, AsyncTask> mTasks = ArrayListMultimap.create();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 初始化重要数据
if ("".equals(BaseConfig.sUid)) {
BaseConfig.sUid = PrefsUtils.getString(Constants.PREFS_CUR_UID, "");
}
BaseConfig.sSDCardExist = FileUtils.hasStorage();
BaseConfig.sAccount = AccountUtil.readAccount(BaseConfig.sUid, false);
BaseSettings.sSettings = SettingsUtil.readSettings(BaseConfig.sUid, false);
if (BaseConfig.sAccessToken == null) {
BaseConfig.sAccessToken = AccessTokenKeeper.readAccessToken(BaseConfig.sUid, false);
}
}
@Override
protected void onPause() {
super.onPause();
MobclickAgent.onPause(this);
}
@Override
protected void onResume() {
super.onResume();
MobclickAgent.onResume(this);
}
/**
* 创建一个下载任务
*
* @param url 下载地址
* @param path 下载路径(含文件名)
* @return
*/
protected BaseDownloadTask createDownloadTask(String url, String path, final TextView textView, final boolean share) {
return FileDownloader.getImpl().create(url)
.setPath(path, false)
.setCallbackProgressTimes(300)
.setMinIntervalUpdateSpeed(400)
.setListener(new FileDownloadSampleListener() {
@Override
protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
super.pending(task, soFarBytes, totalBytes);
if (textView != null) {
textView.setText("等待下载");
}
AppToast.showToast("等待下载");
}
@Override
protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
super.progress(task, soFarBytes, totalBytes);
int rate = soFarBytes * 100 / totalBytes;
if (textView != null) {
textView.setText("已下载 " + rate + "%");
}
}
@Override
protected void error(BaseDownloadTask task, Throwable e) {
super.error(task, e);
if (textView != null) {
textView.setText("下载失败");
}
AppToast.showToast("下载失败:" + e.getMessage());
}
@Override
protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
super.connected(task, etag, isContinue, soFarBytes, totalBytes);
}
@Override
protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
super.paused(task, soFarBytes, totalBytes);
if (textView != null) {
textView.setText("已暂停");
}
AppToast.showToast("已暂停");
}
@Override
protected void completed(BaseDownloadTask task) {
super.completed(task);
if (textView != null) {
textView.setText("下载完成");
}
if (share) {
// 分享图片
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(task.getTargetFilePath())));
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "分享图片到"));
} else {
AppToast.showToast(task.getFilename() + " 下载完成");
}
}
@Override
protected void warn(BaseDownloadTask task) {
super.warn(task);
if (textView != null) {
textView.setText("任务重复");
}
AppToast.showToast("任务重复");
}
@Override
protected void started(BaseDownloadTask task) {
super.started(task);
if (textView != null) {
textView.setText("开始下载");
}
AppToast.showToast("开始下载");
}
});
}
/**
* 创建一个下载任务
*
* @param url 下载地址
* @param path 下载路径(含文件名)
* @return
*/
protected BaseDownloadTask createAPKDownloadTask(String url, String path, final TextView tvProgress,
final ProgressBar pb, final AlertDialog dialog) {
return FileDownloader.getImpl().create(url)
.setPath(path, false)
.setCallbackProgressTimes(300)
.setMinIntervalUpdateSpeed(400)
.setListener(new FileDownloadSampleListener() {
@Override
protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
super.pending(task, soFarBytes, totalBytes);
if (tvProgress != null) {
tvProgress.setText("等待");
}
}
@Override
protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
super.progress(task, soFarBytes, totalBytes);
int rate = soFarBytes * 100 / totalBytes;
if (tvProgress != null) {
tvProgress.setText(rate + "%");
}
if (pb != null) {
pb.setProgress(rate);
}
}
@Override
protected void error(BaseDownloadTask task, Throwable e) {
super.error(task, e);
if (tvProgress != null) {
tvProgress.setText("失败");
}
AppToast.showToast("下载失败:" + e.getMessage());
}
@Override
protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
super.connected(task, etag, isContinue, soFarBytes, totalBytes);
}
@Override
protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
super.paused(task, soFarBytes, totalBytes);
if (tvProgress != null) {
tvProgress.setText("已暂停");
}
}
@Override
protected void completed(BaseDownloadTask task) {
super.completed(task);
if (dialog != null) {
dialog.dismiss();
}
// 下载完成,开始安装
Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
intent.addCategory("android.intent.category.DEFAULT");
intent.setDataAndType(Uri.fromFile(new File(task.getTargetFilePath())),
"application/vnd.android.package-archive");
startActivity(intent);
}
@Override
protected void warn(BaseDownloadTask task) {
super.warn(task);
AppToast.showToast("任务重复");
}
@Override
protected void started(BaseDownloadTask task) {
super.started(task);
if (tvProgress != null) {
tvProgress.setText("开始");
}
}
});
}
/**
* 注册任务
*
* @param clazz Activity Class
* @param task AsyncTask对象
*/
public void registerAsyncTask(Class<? extends BaseActivity> clazz, AsyncTask task) {
boolean b = mTasks.put(clazz, task);
if (!b) {
Log.e(TAG, "任务注册异常");
}
}
/**
* 如果任务未执行完毕,则取消任务
*
* @param clazz Activity Class
*/
public void unregisterAsyncTask(Class<? extends BaseActivity> clazz) {
ArrayList<AsyncTask> tasks = new ArrayList<>(mTasks.removeAll(clazz));
int size = tasks.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
AsyncTask task = tasks.get(i);
//you may call the cancel() method but if it is not handled in doInBackground() method
if (task != null && task.getStatus() != AsyncTask.Status.FINISHED) {
task.cancel(true);
}
}
}
}
}
| 38.833333 | 134 | 0.494814 |
275dde5f219fb815a785155a901cadce144c1568 | 477 | package com.gpms20201.brasilemchamas.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/mq")
public class MapaQueimadasController {
@RequestMapping(value = { "", "/index" })
public String index(Model modelo) {
modelo.addAttribute("titulo", "Mapa das Queimadas");
return "mapaQueimadas/mapa.html";
}
}
| 23.85 | 62 | 0.740042 |
90b15b73c0ca35288548041fa9aa2af465343653 | 1,837 | package com.example.oasis_hackathon_app.methods.message.request;
import com.example.oasis_hackathon_app.methods.Query_manager;
import com.example.oasis_hackathon_app.methods.message.model.Message;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.IOException;
import java.util.ArrayList;
public class GetMessage {
Query_manager query_manager;
int message_group_id;
ArrayList<Message> result_list;
String get_articles_url = "http://52.79.54.196:2500/message/get_messages";
Request_Thread request_thread;
String new_get_articles_url;
public GetMessage(int message_group_id) {
this.message_group_id = message_group_id;
request_thread = new Request_Thread();
query_manager = new Query_manager();
}
public ArrayList<Message> query() {
result_list = new ArrayList<Message>();
new_get_articles_url = get_articles_url + "?group_id=" + Integer.toString(message_group_id);
request_thread.start();
try {
request_thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
return result_list;
}
private class Request_Thread extends Thread {
public void run() {
JSONArray result;
try {
result = query_manager.request_arr(new_get_articles_url, "GET", null);
for (int i = 0; i < result.length(); i++) {
result_list.add(new Message(result.getJSONObject(i)));
}
} catch (IOException | JSONException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
}
}
| 28.703125 | 100 | 0.63092 |
ffc49866e60b5fb0816144ed1d71a9a3f70861f7 | 16,785 | /*-
* ---license-start
* EU Digital Green Certificate Gateway Service / dgc-lib
* ---
* Copyright (C) 2021 T-Systems International GmbH and all other contributors
* ---
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ---license-end
*/
package eu.europa.ec.dgc.gateway.connector;
import eu.europa.ec.dgc.gateway.connector.client.DgcGatewayConnectorRestClient;
import eu.europa.ec.dgc.signing.SignedCertificateMessageParser;
import eu.europa.ec.dgc.testdata.CertificateTestUtils;
import eu.europa.ec.dgc.testdata.DgcTestKeyStore;
import eu.europa.ec.dgc.utils.CertificateUtils;
import feign.FeignException;
import feign.Request;
import feign.RequestTemplate;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStoreException;
import java.security.PrivateKey;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.cert.X509CertificateHolder;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@SpringBootTest
@Slf4j
class UploadConnectorTest {
@MockBean
DgcGatewayConnectorRestClient restClientMock;
@Autowired
DgcGatewayUploadConnector connector;
@Autowired
CertificateUtils certificateUtils;
@Autowired
DgcTestKeyStore testKeyStore;
@Test
void testDownloadOfCertificates() throws Exception {
KeyPair keyPair = KeyPairGenerator.getInstance("ec").generateKeyPair();
X509Certificate dsc = CertificateTestUtils.generateCertificate(keyPair, "EU", "DSC");
ArgumentCaptor<String> argumentCaptor = ArgumentCaptor.forClass(String.class);
when(restClientMock.uploadSignerInformation(argumentCaptor.capture()))
.thenReturn(ResponseEntity.status(HttpStatus.CREATED).build());
connector.uploadTrustedCertificate(dsc);
verify(restClientMock).uploadSignerInformation(any());
SignedCertificateMessageParser parser = new SignedCertificateMessageParser(argumentCaptor.getValue());
Assertions.assertEquals(certificateUtils.convertCertificate(dsc), parser.getPayload());
Assertions.assertEquals(certificateUtils.convertCertificate(testKeyStore.getUpload()), parser.getSigningCertificate());
}
@Test
void testDownloadOfCertificatesHolder() throws Exception {
KeyPair keyPair = KeyPairGenerator.getInstance("ec").generateKeyPair();
X509CertificateHolder dsc = certificateUtils.convertCertificate(
CertificateTestUtils.generateCertificate(keyPair, "EU", "DSC"));
ArgumentCaptor<String> argumentCaptor = ArgumentCaptor.forClass(String.class);
when(restClientMock.uploadSignerInformation(argumentCaptor.capture()))
.thenReturn(ResponseEntity.status(HttpStatus.CREATED).build());
connector.uploadTrustedCertificate(dsc);
verify(restClientMock).uploadSignerInformation(any());
SignedCertificateMessageParser parser = new SignedCertificateMessageParser(argumentCaptor.getValue());
Assertions.assertEquals(dsc, parser.getPayload());
Assertions.assertEquals(certificateUtils.convertCertificate(testKeyStore.getUpload()), parser.getSigningCertificate());
}
@Test
void testDeleteCertificates() throws Exception {
KeyPair keyPair = KeyPairGenerator.getInstance("ec").generateKeyPair();
X509Certificate dsc = CertificateTestUtils.generateCertificate(keyPair, "EU", "DSC");
ArgumentCaptor<String> argumentCaptor = ArgumentCaptor.forClass(String.class);
when(restClientMock.deleteSignerInformation(argumentCaptor.capture()))
.thenReturn(ResponseEntity.status(HttpStatus.NO_CONTENT).build());
connector.deleteTrustedCertificate(dsc);
verify(restClientMock).deleteSignerInformation(any());
SignedCertificateMessageParser parser = new SignedCertificateMessageParser(argumentCaptor.getValue());
Assertions.assertEquals(certificateUtils.convertCertificate(dsc), parser.getPayload());
Assertions.assertEquals(certificateUtils.convertCertificate(testKeyStore.getUpload()), parser.getSigningCertificate());
}
@Test
void testDeleteCertificatesHolder() throws Exception {
KeyPair keyPair = KeyPairGenerator.getInstance("ec").generateKeyPair();
X509CertificateHolder dsc = certificateUtils.convertCertificate(
CertificateTestUtils.generateCertificate(keyPair, "EU", "DSC"));
ArgumentCaptor<String> argumentCaptor = ArgumentCaptor.forClass(String.class);
when(restClientMock.deleteSignerInformation(argumentCaptor.capture()))
.thenReturn(ResponseEntity.status(HttpStatus.NO_CONTENT).build());
connector.deleteTrustedCertificate(dsc);
verify(restClientMock).deleteSignerInformation(any());
SignedCertificateMessageParser parser = new SignedCertificateMessageParser(argumentCaptor.getValue());
Assertions.assertEquals(dsc, parser.getPayload());
Assertions.assertEquals(certificateUtils.convertCertificate(testKeyStore.getUpload()), parser.getSigningCertificate());
}
@Test
void initShouldFailWithoutCertificates() {
X509Certificate uploadCertBackup = testKeyStore.getUpload();
testKeyStore.setUpload(null);
Assertions.assertThrows(KeyStoreException.class, connector::init);
testKeyStore.setUpload(uploadCertBackup);
PrivateKey uploadPrivateKeyBackup = testKeyStore.getUploadPrivateKey();
testKeyStore.setUploadPrivateKey(null);
Assertions.assertThrows(KeyStoreException.class, connector::init);
testKeyStore.setUploadPrivateKey(uploadPrivateKeyBackup);
Assertions.assertDoesNotThrow(connector::init);
}
@Test
void shouldThrowAnExceptionWhenCertConversionFailed() throws CertificateEncodingException {
X509Certificate certificateMock = mock(X509Certificate.class);
doThrow(new CertificateEncodingException()).when(certificateMock).getEncoded();
Assertions.assertThrows(DgcGatewayUploadConnector.DgcCertificateUploadException.class,
() -> connector.uploadTrustedCertificate(certificateMock));
}
@Test
void shouldThrowAnExceptionWhenCertConversionFailedAtDelete() throws CertificateEncodingException {
X509Certificate certificateMock = mock(X509Certificate.class);
doThrow(new CertificateEncodingException()).when(certificateMock).getEncoded();
Assertions.assertThrows(DgcGatewayUploadConnector.DgcCertificateUploadException.class,
() -> connector.deleteTrustedCertificate(certificateMock));
}
@Test
void shouldThrowAnExceptionWhenUploadRequestFailed() {
X509CertificateHolder certificateMock = mock(X509CertificateHolder.class);
String problemReport = "{" +
"\"code\": \"0x500\"," +
"\"problem\": \"problem\"," +
"\"sendValue\": \"val\"," +
"\"details\": \"details\"" +
"}";
doThrow(new FeignException.BadRequest("", dummyRequest(), problemReport.getBytes(StandardCharsets.UTF_8), null))
.when(restClientMock).uploadSignerInformation(any());
DgcGatewayUploadConnector.DgcCertificateUploadException e =
Assertions.assertThrows(DgcGatewayUploadConnector.DgcCertificateUploadException.class,
() -> connector.uploadTrustedCertificate(certificateMock));
Assertions.assertEquals(DgcGatewayUploadConnector.DgcCertificateUploadException.Reason.UNKNOWN_ERROR, e.getReason());
}
@Test
void shouldThrowAnExceptionWhenUploadRequestFailedWithBadJson() {
X509CertificateHolder certificateMock = mock(X509CertificateHolder.class);
String problemReport = "{" +
"code: \"0x500\"," +
"problem: \"problem\"," +
"sendValue: \"val\"," +
"details: \"details\"" +
"}";
doThrow(new FeignException.BadRequest("", dummyRequest(), problemReport.getBytes(StandardCharsets.UTF_8), null))
.when(restClientMock).uploadSignerInformation(any());
DgcGatewayUploadConnector.DgcCertificateUploadException e =
Assertions.assertThrows(DgcGatewayUploadConnector.DgcCertificateUploadException.class,
() -> connector.uploadTrustedCertificate(certificateMock));
Assertions.assertEquals(DgcGatewayUploadConnector.DgcCertificateUploadException.Reason.UNKNOWN_ERROR, e.getReason());
}
@Test
void shouldThrowAnExceptionWhenUploadRequestGetsInternalServerError() {
X509CertificateHolder certificateMock = mock(X509CertificateHolder.class);
doThrow(new FeignException.InternalServerError("", dummyRequest(), null, null))
.when(restClientMock).uploadSignerInformation(any());
DgcGatewayUploadConnector.DgcCertificateUploadException e =
Assertions.assertThrows(DgcGatewayUploadConnector.DgcCertificateUploadException.class,
() -> connector.uploadTrustedCertificate(certificateMock));
Assertions.assertEquals(DgcGatewayUploadConnector.DgcCertificateUploadException.Reason.SERVER_ERROR, e.getReason());
}
@Test
void shouldThrowAnExceptionWhenUploadRequestGetsUnauthorizedError() {
X509CertificateHolder certificateMock = mock(X509CertificateHolder.class);
doThrow(new FeignException.Unauthorized("", dummyRequest(), null, null))
.when(restClientMock).uploadSignerInformation(any());
DgcGatewayUploadConnector.DgcCertificateUploadException e =
Assertions.assertThrows(DgcGatewayUploadConnector.DgcCertificateUploadException.class,
() -> connector.uploadTrustedCertificate(certificateMock));
Assertions.assertEquals(DgcGatewayUploadConnector.DgcCertificateUploadException.Reason.INVALID_AUTHORIZATION, e.getReason());
}
@Test
void shouldThrowAnExceptionWhenUploadRequestGetsForbiddenError() {
X509CertificateHolder certificateMock = mock(X509CertificateHolder.class);
doThrow(new FeignException.Forbidden("", dummyRequest(), null, null))
.when(restClientMock).uploadSignerInformation(any());
DgcGatewayUploadConnector.DgcCertificateUploadException e =
Assertions.assertThrows(DgcGatewayUploadConnector.DgcCertificateUploadException.class,
() -> connector.uploadTrustedCertificate(certificateMock));
Assertions.assertEquals(DgcGatewayUploadConnector.DgcCertificateUploadException.Reason.INVALID_AUTHORIZATION, e.getReason());
}
@Test
void shouldNotThrowAnExceptionWhenUploadRequestGetsConflictError() {
X509CertificateHolder certificateMock = mock(X509CertificateHolder.class);
doThrow(new FeignException.Conflict("", dummyRequest(), null, null))
.when(restClientMock).uploadSignerInformation(any());
Assertions.assertDoesNotThrow(() -> connector.uploadTrustedCertificate(certificateMock));
}
@Test
void shouldThrowAnExceptionWhenDeleteRequestFailed() {
X509CertificateHolder certificateMock = mock(X509CertificateHolder.class);
String problemReport = "{" +
"\"code\": \"0x500\"," +
"\"problem\": \"problem\"," +
"\"sendValue\": \"val\"," +
"\"details\": \"details\"" +
"}";
doThrow(new FeignException.BadRequest("", dummyRequest(), problemReport.getBytes(StandardCharsets.UTF_8), null))
.when(restClientMock).deleteSignerInformation(any());
DgcGatewayUploadConnector.DgcCertificateUploadException e =
Assertions.assertThrows(DgcGatewayUploadConnector.DgcCertificateUploadException.class,
() -> connector.deleteTrustedCertificate(certificateMock));
Assertions.assertEquals(DgcGatewayUploadConnector.DgcCertificateUploadException.Reason.UNKNOWN_ERROR, e.getReason());
}
@Test
void shouldThrowAnExceptionWhenDeleteRequestFailedWithBadJson() {
X509CertificateHolder certificateMock = mock(X509CertificateHolder.class);
String problemReport = "{" +
"code: \"0x500\"," +
"problem: \"problem\"," +
"sendValue: \"val\"," +
"details: \"details\"" +
"}";
doThrow(new FeignException.BadRequest("", dummyRequest(), problemReport.getBytes(StandardCharsets.UTF_8), null))
.when(restClientMock).deleteSignerInformation(any());
DgcGatewayUploadConnector.DgcCertificateUploadException e =
Assertions.assertThrows(DgcGatewayUploadConnector.DgcCertificateUploadException.class,
() -> connector.deleteTrustedCertificate(certificateMock));
Assertions.assertEquals(DgcGatewayUploadConnector.DgcCertificateUploadException.Reason.UNKNOWN_ERROR, e.getReason());
}
@Test
void shouldThrowAnExceptionWhenDeleteRequestGetsInternalServerError() {
X509CertificateHolder certificateMock = mock(X509CertificateHolder.class);
doThrow(new FeignException.InternalServerError("", dummyRequest(), null, null))
.when(restClientMock).deleteSignerInformation(any());
DgcGatewayUploadConnector.DgcCertificateUploadException e =
Assertions.assertThrows(DgcGatewayUploadConnector.DgcCertificateUploadException.class,
() -> connector.deleteTrustedCertificate(certificateMock));
Assertions.assertEquals(DgcGatewayUploadConnector.DgcCertificateUploadException.Reason.SERVER_ERROR, e.getReason());
}
@Test
void shouldThrowAnExceptionWhenDeleteRequestGetsUnauthorizedError() {
X509CertificateHolder certificateMock = mock(X509CertificateHolder.class);
doThrow(new FeignException.Unauthorized("", dummyRequest(), null, null))
.when(restClientMock).deleteSignerInformation(any());
DgcGatewayUploadConnector.DgcCertificateUploadException e =
Assertions.assertThrows(DgcGatewayUploadConnector.DgcCertificateUploadException.class,
() -> connector.deleteTrustedCertificate(certificateMock));
Assertions.assertEquals(DgcGatewayUploadConnector.DgcCertificateUploadException.Reason.INVALID_AUTHORIZATION, e.getReason());
}
@Test
void shouldThrowAnExceptionWhenDeleteRequestGetsForbiddenError() {
X509CertificateHolder certificateMock = mock(X509CertificateHolder.class);
doThrow(new FeignException.Forbidden("", dummyRequest(), null, null))
.when(restClientMock).deleteSignerInformation(any());
DgcGatewayUploadConnector.DgcCertificateUploadException e =
Assertions.assertThrows(DgcGatewayUploadConnector.DgcCertificateUploadException.class,
() -> connector.deleteTrustedCertificate(certificateMock));
Assertions.assertEquals(DgcGatewayUploadConnector.DgcCertificateUploadException.Reason.INVALID_AUTHORIZATION, e.getReason());
}
@Test
void shouldNotThrowAnExceptionWhenDeleteRequestGetsNotFoundError() {
X509CertificateHolder certificateMock = mock(X509CertificateHolder.class);
doThrow(new FeignException.NotFound("", dummyRequest(), null, null))
.when(restClientMock).deleteSignerInformation(any());
Assertions.assertDoesNotThrow(() -> connector.deleteTrustedCertificate(certificateMock));
}
/**
* Method to create dummy request which is required to throw FeignExceptions.
*/
private Request dummyRequest() {
return Request.create(Request.HttpMethod.GET, "url", new HashMap<>(), null, new RequestTemplate());
}
}
| 43.597403 | 133 | 0.73804 |
922ada3f719620e669988a3c500e89493d72beef | 3,072 | /*
* MIT License
*
* Copyright (c) 2018-2021 Alexis Jehan
*
* 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.github.alexisjehan.javanilla.io.lines;
import com.github.alexisjehan.javanilla.io.chars.Readers;
import com.github.alexisjehan.javanilla.lang.array.ObjectArrays;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatNullPointerException;
/**
* <p>{@link CountLineReader} unit tests.</p>
*/
final class CountLineReaderTest {
private static final String[] LINES = ObjectArrays.of("abc", "def", "ghi");
@Test
void testConstructorInvalid() {
assertThatNullPointerException().isThrownBy(() -> new CountLineReader(null));
}
@Test
void testRead() throws IOException {
try (final var countLineReader = new CountLineReader(new LineReader(Readers.of(String.join("\n", LINES))))) {
assertThat(countLineReader.getCount()).isZero();
assertThat(countLineReader.read()).isEqualTo(LINES[0]);
assertThat(countLineReader.getCount()).isEqualTo(1L);
assertThat(countLineReader.read()).isEqualTo(LINES[1]);
assertThat(countLineReader.getCount()).isEqualTo(2L);
assertThat(countLineReader.read()).isEqualTo(LINES[2]);
assertThat(countLineReader.getCount()).isEqualTo(3L);
assertThat(countLineReader.read()).isNull();
assertThat(countLineReader.getCount()).isEqualTo(3L);
}
}
@Test
void testSkip() throws IOException {
try (final var countLineReader = new CountLineReader(new LineReader(Readers.of(String.join("\n", LINES))))) {
assertThat(countLineReader.getCount()).isZero();
assertThat(countLineReader.skip(-1L)).isZero();
assertThat(countLineReader.skip(0L)).isZero();
assertThat(countLineReader.getCount()).isZero();
assertThat(countLineReader.skip(2L)).isEqualTo(2L);
assertThat(countLineReader.getCount()).isEqualTo(2L);
assertThat(countLineReader.skip(2L)).isEqualTo(1L);
assertThat(countLineReader.getCount()).isEqualTo(3L);
}
}
} | 40.96 | 111 | 0.755534 |
cf5a397568641104fdc677291be1cbf51f7f2b10 | 2,438 | package com.example.codingtr.lolquery.Management;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import com.example.codingtr.lolquery.Activity.Login_Activity;
import com.example.codingtr.lolquery.Home_Activity;
import java.util.HashMap;
public class SessionManagement {
SharedPreferences sharedPreferences;
public SharedPreferences.Editor editor;
public Context context;
int PRIVATE_MODE = 0;
private static final String PREF_NAME = "LOGIN";
private static final String LOGIN = "IS_LOGIN";
public static final String NAME = "NAME";
public static final String EMAIL = "EMAIL";
public static final String ID = "ID";
public SessionManagement(Context context){
this.context = context;
sharedPreferences = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = sharedPreferences.edit();
}
public void createSession(String name, String email, String id){
editor.putBoolean(LOGIN, true);
editor.putString(NAME, name);
editor.putString(EMAIL, email);
editor.putString(ID, id);
editor.apply();
}
public boolean isLoggin(){
return sharedPreferences.getBoolean(LOGIN, false);
}
public void checkLogin(){
if(!this.isLoggin()){
Intent intent = new Intent(context, Login_Activity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
((Home_Activity) context).finish();
}
}
public HashMap<String, String> getUserDetail(){
HashMap<String, String> user = new HashMap<>();
user.put(NAME, sharedPreferences.getString(NAME, null));
user.put(EMAIL , sharedPreferences.getString(EMAIL, null));
user.put(ID, sharedPreferences.getString(ID, null));
return user;
}
public void logOut(){
editor.clear();
editor.commit();
Intent intent = new Intent(context, Login_Activity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
((Home_Activity) context).finish();
}
}
| 32.506667 | 126 | 0.686628 |
f71de337620914e4851eec2e6e1fb6fd352abe2c | 221 | package com.si.jupiter.smart.client.example;
import io.netty.util.concurrent.Future;
import org.apache.thrift.TException;
public interface SIface {
public Future<String> helloString(String para) throws TException;
} | 27.625 | 69 | 0.800905 |
79fb33ea0826ae8ec2f7aa60ce6d20371b78456a | 1,903 | package org.osio.hdd.istio.com;
//import io.fabric8.kubernetes.api.model.v3_1.Pod;
//import io.fabric8.kubernetes.api.model.v3_1.Service;
//import io.fabric8.kubernetes.api.model.v3_1.apiextensions.CustomResourceDefinition;
import io.fabric8.kubernetes.clnt.v3_1.Config;
import io.fabric8.kubernetes.clnt.v3_1.KubernetesClient;
//import me.snowdrop.istio.api.model.IstioResource;
import me.snowdrop.istio.client.IstioClient;
import me.snowdrop.istio.client.IstioClientFactory;
import java.io.InputStream;
import java.nio.file.*;
public class App
{
public static String readFileAsString(String fileName)throws Exception
{
String data = "";
data = new String(Files.readAllBytes(Paths.get(fileName)));
return data;
}
public static void main( String[] args )
{
Config istioConfig = new Config();
istioConfig.setApiVersion("config.istio.io/v1alpha2");
//istioConfig.setApiVersion("v1");
istioConfig.setMasterUrl("https://172.30.0.1");
istioConfig.setTrustCerts(true);
istioConfig.setOauthToken("vlJNtTSfowe9Y_m8O17f9z9y4jFB0Zbq-I9aQeiJAPo");
istioConfig.setNamespace("istio-system");
IstioClient istioClient = IstioClientFactory.defaultClient(istioConfig);
//KubernetesClient kubernetesClient = istioClient.getKubernetesClient();
/*for (Pod pod : istioClient.getKubernetesClient().pods().list().getItems()) {
System.out.println(pod.toString() + "\n\n\n");
}
for (Service service: kubernetesClient.services().list().getItems()) {
System.out.println(service.toString()+ "\n\n");
}*/
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream("metric.yaml");
try {
istioClient.registerCustomResources(is);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| 37.313725 | 86 | 0.72412 |
810b3f4334cc2aa9e9856730bd5214287888debf | 3,369 | package io.luna.game.model.chunk;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import io.luna.game.model.Entity;
import io.luna.game.model.EntityType;
import java.util.EnumMap;
import java.util.Map;
import java.util.Set;
/**
* A model containing entities and updates for those entities within a chunk.
*
* @author lare96 <http://github.com/lare96>
*/
public final class Chunk {
/**
* This chunk's position.
*/
private final ChunkPosition position;
/**
* A map of entities.
*/
private final ImmutableMap<EntityType, Set<Entity>> entities;
{
Map<EntityType, Set<Entity>> map = new EnumMap<>(EntityType.class);
for (EntityType type : EntityType.ALL) {
// Create concurrent sets for each entity type.
map.put(type, Sets.newConcurrentHashSet());
}
entities = Maps.immutableEnumMap(map);
}
/**
* Creates a new {@link ChunkPosition}.
*
* @param position The chunk position.
*/
Chunk(ChunkPosition position) {
this.position = position;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this).add("position", position).
add("entities", entities).toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof Chunk) {
Chunk other = (Chunk) obj;
return position.equals(other.position);
}
return false;
}
@Override
public int hashCode() {
return position.hashCode();
}
/**
* Adds an entity to this chunk.
*
* @param entity The entity to add.
* @return {@code true} if successful, {@code false} otherwise.
*/
public boolean add(Entity entity) {
return entities.get(entity.getType()).add(entity);
}
/**
* Removes an entity from this chunk.
*
* @param entity The entity to remove.
* @return {@code true} if successful, {@code false} otherwise.
*/
public boolean remove(Entity entity) {
return entities.get(entity.getType()).remove(entity);
}
/**
* Determines if this chunk contains an entity.
*
* @param entity The entity to determine for.
* @return {@code true} if this chunk contains the entity, {@code false} otherwise.
*/
public boolean contains(Entity entity) {
return entities.get(entity.getType()).contains(entity);
}
/**
* Returns a {@link Set} containing all entities of the specified type in this chunk. The cast type
* must match the argued type or a {@link ClassCastException} will be thrown.
*
* @param type The type of entities to get.
* @param <E> The type to cast to. Must be a subclass of Entity.
* @return A set of entities casted to {@code <E>}. As long as {@code <E>} matches {@code type}, no errors will
* be thrown.
*/
public <E extends Entity> Set<E> getAll(EntityType type) {
//noinspection unchecked
return (Set<E>) entities.get(type);
}
/**
* @return The position.
*/
public ChunkPosition getPosition() {
return position;
}
} | 27.614754 | 115 | 0.614426 |
8e892e0f7b229bc8d98c65aa2544652119ab6611 | 4,231 | /*
* Copyright (c) 2008, 2020, 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
*
* @summary converted from VM Testbase jit/deoptimization/test04.
* VM Testbase keywords: [jit, quick]
*
* @library /vmTestbase
* /test/lib
* @run main/othervm jit.deoptimization.test04.test04
*/
package jit.deoptimization.test04;
import nsk.share.TestFailure;
/*
*
*/
public class test04 {
public static void main (String[] args) {
A obj = new A();
int result = -1;
for (int index = 0; index < 1; index++) {
result += obj.used_alot();
}
if (result != 1) {
throw new TestFailure("result : " + result + " must equal 1");
}
}
}
class A {
protected int count;
public int foo(int index) {
int rv = ++count;
if (index < A.sIndex / 2)
rv = index;
else {
try {
rv = ((A)Class.forName("jit.deoptimization.test04.B").newInstance()).foo(index);
}
catch(Exception e) {
}
}
return rv;
}
public int used_alot() {
int result = 1;
for (int i = 0; i < A.sIndex; i++) {
result = foo(i);
}
return result;
}
protected static final int sIndex = 25000;
}
class B extends A {
public int foo(int index) {
int rv = 0;
int qrtr = A.sIndex / 4;
if (index > 3 * qrtr) {
try {
if (index < A.sIndex - qrtr)
rv = ((B)Class.forName("jit.deoptimization.test04.C").newInstance()).foo(index);
else
rv = ((B)Class.forName("jit.deoptimization.test04.D").newInstance()).foo(index);
}
catch(Exception e) {
}
}
else {
rv = 1;
}
return rv;
}
}
class C extends B {
public C () {
--this.count;
}
public int foo(int index) {
int j = count;
for (int i=0; i<500; i++)
j += used_alot();
return j;
}
public int used_alot() {
int i=1;
int j=4;
int k=i+j;
byte ba[] = new byte[1000];
int ia[] = new int[1000];
return this.count + (ba.length + i + j - k - ia.length);
}
protected int count = 1;
}
class D extends C {
public D () {
super();
this.count+=2;
}
public int foo(int index) {
return super.foo(index);
}
public synchronized int used_alot() {
count += (--count);
return 0;
}
}
| 28.782313 | 120 | 0.468684 |
1e72a6fed37dac3b684fd9dafde18114712339d6 | 80,778 | /*
* Copyright 2019 Web3 Labs LTD.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.web3j.protocol.core;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.junit.Test;
import org.web3j.protocol.ResponseTester;
import org.web3j.protocol.core.methods.response.AbiDefinition;
import org.web3j.protocol.core.methods.response.DbGetHex;
import org.web3j.protocol.core.methods.response.DbGetString;
import org.web3j.protocol.core.methods.response.DbPutHex;
import org.web3j.protocol.core.methods.response.DbPutString;
import org.web3j.protocol.core.methods.response.EthAccounts;
import org.web3j.protocol.core.methods.response.EthBlock;
import org.web3j.protocol.core.methods.response.EthBlockNumber;
import org.web3j.protocol.core.methods.response.EthCall;
import org.web3j.protocol.core.methods.response.EthCompileLLL;
import org.web3j.protocol.core.methods.response.EthCompileSerpent;
import org.web3j.protocol.core.methods.response.EthCompileSolidity;
import org.web3j.protocol.core.methods.response.EthEstimateGas;
import org.web3j.protocol.core.methods.response.EthFilter;
import org.web3j.protocol.core.methods.response.EthGasPrice;
import org.web3j.protocol.core.methods.response.EthGetBalance;
import org.web3j.protocol.core.methods.response.EthGetBlockTransactionCountByHash;
import org.web3j.protocol.core.methods.response.EthGetBlockTransactionCountByNumber;
import org.web3j.protocol.core.methods.response.EthGetCode;
import org.web3j.protocol.core.methods.response.EthGetCompilers;
import org.web3j.protocol.core.methods.response.EthGetStorageAt;
import org.web3j.protocol.core.methods.response.EthGetTransactionCount;
import org.web3j.protocol.core.methods.response.EthGetTransactionReceipt;
import org.web3j.protocol.core.methods.response.EthGetUncleCountByBlockHash;
import org.web3j.protocol.core.methods.response.EthGetUncleCountByBlockNumber;
import org.web3j.protocol.core.methods.response.EthGetWork;
import org.web3j.protocol.core.methods.response.EthHashrate;
import org.web3j.protocol.core.methods.response.EthLog;
import org.web3j.protocol.core.methods.response.EthMining;
import org.web3j.protocol.core.methods.response.EthProtocolVersion;
import org.web3j.protocol.core.methods.response.EthSendRawTransaction;
import org.web3j.protocol.core.methods.response.EthSendTransaction;
import org.web3j.protocol.core.methods.response.EthSign;
import org.web3j.protocol.core.methods.response.EthSubmitHashrate;
import org.web3j.protocol.core.methods.response.EthSubmitWork;
import org.web3j.protocol.core.methods.response.EthSyncing;
import org.web3j.protocol.core.methods.response.EthTransaction;
import org.web3j.protocol.core.methods.response.EthUninstallFilter;
import org.web3j.protocol.core.methods.response.Log;
import org.web3j.protocol.core.methods.response.NetListening;
import org.web3j.protocol.core.methods.response.NetPeerCount;
import org.web3j.protocol.core.methods.response.NetVersion;
import org.web3j.protocol.core.methods.response.ShhAddToGroup;
import org.web3j.protocol.core.methods.response.ShhHasIdentity;
import org.web3j.protocol.core.methods.response.ShhMessages;
import org.web3j.protocol.core.methods.response.ShhNewFilter;
import org.web3j.protocol.core.methods.response.ShhNewGroup;
import org.web3j.protocol.core.methods.response.ShhNewIdentity;
import org.web3j.protocol.core.methods.response.ShhPost;
import org.web3j.protocol.core.methods.response.ShhUninstallFilter;
import org.web3j.protocol.core.methods.response.ShhVersion;
import org.web3j.protocol.core.methods.response.Transaction;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.core.methods.response.Web3ClientVersion;
import org.web3j.protocol.core.methods.response.Web3Sha3;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
/** Core Protocol Response tests. */
public class ResponseTest extends ResponseTester {
@Test
public void testErrorResponse() {
buildResponse(
"{"
+ " \"jsonrpc\":\"2.0\","
+ " \"id\":1,"
+ " \"error\":{"
+ " \"code\":-32602,"
+ " \"message\":\"Invalid address length, expected 40 got 64 bytes\","
+ " \"data\":null"
+ " }"
+ "}");
EthBlock ethBlock = deserialiseResponse(EthBlock.class);
assertTrue(ethBlock.hasError());
assertThat(
ethBlock.getError(),
equalTo(
new Response.Error(
-32602, "Invalid address length, expected 40 got 64 bytes")));
}
@Test
public void testErrorResponseComplexData() {
buildResponse(
"{"
+ " \"jsonrpc\":\"2.0\","
+ " \"id\":1,"
+ " \"error\":{"
+ " \"code\":-32602,"
+ " \"message\":\"Invalid address length, expected 40 got 64 bytes\","
+ " \"data\":{\"foo\":\"bar\"}"
+ " }"
+ "}");
EthBlock ethBlock = deserialiseResponse(EthBlock.class);
assertTrue(ethBlock.hasError());
assertThat(ethBlock.getError().getData(), equalTo("{\"foo\":\"bar\"}"));
}
@Test
public void testWeb3ClientVersion() {
buildResponse(
"{\n"
+ " \"id\":67,\n"
+ " \"jsonrpc\":\"2.0\",\n"
+ " \"result\": \"Mist/v0.9.3/darwin/go1.4.1\"\n"
+ "}");
Web3ClientVersion web3ClientVersion = deserialiseResponse(Web3ClientVersion.class);
assertThat(web3ClientVersion.getWeb3ClientVersion(), is("Mist/v0.9.3/darwin/go1.4.1"));
}
@Test
public void testWeb3Sha3() throws IOException {
buildResponse(
"{\n"
+ " \"id\":64,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": "
+ "\"0x47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad\"\n"
+ "}");
Web3Sha3 web3Sha3 = deserialiseResponse(Web3Sha3.class);
assertThat(
web3Sha3.getResult(),
is("0x47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad"));
}
@Test
public void testNetVersion() throws IOException {
buildResponse(
"{\n"
+ " \"id\":67,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": \"59\"\n"
+ "}");
NetVersion netVersion = deserialiseResponse(NetVersion.class);
assertThat(netVersion.getNetVersion(), is("59"));
}
@Test
public void testNetListening() throws IOException {
buildResponse(
"{\n"
+ " \"id\":67,\n"
+ " \"jsonrpc\":\"2.0\",\n"
+ " \"result\":true\n"
+ "}");
NetListening netListening = deserialiseResponse(NetListening.class);
assertThat(netListening.isListening(), is(true));
}
@Test
public void testNetPeerCount() throws IOException {
buildResponse(
"{\n"
+ " \"id\":74,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": \"0x2\"\n"
+ "}");
NetPeerCount netPeerCount = deserialiseResponse(NetPeerCount.class);
assertThat(netPeerCount.getQuantity(), equalTo(BigInteger.valueOf(2L)));
}
@Test
public void testEthProtocolVersion() throws IOException {
buildResponse(
"{\n"
+ " \"id\":67,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": \"54\"\n"
+ "}");
EthProtocolVersion ethProtocolVersion = deserialiseResponse(EthProtocolVersion.class);
assertThat(ethProtocolVersion.getProtocolVersion(), is("54"));
}
@Test
public void testEthSyncingInProgress() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": {\n"
+ " \"startingBlock\": \"0x384\",\n"
+ " \"currentBlock\": \"0x386\",\n"
+ " \"highestBlock\": \"0x454\"\n"
+ " }\n"
+ "}");
// Response received from Geth node
// "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"currentBlock\":\"0x117a\",
// \"highestBlock\":\"0x21dab4\",\"knownStates\":\"0x0\",\"pulledStates\":\"0x0\",
// \"startingBlock\":\"0xa51\"}}"
EthSyncing ethSyncing = deserialiseResponse(EthSyncing.class);
assertThat(
ethSyncing.getResult(),
equalTo(new EthSyncing.Syncing("0x384", "0x386", "0x454", null, null)));
}
@Test
public void testEthSyncing() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": false\n"
+ "}");
EthSyncing ethSyncing = deserialiseResponse(EthSyncing.class);
assertThat(ethSyncing.isSyncing(), is(false));
}
@Test
public void testEthMining() {
buildResponse(
"{\n"
+ " \"id\":71,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": true\n"
+ "}");
EthMining ethMining = deserialiseResponse(EthMining.class);
assertThat(ethMining.isMining(), is(true));
}
@Test
public void testEthHashrate() {
buildResponse(
"{\n"
+ " \"id\":71,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": \"0x38a\"\n"
+ "}");
EthHashrate ethHashrate = deserialiseResponse(EthHashrate.class);
assertThat(ethHashrate.getHashrate(), equalTo(BigInteger.valueOf(906L)));
}
@Test
public void testEthGasPrice() {
buildResponse(
"{\n"
+ " \"id\":73,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": \"0x9184e72a000\"\n"
+ "}");
EthGasPrice ethGasPrice = deserialiseResponse(EthGasPrice.class);
assertThat(ethGasPrice.getGasPrice(), equalTo(BigInteger.valueOf(10000000000000L)));
}
@Test
public void testEthAccounts() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": [\"0x407d73d8a49eeb85d32cf465507dd71d507100c1\"]\n"
+ "}");
EthAccounts ethAccounts = deserialiseResponse(EthAccounts.class);
assertThat(
ethAccounts.getAccounts(),
equalTo(Arrays.asList("0x407d73d8a49eeb85d32cf465507dd71d507100c1")));
}
@Test
public void testEthBlockNumber() {
buildResponse(
"{\n"
+ " \"id\":83,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": \"0x4b7\"\n"
+ "}");
EthBlockNumber ethBlockNumber = deserialiseResponse(EthBlockNumber.class);
assertThat(ethBlockNumber.getBlockNumber(), equalTo(BigInteger.valueOf(1207L)));
}
@Test
public void testEthGetBalance() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": \"0x234c8a3397aab58\"\n"
+ "}");
EthGetBalance ethGetBalance = deserialiseResponse(EthGetBalance.class);
assertThat(ethGetBalance.getBalance(), equalTo(BigInteger.valueOf(158972490234375000L)));
}
@Test
public void testEthStorageAt() {
buildResponse(
"{\n"
+ " \"jsonrpc\":\"2.0\","
+ " \"id\":1,"
+ " \"result\":"
+ "\"0x000000000000000000000000000000000000000000000000000000000000162e\""
+ "}");
EthGetStorageAt ethGetStorageAt = deserialiseResponse(EthGetStorageAt.class);
assertThat(
ethGetStorageAt.getResult(),
is("0x000000000000000000000000000000000000000000000000000000000000162e"));
}
@Test
public void testEthGetTransactionCount() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": \"0x1\"\n"
+ "}");
EthGetTransactionCount ethGetTransactionCount =
deserialiseResponse((EthGetTransactionCount.class));
assertThat(ethGetTransactionCount.getTransactionCount(), equalTo(BigInteger.valueOf(1L)));
}
@Test
public void testEthGetBlockTransactionCountByHash() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": \"0xb\"\n"
+ "}");
EthGetBlockTransactionCountByHash ethGetBlockTransactionCountByHash =
deserialiseResponse(EthGetBlockTransactionCountByHash.class);
assertThat(
ethGetBlockTransactionCountByHash.getTransactionCount(),
equalTo(BigInteger.valueOf(11)));
}
@Test
public void testEthGetBlockTransactionCountByNumber() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": \"0xa\"\n"
+ "}");
EthGetBlockTransactionCountByNumber ethGetBlockTransactionCountByNumber =
deserialiseResponse(EthGetBlockTransactionCountByNumber.class);
assertThat(
ethGetBlockTransactionCountByNumber.getTransactionCount(),
equalTo(BigInteger.valueOf(10)));
}
@Test
public void testEthGetUncleCountByBlockHash() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": \"0x1\"\n"
+ "}");
EthGetUncleCountByBlockHash ethGetUncleCountByBlockHash =
deserialiseResponse(EthGetUncleCountByBlockHash.class);
assertThat(ethGetUncleCountByBlockHash.getUncleCount(), equalTo(BigInteger.valueOf(1)));
}
@Test
public void testEthGetUncleCountByBlockNumber() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": \"0x1\"\n"
+ "}");
EthGetUncleCountByBlockNumber ethGetUncleCountByBlockNumber =
deserialiseResponse(EthGetUncleCountByBlockNumber.class);
assertThat(ethGetUncleCountByBlockNumber.getUncleCount(), equalTo(BigInteger.valueOf(1)));
}
@Test
public void testGetCode() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": \"0x600160008035811a818181146012578301005b601b60013560255"
+ "65b8060005260206000f25b600060078202905091905056\"\n"
+ "}");
EthGetCode ethGetCode = deserialiseResponse(EthGetCode.class);
assertThat(
ethGetCode.getCode(),
is(
"0x600160008035811a818181146012578301005b601b60013560255"
+ "65b8060005260206000f25b600060078202905091905056"));
}
@Test
public void testEthSign() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": "
+ "\"0xbd685c98ec39490f50d15c67ba2a8e9b5b1d6d7601fca80b295e7d717446bd8b712"
+ "7ea4871e996cdc8cae7690408b4e800f60ddac49d2ad34180e68f1da0aaf001\"\n"
+ "}");
EthSign ethSign = deserialiseResponse(EthSign.class);
assertThat(
ethSign.getSignature(),
is(
"0xbd685c98ec39490f50d15c67ba2a8e9b5b1d6d7601fca80b295e7d717446bd8b7127ea4871e9"
+ "96cdc8cae7690408b4e800f60ddac49d2ad34180e68f1da0aaf001"));
}
@Test
public void testEthSendTransaction() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": "
+ "\"0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331\"\n"
+ "}");
EthSendTransaction ethSendTransaction = deserialiseResponse(EthSendTransaction.class);
assertThat(
ethSendTransaction.getTransactionHash(),
is("0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331"));
}
@Test
public void testEthSendRawTransaction() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": "
+ "\"0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331\"\n"
+ "}");
EthSendRawTransaction ethSendRawTransaction =
deserialiseResponse(EthSendRawTransaction.class);
assertThat(
ethSendRawTransaction.getTransactionHash(),
is("0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331"));
}
@Test
public void testEthCall() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": \"0x\"\n"
+ "}");
EthCall ethCall = deserialiseResponse(EthCall.class);
assertThat(ethCall.getValue(), is("0x"));
assertFalse(ethCall.reverts());
assertNull(ethCall.getRevertReason());
}
@Test
public void testEthCallReverted() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": \"0x08c379a0"
+ "0000000000000000000000000000000000000000000000000000000000000020"
+ "00000000000000000000000000000000000000000000000000000000000000ee"
+ "536f6c696469747920757365732073746174652d726576657274696e67206578"
+ "63657074696f6e7320746f2068616e646c65206572726f72732e205468652072"
+ "6571756972652066756e6374696f6e2073686f756c6420626520757365642074"
+ "6f20656e737572652076616c696420636f6e646974696f6e732c207375636820"
+ "617320696e707574732c206f7220636f6e747261637420737461746520766172"
+ "6961626c657320617265206d65742c206f7220746f2076616c69646174652072"
+ "657475726e2076616c7565732066726f6d2063616c6c7320746f206578746572"
+ "6e616c20636f6e7472616374732e000000000000000000000000000000000000\"\n"
+ "}");
EthCall ethCall = deserialiseResponse(EthCall.class);
assertTrue(ethCall.reverts());
assertThat(
ethCall.getRevertReason(),
is(
"Solidity uses state-reverting exceptions to "
+ "handle errors. The require function should be "
+ "used to ensure valid conditions, such as inputs, "
+ "or contract state variables are met, or to "
+ "validate return values from calls to "
+ "external contracts."));
}
@Test
public void testEthEstimateGas() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": \"0x5208\"\n"
+ "}");
EthEstimateGas ethEstimateGas = deserialiseResponse(EthEstimateGas.class);
assertThat(ethEstimateGas.getAmountUsed(), equalTo(BigInteger.valueOf(21000)));
}
@Test
public void testEthBlockTransactionHashes() {
buildResponse(
"{\n"
+ "\"id\":1,\n"
+ "\"jsonrpc\":\"2.0\",\n"
+ "\"result\": {\n"
+ " \"number\": \"0x1b4\",\n"
+ " \"hash\": \"0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331\",\n"
+ " \"parentHash\": \"0x9646252be9520f6e71339a8df9c55e4d7619deeb018d2a3f2d21fc165dde5eb5\",\n"
+ " \"nonce\": \"0xe04d296d2460cfb8472af2c5fd05b5a214109c25688d3704aed5484f9a7792f2\",\n"
+ " \"sha3Uncles\": \"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347\",\n"
+ " \"logsBloom\": \"0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331\",\n"
+ " \"transactionsRoot\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n"
+ " \"stateRoot\": \"0xd5855eb08b3387c0af375e9cdb6acfc05eb8f519e419b874b6ff2ffda7ed1dff\",\n"
+ " \"receiptsRoot\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n"
+ " \"author\": \"0x1a95ad5ccdb0677af951810c6ddf4935afe4e5a6\",\n"
+ " \"miner\": \"0x4e65fda2159562a496f9f3522f89122a3088497a\",\n"
+ " \"mixHash\": \"0x57919c4e72e79ad7705a26e7ecd5a08ff546ac4fa37882e9cc57be87a3dab26b\",\n"
+ " \"difficulty\": \"0x027f07\",\n"
+ " \"totalDifficulty\": \"0x027f07\",\n"
+ " \"extraData\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n"
+ " \"size\": \"0x027f07\",\n"
+ " \"gasLimit\": \"0x9f759\",\n"
+ " \"gasUsed\": \"0x9f759\",\n"
+ " \"timestamp\": \"0x54e34e8e\",\n"
+ " \"transactions\": ["
+ " \"0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331\",\n"
+ " \"0xd5855eb08b3387c0af375e9cdb6acfc05eb8f519e419b874b6ff2ffda7ed1df\"\n"
+ " ], \n"
+ " \"uncles\": [\n"
+ " \"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347\",\n"
+ " \"0xd5855eb08b3387c0af375e9cdb6acfc05eb8f519e419b874b6ff2ffda7ed1dff\"\n"
+ " ],\n"
+ " \"sealFields\": [\n"
+ " \"0x57919c4e72e79ad7705a26e7ecd5a08ff546ac4fa37882e9cc57be87a3dab26b\",\n"
+ " \"0x39a3eb432fbef1fc\"\n"
+ " ]\n"
+ " }\n"
+ "}");
EthBlock ethBlock = deserialiseResponse(EthBlock.class);
EthBlock.Block block =
new EthBlock.Block(
"0x1b4",
"0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331",
"0x9646252be9520f6e71339a8df9c55e4d7619deeb018d2a3f2d21fc165dde5eb5",
"0xe04d296d2460cfb8472af2c5fd05b5a214109c25688d3704aed5484f9a7792f2",
"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
"0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331",
"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
"0xd5855eb08b3387c0af375e9cdb6acfc05eb8f519e419b874b6ff2ffda7ed1dff",
"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
"0x1a95ad5ccdb0677af951810c6ddf4935afe4e5a6",
"0x4e65fda2159562a496f9f3522f89122a3088497a",
"0x57919c4e72e79ad7705a26e7ecd5a08ff546ac4fa37882e9cc57be87a3dab26b",
"0x027f07",
"0x027f07",
"0x0000000000000000000000000000000000000000000000000000000000000000",
"0x027f07",
"0x9f759",
"0x9f759",
"0x54e34e8e",
Arrays.asList(
new EthBlock.TransactionHash(
"0xe670ec64341771606e55d6b4ca35a1a6b"
+ "75ee3d5145a99d05921026d1527331"),
new EthBlock.TransactionHash(
"0xd5855eb08b3387c0af375e9cdb6acfc05eb8f519e419b874b6ff2ffda7ed1df")),
Arrays.asList(
"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
"0xd5855eb08b3387c0af375e9cdb6acfc05eb8f519e419b874b6ff2ffda7ed1dff"),
Arrays.asList(
"0x57919c4e72e79ad7705a26e7ecd5a08ff546ac4fa37882e9cc57be87a3dab26b",
"0x39a3eb432fbef1fc"));
assertThat(ethBlock.getBlock(), equalTo(block));
}
@Test
public void testEthBlockFullTransactionsParity() {
buildResponse(
"{\n"
+ "\"id\":1,\n"
+ "\"jsonrpc\":\"2.0\",\n"
+ "\"result\": {\n"
+ " \"number\": \"0x1b4\",\n"
+ " \"hash\": \"0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331\",\n"
+ " \"parentHash\": \"0x9646252be9520f6e71339a8df9c55e4d7619deeb018d2a3f2d21fc165dde5eb5\",\n"
+ " \"nonce\": \"0xe04d296d2460cfb8472af2c5fd05b5a214109c25688d3704aed5484f9a7792f2\",\n"
+ " \"sha3Uncles\": \"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347\",\n"
+ " \"logsBloom\": \"0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331\",\n"
+ " \"transactionsRoot\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n"
+ " \"stateRoot\": \"0xd5855eb08b3387c0af375e9cdb6acfc05eb8f519e419b874b6ff2ffda7ed1dff\",\n"
+ " \"receiptsRoot\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n"
+ " \"author\": \"0x1a95ad5ccdb0677af951810c6ddf4935afe4e5a6\",\n"
+ " \"miner\": \"0x4e65fda2159562a496f9f3522f89122a3088497a\",\n"
+ " \"mixHash\": \"0x57919c4e72e79ad7705a26e7ecd5a08ff546ac4fa37882e9cc57be87a3dab26b\",\n"
+ " \"difficulty\": \"0x027f07\",\n"
+ " \"totalDifficulty\": \"0x027f07\",\n"
+ " \"extraData\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n"
+ " \"size\": \"0x027f07\",\n"
+ " \"gasLimit\": \"0x9f759\",\n"
+ " \"gasUsed\": \"0x9f759\",\n"
+ " \"timestamp\": \"0x54e34e8e\",\n"
+ " \"transactions\": [{"
+ " \"hash\":\"0xc6ef2fc5426d6ad6fd9e2a26abeab0aa2411b7ab17f30a99d3cb96aed1d1055b\",\n"
+ " \"nonce\":\"0x\",\n"
+ " \"blockHash\": \"0xbeab0aa2411b7ab17f30a99d3cb9c6ef2fc5426d6ad6fd9e2a26a6aed1d1055b\",\n"
+ " \"blockNumber\": \"0x15df\",\n"
+ " \"transactionIndex\": \"0x1\",\n"
+ " \"from\":\"0x407d73d8a49eeb85d32cf465507dd71d507100c1\",\n"
+ " \"to\":\"0x85h43d8a49eeb85d32cf465507dd71d507100c1\",\n"
+ " \"value\":\"0x7f110\",\n"
+ " \"gas\": \"0x7f110\",\n"
+ " \"gasPrice\":\"0x09184e72a000\",\n"
+ " \"input\":\"0x603880600c6000396000f300603880600c6000396000f3603880600c6000396000f360\","
+ " \"creates\":null,\n"
+ " \"publicKey\":\"0x6614d7d7bfe989295821985de0439e868b26ff05f98ae0da0ce5bccc24ea368a083b785323c9fcb405dd4c10a2c95d93312a1b2d68beb24ab4ea7c3c2f7c455b\",\n"
+ " \"raw\":\"0xf8cd83103a048504a817c800830e57e0945927c5cc723c4486f93bf90bad3be8831139499e80b864140f8dd300000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000c03905df347aa6490d5a98fbb8d8e49520000000000000000000000000000000000000000000000000000000057d56ee61ba0f115cc4d7516dd430046504e1c888198e0323e8ded016d755f89c226ba3481dca04a2ae8ee49f1100b5c0202b37ed8bacf4caeddebde6b7f77e12e7a55893e9f62\",\n"
+ " \"r\":\"0xf115cc4d7516dd430046504e1c888198e0323e8ded016d755f89c226ba3481dc\",\n"
+ " \"s\":\"0x4a2ae8ee49f1100b5c0202b37ed8bacf4caeddebde6b7f77e12e7a55893e9f62\",\n"
+ " \"v\":0\n"
+ " }], \n"
+ " \"uncles\": [\n"
+ " \"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347\",\n"
+ " \"0xd5855eb08b3387c0af375e9cdb6acfc05eb8f519e419b874b6ff2ffda7ed1dff\"\n"
+ " ],\n"
+ " \"sealFields\": [\n"
+ " \"0x57919c4e72e79ad7705a26e7ecd5a08ff546ac4fa37882e9cc57be87a3dab26b\",\n"
+ " \"0x39a3eb432fbef1fc\"\n"
+ " ]\n"
+ " }\n"
+ "}");
EthBlock ethBlock = deserialiseResponse(EthBlock.class);
EthBlock.Block block =
new EthBlock.Block(
"0x1b4",
"0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331",
"0x9646252be9520f6e71339a8df9c55e4d7619deeb018d2a3f2d21fc165dde5eb5",
"0xe04d296d2460cfb8472af2c5fd05b5a214109c25688d3704aed5484f9a7792f2",
"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
"0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331",
"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
"0xd5855eb08b3387c0af375e9cdb6acfc05eb8f519e419b874b6ff2ffda7ed1dff",
"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
"0x1a95ad5ccdb0677af951810c6ddf4935afe4e5a6",
"0x4e65fda2159562a496f9f3522f89122a3088497a",
"0x57919c4e72e79ad7705a26e7ecd5a08ff546ac4fa37882e9cc57be87a3dab26b",
"0x027f07",
"0x027f07",
"0x0000000000000000000000000000000000000000000000000000000000000000",
"0x027f07",
"0x9f759",
"0x9f759",
"0x54e34e8e",
Arrays.asList(
new EthBlock.TransactionObject(
"0xc6ef2fc5426d6ad6fd9e2a26abeab0aa2411b7ab17f30a99d3cb96aed1d1055b",
"0x",
"0xbeab0aa2411b7ab17f30a99d3cb9c6ef2fc5426d6ad6fd9e2a26a6aed1d1055b",
"0x15df",
"0x1",
"0x407d73d8a49eeb85d32cf465507dd71d507100c1",
"0x85h43d8a49eeb85d32cf465507dd71d507100c1",
"0x7f110",
"0x09184e72a000",
"0x7f110",
"0x603880600c6000396000f300603880600c6000396000f3603880600c6000396000f360",
null,
"0x6614d7d7bfe989295821985de0439e868b26ff05f98ae0da0ce5bccc24ea368a083b785323c9fcb405dd4c10a2c95d93312a1b2d68beb24ab4ea7c3c2f7c455b",
"0xf8cd83103a048504a817c800830e57e0945927c5cc723c4486f93bf90bad3be8831139499e80b864140f8dd300000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000c03905df347aa6490d5a98fbb8d8e49520000000000000000000000000000000000000000000000000000000057d56ee61ba0f115cc4d7516dd430046504e1c888198e0323e8ded016d755f89c226ba3481dca04a2ae8ee49f1100b5c0202b37ed8bacf4caeddebde6b7f77e12e7a55893e9f62",
"0xf115cc4d7516dd430046504e1c888198e0323e8ded016d755f89c226ba3481dc",
"0x4a2ae8ee49f1100b5c0202b37ed8bacf4caeddebde6b7f77e12e7a55893e9f62",
(byte) 0)),
Arrays.asList(
"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
"0xd5855eb08b3387c0af375e9cdb6acfc05eb8f519e419b874b6ff2ffda7ed1dff"),
Arrays.asList(
"0x57919c4e72e79ad7705a26e7ecd5a08ff546ac4fa37882e9cc57be87a3dab26b",
"0x39a3eb432fbef1fc"));
assertThat(ethBlock.getBlock(), equalTo(block));
}
// Remove once Geth & Parity return the same v value in transactions
@Test
public void testEthBlockFullTransactionsGeth() {
buildResponse(
"{\n"
+ "\"id\":1,\n"
+ "\"jsonrpc\":\"2.0\",\n"
+ "\"result\": {\n"
+ " \"number\": \"0x1b4\",\n"
+ " \"hash\": \"0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331\",\n"
+ " \"parentHash\": \"0x9646252be9520f6e71339a8df9c55e4d7619deeb018d2a3f2d21fc165dde5eb5\",\n"
+ " \"nonce\": \"0xe04d296d2460cfb8472af2c5fd05b5a214109c25688d3704aed5484f9a7792f2\",\n"
+ " \"sha3Uncles\": \"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347\",\n"
+ " \"logsBloom\": \"0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331\",\n"
+ " \"transactionsRoot\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n"
+ " \"stateRoot\": \"0xd5855eb08b3387c0af375e9cdb6acfc05eb8f519e419b874b6ff2ffda7ed1dff\",\n"
+ " \"receiptsRoot\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n"
+ " \"author\": \"0x1a95ad5ccdb0677af951810c6ddf4935afe4e5a6\",\n"
+ " \"miner\": \"0x4e65fda2159562a496f9f3522f89122a3088497a\",\n"
+ " \"mixHash\": \"0x57919c4e72e79ad7705a26e7ecd5a08ff546ac4fa37882e9cc57be87a3dab26b\",\n"
+ " \"difficulty\": \"0x027f07\",\n"
+ " \"totalDifficulty\": \"0x027f07\",\n"
+ " \"extraData\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n"
+ " \"size\": \"0x027f07\",\n"
+ " \"gasLimit\": \"0x9f759\",\n"
+ " \"gasUsed\": \"0x9f759\",\n"
+ " \"timestamp\": \"0x54e34e8e\",\n"
+ " \"transactions\": [{"
+ " \"hash\":\"0xc6ef2fc5426d6ad6fd9e2a26abeab0aa2411b7ab17f30a99d3cb96aed1d1055b\",\n"
+ " \"nonce\":\"0x\",\n"
+ " \"blockHash\": \"0xbeab0aa2411b7ab17f30a99d3cb9c6ef2fc5426d6ad6fd9e2a26a6aed1d1055b\",\n"
+ " \"blockNumber\": \"0x15df\",\n"
+ " \"transactionIndex\": \"0x1\",\n"
+ " \"from\":\"0x407d73d8a49eeb85d32cf465507dd71d507100c1\",\n"
+ " \"to\":\"0x85h43d8a49eeb85d32cf465507dd71d507100c1\",\n"
+ " \"value\":\"0x7f110\",\n"
+ " \"gas\": \"0x7f110\",\n"
+ " \"gasPrice\":\"0x09184e72a000\",\n"
+ " \"input\":\"0x603880600c6000396000f300603880600c6000396000f3603880600c6000396000f360\","
+ " \"creates\":null,\n"
+ " \"publicKey\":\"0x6614d7d7bfe989295821985de0439e868b26ff05f98ae0da0ce5bccc24ea368a083b785323c9fcb405dd4c10a2c95d93312a1b2d68beb24ab4ea7c3c2f7c455b\",\n"
+ " \"raw\":\"0xf8cd83103a048504a817c800830e57e0945927c5cc723c4486f93bf90bad3be8831139499e80b864140f8dd300000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000c03905df347aa6490d5a98fbb8d8e49520000000000000000000000000000000000000000000000000000000057d56ee61ba0f115cc4d7516dd430046504e1c888198e0323e8ded016d755f89c226ba3481dca04a2ae8ee49f1100b5c0202b37ed8bacf4caeddebde6b7f77e12e7a55893e9f62\",\n"
+ " \"r\":\"0xf115cc4d7516dd430046504e1c888198e0323e8ded016d755f89c226ba3481dc\",\n"
+ " \"s\":\"0x4a2ae8ee49f1100b5c0202b37ed8bacf4caeddebde6b7f77e12e7a55893e9f62\",\n"
+ " \"v\":\"0x9d\"\n"
+ " }], \n"
+ " \"uncles\": [\n"
+ " \"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347\",\n"
+ " \"0xd5855eb08b3387c0af375e9cdb6acfc05eb8f519e419b874b6ff2ffda7ed1dff\"\n"
+ " ],\n"
+ " \"sealFields\": [\n"
+ " \"0x57919c4e72e79ad7705a26e7ecd5a08ff546ac4fa37882e9cc57be87a3dab26b\",\n"
+ " \"0x39a3eb432fbef1fc\"\n"
+ " ]\n"
+ " }\n"
+ "}");
EthBlock ethBlock = deserialiseResponse(EthBlock.class);
EthBlock.Block block =
new EthBlock.Block(
"0x1b4",
"0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331",
"0x9646252be9520f6e71339a8df9c55e4d7619deeb018d2a3f2d21fc165dde5eb5",
"0xe04d296d2460cfb8472af2c5fd05b5a214109c25688d3704aed5484f9a7792f2",
"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
"0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331",
"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
"0xd5855eb08b3387c0af375e9cdb6acfc05eb8f519e419b874b6ff2ffda7ed1dff",
"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
"0x1a95ad5ccdb0677af951810c6ddf4935afe4e5a6",
"0x4e65fda2159562a496f9f3522f89122a3088497a",
"0x57919c4e72e79ad7705a26e7ecd5a08ff546ac4fa37882e9cc57be87a3dab26b",
"0x027f07",
"0x027f07",
"0x0000000000000000000000000000000000000000000000000000000000000000",
"0x027f07",
"0x9f759",
"0x9f759",
"0x54e34e8e",
Arrays.asList(
new EthBlock.TransactionObject(
"0xc6ef2fc5426d6ad6fd9e2a26abeab0aa2411b7ab17f30a99d3cb96aed1d1055b",
"0x",
"0xbeab0aa2411b7ab17f30a99d3cb9c6ef2fc5426d6ad6fd9e2a26a6aed1d1055b",
"0x15df",
"0x1",
"0x407d73d8a49eeb85d32cf465507dd71d507100c1",
"0x85h43d8a49eeb85d32cf465507dd71d507100c1",
"0x7f110",
"0x09184e72a000",
"0x7f110",
"0x603880600c6000396000f300603880600c6000396000f3603880600c6000396000f360",
null,
"0x6614d7d7bfe989295821985de0439e868b26ff05f98ae0da0ce5bccc24ea368a083b785323c9fcb405dd4c10a2c95d93312a1b2d68beb24ab4ea7c3c2f7c455b",
"0xf8cd83103a048504a817c800830e57e0945927c5cc723c4486f93bf90bad3be8831139499e80b864140f8dd300000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000c03905df347aa6490d5a98fbb8d8e49520000000000000000000000000000000000000000000000000000000057d56ee61ba0f115cc4d7516dd430046504e1c888198e0323e8ded016d755f89c226ba3481dca04a2ae8ee49f1100b5c0202b37ed8bacf4caeddebde6b7f77e12e7a55893e9f62",
"0xf115cc4d7516dd430046504e1c888198e0323e8ded016d755f89c226ba3481dc",
"0x4a2ae8ee49f1100b5c0202b37ed8bacf4caeddebde6b7f77e12e7a55893e9f62",
0x9d)),
Arrays.asList(
"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
"0xd5855eb08b3387c0af375e9cdb6acfc05eb8f519e419b874b6ff2ffda7ed1dff"),
Arrays.asList(
"0x57919c4e72e79ad7705a26e7ecd5a08ff546ac4fa37882e9cc57be87a3dab26b",
"0x39a3eb432fbef1fc"));
assertThat(ethBlock.getBlock(), equalTo(block));
}
@Test
public void testEthBlockNull() {
buildResponse("{\n" + " \"result\": null\n" + "}");
EthBlock ethBlock = deserialiseResponse(EthBlock.class);
assertNull(ethBlock.getBlock());
}
@Test
public void testEthTransaction() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\":\"2.0\",\n"
+ " \"result\": {\n"
+ " \"hash\":\"0xc6ef2fc5426d6ad6fd9e2a26abeab0aa2411b7ab17f30a99d3cb96aed1d1055b\",\n"
+ " \"nonce\":\"0x\",\n"
+ " \"blockHash\": \"0xbeab0aa2411b7ab17f30a99d3cb9c6ef2fc5426d6ad6fd9e2a26a6aed1d1055b\",\n"
+ " \"blockNumber\": \"0x15df\",\n"
+ " \"transactionIndex\": \"0x1\",\n"
+ " \"from\":\"0x407d73d8a49eeb85d32cf465507dd71d507100c1\",\n"
+ " \"to\":\"0x85h43d8a49eeb85d32cf465507dd71d507100c1\",\n"
+ " \"value\":\"0x7f110\",\n"
+ " \"gas\": \"0x7f110\",\n"
+ " \"gasPrice\":\"0x09184e72a000\",\n"
+ " \"input\":\"0x603880600c6000396000f300603880600c6000396000f3603880600c6000396000f360\",\n"
+ " \"creates\":null,\n"
+ " \"publicKey\":\"0x6614d7d7bfe989295821985de0439e868b26ff05f98ae0da0ce5bccc24ea368a083b785323c9fcb405dd4c10a2c95d93312a1b2d68beb24ab4ea7c3c2f7c455b\",\n"
+ " \"raw\":\"0xf8cd83103a048504a817c800830e57e0945927c5cc723c4486f93bf90bad3be8831139499e80b864140f8dd300000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000c03905df347aa6490d5a98fbb8d8e49520000000000000000000000000000000000000000000000000000000057d56ee61ba0f115cc4d7516dd430046504e1c888198e0323e8ded016d755f89c226ba3481dca04a2ae8ee49f1100b5c0202b37ed8bacf4caeddebde6b7f77e12e7a55893e9f62\",\n"
+ " \"r\":\"0xf115cc4d7516dd430046504e1c888198e0323e8ded016d755f89c226ba3481dc\",\n"
+ " \"s\":\"0x4a2ae8ee49f1100b5c0202b37ed8bacf4caeddebde6b7f77e12e7a55893e9f62\",\n"
+ " \"v\":0\n"
+ " }\n"
+ "}");
Transaction transaction =
new Transaction(
"0xc6ef2fc5426d6ad6fd9e2a26abeab0aa2411b7ab17f30a99d3cb96aed1d1055b",
"0x",
"0xbeab0aa2411b7ab17f30a99d3cb9c6ef2fc5426d6ad6fd9e2a26a6aed1d1055b",
"0x15df",
"0x1",
"0x407d73d8a49eeb85d32cf465507dd71d507100c1",
"0x85h43d8a49eeb85d32cf465507dd71d507100c1",
"0x7f110",
"0x7f110",
"0x09184e72a000",
"0x603880600c6000396000f300603880600c6000396000f3603880600c6000396000f360",
null,
"0x6614d7d7bfe989295821985de0439e868b26ff05f98ae0da0ce5bccc24ea368a083b785323c9fcb405dd4c10a2c95d93312a1b2d68beb24ab4ea7c3c2f7c455b",
"0xf8cd83103a048504a817c800830e57e0945927c5cc723c4486f93bf90bad3be8831139499e80b864140f8dd300000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000c03905df347aa6490d5a98fbb8d8e49520000000000000000000000000000000000000000000000000000000057d56ee61ba0f115cc4d7516dd430046504e1c888198e0323e8ded016d755f89c226ba3481dca04a2ae8ee49f1100b5c0202b37ed8bacf4caeddebde6b7f77e12e7a55893e9f62",
"0xf115cc4d7516dd430046504e1c888198e0323e8ded016d755f89c226ba3481dc",
"0x4a2ae8ee49f1100b5c0202b37ed8bacf4caeddebde6b7f77e12e7a55893e9f62",
(byte) 0);
EthTransaction ethTransaction = deserialiseResponse(EthTransaction.class);
assertThat(ethTransaction.getTransaction().get(), equalTo(transaction));
}
@Test
public void testTransactionChainId() {
Transaction transaction = new Transaction();
transaction.setV(0x25);
assertThat(transaction.getChainId(), equalTo(1L));
}
@Test
public void testTransactionLongChainId() {
Transaction transaction = new Transaction();
transaction.setV(0x4A817C823L);
assertThat(transaction.getChainId(), equalTo(10000000000L));
}
@Test
public void testEthTransactionNull() {
buildResponse("{\n" + " \"result\": null\n" + "}");
EthTransaction ethTransaction = deserialiseResponse(EthTransaction.class);
assertThat(ethTransaction.getTransaction(), is(Optional.empty()));
}
@Test
public void testeEthGetTransactionReceiptBeforeByzantium() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\":\"2.0\",\n"
+ " \"result\": {\n"
+ " \"transactionHash\": \"0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238\",\n"
+ " \"transactionIndex\": \"0x1\",\n"
+ " \"blockHash\": \"0xc6ef2fc5426d6ad6fd9e2a26abeab0aa2411b7ab17f30a99d3cb96aed1d1055b\",\n"
+ " \"blockNumber\": \"0xb\",\n"
+ " \"cumulativeGasUsed\": \"0x33bc\",\n"
+ " \"gasUsed\": \"0x4dc\",\n"
+ " \"contractAddress\": \"0xb60e8dd61c5d32be8058bb8eb970870f07233155\",\n"
+ " \"root\": \"9307ba10e41ecf3d40507fc908655fe72fc129d46f6d99baf7605d0e29184911\",\n"
+ " \"from\":\"0x407d73d8a49eeb85d32cf465507dd71d507100c1\",\n"
+ " \"to\":\"0x85h43d8a49eeb85d32cf465507dd71d507100c1\",\n"
+ " \"logs\": [{\n"
+ " \"removed\": false,\n"
+ " \"logIndex\": \"0x1\",\n"
+ " \"transactionIndex\": \"0x0\",\n"
+ " \"transactionHash\": \"0xdf829c5a142f1fccd7d8216c5785ac562ff41e2dcfdf5785ac562ff41e2dcf\",\n"
+ " \"blockHash\": \"0x8216c5785ac562ff41e2dcfdf5785ac562ff41e2dcfdf829c5a142f1fccd7d\",\n"
+ " \"blockNumber\":\"0x1b4\",\n"
+ " \"address\": \"0x16c5785ac562ff41e2dcfdf829c5a142f1fccd7d\",\n"
+ " \"data\":\"0x0000000000000000000000000000000000000000000000000000000000000000\",\n"
+ " \"type\":\"mined\",\n"
+ " \"topics\": [\"0x59ebeb90bc63057b6515673c3ecf9438e5058bca0f92585014eced636878c9a5\"]"
+ " }],\n"
+ " \"logsBloom\":\"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\"\n"
+ " }\n"
+ "}");
TransactionReceipt transactionReceipt =
new TransactionReceipt(
"0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238",
"0x1",
"0xc6ef2fc5426d6ad6fd9e2a26abeab0aa2411b7ab17f30a99d3cb96aed1d1055b",
"0xb",
"0x33bc",
"0x4dc",
"0xb60e8dd61c5d32be8058bb8eb970870f07233155",
"9307ba10e41ecf3d40507fc908655fe72fc129d46f6d99baf7605d0e29184911",
null,
"0x407d73d8a49eeb85d32cf465507dd71d507100c1",
"0x85h43d8a49eeb85d32cf465507dd71d507100c1",
Arrays.asList(
new Log(
false,
"0x1",
"0x0",
"0xdf829c5a142f1fccd7d8216c5785ac562ff41e2dcfdf5785ac562ff41e2dcf",
"0x8216c5785ac562ff41e2dcfdf5785ac562ff41e2dcfdf829c5a142f1fccd7d",
"0x1b4",
"0x16c5785ac562ff41e2dcfdf829c5a142f1fccd7d",
"0x0000000000000000000000000000000000000000000000000000000000000000",
"mined",
Arrays.asList(
"0x59ebeb90bc63057b6515673c3ecf9438e5058bca0f92585014eced636878c9a5"))),
"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
EthGetTransactionReceipt ethGetTransactionReceipt =
deserialiseResponse(EthGetTransactionReceipt.class);
assertThat(
ethGetTransactionReceipt.getTransactionReceipt().get(),
equalTo(transactionReceipt));
}
@Test
public void testeEthGetTransactionReceiptAfterByzantium() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\":\"2.0\",\n"
+ " \"result\": {\n"
+ " \"transactionHash\": \"0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238\",\n"
+ " \"transactionIndex\": \"0x1\",\n"
+ " \"blockHash\": \"0xc6ef2fc5426d6ad6fd9e2a26abeab0aa2411b7ab17f30a99d3cb96aed1d1055b\",\n"
+ " \"blockNumber\": \"0xb\",\n"
+ " \"cumulativeGasUsed\": \"0x33bc\",\n"
+ " \"gasUsed\": \"0x4dc\",\n"
+ " \"contractAddress\": \"0xb60e8dd61c5d32be8058bb8eb970870f07233155\",\n"
+ " \"status\": \"0x1\",\n"
+ " \"from\":\"0x407d73d8a49eeb85d32cf465507dd71d507100c1\",\n"
+ " \"to\":\"0x85h43d8a49eeb85d32cf465507dd71d507100c1\",\n"
+ " \"logs\": [{\n"
+ " \"removed\": false,\n"
+ " \"logIndex\": \"0x1\",\n"
+ " \"transactionIndex\": \"0x0\",\n"
+ " \"transactionHash\": \"0xdf829c5a142f1fccd7d8216c5785ac562ff41e2dcfdf5785ac562ff41e2dcf\",\n"
+ " \"blockHash\": \"0x8216c5785ac562ff41e2dcfdf5785ac562ff41e2dcfdf829c5a142f1fccd7d\",\n"
+ " \"blockNumber\":\"0x1b4\",\n"
+ " \"address\": \"0x16c5785ac562ff41e2dcfdf829c5a142f1fccd7d\",\n"
+ " \"data\":\"0x0000000000000000000000000000000000000000000000000000000000000000\",\n"
+ " \"type\":\"mined\",\n"
+ " \"topics\": [\"0x59ebeb90bc63057b6515673c3ecf9438e5058bca0f92585014eced636878c9a5\"]"
+ " }],\n"
+ " \"logsBloom\":\"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\"\n"
+ " }\n"
+ "}");
TransactionReceipt transactionReceipt =
new TransactionReceipt(
"0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238",
"0x1",
"0xc6ef2fc5426d6ad6fd9e2a26abeab0aa2411b7ab17f30a99d3cb96aed1d1055b",
"0xb",
"0x33bc",
"0x4dc",
"0xb60e8dd61c5d32be8058bb8eb970870f07233155",
null,
"0x1",
"0x407d73d8a49eeb85d32cf465507dd71d507100c1",
"0x85h43d8a49eeb85d32cf465507dd71d507100c1",
Arrays.asList(
new Log(
false,
"0x1",
"0x0",
"0xdf829c5a142f1fccd7d8216c5785ac562ff41e2dcfdf5785ac562ff41e2dcf",
"0x8216c5785ac562ff41e2dcfdf5785ac562ff41e2dcfdf829c5a142f1fccd7d",
"0x1b4",
"0x16c5785ac562ff41e2dcfdf829c5a142f1fccd7d",
"0x0000000000000000000000000000000000000000000000000000000000000000",
"mined",
Arrays.asList(
"0x59ebeb90bc63057b6515673c3ecf9438e5058bca0f92585014eced636878c9a5"))),
"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
EthGetTransactionReceipt ethGetTransactionReceipt =
deserialiseResponse(EthGetTransactionReceipt.class);
assertThat(
ethGetTransactionReceipt.getTransactionReceipt().get(),
equalTo(transactionReceipt));
}
@Test
public void testTransactionReceiptIsStatusOK() {
TransactionReceipt transactionReceipt = new TransactionReceipt();
transactionReceipt.setStatus("0x1");
assertThat(transactionReceipt.isStatusOK(), equalTo(true));
TransactionReceipt transactionReceiptNoStatus = new TransactionReceipt();
assertThat(transactionReceiptNoStatus.isStatusOK(), equalTo(true));
TransactionReceipt transactionReceiptZeroStatus = new TransactionReceipt();
transactionReceiptZeroStatus.setStatus("0x0");
assertThat(transactionReceiptZeroStatus.isStatusOK(), equalTo(false));
}
@Test
public void testEthGetCompilers() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": [\"solidity\", \"lll\", \"serpent\"]\n"
+ "}");
EthGetCompilers ethGetCompilers = deserialiseResponse(EthGetCompilers.class);
assertThat(
ethGetCompilers.getCompilers(),
equalTo(Arrays.asList("solidity", "lll", "serpent")));
}
@Test
public void testEthCompileSolidity() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": {\n"
+ " \"test\": {\n"
+ " \"code\": \"0x605280600c6000396000f3006000357c010000000000000000000000000000000000000000000000000000000090048063c6888fa114602e57005b60376004356041565b8060005260206000f35b6000600782029050604d565b91905056\",\n"
+ " \"info\": {\n"
+ " \"source\": \"contract test {\\n\\tfunction multiply(uint a) returns(uint d) {\\n\\t\\treturn a * 7;\\n\\t}\\n}\\n\",\n"
+ " \"language\": \"Solidity\",\n"
+ " \"languageVersion\": \"0\",\n"
+ " \"compilerVersion\": \"0.8.2\",\n"
+ " \"compilerOptions\": \"--bin --abi --userdoc --devdoc --add-std --optimize -o /var/folders/3m/_6gnl12n1tj_5kf7sc3d72dw0000gn/T/solc498936951\",\n"
+ " \"abiDefinition\": [\n"
+ " {\n"
+ " \"constant\": false,\n"
+ " \"inputs\": [\n"
+ " {\n"
+ " \"name\": \"a\",\n"
+ " \"type\": \"uint256\"\n"
+ " }\n"
+ " ],\n"
+ " \"name\": \"multiply\",\n"
+ " \"outputs\": [\n"
+ " {\n"
+ " \"name\": \"d\",\n"
+ " \"type\": \"uint256\"\n"
+ " }\n"
+ " ],\n"
+ " \"type\": \"function\",\n"
+ " \"payable\": false\n"
+ " }\n"
+ " ],\n"
+ " \"userDoc\": {\n"
+ " \"methods\": {}\n"
+ " },\n"
+ " \"developerDoc\": {\n"
+ " \"methods\": {}\n"
+ " }\n"
+ " }\n"
+ " }\n"
+ " }"
+ " }\n"
+ "}");
Map<String, EthCompileSolidity.Code> compiledSolidity = new HashMap<>(1);
compiledSolidity.put(
"test",
new EthCompileSolidity.Code(
"0x605280600c6000396000f3006000357c010000000000000000000000000000000000000000000000000000000090048063c6888fa114602e57005b60376004356041565b8060005260206000f35b6000600782029050604d565b91905056",
new EthCompileSolidity.SolidityInfo(
"contract test {\n\tfunction multiply(uint a) returns(uint d) {\n"
+ "\t\treturn a * 7;\n\t}\n}\n",
"Solidity",
"0",
"0.8.2",
"--bin --abi --userdoc --devdoc --add-std --optimize -o "
+ "/var/folders/3m/_6gnl12n1tj_5kf7sc3d72dw0000gn/T/solc498936951",
Arrays.asList(
new AbiDefinition(
false,
Arrays.asList(
new AbiDefinition.NamedType(
"a", "uint256")),
"multiply",
Arrays.asList(
new AbiDefinition.NamedType(
"d", "uint256")),
"function",
false)),
new EthCompileSolidity.Documentation(),
new EthCompileSolidity.Documentation())));
EthCompileSolidity ethCompileSolidity = deserialiseResponse(EthCompileSolidity.class);
assertThat(ethCompileSolidity.getCompiledSolidity(), equalTo(compiledSolidity));
}
@Test
public void testEthCompileLLL() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": \"0x603880600c6000396000f3006001600060e060020a60003504806"
+ "3c6888fa114601857005b6021600435602b565b8060005260206000f35b600081600702"
+ "905091905056\"\n"
+ "}");
EthCompileLLL ethCompileLLL = deserialiseResponse(EthCompileLLL.class);
assertThat(
ethCompileLLL.getCompiledSourceCode(),
is(
"0x603880600c6000396000f3006001600060e060020a600035048063c6888fa114601857005b60"
+ "21600435602b565b8060005260206000f35b600081600702905091905056"));
}
@Test
public void testEthCompileSerpent() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": \"0x603880600c6000396000f3006001600060e060020a60003504806"
+ "3c6888fa114601857005b6021600435602b565b8060005260206000f35b600081600702"
+ "905091905056\"\n"
+ "}");
EthCompileSerpent ethCompileSerpent = deserialiseResponse(EthCompileSerpent.class);
assertThat(
ethCompileSerpent.getCompiledSourceCode(),
is(
"0x603880600c6000396000f3006001600060e060020a600035048063c6888fa114601857005b60"
+ "21600435602b565b8060005260206000f35b600081600702905091905056"));
}
@Test
public void testEthFilter() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": \"0x1\"\n"
+ "}");
EthFilter ethFilter = deserialiseResponse(EthFilter.class);
assertThat(ethFilter.getFilterId(), is(BigInteger.valueOf(1)));
}
@Test
public void testEthUninstallFilter() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": true\n"
+ "}");
EthUninstallFilter ethUninstallFilter = deserialiseResponse(EthUninstallFilter.class);
assertThat(ethUninstallFilter.isUninstalled(), is(true));
}
@Test
public void testEthLog() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\":\"2.0\",\n"
+ " \"result\": [{\n"
+ " \"removed\": false,\n"
+ " \"logIndex\": \"0x1\",\n"
+ " \"transactionIndex\": \"0x0\",\n"
+ " \"transactionHash\": \"0xdf829c5a142f1fccd7d8216c5785ac562ff41e2dcfdf5785ac562ff41e2dcf\",\n"
+ " \"blockHash\": \"0x8216c5785ac562ff41e2dcfdf5785ac562ff41e2dcfdf829c5a142f1fccd7d\",\n"
+ " \"blockNumber\":\"0x1b4\",\n"
+ " \"address\": \"0x16c5785ac562ff41e2dcfdf829c5a142f1fccd7d\",\n"
+ " \"data\":\"0x0000000000000000000000000000000000000000000000000000000000000000\",\n"
+ " \"type\":\"mined\",\n"
+ " \"topics\": [\"0x59ebeb90bc63057b6515673c3ecf9438e5058bca0f92585014eced636878c9a5\"]"
+ " }]"
+ "}");
List<Log> logs =
Collections.singletonList(
new EthLog.LogObject(
false,
"0x1",
"0x0",
"0xdf829c5a142f1fccd7d8216c5785ac562ff41e2dcfdf5785ac562ff41e2dcf",
"0x8216c5785ac562ff41e2dcfdf5785ac562ff41e2dcfdf829c5a142f1fccd7d",
"0x1b4",
"0x16c5785ac562ff41e2dcfdf829c5a142f1fccd7d",
"0x0000000000000000000000000000000000000000000000000000000000000000",
"mined",
Collections.singletonList(
"0x59ebeb90bc63057b6515673c3ecf9438e5058bca0f92585014eced636878c9a5")));
EthLog ethLog = deserialiseResponse(EthLog.class);
assertThat(ethLog.getLogs(), is(logs));
}
@Test
public void testEthGetWork() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\":\"2.0\",\n"
+ " \"result\": [\n"
+ " \"0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef\",\n"
+ " \"0x5EED00000000000000000000000000005EED0000000000000000000000000000\",\n"
+ " \"0xd1ff1c01710000000000000000000000d1ff1c01710000000000000000000000\"\n"
+ " ]\n"
+ "}");
EthGetWork ethGetWork = deserialiseResponse(EthGetWork.class);
assertThat(
ethGetWork.getCurrentBlockHeaderPowHash(),
is("0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"));
assertThat(
ethGetWork.getSeedHashForDag(),
is("0x5EED00000000000000000000000000005EED0000000000000000000000000000"));
assertThat(
ethGetWork.getBoundaryCondition(),
is("0xd1ff1c01710000000000000000000000d1ff1c01710000000000000000000000"));
}
@Test
public void testEthSubmitWork() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\":\"2.0\",\n"
+ " \"result\": true\n"
+ "}");
EthSubmitWork ethSubmitWork = deserialiseResponse(EthSubmitWork.class);
assertThat(ethSubmitWork.solutionValid(), is(true));
}
@Test
public void testEthSubmitHashrate() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\":\"2.0\",\n"
+ " \"result\": true\n"
+ "}");
EthSubmitHashrate ethSubmitHashrate = deserialiseResponse(EthSubmitHashrate.class);
assertThat(ethSubmitHashrate.submissionSuccessful(), is(true));
}
@Test
public void testDbPutString() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\":\"2.0\",\n"
+ " \"result\": true\n"
+ "}");
DbPutString dbPutString = deserialiseResponse(DbPutString.class);
assertThat(dbPutString.valueStored(), is(true));
}
@Test
public void testDbGetString() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\":\"2.0\",\n"
+ " \"result\": \"myString\"\n"
+ "}");
DbGetString dbGetString = deserialiseResponse(DbGetString.class);
assertThat(dbGetString.getStoredValue(), is("myString"));
}
@Test
public void testDbPutHex() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\":\"2.0\",\n"
+ " \"result\": true\n"
+ "}");
DbPutHex dbPutHex = deserialiseResponse(DbPutHex.class);
assertThat(dbPutHex.valueStored(), is(true));
}
@Test
public void testDbGetHex() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\":\"2.0\",\n"
+ " \"result\": \"0x68656c6c6f20776f726c64\"\n"
+ "}");
DbGetHex dbGetHex = deserialiseResponse(DbGetHex.class);
assertThat(dbGetHex.getStoredValue(), is("0x68656c6c6f20776f726c64"));
}
@Test
public void testSshVersion() {
buildResponse(
"{\n"
+ " \"id\":67,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": \"2\"\n"
+ "}");
ShhVersion shhVersion = deserialiseResponse(ShhVersion.class);
assertThat(shhVersion.getVersion(), is("2"));
}
@Test
public void testSshPost() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\":\"2.0\",\n"
+ " \"result\": true\n"
+ "}");
ShhPost shhPost = deserialiseResponse(ShhPost.class);
assertThat(shhPost.messageSent(), is(true));
}
@Test
public void testSshNewIdentity() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": "
+ "\"0xc931d93e97ab07fe42d923478ba2465f283f440fd6cabea4dd7a2c807108f651b713"
+ "5d1d6ca9007d5b68aa497e4619ac10aa3b27726e1863c1fd9b570d99bbaf\"\n"
+ "}");
ShhNewIdentity shhNewIdentity = deserialiseResponse(ShhNewIdentity.class);
assertThat(
shhNewIdentity.getAddress(),
is(
"0xc931d93e97ab07fe42d923478ba2465f283f440fd6cabea4dd7a2c807108f651b7135d1d6ca9"
+ "007d5b68aa497e4619ac10aa3b27726e1863c1fd9b570d99bbaf"));
}
@Test
public void testSshHasIdentity() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": true\n"
+ "}");
ShhHasIdentity shhHasIdentity = deserialiseResponse(ShhHasIdentity.class);
assertThat(shhHasIdentity.hasPrivateKeyForIdentity(), is(true));
}
@Test
public void testSshNewGroup() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": "
+ "\"0xc65f283f440fd6cabea4dd7a2c807108f651b7135d1d6ca90931d93e97ab07fe42d9"
+ "23478ba2407d5b68aa497e4619ac10aa3b27726e1863c1fd9b570d99bbaf\"\n"
+ "}");
ShhNewGroup shhNewGroup = deserialiseResponse(ShhNewGroup.class);
assertThat(
shhNewGroup.getAddress(),
is(
"0xc65f283f440fd6cabea4dd7a2c807108f651b7135d1d6ca90931d93e97ab07fe42d923478ba24"
+ "07d5b68aa497e4619ac10aa3b27726e1863c1fd9b570d99bbaf"));
}
@Test
public void testSshAddToGroup() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"result\": true\n"
+ "}");
ShhAddToGroup shhAddToGroup = deserialiseResponse(ShhAddToGroup.class);
assertThat(shhAddToGroup.addedToGroup(), is(true));
}
@Test
public void testSshNewFilter() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\":\"2.0\",\n"
+ " \"result\": \"0x7\"\n"
+ "}");
ShhNewFilter shhNewFilter = deserialiseResponse(ShhNewFilter.class);
assertThat(shhNewFilter.getFilterId(), is(BigInteger.valueOf(7)));
}
@Test
public void testSshUninstallFilter() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\":\"2.0\",\n"
+ " \"result\": true\n"
+ "}");
ShhUninstallFilter shhUninstallFilter = deserialiseResponse(ShhUninstallFilter.class);
assertThat(shhUninstallFilter.isUninstalled(), is(true));
}
@Test
public void testSshMessages() {
buildResponse(
"{\n"
+ " \"id\":1,\n"
+ " \"jsonrpc\":\"2.0\",\n"
+ " \"result\": [{\n"
+ " \"hash\": \"0x33eb2da77bf3527e28f8bf493650b1879b08c4f2a362beae4ba2f"
+ "71bafcd91f9\",\n"
+ " \"from\": \"0x3ec052fc33...\",\n"
+ " \"to\": \"0x87gdf76g8d7fgdfg...\",\n"
+ " \"expiry\": \"0x54caa50a\",\n"
+ " \"ttl\": \"0x64\",\n"
+ " \"sent\": \"0x54ca9ea2\",\n"
+ " \"topics\": [\"0x6578616d\"],\n"
+ " \"payload\": \"0x7b2274797065223a226d657373616765222c2263686...\",\n"
+ " \"workProved\": \"0x0\"\n"
+ " }]\n"
+ "}");
List<ShhMessages.SshMessage> messages =
Arrays.asList(
new ShhMessages.SshMessage(
"0x33eb2da77bf3527e28f8bf493650b1879b08c4f2a362beae4ba2f71bafcd91f9",
"0x3ec052fc33...",
"0x87gdf76g8d7fgdfg...",
"0x54caa50a",
"0x64",
"0x54ca9ea2",
Arrays.asList("0x6578616d"),
"0x7b2274797065223a226d657373616765222c2263686...",
"0x0"));
ShhMessages shhMessages = deserialiseResponse(ShhMessages.class);
assertThat(shhMessages.getMessages(), equalTo(messages));
}
}
| 52.658409 | 570 | 0.516217 |
fae9fb2fc7d655c352f6c333a2ea764b93c5d846 | 10,988 | package com.example.android.sunshine.app;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.wearable.DataItem;
import com.google.android.gms.wearable.DataItemBuffer;
import com.google.android.gms.wearable.DataMap;
import com.google.android.gms.wearable.DataMapItem;
import com.google.android.gms.wearable.Wearable;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;
/**
* Created by jim on 9/24/2016.
*/
public class SunshineWatchFace implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = SunshineWatchFace.class.getSimpleName();
private GoogleApiClient mGoogleApiClient;
private final Paint mTimeObject;
private final Paint mDateObject;
private final Paint mLowTempObject;
private final Paint mHighTempObject;
private Bitmap mWeatherIcon;
private static String mDateText = "0";
private static String mTimeText = "0";
private static String mLowTempText = "0";
private static String mHighTempText = "0";
private static int mWeatherId = 0;
private Resources mAppResources;
private SharedPreferences mSharedPreferences;
private static final String TIME_FORMAT = "kk:mm";
private static final String DATE_FORMAT = "MMMM dd";
// public static SunshineWatchFace newInstance(Context context) {
public static SunshineWatchFace newInstance(Context context) {
Log.d(TAG, "new Instance of sunshine watch");
Paint mTimeObject = new Paint();
mTimeObject.setColor(Color.GREEN);
mTimeObject.setTextSize(55);
Paint mDateObject = new Paint();
mDateObject.setColor(Color.WHITE);
mDateObject.setTextSize(30);
Paint mLowTempObject = new Paint();
mLowTempObject.setColor(Color.WHITE);
mLowTempObject.setTextSize(25);
Paint mHighTempObject = new Paint();
mHighTempObject.setColor(Color.WHITE);
mHighTempObject.setTextSize(25);
return new SunshineWatchFace(context, mTimeObject, mDateObject, mLowTempObject, mHighTempObject);
}
private SunshineWatchFace(Context context, Paint objTime, Paint objDate, Paint objLowTemp, Paint objHighTemp) {
this.mTimeObject = objTime;
this.mDateObject = objDate;
this.mLowTempObject = objLowTemp;
this.mHighTempObject = objHighTemp;
mAppResources = context.getResources();
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
/* client for Wearable Data Layer */
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
// Method to update the watch face each time an update has occurred
public void draw(Canvas canvas, Rect bounds) {
canvas.drawColor(Color.BLACK);
mTimeText = new SimpleDateFormat(TIME_FORMAT).format(Calendar.getInstance().getTime());
mDateText = new SimpleDateFormat(DATE_FORMAT).format(Calendar.getInstance().getTime());
mHighTempText = mSharedPreferences.getString("high_temp", "");
mLowTempText = mSharedPreferences.getString("low_temp", "");
mWeatherId = mSharedPreferences.getInt("weather_id", 0);
// Date
float dateXOffset = calcXOffset(mDateText, mDateObject, bounds);
float dateYOffset = bounds.exactCenterY()/2.0f;
canvas.drawText(mDateText, dateXOffset, dateYOffset, mDateObject);
// Time
float timeXOffset = calcXOffset(mTimeText, mTimeObject, bounds);
float timeYOffset = calcTimeYOffset(bounds);
canvas.drawText(mTimeText, timeXOffset, timeYOffset, mTimeObject);
// Weather Icon
mWeatherIcon = BitmapFactory
.decodeResource(mAppResources,
getIconResourceForWeatherCondition(mWeatherId) );
if (mWeatherIcon != null) {
// icon
float iconXOffset = calcIconXOffset(mWeatherIcon, bounds);
float iconYOffset = calcIconYOffset(mWeatherIcon, bounds);
canvas.drawBitmap(mWeatherIcon, iconXOffset, iconYOffset, null);
float highTempXOffset = calcHighTempXOffset(mWeatherIcon, mHighTempText, mHighTempObject, bounds);
float highTempYOffset = calcHighTempYOffset(mWeatherIcon, bounds);
canvas.drawText(mHighTempText, highTempXOffset, highTempYOffset, mHighTempObject);
float lowTempXOffset = calcLowTempXOffset(mWeatherIcon, mLowTempText, mLowTempObject, bounds);
float lowTempYOffset = calcLowTempYOffset(mWeatherIcon, bounds);
canvas.drawText(mLowTempText, lowTempXOffset, lowTempYOffset, mLowTempObject);
}
}
private float calcHighTempXOffset(Bitmap weatherIcon, String temp, Paint paint, Rect watchBounds ) {
float centerX = watchBounds.exactCenterX();
Rect textBounds = new Rect();
paint.getTextBounds(temp, 0, temp.length(), textBounds);
return centerX + weatherIcon.getHeight()/2;
}
private float calcHighTempYOffset(Bitmap weatherIcon, Rect watchBounds) {
float centerY = watchBounds.exactCenterY();
return centerY + weatherIcon.getHeight()/1.5f;
}
private float calcLowTempXOffset(Bitmap weatherIcon, String temp, Paint paint, Rect watchBounds) {
float centerX = watchBounds.exactCenterX();
Rect textBounds = new Rect();
paint.getTextBounds(temp, 0, temp.length(), textBounds);
return centerX + weatherIcon.getHeight()/2;
}
private float calcLowTempYOffset(Bitmap weatherIcon, Rect watchBounds) {
float centerY = watchBounds.exactCenterY();
return centerY + (1.2f * weatherIcon.getHeight());
}
private float calcIconXOffset(Bitmap icon, Rect watchBounds) {
float centerX = watchBounds.exactCenterX();
float width = icon.getWidth();
return centerX - width/1.5f;
}
private float calcIconYOffset(Bitmap icon, Rect watchBounds) {
float centerY = watchBounds.exactCenterY();
float height = icon.getHeight();
return centerY + height/3f;
}
// calc Time Y-Offset
private float calcTimeYOffset(Rect watchBounds) {
return watchBounds.exactCenterY();
}
// calc the X-Offset using our Time Label as the offset
private float calcXOffset(String text, Paint paint, Rect watchBounds) {
float centerX = watchBounds.exactCenterX();
float timeLength = paint.measureText(text);
return centerX - (timeLength / 2.0f);
}
public void setAntiAlias(boolean antiAlias) {
mTimeObject.setAntiAlias(antiAlias);
mDateObject.setAntiAlias(antiAlias);
}
// Set each of our objects colors
public void setColor(int green, int white) {
mTimeObject.setColor(green);
mDateObject.setColor(white);
}
// method to get our current timezone and update the time field
public void updateTimeZoneWith(String timeZone) {
// Set our default time zone
TimeZone.setDefault(TimeZone.getTimeZone(timeZone));
// Get the current time for our current timezone
mTimeText = new SimpleDateFormat(TIME_FORMAT).format(Calendar.getInstance().getTime());
}
private static int getIconResourceForWeatherCondition(int weatherId) {
// Based on weather code data found at:
// http://bugs.openweathermap.org/projects/api/wiki/Weather_Condition_Codes
if (weatherId >= 200 && weatherId <= 232) {
return R.drawable.ic_storm;
} else if (weatherId >= 300 && weatherId <= 321) {
return R.drawable.ic_light_rain;
} else if (weatherId >= 500 && weatherId <= 504) {
return R.drawable.ic_rain;
} else if (weatherId == 511) {
return R.drawable.ic_snow;
} else if (weatherId >= 520 && weatherId <= 531) {
return R.drawable.ic_rain;
} else if (weatherId >= 600 && weatherId <= 622) {
return R.drawable.ic_snow;
} else if (weatherId >= 701 && weatherId <= 761) {
return R.drawable.ic_fog;
} else if (weatherId == 761 || weatherId == 781) {
return R.drawable.ic_storm;
} else if (weatherId == 800) {
return R.drawable.ic_clear;
} else if (weatherId == 801) {
return R.drawable.ic_light_clouds;
} else if (weatherId >= 802 && weatherId <= 804) {
return R.drawable.ic_cloudy;
}
return -1;
}
@Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "onConnected");
Wearable.DataApi
.getDataItems(mGoogleApiClient)
.setResultCallback(onConnectedResultCallback);
}
private final ResultCallback<DataItemBuffer>
onConnectedResultCallback = new ResultCallback<DataItemBuffer>() {
@Override
public void onResult(DataItemBuffer dataItems) {
Log.d(TAG, "onResult");
for (DataItem item : dataItems) {
setWeatherData(item);
}
dataItems.release();
}
};
@Override
public void onConnectionSuspended(int i) { }
@Override
public void onConnectionFailed(ConnectionResult connectionResult) { }
private void setWeatherData(DataItem item) {
Log.d(TAG, "setWeatherData()" + item.toString());
String highTemp = "";
String lowTemp = "";
int weatherId = 0;
if ((item.getUri().getPath()).equals("/weather_data")) {
DataMap dataMap = DataMapItem.fromDataItem(item).getDataMap();
if (dataMap.containsKey("high_temp")) {
highTemp = dataMap.get("high_temp");
}
if (dataMap.containsKey("low_temp")) {
lowTemp = dataMap.get("low_temp");
}
if (dataMap.containsKey("weather_id")) {
weatherId = dataMap.getInt("weather_id");
}
mSharedPreferences.edit()
.putString("high_temp", highTemp)
.putString("low_temp", lowTemp)
.putInt("weather_id", weatherId)
.apply();
}
}
} | 38.152778 | 115 | 0.662905 |
bec088743623b070abe1e6fd9ff47a5f001658b1 | 6,120 | package adnascreen;
import static org.junit.Assert.*;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class FASTQHeaderTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void identical(){
String header = "@NS500217:348:HTW2FBGXY:1:11101:22352:1064 1:N:0:0";
FASTQHeader h1 = new FASTQHeader(header);
FASTQHeader h2 = new FASTQHeader(header);
assertTrue(h1.equalsExceptRead(h2));
assertEquals(h1, h2);
}
@Test
public void fields(){
String header = "@NS500217:348:HTW2FBGXY:1:11101:22352:1064 1:N:0:0";
FASTQHeader h1 = new FASTQHeader(header);
assertEquals("NS500217", h1.getInstrument());
assertEquals(348, h1.getRunNumber());
assertEquals("HTW2FBGXY", h1.getFlowcellID());
assertEquals(1, h1.getLane());
assertEquals(11101, h1.getTile());
assertEquals(22352, h1.getX());
assertEquals(1064, h1.getY());
assertEquals(1, h1.getRead());
assertEquals(false, h1.isFiltered());
assertEquals(0, h1.getControlNumber());
assertEquals("0", h1.getIndex());
}
@Test
public void to_string(){
String header = "@NS500217:348:HTW2FBGXY:1:11101:22352:1064 1:N:0:0";
FASTQHeader h1 = new FASTQHeader(header);
String s = h1.toString();
assertEquals(s, header);
}
@Test
public void different_read(){
FASTQHeader h1 = new FASTQHeader("@NS500217:348:HTW2FBGXY:1:11101:22352:1064 1:N:0:0");
FASTQHeader h2 = new FASTQHeader("@NS500217:348:HTW2FBGXY:1:11101:22352:1064 2:N:0:0");
assertTrue(h1.equalsExceptRead(h2));
assertNotEquals(h1, h2);
}
@Test
public void different_instrument(){
FASTQHeader h1 = new FASTQHeader("@NS500217:348:HTW2FBGXY:1:11101:22352:1064 1:N:0:0");
FASTQHeader h2 = new FASTQHeader("@NS500218:348:HTW2FBGXY:1:11101:22352:1064 1:N:0:0");
assertFalse(h1.equalsExceptRead(h2));
assertNotEquals(h1, h2);
}
@Test
public void bad_filteredField(){
thrown.expect(IllegalArgumentException.class);
new FASTQHeader("@NS500217:348:HTW2FBGXY:1:11101:22352:1064 1:Z:0:0");
fail("Filtered field has invalid character but was accepted"); // should not reach here
}
@Test
public void readGroupElements(){
String header = "@NS500217:348:HTW2FBGXY:1:11101:22352:1064 1:N:0:0";
FASTQHeader h1 = new FASTQHeader(header);
String expected = "PM:NS500217\tPU:HTW2FBGXY.348.1";
String s = h1.getReadGroupElements();
assertEquals(expected, s);
}
@Test
public void hasIndex(){
String header = "@NS500217:33:H0NW5AGXX:1:11101:10568:3456 1:N:0:TAATTCG+GAAATAA";
FASTQHeader h1 = new FASTQHeader(header);
String expected = "TAATTCG+GAAATAA";
String s = h1.getIndex();
assertEquals(expected, s);
}
// Other tests use data from NextSeq runs. Following tests use data from a Broad HiSeq X10.
@Test
public void badBroadRunNumber() {
String header = "@E00151:HY352CCXY190421:HY352CCXY:1:1101:10003:10029 1:N:0:";
FASTQHeader h1 = new FASTQHeader(header);
assertEquals("E00151", h1.getInstrument());
assertEquals(0, h1.getRunNumber()); // bad run numbers are converted to 0
assertEquals("HY352CCXY", h1.getFlowcellID());
assertEquals(1, h1.getLane());
assertEquals(1101, h1.getTile());
assertEquals(10003, h1.getX());
assertEquals(10029, h1.getY());
assertEquals(1, h1.getRead());
assertEquals(false, h1.isFiltered());
assertEquals(0, h1.getControlNumber());
assertEquals("", h1.getIndex());
}
@Test
public void badBroadRunNumber2() {
String header = "@E00151:HY352CCXY190421:HY352CCXY:1:1101:10003:10029 2:N:0:";
FASTQHeader h1 = new FASTQHeader(header);
assertEquals("E00151", h1.getInstrument());
assertEquals(0, h1.getRunNumber()); // bad run numbers are converted to 0
assertEquals("HY352CCXY", h1.getFlowcellID());
assertEquals(1, h1.getLane());
assertEquals(1101, h1.getTile());
assertEquals(10003, h1.getX());
assertEquals(10029, h1.getY());
assertEquals(2, h1.getRead());
assertEquals(false, h1.isFiltered());
assertEquals(0, h1.getControlNumber());
assertEquals("", h1.getIndex());
}
@Test
public void badBroadReadNumber() {
String header = "@E00151:HY352CCXY190421:HY352CCXY:1:1101:10003:10029 :N:0:";
FASTQHeader h1 = new FASTQHeader(header);
assertEquals("E00151", h1.getInstrument());
assertEquals(0, h1.getRunNumber()); // bad run numbers are converted to 0
assertEquals("HY352CCXY", h1.getFlowcellID());
assertEquals(1, h1.getLane());
assertEquals(1101, h1.getTile());
assertEquals(10003, h1.getX());
assertEquals(10029, h1.getY());
assertEquals(0, h1.getRead()); // bad read numbers are converted to 0
assertEquals(false, h1.isFiltered());
assertEquals(0, h1.getControlNumber());
assertEquals("", h1.getIndex());
}
@Test
// The Picard SamToFastq program also produces non-standard fastq headers
public void broad_samtofastq() {
String header = "@H2NMFCCXY170825:1:1101:10003:10029/2";
FASTQHeader h1 = new FASTQHeader(header);
assertEquals("", h1.getInstrument());
assertEquals(0, h1.getRunNumber());
assertEquals("H2NMFCCXY", h1.getFlowcellID());
assertEquals(1, h1.getLane());
assertEquals(1101, h1.getTile());
assertEquals(10003, h1.getX());
assertEquals(10029, h1.getY());
assertEquals(2, h1.getRead());
assertEquals(false, h1.isFiltered());
assertEquals(0, h1.getControlNumber());
assertEquals("", h1.getIndex());
}
@Test
public void fastqWithIndexAndBarcodeKey() {
String header = "@NS500217:706:HGL7NBGXB:1:11101:5330:1044;CCGGATG_GGCGGTC_TGATCTC:ATCAGAG:CAGCTCT:GCTGAGA.4_CTACTCG:GACGAGT:TCGTCTA:AGTAGAC.2 1:N:0:0";
FASTQHeader h1 = new FASTQHeader(header);
assertEquals(header, h1.toString());
assertEquals(5330, h1.getX());
assertEquals(1044, h1.getY());
assertEquals(1, h1.getRead());
assertEquals(false, h1.isFiltered());
assertEquals(0, h1.getControlNumber());
IndexAndBarcodeKey key = h1.getKey();
assertEquals("CCGGATG", key.getI5Label());
assertEquals("GGCGGTC", key.getI7Label());
assertEquals("TGATCTC:ATCAGAG:CAGCTCT:GCTGAGA.4", key.getP5Label());
assertEquals("CTACTCG:GACGAGT:TCGTCTA:AGTAGAC.2", key.getP7Label());
}
}
| 33.26087 | 154 | 0.715359 |
74adf3dbc759ac809a28fd78979d68ccdfd35527 | 1,180 | package conversion.engine;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import phase.api.PhaseDB;
public class PhaseDBConverter implements Converter {
@Override
public void marshal(Object o, HierarchicalStreamWriter writer, MarshallingContext ctx) {
var db = (PhaseDB) o;
var graphConverter = new PhaseGraphConverter();
db.phaseGraphs().forEach(graph -> {
graphConverter.marshal(graph, writer, ctx);
});
var blockGraphConverter = new BlockGraphConverter();
writer.startNode("winCondition");
blockGraphConverter.marshal(db.winCondition(), writer, ctx);
writer.endNode();
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext ctx) {
return reader.getValue();
}
@Override
public boolean canConvert(Class aClass) {
return aClass.equals(PhaseDB.class);
}
}
| 33.714286 | 92 | 0.729661 |
f86b82bc9d59a861e237b774f847f205bb09d133 | 884 | package net.modificationstation.stationapi.mixin.render.client;
import net.minecraft.client.resource.ZippedTexturePack;
import net.modificationstation.stationapi.api.client.texture.atlas.ExpandableAtlas;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.io.*;
@Mixin(ZippedTexturePack.class)
public class MixinZippedTexturePack {
@Inject(method = "getResourceAsStream(Ljava/lang/String;)Ljava/io/InputStream;", at = @At("HEAD"), cancellable = true)
private void getExpandableAtlas(String name, CallbackInfoReturnable<InputStream> cir) {
ExpandableAtlas atlas = ExpandableAtlas.getByPath(name);
if (atlas != null)
cir.setReturnValue(atlas.getStream());
}
}
| 40.181818 | 122 | 0.783937 |
7f48f8912fa166836e41467c2e19a752f86bbf72 | 1,193 | package dev.vality.adapter.bank.spring.boot.starter.utils;
import dev.vality.adapter.common.utils.CardDataUtils;
import dev.vality.cds.storage.AuthData;
import dev.vality.cds.storage.CardSecurityCode;
import dev.vality.cds.storage.SessionData;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class SessionDataUtilsTest {
private static final String CARD_SECURITY_CODE = "adfdfs";
@Test
public void getCvv2() {
SessionData sessionData = new SessionData();
String cvv2 = CardDataUtils.extractCvv2(sessionData);
Assertions.assertNull(cvv2);
AuthData authData = new AuthData();
sessionData.setAuthData(authData);
cvv2 = CardDataUtils.extractCvv2(sessionData);
Assertions.assertNull(cvv2);
CardSecurityCode cardSecurityCode = new CardSecurityCode();
authData.setCardSecurityCode(cardSecurityCode);
cvv2 = CardDataUtils.extractCvv2(sessionData);
Assertions.assertNull(cvv2);
cardSecurityCode.setValue(CARD_SECURITY_CODE);
cvv2 = CardDataUtils.extractCvv2(sessionData);
Assertions.assertEquals(CARD_SECURITY_CODE, cvv2);
}
} | 29.825 | 67 | 0.732607 |
b8bc13f8eb579ccf9cb7561e9d25a07e0683e70d | 2,039 | package com.s6.plugin.feign.adapter.tools;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
public class ReplacementLibraryTest {
@Test
public void testEquals() {
{
ReplacementLibrary lib1 = new ReplacementLibrary();
lib1.setGroupId("");
lib1.setArtifactId("");
lib1.setClasses(new String[] { "" });
lib1.setSkipFiles(new String[] { "a" });
ReplacementLibrary lib2 = new ReplacementLibrary();
lib2.setGroupId(null);
lib2.setArtifactId("");
lib2.setClasses(new String[] { "" });
lib1.setSkipFiles(new String[] { "d" });
assertNotEquals(lib1, lib2);
assertEquals(lib1.hashCode(), lib2.hashCode());
}
{
ReplacementLibrary lib1 = new ReplacementLibrary();
lib1.setGroupId("");
lib1.setArtifactId("");
lib1.setClasses(new String[] { "a" });
lib1.setSkipFiles(new String[] { "d" });
ReplacementLibrary lib2 = new ReplacementLibrary();
lib2.setGroupId("");
lib2.setArtifactId("");
lib2.setClasses(new String[] { "b" });
lib1.setSkipFiles(new String[] { "c" });
assertEquals(lib1, lib2);
assertEquals(lib1.hashCode(), lib2.hashCode());
}
{
ReplacementLibrary lib1 = new ReplacementLibrary();
lib1.setGroupId("a");
lib1.setArtifactId("b");
lib1.setClasses(new String[] { "c" });
lib1.setSkipFiles(new String[] { "d" });
ReplacementLibrary lib2 = new ReplacementLibrary();
lib2.setGroupId("a");
lib2.setArtifactId("b");
lib2.setClasses(new String[] { "b" });
lib1.setSkipFiles(new String[] { "c" });
assertEquals(lib1, lib2);
assertEquals(lib1.hashCode(), lib2.hashCode());
}
}
} | 32.887097 | 63 | 0.544385 |
ce01a497b1796936337ac648182fb7e9e7da8592 | 3,502 | package com.github.kindrat.cassandra.client.ui.fx;
import com.datastax.driver.core.CodecRegistry;
import com.datastax.driver.core.DataType;
import com.datastax.driver.core.TypeCodec;
import javafx.beans.binding.DoubleBinding;
import javafx.beans.property.ReadOnlyDoubleProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumnBase;
import javafx.scene.control.Tooltip;
import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.scene.control.cell.ComboBoxTableCell;
import javafx.stage.Window;
import lombok.experimental.UtilityClass;
import org.apache.commons.lang3.EnumUtils;
import java.util.List;
import java.util.function.Function;
import static com.github.kindrat.cassandra.client.util.UIUtil.computeTextContainerWidth;
@UtilityClass
public class TableColumns {
public static <T> TableColumn<T, Object> buildColumn(DataType dataType, String labelText) {
TableColumn<T, Object> tableColumn = new TableColumn<>();
Label label = new Label(labelText);
label.setTooltip(new Tooltip(dataType.asFunctionParameterString()));
TypeCodec<Object> typeCodec = CodecRegistry.DEFAULT_INSTANCE.codecFor(dataType);
tableColumn.setCellFactory(CellFactory.create(typeCodec));
tableColumn.setGraphic(label);
tableColumn.setMinWidth(computeTextContainerWidth(label.getText(), label.getFont()));
return tableColumn;
}
public static <T> TableColumn<T, Boolean> buildCheckBoxColumn(String labelText,
Function<T, ObservableValue<Boolean>> extractor) {
TableColumn<T, Boolean> tableColumn = new TableColumn<>();
Label label = new Label(labelText);
tableColumn.setCellFactory(CheckBoxTableCell.forTableColumn(param -> {
ObservableList<T> items = tableColumn.getTableView().getItems();
return extractor.apply(items.get(param));
}));
tableColumn.setGraphic(label);
tableColumn.setMinWidth(computeTextContainerWidth(label.getText(), label.getFont()));
return tableColumn;
}
public static <T, S extends Enum<S>> TableColumn<T, S> buildColumn(Class<S> enumType, String labelText) {
TableColumn<T, S> tableColumn = new TableColumn<>();
Label label = new Label(labelText);
label.setTooltip(new Tooltip(enumType.getSimpleName()));
List<S> values = EnumUtils.getEnumList(enumType);
tableColumn.setCellFactory(param -> {
ComboBoxTableCell<T, S> cell = new ComboBoxTableCell<>(FXCollections.observableArrayList(values));
cell.setConverter(new EnumStringConverter<>(enumType));
return cell;
});
tableColumn.setGraphic(label);
tableColumn.setMinWidth(computeTextContainerWidth(label.getText(), label.getFont()));
return tableColumn;
}
public static <T, S> void bindTableColumnWidth(TableColumnBase<S, T> column, Window parent, double percents) {
ReadOnlyDoubleProperty parentWidth = parent.widthProperty();
DoubleBinding width = parentWidth.multiply(percents);
column.setPrefWidth(width.doubleValue());
column.prefWidthProperty().bind(width);
column.minWidthProperty().bind(width);
column.maxWidthProperty().bind(width);
}
}
| 43.234568 | 116 | 0.719589 |
a38b1a9a9980f6abe4689b25a3145aba955a3bc8 | 476 | package nl.quintor.studybits.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.Entity;
@Embeddable
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Transcript {
@Column
private String degree;
@Column
private String status;
@Column
private String average;
@Column
private boolean proven;
}
| 17 | 36 | 0.768908 |
c2ee9b6c53eb896eebffaab81437f285fcc331c2 | 2,061 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.smartdata.model.rule;
import org.smartdata.model.RuleInfo;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class RulePluginManager {
private static final RulePluginManager inst = new RulePluginManager();
private static List<RulePlugin> plugins = new ArrayList<>();
private RulePluginManager() {
}
public static RulePluginManager getInstance() {
return inst;
}
public static synchronized void addPlugin(RulePlugin plugin) {
if (!plugins.contains(plugin)) {
plugins.add(plugin);
}
}
public static synchronized void deletePlugin(RulePlugin plugin) {
if (plugins.contains(plugin)) {
plugins.remove(plugin);
}
}
public static synchronized List<RulePlugin> getPlugins() {
List<RulePlugin> copy = new ArrayList<>();
copy.addAll(plugins);
return copy;
}
public static void onAddingNewRule(RuleInfo ruleInfo, TranslateResult tr)
throws IOException {
for (RulePlugin plugin : getPlugins()) {
plugin.onAddingNewRule(ruleInfo, tr);
}
}
public static void onNewRuleAdded(RuleInfo ruleInfo, TranslateResult tr) {
for (RulePlugin plugin : getPlugins()) {
plugin.onNewRuleAdded(ruleInfo, tr);
}
}
}
| 29.869565 | 76 | 0.725376 |
fc10d1dbdaa250f036b68a1b17037cafeada0b53 | 526 | package org.odddev.githubsearcher.core.di;
import android.support.annotation.NonNull;
/**
* @author kenrube
* @since 01.12.16
*/
public class Injector {
private static AppComponent appComponent;
public static void init(@NonNull AppComponent appComponent) {
Injector.appComponent = appComponent;
}
@NonNull
public static AppComponent getAppComponent() {
if (appComponent == null) throw new RuntimeException("AppComponent not initialized yet!");
return appComponent;
}
}
| 21.916667 | 98 | 0.705323 |
a4379103d84f03524331d1c2e832c448c6393779 | 7,451 | /*
* Copyright 2012-2015 MarkLogic Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marklogic.client.impl;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.marklogic.client.DatabaseClientFactory.HandleFactoryRegistry;
import com.marklogic.client.admin.ExtensionMetadata;
import com.marklogic.client.admin.ExtensionMetadata.ScriptLanguage;
import com.marklogic.client.admin.ResourceExtensionsManager;
import com.marklogic.client.io.Format;
import com.marklogic.client.io.marker.ContentHandle;
import com.marklogic.client.io.marker.StructureReadHandle;
import com.marklogic.client.io.marker.TextReadHandle;
import com.marklogic.client.io.marker.TextWriteHandle;
import com.marklogic.client.util.RequestParameters;
@SuppressWarnings({"unchecked", "rawtypes"})
class ResourceExtensionsImpl
extends AbstractLoggingManager
implements ResourceExtensionsManager
{
static final private Logger logger = LoggerFactory.getLogger(ResourceExtensionsImpl.class);
private RESTServices services;
private HandleFactoryRegistry handleRegistry;
ResourceExtensionsImpl(RESTServices services) {
super();
this.services = services;
}
HandleFactoryRegistry getHandleRegistry() {
return handleRegistry;
}
void setHandleRegistry(HandleFactoryRegistry handleRegistry) {
this.handleRegistry = handleRegistry;
}
@Override
public <T> T listServicesAs(Format format, Class<T> as) {
return listServicesAs(format, as, true);
}
@Override
public <T> T listServicesAs(Format format, Class<T> as, boolean refresh) {
ContentHandle<T> handle = getHandleRegistry().makeHandle(as);
if (!StructureReadHandle.class.isAssignableFrom(handle.getClass())) {
throw new IllegalArgumentException(
"Handle "+handle.getClass().getName()+
" cannot be used to list resource services as "+as.getName()
);
}
Utilities.setHandleStructuredFormat(handle, format);
listServices((StructureReadHandle) handle, refresh);
return handle.get();
}
@Override
public <T extends StructureReadHandle> T listServices(T listHandle) {
return listServices(listHandle, true);
}
@Override
public <T extends StructureReadHandle> T listServices(T listHandle, boolean refresh) {
if (listHandle == null)
throw new IllegalArgumentException("null handle for listing resource services");
if (logger.isInfoEnabled())
logger.info("Reading resource services list");
HandleImplementation listBase = HandleAccessor.checkHandle(listHandle, "resource");
Format listFormat = listBase.getFormat();
if (!(Format.JSON == listFormat || Format.XML == listFormat))
throw new IllegalArgumentException(
"list handle for unsupported format: "+listFormat.getClass().getName());
RequestParameters extraParams = null;
if (!refresh) {
extraParams = new RequestParameters();
extraParams.put("refresh", "false");
}
listBase.receiveContent(
services.getValues(requestLogger, "config/resources", extraParams,
listFormat.getDefaultMimetype(), listBase.receiveAs())
);
return listHandle;
}
@Override
public <T> T readServicesAs(String resourceName, Class<T> as) {
ContentHandle<T> handle = getHandleRegistry().makeHandle(as);
if (!TextReadHandle.class.isAssignableFrom(handle.getClass())) {
throw new IllegalArgumentException(
"Handle "+handle.getClass().getName()+
" cannot be used to read resource service source as "+as.getName()
);
}
readServices(resourceName, (TextReadHandle) handle);
return handle.get();
}
@Override
public <T extends TextReadHandle> T readServices(String resourceName, T sourceHandle) {
if (resourceName == null)
throw new IllegalArgumentException("Reading resource services source with null name");
if (logger.isInfoEnabled())
logger.info("Reading resource services source for {}", resourceName);
HandleImplementation sourceBase =
HandleAccessor.checkHandle(sourceHandle, "resource");
sourceBase.receiveContent(
services.getValue(requestLogger, "config/resources", resourceName, true,
sourceBase.getMimetype(), sourceBase.receiveAs())
);
return sourceHandle;
}
@Override
public void writeServicesAs(
String resourceName, Object source, ExtensionMetadata metadata, MethodParameters... methodParams
) {
if (source == null) {
throw new IllegalArgumentException("no source to write");
}
Class<?> as = source.getClass();
TextWriteHandle sourceHandle = null;
if (TextWriteHandle.class.isAssignableFrom(as)) {
sourceHandle = (TextWriteHandle) source;
} else {
ContentHandle<?> handle = getHandleRegistry().makeHandle(as);
if (!TextWriteHandle.class.isAssignableFrom(handle.getClass())) {
throw new IllegalArgumentException(
"Handle "+handle.getClass().getName()+
" cannot be used to write resource service source as "+as.getName()
);
}
Utilities.setHandleContent(handle, source);
sourceHandle = (TextWriteHandle) handle;
}
writeServices(resourceName, sourceHandle, metadata, methodParams);
}
@Override
public void writeServices(
String resourceName, TextWriteHandle sourceHandle, ExtensionMetadata metadata, MethodParameters... methodParams
) {
if (resourceName == null)
throw new IllegalArgumentException("Writing resource services with null name");
if (logger.isInfoEnabled())
logger.info("Writing resource services source for {}", resourceName);
HandleImplementation sourceBase =
HandleAccessor.checkHandle(sourceHandle, "resource");
RequestParameters extraParams =
(metadata != null) ? metadata.asParameters() : new RequestParameters();
if (methodParams != null) {
for (MethodParameters params : methodParams) {
String method = params.getMethod().toString().toLowerCase();
extraParams.add("method", method);
String prefix = method+":";
for (Map.Entry<String,List<String>> entry: params.entrySet()) {
extraParams.put(prefix+entry.getKey(), entry.getValue());
}
}
}
String contentType = null;
if ( metadata == null ) {
} else if ( metadata.getScriptLanguage() == null ) {
throw new IllegalArgumentException("scriptLanguage cannot be null");
} else if ( metadata.getScriptLanguage() == ScriptLanguage.JAVASCRIPT ) {
contentType = "application/vnd.marklogic-javascript";
} else if ( metadata.getScriptLanguage() == ScriptLanguage.XQUERY ) {
contentType = "application/xquery";
}
services.putValue(requestLogger, "config/resources", resourceName, extraParams,
contentType, sourceBase);
}
@Override
public void deleteServices(String resourceName) {
if (resourceName == null)
throw new IllegalArgumentException("Deleting resource services with null name");
if (logger.isInfoEnabled())
logger.info("Deleting resource services for {}", resourceName);
services.deleteValue(requestLogger, "config/resources", resourceName);
}
}
| 33.714932 | 113 | 0.745403 |
4ec7114543fb9d48c56289962494921c2208f550 | 10,307 | package com.demoncat.dcapp.network;
import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;
import org.spongycastle.jce.provider.BouncyCastleProvider;
import org.spongycastle.jsse.provider.BouncyCastleJsseProvider;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import javax.net.ssl.HandshakeCompletedEvent;
import javax.net.ssl.HandshakeCompletedListener;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
/**
* Make ssl factory and provide host name verify.
* @author archermind on 2017/5/7
*/
public class SSLHelper {
private static final String TAG = SSLHelper.class.getSimpleName();
private static final String CERT_ENTRY_ALIAS = "trust";
/**
* Get ssl socket factory according to correspond certificate
* @param context
* @param cert
* @param factory
* @return
*/
public static SSLSocketFactory getSSLSocketFactoryLocally(Context context, String cert, TrustManagerFactory factory) {
if (context == null) {
Log.e(TAG, "getSSLSocketFactory context is null.");
return null;
}
Security.setProperty("ocsp.enable", "true");
System.setProperty("com.sun.net.ssl.checkRevocation", "true");
System.setProperty("com.sun.security.enableCRLDP", "true");
System.setProperty("jdk.tls.client.enableStatusRequestExtension", "true");
// socket connect timeout
System.setProperty("sun.net.client.defaultConnectTimeout", String
.valueOf(50000));// (单位:毫秒)
System.setProperty("sun.net.client.defaultReadTimeout", String
.valueOf(50000)); // (单位:毫秒)
CertificateFactory certificateFactory;
try {
certificateFactory = CertificateFactory.getInstance("X.509",
BouncyCastleProvider.PROVIDER_NAME);
Log.d(TAG, "getSSLSocketFactory cf: " +
certificateFactory + ", provider: " + certificateFactory.getProvider());
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType(),
BouncyCastleProvider.PROVIDER_NAME);
Log.d(TAG, "getSSLSocketFactory ks: " +
KeyStore.getDefaultType() + ", provider: " + keyStore.getProvider());
keyStore.load(null, null);
InputStream certificate = context.getAssets().open(cert);
Certificate cer = certificateFactory.generateCertificate(certificate);
keyStore.setCertificateEntry(CERT_ENTRY_ALIAS, cer);
if (certificate != null) {
certificate.close();
}
SSLContext sslContext = SSLContext.getInstance("TLSv1.2",
BouncyCastleJsseProvider.PROVIDER_NAME);
Log.d(TAG, "getSSLSocketFactory sslContext provider: " + sslContext.getProvider());
factory.init(keyStore);
Provider provider = factory.getProvider();
Log.d(TAG, "getSSLSocketFactory trust factory provider: " + provider);
TrustManager[] trustManagers = factory.getTrustManagers();
for (int i = 0; i < trustManagers.length; i ++) {
Log.d(TAG,
"getSSLSocketFactory trust manager " + i + ", " + trustManagers[i]);
}
sslContext.init(null, factory.getTrustManagers(), new SecureRandom());
SSLSocketFactory socketFactory = sslContext.getSocketFactory();
Log.d(TAG, "getSSLSocketFactory socket factory: " + socketFactory +
"provider: " + provider);
return new Tls12SocketFactory(socketFactory);
} catch (Exception e) {
Log.d(TAG, "getSSLSocketFactoryFromAssets error occurs.", e);
e.printStackTrace();
}
return null;
}
/**
* Get X509 Trust Manager
* @param factory
* @return
*/
public static X509TrustManager getX509TrustManager(TrustManagerFactory factory) {
if (factory != null) {
TrustManager[] managers = factory.getTrustManagers();
for (TrustManager manager : managers) {
if (manager != null && manager instanceof X509TrustManager) {
return (X509TrustManager) manager;
}
}
}
return null;
}
/**
* Get trust manager factory
* @return
*/
public static TrustManagerFactory getTrustManagerFactory() {
try {
TrustManagerFactory factory = TrustManagerFactory.getInstance("PKIX",
BouncyCastleJsseProvider.PROVIDER_NAME);
Log.d(TAG,
"getTrustManagerFactory algorithm: " + factory.getAlgorithm() +
", provider: " + factory.getProvider());
return factory;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
}
return null;
}
/**
* Get host verifier for specified host urls
* @param hostUrls
* @return
*/
public static HostnameVerifier getHostnameVerifier(final String[] hostUrls) {
return new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
for (String host : hostUrls) {
if (host.equalsIgnoreCase(hostname)) {
return true;
}
}
return false;
// for (String host : hostUrls) {
// boolean verified
// = HttpsURLConnection.getDefaultHostnameVerifier().verify(host, session);
// if (verified) {
// return true;
// }
// }
// return false;
}
};
}
//----------Trust all https certs---------
public static SSLSocketFactory getTrustAllSSLSocketFactory() {
SSLSocketFactory ssfFactory = null;
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, new TrustManager[] { new TrustAllCerts() }, new SecureRandom());
ssfFactory = new Tls12SocketFactory(sc.getSocketFactory());
// ssfFactory = sc.getSocketFactory();
} catch (Exception e) {
e.printStackTrace();
}
return ssfFactory;
}
public static class TrustAllCerts implements X509TrustManager {
@SuppressLint("TrustAllX509TrustManager")
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
@SuppressLint("TrustAllX509TrustManager")
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
@Override
public X509Certificate[] getAcceptedIssuers() {return new X509Certificate[0];}
}
/**
* Get trust all host name verifier
* @return
*/
public static HostnameVerifier getTrustAllHostnameVerifier() {
return new HostnameVerifier() {
@SuppressLint("BadHostnameVerifier")
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
}
/*--------TLS1.1 & TLS1.2 Support---------*/
public static class Tls12SocketFactory extends SSLSocketFactory {
private static final String[] TLS_SUPPORT_VERSION = {"TLSv1.1", "TLSv1.2"};
final SSLSocketFactory delegate;
public Tls12SocketFactory(SSLSocketFactory base) {
this.delegate = base;
}
@Override
public String[] getDefaultCipherSuites() {
return delegate.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return delegate.getSupportedCipherSuites();
}
@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
return patch(delegate.createSocket(s, host, port, autoClose));
}
@Override
public Socket createSocket(String host, int port) throws IOException {
return patch(delegate.createSocket(host, port));
}
@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException {
return patch(delegate.createSocket(host, port, localHost, localPort));
}
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
return patch(delegate.createSocket(host, port));
}
@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
return patch(delegate.createSocket(address, port, localAddress, localPort));
}
private Socket patch(Socket s) {
Log.d(TAG, "patch Socket: " + s);
if (s instanceof SSLSocket) {
((SSLSocket) s).setEnabledProtocols(TLS_SUPPORT_VERSION);
((SSLSocket) s).addHandshakeCompletedListener(new HandshakeCompletedListener() {
@Override
public void handshakeCompleted(HandshakeCompletedEvent event) {
Log.d(TAG, "handshakeCompleted event: " + event);
}
});
}
return s;
}
}
}
| 37.209386 | 127 | 0.616959 |
00b16e66557aacf9ec27bea41f4776baa23af245 | 382 | package org.wso2.analytics.apim.rest.api.file;
import org.wso2.msf4j.formparam.FileInfo;
import org.wso2.msf4j.Request;
import java.io.InputStream;
import javax.ws.rs.core.Response;
public abstract class UsageApiService {
public abstract Response usageUploadFilePost(InputStream analyticsInputStream, FileInfo analyticsDetail
,Request request) throws NotFoundException;
}
| 27.285714 | 107 | 0.82199 |
ff645894838af1cf456d4c85804258c10268117b | 5,739 | package org.ga4gh.cts.api.variants;
import org.apache.avro.AvroRemoteException;
import org.ga4gh.ctk.CtkLogs;
import org.ga4gh.ctk.transport.URLMAPPING;
import org.ga4gh.ctk.transport.protocols.Client;
import org.ga4gh.cts.api.TestData;
import org.ga4gh.cts.api.Utils;
import org.ga4gh.methods.GAException;
import org.ga4gh.methods.SearchVariantSetsRequest;
import org.ga4gh.methods.SearchVariantSetsResponse;
import org.ga4gh.models.VariantSet;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test the <tt>/variantsets/search</tt> paging behavior.
*
* @author Herb Jellinek
*/
@Category(VariantsTests.class)
public class VariantSetsPagingIT implements CtkLogs {
private static Client client = new Client(URLMAPPING.getInstance());
/**
* Check that we can page 1 by 1 through the {@link VariantSet}s we receive from
* {@link org.ga4gh.ctk.transport.protocols.Client.Variants#searchVariantSets(SearchVariantSetsRequest)}.
*
* @throws AvroRemoteException if there's a communication problem or server exception ({@link GAException})
*/
@Test
public void checkPagingOneByOneThroughVariantSets() throws AvroRemoteException {
// retrieve them all first
final List<VariantSet> listOfVariantSets = Utils.getAllVariantSets(client);
assertThat(listOfVariantSets).isNotEmpty();
// we will remove VariantSets from this Set and assert at the end that we have zero
final Set<VariantSet> setOfVariants = new HashSet<>(listOfVariantSets);
assertThat(listOfVariantSets).hasSize(setOfVariants.size());
// page through the VariantSets using the same query parameters
String pageToken = null;
for (VariantSet ignored : listOfVariantSets) {
final SearchVariantSetsRequest pageReq =
SearchVariantSetsRequest.newBuilder()
.setDatasetId(TestData.getDatasetId())
.setPageSize(1)
.setPageToken(pageToken)
.build();
final SearchVariantSetsResponse pageResp = client.variants.searchVariantSets(pageReq);
final List<VariantSet> pageOfVariantSets = pageResp.getVariantSets();
pageToken = pageResp.getNextPageToken();
assertThat(pageOfVariantSets).hasSize(1);
assertThat(setOfVariants).contains(pageOfVariantSets.get(0));
setOfVariants.remove(pageOfVariantSets.get(0));
}
assertThat(pageToken).isNull();
assertThat(setOfVariants).isEmpty();
}
/**
* Check that we can page through the {@link VariantSet}s we receive from
* {@link org.ga4gh.ctk.transport.protocols.Client.Variants#searchVariantSets(SearchVariantSetsRequest)}
* using an increment as large as the non-paged set of results.
*
* @throws AvroRemoteException if there's a communication problem or server exception ({@link GAException})
*/
@Test
public void checkPagingByOneChunkThroughVariantSets() throws AvroRemoteException {
final List<VariantSet> listOfVariantSets = Utils.getAllVariantSets(client);
// page through the variants in one gulp
checkSinglePageOfVariantSets(listOfVariantSets.size(),
listOfVariantSets);
}
/**
* Check that we can page through the {@link VariantSet}s we receive from
* {@link org.ga4gh.ctk.transport.protocols.Client.Variants#searchVariantSets(SearchVariantSetsRequest)}
* using an increment twice as large as the non-paged set of results.
*
* @throws AvroRemoteException if there's a communication problem or server exception ({@link GAException})
*/
@Test
public void checkPagingByOneTooLargeChunkThroughVariantSets() throws AvroRemoteException {
final List<VariantSet> listOfVariantSets = Utils.getAllVariantSets(client);
checkSinglePageOfVariantSets(listOfVariantSets.size() * 2,
listOfVariantSets);
}
/**
* Check that we can receive expected results when we request a single
* page of {@link VariantSet}s from
* {@link org.ga4gh.ctk.transport.protocols.Client.Variants#searchVariantSets
* (SearchVariantSetsRequest)},
* using <tt>pageSize</tt> as the page size.
*
* @param pageSize the page size we'll request
* @param expectedVariantSets all of the {@link VariantSet} objects we expect to receive
* @throws AvroRemoteException if there's a communication problem or server exception
*/
private void checkSinglePageOfVariantSets(int pageSize,
List<VariantSet> expectedVariantSets)
throws AvroRemoteException {
final SearchVariantSetsRequest pageReq =
SearchVariantSetsRequest.newBuilder()
.setDatasetId(TestData.getDatasetId())
.setPageSize(pageSize)
.build();
final SearchVariantSetsResponse pageResp = client.variants.searchVariantSets(pageReq);
final List<VariantSet> pageOfVariantSets = pageResp.getVariantSets();
final String pageToken = pageResp.getNextPageToken();
assertThat(pageOfVariantSets).hasSize(expectedVariantSets.size());
assertThat(expectedVariantSets).containsAll(pageOfVariantSets);
assertThat(pageToken).isNull();
}
}
| 42.198529 | 111 | 0.67503 |
e83c0512b915593b70de31a66ac11961bd11f579 | 919 | package com.dalefe.generator.util;
import org.yaml.snakeyaml.Yaml;
import java.io.InputStream;
import java.net.URL;
/**
* @author dalefe
* @version 2019/11/07
*/
public class ConfigUtil {
private static Configuration configuration;
static {
URL url = ConfigUtil.class.getClassLoader().getResource("generator.yaml");
if (url.getPath().contains("jar")) { // 用户未提供配置文件
System.err.println("Can not find file named 'generator.yaml' at resources path, please make sure that you have defined that file.");
System.exit(0);
} else {
InputStream inputStream = ConfigUtil.class.getClassLoader().getResourceAsStream("generator.yaml");
Yaml yaml = new Yaml();
configuration = yaml.loadAs(inputStream, Configuration.class);
}
}
public static Configuration getConfiguration() {
return configuration;
}
}
| 28.71875 | 144 | 0.659412 |
e393ed0fdaa2265466889d0c6fff5032b6ebf1c8 | 1,386 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: grpc/table/table_master.proto
package alluxio.grpc.table;
public interface GetTableColumnStatisticsPRequestOrBuilder extends
// @@protoc_insertion_point(interface_extends:alluxio.grpc.table.GetTableColumnStatisticsPRequest)
com.google.protobuf.MessageOrBuilder {
/**
* <code>optional string db_name = 1;</code>
*/
boolean hasDbName();
/**
* <code>optional string db_name = 1;</code>
*/
java.lang.String getDbName();
/**
* <code>optional string db_name = 1;</code>
*/
com.google.protobuf.ByteString
getDbNameBytes();
/**
* <code>optional string table_name = 2;</code>
*/
boolean hasTableName();
/**
* <code>optional string table_name = 2;</code>
*/
java.lang.String getTableName();
/**
* <code>optional string table_name = 2;</code>
*/
com.google.protobuf.ByteString
getTableNameBytes();
/**
* <code>repeated string col_names = 3;</code>
*/
java.util.List<java.lang.String>
getColNamesList();
/**
* <code>repeated string col_names = 3;</code>
*/
int getColNamesCount();
/**
* <code>repeated string col_names = 3;</code>
*/
java.lang.String getColNames(int index);
/**
* <code>repeated string col_names = 3;</code>
*/
com.google.protobuf.ByteString
getColNamesBytes(int index);
}
| 24.315789 | 102 | 0.65873 |
1c2af6e80d504ca4a1d65c28c7459665dc17afab | 1,033 | package com.fastjrun.web.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class JsonFilter implements Filter {
private static final Log log = LogFactory.getLog(JsonFilter.class);
public void init(FilterConfig initconfig) throws ServletException {
}
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
String reqMsg = IOUtils.toString(request.getInputStream());
String reqestUrl = request.getRequestURI();
log.info("reqMsg is :\t"+reqestUrl+"\t"+reqMsg);
chain.doFilter(req, res);
}
public void destroy() {
}
}
| 29.514286 | 120 | 0.796709 |
680d3617153ea9d85d9e83b97ddee5e788cf14f3 | 12,451 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.lenya.cms.publication;
//import org.apache.lenya.cms.publication.util.DocumentSet;
/**
* Helper to manage documents. It takes care of attachments etc.
*
* @version $Id$
*/
public interface DocumentManager {
/**
* The Avalon component role.
*/
String ROLE = DocumentManager.class.getName();
/**
* Copies a document from one location to another location.
* @param sourceDocument The document to copy.
* @param destination The destination document.
* @throws PublicationException if a document which destinationDocument depends on does not
* exist.
*/
//florent commented cause of change in document api
/*
void copy(Document sourceDocument, DocumentLocator destination) throws PublicationException;
*/
/**
* Copies a document to another area.
* @param sourceDocument The document to copy.
* @param destinationArea The destination area.
* @throws PublicationException if a document which the destination document depends on does not
* exist.
*/
//florent commented cause of change in document api
/*
void copyToArea(Document sourceDocument, String destinationArea) throws PublicationException;
*/
/**
* Copies a document set to another area.
* @param documentSet The document set to copy.
* @param destinationArea The destination area.
* @throws PublicationException if a document which one of the destination documents depends on
* does not exist.
*/
//florent commented cause of change in document api
/*
void copyToArea(DocumentSet documentSet, String destinationArea) throws PublicationException;
*/
/**
* Creates a new document in the same publication the <code>parentDocument</code> belongs to
* with the given parameters:
*
* @param sourceDocument The document to initialize the contents and meta data from.
* @param area The target area.
* @param path The target path.
* @param language The target language.
* @param extension The extension to use for the document source.
* @param navigationTitle navigation title
* @param visibleInNav determines the visibility of a node in the navigation
* @return The added document.
*
* @throws DocumentBuildException if the document can not be created
* @throws PublicationException if the document is already contained.
*/
//florent : comment cause of document.getPublication() not still in api
/*
Document add(Document sourceDocument, String area, String path, String language,
String extension, String navigationTitle, boolean visibleInNav)
throws DocumentBuildException, PublicationException;
*/
/**
* Creates a new document with the given parameters:
* @param resourceType the document type (aka resource type) of the new document
* @param contentSourceUri The URI to read the content from.
* @param pub The publication.
* @param area The area.
* @param path The path.
* @param language The language.
* @param extension The extension to use for the document source, without the leading dot.
* @param navigationTitle The navigation title.
* @param visibleInNav The navigation visibility.
* @return The added document.
*
* @throws DocumentBuildException if the document can not be created
* @throws PublicationException if the document is already contained.
*/
//florent : comment cause of document.getPublication() not still in api
/*
Document add(ResourceType resourceType, String contentSourceUri,
Publication pub, String area, String path, String language, String extension,
String navigationTitle, boolean visibleInNav) throws DocumentBuildException,
PublicationException;
*/
/**
* Creates a new document without adding it to the site structure.
* @param resourceType the document type (aka resource type) of the new document
* @param contentSourceUri The URI to read the content from.
* @param pub The publication.
* @param area The area.
* @param language The language.
* @param extension The extension to use for the document source, without the leading dot.
* @return The added document.
*
* @throws DocumentBuildException if the document can not be created
* @throws PublicationException if the document is already contained.
*/
//florent : comment cause of document.getPublication() not still in api
/*
Document add(ResourceType resourceType, String contentSourceUri,
Publication pub, String area, String language, String extension)
throws DocumentBuildException, PublicationException;
*/
/**
* Adds a new version of a document with a different language and / or in a different area.
*
* @param sourceDocument The document to initialize the contents and meta data from.
* @param area The area.
* @param language The language of the new document.
* @return The added document.
*
* @throws DocumentBuildException if the document can not be created
* @throws PublicationException if the document is already contained.
*/
//florent : comment cause of document.getPublication() not still in api
/*
Document addVersion(Document sourceDocument, String area, String language)
throws DocumentBuildException, PublicationException;
*/
/**
* Adds a new version of a document with a different language and / or in a different area.
*
* @param sourceDocument The document to initialize the contents and meta data from.
* @param area The area.
* @param language The language of the new document.
* @param addToSite If the new version should be added to the site structure.
* @return The added document.
*
* @throws DocumentBuildException if the document can not be created
* @throws PublicationException if the document is already contained.
*/
//florent : comment cause of document.getPublication() not still in api
/*
Document addVersion(Document sourceDocument, String area, String language, boolean addToSite)
throws DocumentBuildException, PublicationException;
*/
/**
* Deletes a document from the content repository and from the site structure.
* @param document The document to delete.
* @throws PublicationException when something went wrong.
*/
//florent commented cause of change in document api
/*
void delete(Document document) throws PublicationException;
*/
/**
* Moves a document from one location to another.
* @param sourceDocument The source document.
* @param destination The destination document.
* @throws PublicationException if a document which the destination document depends on does not
* exist.
*/
//florent commented cause of change in document api
/*
void move(Document sourceDocument, DocumentLocator destination) throws PublicationException;
*/
/**
* Moves a document set from one location to another. A source is moved to the destination of
* the same position in the set.
* @param sources The source documents.
* @param destinations The destination documents.
* @throws PublicationException if a document which the destination document depends on does not
* exist.
*/
//florent : comment cause of document.getPublication() not still in api
/*
void move(DocumentSet sources, DocumentSet destinations) throws PublicationException;
*/
/**
* Copies a document set from one location to another. A source is copied to the destination of
* the same position in the set.
* @param sources The source documents.
* @param destinations The destination documents.
* @throws PublicationException if a document which the destination document depends on does not
* exist.
*/
//florent : comment cause of document.getPublication() not still in api
/*
void copy(DocumentSet sources, DocumentSet destinations) throws PublicationException;
*/
/**
* Moves a document to another location, incl. all requiring documents. If a sitetree is used,
* this means that the whole subtree is moved.
* @param sourceArea The source area.
* @param sourcePath The source path.
* @param targetArea The target area.
* @param targetPath The target path.
* @throws PublicationException if an error occurs.
*/
//florent : comment cause of document.getPublication() not still in api
/*
void moveAll(Area sourceArea, String sourcePath, Area targetArea, String targetPath)
throws PublicationException;
*/
/**
* Moves all language versions of a document to another location.
* @param sourceArea The source area.
* @param sourcePath The source path.
* @param targetArea The target area.
* @param targetPath The target path.
* @throws PublicationException if the documents could not be moved.
*/
//florent : comment cause of document.getPublication() not still in api
/*
void moveAllLanguageVersions(Area sourceArea, String sourcePath, Area targetArea,
String targetPath) throws PublicationException;
*/
/**
* Copies a document to another location, incl. all requiring documents. If a sitetree is used,
* this means that the whole subtree is copied.
* @param sourceArea The source area.
* @param sourcePath The source path.
* @param targetArea The target area.
* @param targetPath The target path.
* @throws PublicationException if an error occurs.
*/
//florent : comment cause of document.getPublication() not still in api
/*
void copyAll(Area sourceArea, String sourcePath, Area targetArea, String targetPath)
throws PublicationException;
*/
/**
* Copies all language versions of a document to another location.
* @param sourceArea The source area.
* @param sourcePath The source path.
* @param targetArea The target area.
* @param targetPath The target path.
* @throws PublicationException if the documents could not be copied.
*/
//florent : comment cause of document.getPublication() not still in api
/*
void copyAllLanguageVersions(Area sourceArea, String sourcePath, Area targetArea,
String targetPath) throws PublicationException;
*/
/**
* Deletes a document, incl. all requiring documents. If a sitetree is used, this means that the
* whole subtree is deleted.
* @param document The document.
* @throws PublicationException if an error occurs.
*/
//florent commented cause of change in document api
//void deleteAll(Document document) throws PublicationException;
/**
* Deletes all language versions of a document.
* @param document The document.
* @throws PublicationException if the documents could not be copied.
*/
//florent commented cause of change in document api
/*
void deleteAllLanguageVersions(Document document) throws PublicationException;
*/
/**
* Deletes a set of documents.
* @param documents The documents.
* @throws PublicationException if an error occurs.
*/
//florent commented cause of change in document api
/*
void delete(DocumentSet documents) throws PublicationException;
*/
} | 41.503333 | 100 | 0.69392 |
5f1ae048532a7c2aa0cf6c58ac3f55aa209e439c | 1,674 | package leetcode141_150;
/**Sort a linked list using insertion sort.
* Created by eugene on 16/3/6.
*/
public class InsertionSortList {
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
//虽然简洁,但更tricky
public ListNode insertionSortList0(ListNode head) {
ListNode dummy = new ListNode(0);
ListNode pre = dummy;
ListNode cur = head;
while(cur!=null) {
pre = dummy;
while(pre.next!=null && pre.next.val<cur.val) {
pre = pre.next;
}
ListNode next = cur.next;
cur.next = pre.next;
pre.next = cur;
cur = next;
}
return dummy.next;
}
//易于理解,常规思路
public ListNode insertionSortList(ListNode head) {
if (head==null) return null;
if (head.next==null) return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = head;
ListNode curr = head.next;
while (curr!=null) {
if (curr.val<pre.val){
pre.next = curr.next;
ListNode p = dummy;
ListNode q = dummy.next;
while (q!=null){
if (curr.val<q.val){
p.next = curr;
curr.next = q;
break;
}
p = q;
q = q.next;
}
curr = pre.next;
} else {
pre = curr;
curr = curr.next;
}
}
return dummy.next;
}
}
| 26.15625 | 59 | 0.44325 |
fc52b6b59836ba83d5e492de4af1cf260930ca84 | 2,052 | package org.n52.gfz.riesgos.functioninterfaces;
import java.io.IOException;
import java.io.Serializable;
/*
* Copyright (C) 2019 GFZ German Research Centre for Geosciences
*
* 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://apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
import org.n52.gfz.riesgos.cache.DataWithRecreatorTuple;
import org.n52.gfz.riesgos.cmdexecution.IExecutionContext;
import org.n52.gfz.riesgos.exceptions.ConvertToIDataException;
import org.n52.wps.io.data.IData;
/**
* Interface to read the idata from one or moore files
* (maybe on a container).
* @param <T> Type of data
*/
public interface IReadIDataFromFiles<T extends IData> extends Serializable {
/**
* Reads the idata from the filesystem (maybe multiple files, maybe from a
* container).
* @param context context (maybe the container)
* @param workingDirectory the working directory in which the file is /
* the files are
* @param path basic path of a single file / the main file if there are
* several
* @return IData with the recreator (for a caching mechanism)
* @throws ConvertToIDataException if the conversion is not possible this
* exception will be thrown
* @throws IOException will be thrown if there is problem on the IO
* mechanism on java
*/
DataWithRecreatorTuple<T> readFromFiles(
IExecutionContext context,
String workingDirectory,
String path
) throws ConvertToIDataException, IOException;
}
| 38 | 78 | 0.697368 |
4b94c5e7b8c558c80e0060c89d539da1d7ee5dee | 3,200 | /* jcifs smb client library in Java
* Copyright (C) 2000 "Michael B. Allen" <jcifs at samba dot org>
*
* This library 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 2.1 of the License, or (at your option) any later version.
*
* This library 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 this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package jcifs.internal.smb1.com;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jcifs.CIFSContext;
import jcifs.Configuration;
import jcifs.internal.Request;
import jcifs.internal.smb1.SMB1SigningDigest;
import jcifs.internal.smb1.ServerMessageBlock;
import jcifs.internal.util.SMBUtil;
/**
*
*
*/
public class SmbComClose extends ServerMessageBlock implements Request<SmbComBlankResponse> {
private static final Logger log = LoggerFactory.getLogger(SmbComClose.class);
private int fid;
private long lastWriteTime;
/**
*
* @param config
* @param fid
* @param lastWriteTime
*/
public SmbComClose ( Configuration config, int fid, long lastWriteTime ) {
super(config, SMB_COM_CLOSE);
this.fid = fid;
this.lastWriteTime = lastWriteTime;
}
/**
* {@inheritDoc}
*
* @see jcifs.internal.smb1.ServerMessageBlock#getResponse()
*/
@Override
public final SmbComBlankResponse getResponse () {
return (SmbComBlankResponse) super.getResponse();
}
/**
* {@inheritDoc}
*
* @see jcifs.internal.Request#initResponse(jcifs.CIFSContext)
*/
@Override
public SmbComBlankResponse initResponse ( CIFSContext tc ) {
SmbComBlankResponse resp = new SmbComBlankResponse(tc.getConfig());
setResponse(resp);
return resp;
}
@Override
protected int writeParameterWordsWireFormat ( byte[] dst, int dstIndex ) {
SMBUtil.writeInt2(this.fid, dst, dstIndex);
dstIndex += 2;
if ( this.digest != null ) {
SMB1SigningDigest.writeUTime(getConfig(), this.lastWriteTime, dst, dstIndex);
}
else {
log.trace("SmbComClose without a digest");
}
return 6;
}
@Override
protected int writeBytesWireFormat ( byte[] dst, int dstIndex ) {
return 0;
}
@Override
protected int readParameterWordsWireFormat ( byte[] buffer, int bufferIndex ) {
return 0;
}
@Override
protected int readBytesWireFormat ( byte[] buffer, int bufferIndex ) {
return 0;
}
@Override
public String toString () {
return new String("SmbComClose[" + super.toString() + ",fid=" + this.fid + ",lastWriteTime=" + this.lastWriteTime + "]");
}
}
| 26.890756 | 129 | 0.667188 |
f582eb8c879db6cdee826d9aa90ec5f92ffd03ea | 1,663 | /*
* Copyright 2019-2021 CloudNetService team & contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.dytanic.cloudnet.network.listener;
import de.dytanic.cloudnet.CloudNet;
import de.dytanic.cloudnet.driver.network.INetworkChannel;
import de.dytanic.cloudnet.driver.network.protocol.IPacket;
import de.dytanic.cloudnet.driver.network.protocol.IPacketListener;
import de.dytanic.cloudnet.driver.service.ServiceInfoSnapshot;
import de.dytanic.cloudnet.service.ICloudService;
import de.dytanic.cloudnet.service.ICloudServiceManager;
public final class PacketClientServiceInfoUpdateListener implements IPacketListener {
@Override
public void handle(INetworkChannel channel, IPacket packet) {
ServiceInfoSnapshot serviceInfoSnapshot = packet.getBuffer().readObject(ServiceInfoSnapshot.class);
ICloudServiceManager cloudServiceManager = CloudNet.getInstance().getCloudServiceManager();
ICloudService cloudService = cloudServiceManager.getCloudService(serviceInfoSnapshot.getServiceId().getUniqueId());
if (cloudService != null) {
cloudService.updateServiceInfoSnapshot(serviceInfoSnapshot);
}
}
}
| 40.560976 | 119 | 0.794949 |
5a670444ff43f302d24fdd5f51c82c08ba6653a5 | 6,766 | // Dstl (c) Crown Copyright 2017
package uk.gov.dstl.baleen.consumers.csv;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.apache.uima.UimaContext;
import org.apache.uima.fit.descriptor.ConfigurationParameter;
import org.apache.uima.fit.descriptor.ExternalResource;
import org.apache.uima.fit.util.JCasUtil;
import org.apache.uima.jcas.JCas;
import org.apache.uima.resource.ResourceInitializationException;
import uk.gov.dstl.baleen.resources.SharedStopwordResource;
import uk.gov.dstl.baleen.resources.utils.StopwordUtils;
import uk.gov.dstl.baleen.types.language.Sentence;
import uk.gov.dstl.baleen.types.language.WordToken;
import uk.gov.dstl.baleen.types.semantic.Entity;
/**
* Write coreference information to a CSV.
*
* <p>The format is as follows:
*
* <ul>
* <li>source
* <li>id
* <li>reference
* <li>type
* <li>text
* <li>value
* <li>EntityCount
* <li>then EntityCount * Entities (value, type)
* <li>nonEntityNonStopWordsCount
* <li>nonEntityNonStopWordsCount * nonEntityNonStopWords ( (format word then pos)
* <li>NonStopWordsNotCoveredByEntitiesCount
* <li>then NonStopWordsNotCoveredByEntitiesCount * NonStopWordsNotCoveredByEntities (format word
* then pos)
* </ul>
*
* @baleen.javadoc
*/
public class Coreference extends AbstractCsvConsumer {
/**
* The stoplist to use. If the stoplist matches one of the enum's provided in {@link
* uk.gov.dstl.baleen.resources.SharedStopwordResource.StopwordList}, then that list will be
* loaded.
*
* <p>Otherwise, the string is taken to be a file path and that file is used. The format of the
* file is expected to be one stopword per line.
*
* @baleen.config DEFAULT
*/
public static final String PARAM_STOPLIST = "stoplist";
@ConfigurationParameter(name = PARAM_STOPLIST, defaultValue = "DEFAULT")
protected String stoplist;
/**
* Connection to Stopwords Resource
*
* @baleen.resource uk.gov.dstl.baleen.resources.SharedStopwordResource
*/
public static final String KEY_STOPWORDS = "stopwords";
@ExternalResource(key = KEY_STOPWORDS)
protected SharedStopwordResource stopwordResource;
protected Collection<String> stopwords;
@Override
public void doInitialize(UimaContext aContext) throws ResourceInitializationException {
super.doInitialize(aContext);
try {
stopwords =
stopwordResource.getStopwords(SharedStopwordResource.StopwordList.valueOf(stoplist));
} catch (IOException ioe) {
getMonitor().error("Unable to load stopwords", ioe);
throw new ResourceInitializationException(ioe);
}
write(
"source",
"id",
"reference",
"type",
"value",
"EntityCount then Entities... "
+ "then nonEntityNonStopWords (format word then pos) "
+ "then NonStopWordsNotCoveredByEntitiesCount "
+ "then (format word then pos)...");
}
@Override
protected void write(JCas jCas) {
final String source = getDocumentAnnotation(jCas).getSourceUri();
// For each entity we need to find all the other sentences they are contained in
// This should be all entities and sentences
final Map<Entity, List<Sentence>> coveringSentence =
JCasUtil.indexCovering(jCas, Entity.class, Sentence.class);
final Map<Sentence, List<Entity>> coveredEntities =
JCasUtil.indexCovered(jCas, Sentence.class, Entity.class);
final Map<Sentence, List<WordToken>> coveredTokens =
JCasUtil.indexCovered(jCas, Sentence.class, WordToken.class);
final Map<WordToken, List<Entity>> coveringEntity =
JCasUtil.indexCovering(jCas, WordToken.class, Entity.class);
JCasUtil.select(jCas, Entity.class).stream()
.map(
e ->
convertEntityToRow(
source, coveringSentence, coveredEntities, coveredTokens, coveringEntity, e))
.filter(s -> s.length > 0)
.forEach(this::write);
}
private String[] convertEntityToRow(
final String source,
final Map<Entity, List<Sentence>> coveringSentence,
final Map<Sentence, List<Entity>> coveredEntities,
final Map<Sentence, List<WordToken>> coveredTokens,
final Map<WordToken, List<Entity>> coveringEntity,
Entity e) {
final List<String> list = new ArrayList<>();
Sentence sentence = null;
final Collection<Sentence> sentences = coveringSentence.get(e);
if (!sentences.isEmpty()) {
sentence = sentences.iterator().next();
} else {
getMonitor().error("Entity without sentence {}", e.getCoveredText());
return new String[0];
}
list.add(source);
list.add(e.getExternalId());
if (e.getReferent() != null) {
list.add(Long.toString(e.getReferent().getInternalId()));
} else {
list.add("");
}
list.add(e.getType().getShortName());
list.add(normalize(e.getValue()));
final Collection<Entity> entities = coveredEntities.get(sentence);
// Entities
final int entityCountIndex = list.size();
int entityCount = 0;
list.add("0");
for (final Entity x : entities) {
if (x.getInternalId() != e.getInternalId()) {
list.add(normalize(x.getValue()));
list.add(x.getType().getShortName());
entityCount++;
}
}
list.set(entityCountIndex, Integer.toString(entityCount));
// Add (non-stop) words - separate out the entities from the other words
final List<WordToken> entityNonStopWords = new ArrayList<>();
final List<WordToken> nonEntityNonStopWords = new ArrayList<>();
for (final WordToken t : coveredTokens.get(sentence)) {
// Filter out entities
final String word = t.getCoveredText();
if (StopwordUtils.isStopWord(word, stopwords, false)) {
final Collection<Entity> collection = coveringEntity.get(t);
if (collection == null || collection.isEmpty()) {
nonEntityNonStopWords.add(t);
} else if (!collection.stream().anyMatch(x -> e.getInternalId() == x.getInternalId())) {
// Output any entity other than the one we are processing
entityNonStopWords.add(t);
}
}
}
// Output
list.add(Integer.toString(entityNonStopWords.size()));
entityNonStopWords.forEach(
t -> {
list.add(normalize(t.getCoveredText()));
list.add(t.getPartOfSpeech());
});
list.add(Integer.toString(nonEntityNonStopWords.size()));
nonEntityNonStopWords.forEach(
t -> {
list.add(normalize(t.getCoveredText()));
list.add(t.getPartOfSpeech());
});
return list.toArray(new String[list.size()]);
}
}
| 32.373206 | 99 | 0.675732 |
1a940915a4d9f7ab68a53db1faba3f45066958d6 | 1,595 | package com.stefan.ypinmall.product.controller;
import com.stefan.common.utils.R;
import com.stefan.ypinmall.product.entity.CategoryEntity;
import com.stefan.ypinmall.product.service.CategoryService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* 商品三级分类
*
* @author Stefan_Yang
* @email [email protected]
* @date 2020-05-31 23:19:43
*/
@RestController
@RequestMapping("product/category")
public class CategoryController {
@Resource
private CategoryService categoryService;
/**
* 查询所有分类及子分类,以树形结构封装起来
*/
@GetMapping("/list/tree")
public R list(){
List<CategoryEntity> categoryEntityList = categoryService.listWithTree();
return R.ok().put("data", categoryEntityList);
}
/**
* 信息
*/
@RequestMapping("/info/{catId}")
public R info(@PathVariable("catId") Long catId){
CategoryEntity category = categoryService.getById(catId);
return R.ok().put("category", category);
}
/**
* 保存
*/
@RequestMapping("/save")
public R save(@RequestBody CategoryEntity category){
categoryService.save(category);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
public R update(@RequestBody CategoryEntity category){
categoryService.updateById(category);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
public R delete(@RequestBody List<Long> catIds){
categoryService.removeMenuByIds(catIds);
return R.ok();
}
}
| 20.714286 | 81 | 0.652665 |
44d072178d97cf1913dc6abce11acfb034d22dad | 11,455 | package com.whut.getianao.walking_the_world_android.activity;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.whut.getianao.walking_the_world_android.MyApplication;
import com.whut.getianao.walking_the_world_android.R;
import com.whut.getianao.walking_the_world_android.utility.ActivityUtil;
import com.whut.getianao.walking_the_world_android.utility.UploadUtil;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
public class AddNewsActivity extends Activity {
private int CAMERA_RESULT_CODE = 3537;//相机请求码
private int REQUEST_CODE_PICK_IMAGE = 3538;//相册请求码
private String imgName;
private Uri uri;
private File cameraFile = null;
private String path;
private Context _this = this;
private EditText tv_title, tv_detail;
private TextView tv_location;
private ImageView im_addPic;
private Button sendBtn;
String loc; // location
private final int ADD_ACTIVITY_SUCCESS = 1;
private final int ADD_ACTIVITY_FAILED = 2;
private final int UPLOAD_IMAGE_SUCCESS = 3;
private final int UPLOAD_IMAGE_FAILED = 4;
private Handler handler = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_news);
handler = new MyHandler();
//获取Map Fragment传过来的值
Intent intent = getIntent();
loc = intent.getStringExtra("location");
if (loc != null) {
// 设置location
tv_location = findViewById(R.id.sendNews_tv_location);
tv_location.setText(loc);
}
tv_title = findViewById(R.id.sendNews_et_title);
tv_detail = findViewById(R.id.sendNews_et_detail);
im_addPic = findViewById(R.id.sendNews_iv_new_pic);
sendBtn = findViewById(R.id.buttonSend);
initAddpic();
}
private void initAddpic() {
im_addPic.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showSimpleBottomSheetList();
}
});
sendBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
try {
JSONObject upLoadFileResult = null;
// 假如上传了图片,就先把图片上传
if (path != null) {
upLoadFileResult = UploadUtil.uploadFile(new File(path)); // 上传文件
Message msg = Message.obtain();
msg.what = (upLoadFileResult.getInt("status") == 0) ? UPLOAD_IMAGE_SUCCESS : UPLOAD_IMAGE_FAILED; //标志消息的标志
handler.sendMessage(msg);
} else { // 相加拍照上传
upLoadFileResult = UploadUtil.uploadFile(cameraFile); // 上传文件
Message msg = Message.obtain();
msg.what = (upLoadFileResult.getInt("status") == 0) ? UPLOAD_IMAGE_SUCCESS : UPLOAD_IMAGE_FAILED; //标志消息的标志
handler.sendMessage(msg);
}
Map<String, Object> newsData = new HashMap<>();
newsData.put("userId", MyApplication.userId);
newsData.put("title", tv_title.getText().toString());
newsData.put("text", tv_detail.getText().toString());
newsData.put("location", tv_location.getText().toString());
String imgUrls = upLoadFileResult.getString("res");
newsData.put("imgUrls", imgUrls); // 只能上传一张图片
int result = -1;
result = ActivityUtil.addActivity(newsData); // 上传一个动态到服务器
//从全局池中返回一个message实例,避免多次创建message(如new Message)
Message msg2 = Message.obtain();
msg2.what = (result == 0) ? ADD_ACTIVITY_SUCCESS : ADD_ACTIVITY_FAILED; //标志消息的标志
handler.sendMessage(msg2);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
});
}
private void showSimpleBottomSheetList() {
new QMUIBottomSheet.BottomListSheetBuilder(this)
.addItem("拍照")
.addItem("相册")
.setOnSheetItemClickListener(new QMUIBottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
@Override
public void onClick(QMUIBottomSheet dialog, View itemView, int position, String tag) {
dialog.dismiss();
Toast.makeText(_this, "Item " + (position + 1), Toast.LENGTH_SHORT).show();
switch (position) {
case 0: {
openSysCamera();
break;
}
case 1: {
choosePhoto();
break;
}
}
}
})
.build()
.show();
}
//打开相机
private void openSysCamera() {
allow_permission();
// Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// imgName = "酷行天下" + System.currentTimeMillis()+".jpg";
// cameraFile=new File(Environment.getExternalStorageDirectory(), imgName);
// cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile));
// startActivityForResult(cameraIntent, CAMERA_RESULT_CODE);
startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE), CAMERA_RESULT_CODE);
}
/**
* 保存相机的图片
**/
private void saveCameraImage(Intent data) {
// 检查sd card是否存在
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
return;
}
// 为图片命名啊
String name = "酷行天下" + System.currentTimeMillis() + ".jpg";
Bitmap bmp = (Bitmap) data.getExtras().get("data");// 解析返回的图片成bitmap
// 保存文件
FileOutputStream fos = null;
cameraFile = new File(Environment.getExternalStorageDirectory(), name);
try {// save image
fos = new FileOutputStream(cameraFile);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 显示图片
im_addPic.setImageBitmap(bmp);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_RESULT_CODE) {
// File tempFile = new File(Environment.getExternalStorageDirectory(), imgName);
// uri = Uri.fromFile(cameraFile);
//
// im_addPic.setImageURI(uri);
saveCameraImage(data);
} else if (requestCode == REQUEST_CODE_PICK_IMAGE) {
if (resultCode == RESULT_OK) {//resultcode是setResult里面设置的code值
try {
Uri selectedImage = data.getData(); //获取系统返回的照片的Uri
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);//从系统表中查询指定Uri对应的照片
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
path = cursor.getString(columnIndex); //获取照片路径
cursor.close();
Bitmap bitmap = BitmapFactory.decodeFile(path);
im_addPic.setImageBitmap(bitmap);
} catch (Exception e) {
// TODO Auto-generatedcatch block
e.printStackTrace();
}
}
}
}
void choosePhoto() {
/**
* 打开选择图片的界面
*/
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");//相片类型
startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
}
private void allow_permission() {
/**
* 动态获取权限,Android 6.0 新特性,一些保护权限,除了要在AndroidManifest中声明权限,还要使用如下代码动态获取
*/
if (Build.VERSION.SDK_INT >= 23) {
int REQUEST_CODE_CONTACT = 101;
String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
//验证是否许可权限
for (String str : permissions) {
if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
//申请权限
this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
return;
}
}
}
}
private class MyHandler extends Handler {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) { //判断标志位
case ADD_ACTIVITY_SUCCESS:
Toast.makeText(getApplicationContext(), "新建动态成功!", Toast.LENGTH_LONG).show();
finish(); // 关闭当前页面
break;
case ADD_ACTIVITY_FAILED:
Toast.makeText(getApplicationContext(), "新建动态失败!", Toast.LENGTH_LONG).show();
break;
case UPLOAD_IMAGE_SUCCESS:
Toast.makeText(getApplicationContext(), "上传照片到服务器成功!", Toast.LENGTH_LONG).show();
break;
case UPLOAD_IMAGE_FAILED:
Toast.makeText(getApplicationContext(), "上传照片到服务器是啊比!", Toast.LENGTH_LONG).show();
break;
}
}
}
}
| 38.569024 | 141 | 0.559843 |
b5beed525fa337b3b3c0ab02d98ba0975878f499 | 3,447 | package com.niyongsheng.manager.controller;
import com.github.pagehelper.PageHelper;
import com.niyongsheng.common.enums.ResponseStatusEnum;
import com.niyongsheng.common.exception.ResponseException;
import com.niyongsheng.common.model.ResponseDto;
import com.niyongsheng.persistence.domain.Conversation;
import com.niyongsheng.persistence.service.ConversationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* @author niyongsheng.com
* @version $
* @des
* @updateAuthor $
* @updateDes
*/
@Controller
@RequestMapping("/conversation")
@Api(value = "会话信息")
@Validated
public class ConversationController {
@Autowired
private ConversationService conversationService;
@ResponseBody
@RequestMapping(value = "/getConversationList", method = {RequestMethod.GET, RequestMethod.POST})
@ApiOperation(value = "查询所有的用户信息列表并分页展示", notes = "参数描述", hidden = false)
@ApiImplicitParams({
@ApiImplicitParam(name = "pageNum", value = "页码"),
@ApiImplicitParam(name = "pageSize", value = "分页大小"),
@ApiImplicitParam(name = "isPageBreak", value = "是否分页", defaultValue = "0"),
@ApiImplicitParam(name = "fellowship", value = "团契编号", required = true)
})
public ResponseDto<Conversation> findAllUsers(HttpServletRequest request, Model model,
@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
@RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
@RequestParam(value = "isPageBreak", defaultValue = "0", required = false) boolean isPageBreak,
// @NotBlank(message = "{NotBlank.fellowship}")
@RequestParam(value = "fellowship", required = false) String fellowship
) throws ResponseException {
// 1.是否分页,调用service的方法
List<Conversation> list = null;
if (isPageBreak) {
try {
// 2.1分页查询 设置页码和分页大小
PageHelper.startPage(pageNum, pageSize, false);
list = conversationService.getConversationListByFellowship(1);
} catch (Exception e) {
throw new ResponseException(ResponseStatusEnum.DB_SELECT_ERROR);
}
} else {
try {
// 2.1无分页查询
list = conversationService.getConversationListByFellowship(1);
} catch (Exception e) {
throw new ResponseException(ResponseStatusEnum.DB_SELECT_ERROR);
}
}
// 3.返回查询结果
return new ResponseDto(ResponseStatusEnum.SUCCESS, list);
}
}
| 42.555556 | 145 | 0.663475 |
cd89caafaa3fbc9755d5f7bf684c4c8225bea01f | 555 | package com.jeffersonaraujo.bakingapp.database;
import android.arch.lifecycle.LiveData;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.Query;
import java.util.List;
@Dao
public interface RecipeDao {
@Insert
void insertRecipe(RecipeEntry recipe);
@Query("Delete FROM recipe")
void clean();
@Query("SELECT * FROM recipe")
LiveData<RecipeEntry> loadSelectedRecipeLiveData();
@Query("SELECT * FROM recipe")
RecipeEntry loadSelectedRecipe();
}
| 22.2 | 55 | 0.74955 |
f87f1ff776c350301847d9d35b0818cf268251cb | 3,172 | package net.dzikoysk.funnyguilds.util;
import net.dzikoysk.funnyguilds.FunnyGuilds;
import net.dzikoysk.funnyguilds.util.commons.ChatUtils;
import org.apache.commons.lang3.StringUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public final class IntegerRange {
private int minRange;
private int maxRange;
public IntegerRange(int minRange, int maxRange) {
this.minRange = minRange;
this.maxRange = maxRange;
}
public int getMinRange() {
return this.minRange;
}
public int getMaxRange() {
return this.maxRange;
}
public static <V> V inRange(int value, Map<IntegerRange, V> rangeMap, String rangeType) {
for (Entry<IntegerRange, V> entry : rangeMap.entrySet()) {
IntegerRange range = entry.getKey();
if (value >= range.getMinRange() && value <= range.getMaxRange()) {
return entry.getValue();
}
}
throw new MissingFormatException(value, rangeType);
}
public static Map<IntegerRange, String> parseIntegerRange(List<String> data, boolean color) {
Map<IntegerRange, String> parsed = new HashMap<>();
for (String s : data) {
String[] split = s.split(" ");
if (split.length < 2) {
FunnyGuilds.getInstance().getPluginLogger().parser("\"" + s + "\" is not a valid range String!");
continue;
}
String[] range = split[0].split("-");
if (range.length < 2) {
FunnyGuilds.getInstance().getPluginLogger().parser("\"" + s + "\" is not a valid integer range String!");
continue;
}
int minRange = 0;
int maxRange = 0;
try {
minRange = Integer.parseInt(range[0]);
} catch (NumberFormatException e) {
FunnyGuilds.getInstance().getPluginLogger().parser("\"" + range[0] + "\" of integer range String \"" + s + "\" is not a valid integer!");
continue;
}
try {
maxRange = range[1].equals("*") ? Integer.MAX_VALUE : Integer.parseInt(range[1]);
} catch (NumberFormatException e) {
FunnyGuilds.getInstance().getPluginLogger().parser("\"" + range[1] + "\" of integer range String \"" + s + "\" is not a valid integer!");
continue;
}
String valueString = StringUtils.join(split, " ", 1, split.length);
if (s.endsWith(" ")) {
valueString += " ";
}
parsed.put(new IntegerRange(minRange, maxRange), color ? ChatUtils.colored(valueString) : valueString);
}
return parsed;
}
public static class MissingFormatException extends RuntimeException {
private static final long serialVersionUID = -3225307636114359250L;
public MissingFormatException(int value, String rangeType) {
super("No format for value " + value + " and range " + rangeType + " found!");
}
}
}
| 33.041667 | 153 | 0.56652 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.