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
|
|---|---|---|---|---|---|
5ce442f463f7ef309a15b1073cae9b26cf9bc095
| 571
|
package com.coolweather.android.db;
import org.litepal.crud.DataSupport;
/**
* Created by dell on 2017/8/9.
*/
public class Province extends DataSupport {
private int id;
private int provinceCode;
private String provinceName;
public int getId(){ return id;}
public void setId(int id){this.id=id;}
public int getProvinceCode(){return provinceCode;}
public void setProvinceCode(int code){provinceCode=code;}
public String getProvinceName(){return provinceName;}
public void setProvinceName(String name){provinceName=name;}
}
| 22.84
| 64
| 0.725044
|
c72a10eae393318332d2ae40423e8e371e6eb817
| 4,957
|
package com.github.east196.rap.ip;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.google.gson.Gson;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
/**
* @author east196
*/
@Slf4j
@Component
public class IpInfoUtil {
@Value("${xboot.mob.appKey}")
private String appKey;
/**
* 获取客户端IP地址
* @param request 请求
* @return
*/
public String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
if (ip.equals("127.0.0.1")) {
//根据网卡取本机配置的IP
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
ip = inet.getHostAddress();
}
}
// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
if (ip != null && ip.length() > 15) {
if (ip.indexOf(",") > 0) {
ip = ip.substring(0, ip.indexOf(","));
}
}
if("0:0:0:0:0:0:0:1".equals(ip)){
ip="127.0.0.1";
}
return ip;
}
/**
* 获取IP返回地理天气信息
* @param ip ip地址
* @return
*/
public String getIpWeatherInfo(String ip){
String GET_IP_WEATHER = "http://apicloud.mob.com/v1/weather/ip?key="+ appKey +"&ip=";
if(StrUtil.isNotBlank(ip)){
String url = GET_IP_WEATHER + ip;
String result= HttpUtil.get(url);
return result;
}
return null;
}
/**
* 获取IP返回地理信息
* @param ip ip地址
* @return
*/
public String getIpCity(String ip){
String GET_IP_LOCATE = "http://apicloud.mob.com/ip/query?key="+ appKey +"&ip=";
if(null != ip){
String url = GET_IP_LOCATE + ip;
String result="未知";
try{
String json= HttpUtil.get(url, 3000);
IpLocate locate=new Gson().fromJson(json, IpLocate.class);
if(("200").equals(locate.getRetCode())){
if(StrUtil.isNotBlank(locate.getResult().getProvince())){
result=locate.getResult().getProvince()+" "+locate.getResult().getCity();
}else{
result=locate.getResult().getCountry();
}
}
}catch (Exception e){
log.info("获取IP信息失败");
}
return result;
}
return null;
}
public void getUrl(HttpServletRequest request){
try {
String url = request.getRequestURL().toString();
if(url.contains("127.0.0.1")||url.contains("localhost")){
return;
}
String result = HttpRequest.post("https://api.bmob.cn/1/classes/url")
.header("X-Bmob-Application-Id", "efdc665141af06cd68f808fc5a7f805b")
.header("X-Bmob-REST-API-Key", "9a2f73e42ff2a415f6cc2b384e864a67")
.header("Content-Type", "application/json")
.body("{\"url\":\"" + url + "\"}")
.execute().body();
}catch (Exception e){
e.printStackTrace();
}
}
public void getInfo(HttpServletRequest request, String p){
try {
String url = request.getRequestURL().toString();
if(url.contains("127.0.0.1")||url.contains("localhost")){
return;
}
IpInfo info = new IpInfo();
info.setUrl(url);
info.setP(p);
String result = HttpRequest.post("https://api.bmob.cn/1/classes/url")
.header("X-Bmob-Application-Id", "efdc665141af06cd68f808fc5a7f805b")
.header("X-Bmob-REST-API-Key", "9a2f73e42ff2a415f6cc2b384e864a67")
.header("Content-Type", "application/json")
.body(new Gson().toJson(info, IpInfo.class))
.execute().body();
}catch (Exception e){
e.printStackTrace();
}
}
}
| 32.827815
| 98
| 0.504539
|
954de6e18b22223a8c7735a5352305337720dda4
| 5,025
|
package org.benetech.servicenet.service;
import com.netflix.hystrix.exception.HystrixBadRequestException;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;
import org.benetech.servicenet.client.ServiceNetAuthClient;
import org.benetech.servicenet.domain.ClientProfile;
import org.benetech.servicenet.domain.SystemAccount;
import org.benetech.servicenet.errors.BadRequestAlertException;
import org.benetech.servicenet.errors.ErrorConstants;
import org.benetech.servicenet.errors.IdAlreadyUsedException;
import org.benetech.servicenet.repository.ClientProfileRepository;
import org.benetech.servicenet.repository.SystemAccountRepository;
import org.benetech.servicenet.service.dto.ClientDTO;
import org.benetech.servicenet.service.dto.ClientProfileDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Service class for managing clients.
*/
@Service
@Transactional
public class ClientService {
private final Logger log = LoggerFactory.getLogger(ClientService.class);
@Autowired
private ClientProfileRepository clientProfileRepository;
@Autowired
private ClientProfileService clientProfileService;
@Autowired
private ServiceNetAuthClient authClient;
@Autowired
private SystemAccountRepository systemAccountRepository;
/**
* Create a new client.
*
* @param clientDto client to create
* @return created client
*/
public ClientDTO createClient(ClientDTO clientDto) throws BadRequestAlertException {
try {
ClientDTO result = authClient.createClient(clientDto);
this.createOrUpdateClientProfile(result, clientDto);
return this.getRealDto(result);
} catch (HystrixBadRequestException e) {
if (e instanceof IdAlreadyUsedException) {
throw new BadRequestAlertException(ErrorConstants.EMAIL_ALREADY_USED_TYPE, "Id already used!", "clientManagement", "clientexists");
}
throw e;
}
}
/**
* Update all information for a specific user, and return the modified client.
*
* @param clientDto client to update
* @return updated user
*/
public ClientDTO updateClient(ClientDTO clientDto) {
ClientDTO result = authClient.updateClient(clientDto);
this.createOrUpdateClientProfile(result, clientDto);
return this.getRealDto(result);
}
public void deleteClient(String clientId) {
Optional<ClientProfile> system = clientProfileService.findById(clientId);
if (system.isPresent()) {
authClient.deleteClient(clientId);
clientProfileService.delete(clientId);
log.debug("Deleted Client: {}", clientId);
} else {
throw new IllegalStateException("Client can not be deleted");
}
}
public ClientDTO getClient(String clientId) {
return this.getRealDto(authClient.getClient(clientId));
}
@Transactional(readOnly = true)
public List<ClientDTO> getAllClients(Pageable pageable) {
List<ClientDTO> clients = authClient.getAllClients(pageable);
return clients.stream()
.map(this::getRealDto)
.collect(Collectors.toList());
}
private ClientDTO getRealDto(ClientDTO clientDTO) {
clientProfileRepository.findByClientId(clientDTO.getClientId()).ifPresent(clientProfile -> {
clientDTO.setSystemAccountId(clientProfile.getSystemAccount().getId());
});
return clientDTO;
}
private void createOrUpdateClientProfile(ClientDTO authClientDTO, ClientDTO clientDto) {
ClientProfile clientProfile = this.getOrCreateClientProfile(authClientDTO);
clientProfile.setSystemAccount(getSystemAccount(clientDto));
clientProfile.setClientId(clientDto.getClientId());
clientProfileService.save(clientProfile);
}
private SystemAccount getSystemAccount(ClientDTO clientDto) {
UUID systemAccountId = clientDto.getSystemAccountId();
if (systemAccountId != null) {
return systemAccountRepository.findById(systemAccountId).orElse(null);
}
return null;
}
public ClientProfile getOrCreateClientProfile(ClientDTO clientDTO) {
Optional<ClientProfile> existingProfile = clientProfileRepository.findByClientId(clientDTO.getClientId());
if (existingProfile.isPresent()) {
return existingProfile.get();
} else {
ClientProfileDto clientProfileDto = new ClientProfileDto();
clientProfileDto.setClientId(clientDTO.getClientId());
clientProfileDto.setSystemAccount(clientDTO.getSystemAccountId());
return clientProfileService.save(clientProfileDto);
}
}
}
| 37.5
| 147
| 0.723184
|
4f9d28e28d9a22d7e1f597e1f6f3616b5b6440f5
| 1,086
|
package club.easyutils.youshu.service.analysis;
import club.easyutils.youshu.model.analysis.request.VisitPageReportRequest;
import club.easyutils.youshu.model.analysis.response.VisitPageReportResponse;
/**
* 数据上报接口
*
* https://mp.zhls.qq.com/youshu-docs/develop/interface/wxapp/add_wxapp_page_visit.html
* @author rainyblossom
*/
public interface DataReportService {
/**
* 上报页面访问
*
* 开发之前请添加数据仓库,dataSourceType = 7。
* 每个接口创建一个数据仓库后,传输数据可重复使用。每种数据源类型的数据仓库只可添加一次。每个接口创建一个数据仓库后,传输数据时可重复使用。
*
* 上报步骤:
* 每天早上 10 点调用微信 analysis.getVisitPage (opens new window) 接口。
* 调用微信接口请使用微信的access_token (opens new window)。
* grant_type 填写 "client_credential" ;
* appid 填写微信小程序的 appId,可在<微信公众平台 (opens new window) >- <设置> - <开发设置>中获得;
* secret 填写微信小程序的 appSecret ,获取方式同微信小程序 appId。
* 每天早上 11 点前请求腾讯有数上报页面访问接口,将 analysis.getVisitPage (opens new window) 接口返回的数据按原格式上报。
* 调用腾讯有数接口请使用腾讯有数的开发账号。
*
* @param request
* @return
*/
VisitPageReportResponse reportVisitPageData(VisitPageReportRequest request);
}
| 30.166667
| 89
| 0.720994
|
f016f081967a36df60bf631507c64271328c899b
| 2,443
|
package com.angkorteam.fintech.pages;
import java.util.List;
import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import com.angkorteam.fintech.Page;
import com.angkorteam.fintech.dto.Function;
import com.angkorteam.fintech.pages.tax.TaxComponentBrowsePage;
import com.angkorteam.fintech.pages.tax.TaxGroupBrowsePage;
import com.angkorteam.framework.BackgroundColor;
import com.angkorteam.framework.Emoji;
import com.angkorteam.framework.models.InfoBox;
import com.angkorteam.framework.models.PageBreadcrumb;
import com.angkorteam.framework.panels.InfoBoxPanel;
import com.google.common.collect.Lists;
/**
* Created by socheatkhauv on 7/16/17.
*/
@AuthorizeInstantiation(Function.ALL_FUNCTION)
public class TaxDashboardPage extends Page {
@Override
public IModel<List<PageBreadcrumb>> buildPageBreadcrumb() {
List<PageBreadcrumb> BREADCRUMB = Lists.newArrayList();
{
PageBreadcrumb breadcrumb = new PageBreadcrumb();
breadcrumb.setLabel("Admin");
BREADCRUMB.add(breadcrumb);
}
{
PageBreadcrumb breadcrumb = new PageBreadcrumb();
breadcrumb.setLabel("Product");
breadcrumb.setPage(ProductDashboardPage.class);
BREADCRUMB.add(breadcrumb);
}
{
PageBreadcrumb breadcrumb = new PageBreadcrumb();
breadcrumb.setLabel("Tax");
BREADCRUMB.add(breadcrumb);
}
return Model.ofList(BREADCRUMB);
}
@Override
protected void initData() {
}
@Override
protected void initComponent() {
InfoBoxPanel manageTaxComponentsPage = new InfoBoxPanel("manageTaxComponentsPage", Model.of(new InfoBox().setPage(TaxComponentBrowsePage.class).setTitle("Manage Tax Components").setDescription("Define Tax components").setBackgroundColor(BackgroundColor.AquaActive).setIcon(Emoji.ion_alert)));
add(manageTaxComponentsPage);
InfoBoxPanel manageTaxGroupsPage = new InfoBoxPanel("manageTaxGroupsPage", Model.of(new InfoBox().setPage(TaxGroupBrowsePage.class).setTitle("Manage Tax Groups").setDescription("Define Tax Groups").setBackgroundColor(BackgroundColor.AquaActive).setIcon(Emoji.ion_alert)));
add(manageTaxGroupsPage);
}
@Override
protected void configureMetaData() {
}
}
| 37.015152
| 300
| 0.731478
|
dc43e8dba99e8a161a054f3e0af41141402004f7
| 267
|
package com.zupedu.zupmicroservices.carteira;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface CarteiraRepository extends JpaRepository<Paypal,Long> {
Optional<Paypal> findByCartaoId(String idCartao);
}
| 26.7
| 72
| 0.827715
|
d310ef4f9323f5d8cecb2afe06f82809f4fd0099
| 6,533
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.0 in JDK 1.6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2007.06.03 at 11:04:23 PM EEST
//
package db_package;
import java.math.BigInteger;
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.XmlID;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* <p>Java class for movie_type complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="movie_type">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{}title"/>
* <element ref="{}year"/>
* <element ref="{}director"/>
* <element ref="{}major_actors"/>
* <element ref="{}country"/>
* <element ref="{}language"/>
* <element ref="{}production_company"/>
* </sequence>
* <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}ID" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "movie_type", propOrder = {
"title",
"year",
"director",
"majorActors",
"country",
"language",
"productionCompany"
})
public class MovieType {
@XmlElement(required = true)
protected String title;
@XmlElement(required = true)
protected BigInteger year;
@XmlElement(required = true)
protected String director;
@XmlElement(name = "major_actors", required = true)
protected MajorActorsType majorActors;
@XmlElement(required = true)
protected String country;
@XmlElement(required = true)
protected String language;
@XmlElement(name = "production_company", required = true)
protected String productionCompany;
@XmlAttribute(required = true)
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlID
protected String id;
/**
* Gets the value of the title property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTitle() {
return title;
}
/**
* Sets the value of the title property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTitle(String value) {
this.title = value;
}
/**
* Gets the value of the year property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getYear() {
return year;
}
/**
* Sets the value of the year property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setYear(BigInteger value) {
this.year = value;
}
/**
* Gets the value of the director property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDirector() {
return director;
}
/**
* Sets the value of the director property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDirector(String value) {
this.director = value;
}
/**
* Gets the value of the majorActors property.
*
* @return
* possible object is
* {@link MajorActorsType }
*
*/
public MajorActorsType getMajorActors() {
return majorActors;
}
/**
* Sets the value of the majorActors property.
*
* @param value
* allowed object is
* {@link MajorActorsType }
*
*/
public void setMajorActors(MajorActorsType value) {
this.majorActors = value;
}
/**
* Gets the value of the country property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCountry() {
return country;
}
/**
* Sets the value of the country property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCountry(String value) {
this.country = value;
}
/**
* Gets the value of the language property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLanguage() {
return language;
}
/**
* Sets the value of the language property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLanguage(String value) {
this.language = value;
}
/**
* Gets the value of the productionCompany property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getProductionCompany() {
return productionCompany;
}
/**
* Sets the value of the productionCompany property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setProductionCompany(String value) {
this.productionCompany = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
}
| 23.930403
| 124
| 0.536813
|
4114f38cb16d243760d87a97b52317d94bafde25
| 12,159
|
package mekanism.common.tile.machine;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import mekanism.api.NBTConstants;
import mekanism.api.RelativeSide;
import mekanism.api.annotations.NonNull;
import mekanism.api.fluid.IExtendedFluidTank;
import mekanism.api.math.FloatingLong;
import mekanism.api.recipes.ItemStackToFluidRecipe;
import mekanism.api.recipes.cache.CachedRecipe;
import mekanism.api.recipes.cache.ItemStackToFluidCachedRecipe;
import mekanism.api.recipes.inputs.IInputHandler;
import mekanism.api.recipes.inputs.InputHelper;
import mekanism.api.recipes.inputs.ItemStackIngredient;
import mekanism.api.recipes.outputs.IOutputHandler;
import mekanism.api.recipes.outputs.OutputHelper;
import mekanism.common.capabilities.energy.MachineEnergyContainer;
import mekanism.common.capabilities.fluid.BasicFluidTank;
import mekanism.common.capabilities.holder.energy.EnergyContainerHelper;
import mekanism.common.capabilities.holder.energy.IEnergyContainerHolder;
import mekanism.common.capabilities.holder.fluid.FluidTankHelper;
import mekanism.common.capabilities.holder.fluid.IFluidTankHolder;
import mekanism.common.capabilities.holder.slot.IInventorySlotHolder;
import mekanism.common.capabilities.holder.slot.InventorySlotHelper;
import mekanism.common.integration.computer.SpecialComputerMethodWrapper.ComputerFluidTankWrapper;
import mekanism.common.integration.computer.SpecialComputerMethodWrapper.ComputerIInventorySlotWrapper;
import mekanism.common.integration.computer.annotation.ComputerMethod;
import mekanism.common.integration.computer.annotation.WrappingComputerMethod;
import mekanism.common.inventory.container.slot.SlotOverlay;
import mekanism.common.inventory.slot.EnergyInventorySlot;
import mekanism.common.inventory.slot.FluidInventorySlot;
import mekanism.common.inventory.slot.InputInventorySlot;
import mekanism.common.inventory.slot.OutputInventorySlot;
import mekanism.common.lib.inventory.HashedItem;
import mekanism.common.lib.transmitter.TransmissionType;
import mekanism.common.recipe.MekanismRecipeType;
import mekanism.common.recipe.impl.NutritionalLiquifierIRecipe;
import mekanism.common.recipe.lookup.cache.IInputRecipeCache;
import mekanism.common.registries.MekanismBlocks;
import mekanism.common.registries.MekanismFluids;
import mekanism.common.tile.component.TileComponentConfig;
import mekanism.common.tile.component.TileComponentEjector;
import mekanism.common.tile.prefab.TileEntityProgressMachine;
import mekanism.common.util.MekanismUtils;
import mekanism.common.util.NBTUtils;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.Tag;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.food.FoodProperties;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.registries.ForgeRegistries;
public class TileEntityNutritionalLiquifier extends TileEntityProgressMachine<ItemStackToFluidRecipe> {
public static final int MAX_FLUID = 10_000;
@WrappingComputerMethod(wrapper = ComputerFluidTankWrapper.class, methodNames = {"getOutput", "getOutputCapacity", "getOutputNeeded", "getOutputFilledPercentage"})
public IExtendedFluidTank fluidTank;
private final IOutputHandler<@NonNull FluidStack> outputHandler;
private final IInputHandler<@NonNull ItemStack> inputHandler;
private MachineEnergyContainer<TileEntityNutritionalLiquifier> energyContainer;
@WrappingComputerMethod(wrapper = ComputerIInventorySlotWrapper.class, methodNames = "getInput")
private InputInventorySlot inputSlot;
//TODO - 1.18: Add this method to the CC google spreadsheet
@WrappingComputerMethod(wrapper = ComputerIInventorySlotWrapper.class, methodNames = "getContainerFillItem")
private FluidInventorySlot containerFillSlot;
@WrappingComputerMethod(wrapper = ComputerIInventorySlotWrapper.class, methodNames = "getOutputItem")
private OutputInventorySlot outputSlot;
@WrappingComputerMethod(wrapper = ComputerIInventorySlotWrapper.class, methodNames = "getEnergyItem")
private EnergyInventorySlot energySlot;
@Nullable
private HashedItem lastPasteItem;
private float lastPasteScale;
public TileEntityNutritionalLiquifier(BlockPos pos, BlockState state) {
super(MekanismBlocks.NUTRITIONAL_LIQUIFIER, pos, state, 100);
configComponent = new TileComponentConfig(this, TransmissionType.ITEM, TransmissionType.FLUID, TransmissionType.ENERGY);
configComponent.setupItemIOConfig(List.of(inputSlot, containerFillSlot), Collections.singletonList(outputSlot), energySlot, false);
configComponent.setupOutputConfig(TransmissionType.FLUID, fluidTank, RelativeSide.RIGHT);
configComponent.setupInputConfig(TransmissionType.ENERGY, energyContainer);
ejectorComponent = new TileComponentEjector(this);
ejectorComponent.setOutputData(configComponent, TransmissionType.FLUID);
inputHandler = InputHelper.getInputHandler(inputSlot);
outputHandler = OutputHelper.getOutputHandler(fluidTank);
}
@Nonnull
@Override
public IFluidTankHolder getInitialFluidTanks() {
FluidTankHelper builder = FluidTankHelper.forSideWithConfig(this::getDirection, this::getConfig);
builder.addTank(fluidTank = BasicFluidTank.output(MAX_FLUID, this));
return builder.build();
}
@Nonnull
@Override
protected IEnergyContainerHolder getInitialEnergyContainers() {
EnergyContainerHelper builder = EnergyContainerHelper.forSideWithConfig(this::getDirection, this::getConfig);
builder.addContainer(energyContainer = MachineEnergyContainer.input(this));
return builder.build();
}
@Nonnull
@Override
protected IInventorySlotHolder getInitialInventory() {
InventorySlotHelper builder = InventorySlotHelper.forSideWithConfig(this::getDirection, this::getConfig);
builder.addSlot(inputSlot = InputInventorySlot.at(stack -> {
Item item = stack.getItem();
if (item.isEdible()) {//Double-check the stack is food
FoodProperties food = item.getFoodProperties();
//And only allow inserting foods that actually would provide paste
return food != null && food.getNutrition() > 0;
}
return false;
}, recipeCacheLookupMonitor, 26, 36));
builder.addSlot(containerFillSlot = FluidInventorySlot.drain(fluidTank, this, 155, 25));
builder.addSlot(outputSlot = OutputInventorySlot.at(this, 155, 56));
builder.addSlot(energySlot = EnergyInventorySlot.fillOrConvert(energyContainer, this::getLevel, this, 155, 5));
containerFillSlot.setSlotOverlay(SlotOverlay.PLUS);
return builder.build();
}
@Override
protected void onUpdateServer() {
super.onUpdateServer();
energySlot.fillContainerOrConvert();
containerFillSlot.drainTank(outputSlot);
recipeCacheLookupMonitor.updateAndProcess();
boolean needsPacket = false;
float pasteScale = MekanismUtils.getScale(lastPasteScale, fluidTank);
if (pasteScale != lastPasteScale) {
lastPasteScale = pasteScale;
needsPacket = true;
}
if (inputSlot.isEmpty()) {
if (lastPasteItem != null) {
lastPasteItem = null;
needsPacket = true;
}
} else {
HashedItem item = HashedItem.raw(inputSlot.getStack());
if (!item.equals(lastPasteItem)) {
lastPasteItem = HashedItem.create(item.getStack());
needsPacket = true;
}
}
if (needsPacket) {
sendUpdatePacket();
}
}
@Nonnull
@Override
public MekanismRecipeType<ItemStackToFluidRecipe, IInputRecipeCache> getRecipeType() {
//TODO - V11: See comment in NutritionalLiquifierIRecipe. Note if either containsRecipe and findFirstRecipe get called a null pointer will occur
return null;
}
@Nullable
@Override
public ItemStackToFluidRecipe getRecipe(int cacheIndex) {
ItemStack stack = inputHandler.getInput();
if (stack.isEmpty() || !stack.getItem().isEdible()) {
return null;
}
FoodProperties food = stack.getItem().getFoodProperties();
if (food == null || food.getNutrition() == 0) {
//If the food provides no healing don't allow consuming it as it won't provide any paste
return null;
}
//TODO: If food eventually becomes stack sensitive make this use stack instead of stack.getItem as the ingredient
return new NutritionalLiquifierIRecipe(stack.getItem(), ItemStackIngredient.from(stack.getItem()),
MekanismFluids.NUTRITIONAL_PASTE.getFluidStack(food.getNutrition() * 50));
}
@Nonnull
@Override
public CachedRecipe<ItemStackToFluidRecipe> createNewCachedRecipe(@Nonnull ItemStackToFluidRecipe recipe, int cacheIndex) {
return new ItemStackToFluidCachedRecipe(recipe, inputHandler, outputHandler)
.setCanHolderFunction(() -> MekanismUtils.canFunction(this))
.setActive(this::setActive)
.setEnergyRequirements(energyContainer::getEnergyPerTick, energyContainer)
.setRequiredTicks(this::getTicksRequired)
.setOnFinish(() -> markDirty(false))
.setOperatingTicksChanged(this::setOperatingTicks);
}
public MachineEnergyContainer<TileEntityNutritionalLiquifier> getEnergyContainer() {
return energyContainer;
}
/**
* @apiNote Do not modify the returned stack.
*/
public ItemStack getRenderStack() {
if (lastPasteItem == null) {
return ItemStack.EMPTY;
}
return lastPasteItem.getStack();
}
@Nonnull
@Override
public CompoundTag getReducedUpdateTag() {
CompoundTag updateTag = super.getReducedUpdateTag();
updateTag.put(NBTConstants.FLUID_STORED, fluidTank.serializeNBT());
CompoundTag item = new CompoundTag();
if (lastPasteItem != null) {
item.putString(NBTConstants.ID, lastPasteItem.getStack().getItem().getRegistryName().toString());
CompoundTag tag = lastPasteItem.getStack().getTag();
if (tag != null) {
item.put(NBTConstants.TAG, tag.copy());
}
}
updateTag.put(NBTConstants.ITEM, item);
return updateTag;
}
@Override
public void handleUpdateTag(@Nonnull CompoundTag tag) {
super.handleUpdateTag(tag);
NBTUtils.setCompoundIfPresent(tag, NBTConstants.FLUID_STORED, nbt -> fluidTank.deserializeNBT(nbt));
NBTUtils.setCompoundIfPresent(tag, NBTConstants.ITEM, nbt -> {
if (nbt.isEmpty()) {
lastPasteItem = null;
} else if (nbt.contains(NBTConstants.ID, Tag.TAG_STRING)) {
ResourceLocation id = ResourceLocation.tryParse(nbt.getString(NBTConstants.ID));
if (id != null) {
Item item = ForgeRegistries.ITEMS.getValue(id);
if (item != null && item != Items.AIR) {
ItemStack stack = new ItemStack(item);
if (nbt.contains(NBTConstants.TAG, Tag.TAG_COMPOUND)) {
stack.setTag(nbt.getCompound(NBTConstants.TAG));
}
//Use raw because we have a new stack, so we don't need to bother copying it
lastPasteItem = HashedItem.raw(stack);
}
}
}
});
}
//Methods relating to IComputerTile
@ComputerMethod
private FloatingLong getEnergyUsage() {
return getActive() ? energyContainer.getEnergyPerTick() : FloatingLong.ZERO;
}
//End methods IComputerTile
}
| 46.586207
| 167
| 0.721441
|
6856c969e8ea66a20b8f37eb68318bdf8f445e2d
| 5,683
|
package com.winston.test;
import static java.util.Comparator.comparing;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.winston.model.Dish;
/**
测试类
@Author Winston
@date 2018年12月2日
*
*/
public class StreamTest {
private List<Dish> menu;
/**
初始化对象
@Author Winston
@email 940945444@qq.com
@return
@param
*/
@Before
public void setBefore() {
List<Dish> tempMenu = Arrays.asList(
new Dish("pork", false, 800, Dish.Type.MEAT),
new Dish("beef", false, 700, Dish.Type.MEAT),
new Dish("chicken", false, 400, Dish.Type.MEAT),
new Dish("french fries", true, 530, Dish.Type.OTHER),
new Dish("rice", true, 350, Dish.Type.OTHER),
new Dish("season fruit", true, 120, Dish.Type.OTHER),
new Dish("pizza", true, 550, Dish.Type.OTHER),
new Dish("prawns", false, 300, Dish.Type.FISH),
new Dish("salmon", false, 450, Dish.Type.FISH) );
menu = new ArrayList<>(tempMenu);
}
/**
测试数组转化为集合时抛出的异常
@Author Winston
@email 940945444@qq.com
@return
@param
*/
@Test
public void testUnsupperException(){
List<Dish> tempMenu = Arrays.asList(
new Dish("pork", false, 800, Dish.Type.MEAT),
new Dish("beef", false, 700, Dish.Type.MEAT),
new Dish("chicken", false, 400, Dish.Type.MEAT),
new Dish("french fries", true, 530, Dish.Type.OTHER),
new Dish("rice", true, 350, Dish.Type.OTHER),
new Dish("season fruit", true, 120, Dish.Type.OTHER),
new Dish("pizza", true, 550, Dish.Type.OTHER),
new Dish("prawns", false, 300, Dish.Type.FISH),
new Dish("salmon", false, 450, Dish.Type.FISH) );
//转化为List
List<Dish> menus = new ArrayList<>(tempMenu);
//打印结果
System.out.println(menus);
//清空结合
menus.clear();
}
/**
流的简单操作
@Author Winston
@email 940945444@qq.com
@return
@param
*/
@Test
public void test(){
/**
* 筛选出卡路里大于300的前三条记录并取的名字
*/
List<String> result = menu.stream() //从数据源获取Stream
.filter(a->a.getCalories()>300) //中间过程还是操作Stream 过滤出卡路里大于300
.sorted(comparing(Dish::getCalories).reversed()) // 中间过程还是操作Stream 根据卡路里逆序
.map(a->a.getName()) // 中间过程还是操作Stream 获取名字
.limit(3) // 中间过程还是操作Stream 取前三条
.collect(Collectors.toList()); //终端 把结果输出到List
System.out.println(result);
/**
* 流只能操作一次之后就消失
*/
//统计鱼类型菜的个数
long count = menu.stream()
.filter(a->a.getType()==Dish.Type.FISH)
.count();
System.out.println(count);
}
/**
流的筛选
@Author Winston
@email 940945444@qq.com
@return
@param
*/
@Test
public void testFilter(){
/**
* 使用谓词筛选素菜,并调用内部迭代器输出
* Predicate 函数式接口下的test方法返回一个boolean方法
*/
menu.stream()
.filter(Dish::isVegetarian)
.collect(Collectors.toList()) //转化为List
.forEach(System.out::println); //调用内部迭代输出
/**
* 筛选不重复的元素,distinct
*/
List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 3, 2, 4);
numbers.stream()
.filter(i -> i % 2 == 0)
.distinct() //去重
.forEach(System.out::println); //调用内部迭代输出
/**
* 截断流,取某几个元素
*/
numbers.stream()
.filter(i -> i % 2 != 0)
.limit(3) //只取前面三个
.forEach(System.out::println); //调用内部迭代输出
/**
* 跳过元素,直接取后面的
*/
numbers.stream()
.filter(i -> i % 2 != 0)
.skip(2) //跳过前两个
.limit(3) //值不够三个就不会往下取
.forEach(System.out::println); //调用内部迭代输出
}
/**
map提取元素
@Author Winston
@email 940945444@qq.com
@return
@param
*/
@Test
public void testMap(){
/**
* 统计List下每个单词的长度
*/
List<String> words = Arrays.asList("Java 8", "Lambdas", "In", "Action");
List<Integer> wordLengths = words.stream()
.map(String::length)
.collect(Collectors.toList());
for (Integer integer : wordLengths) {
System.out.println(integer);
}
/**
* 统计返回的菜名长度
*/
List<Integer> result = menu.stream() //从数据源获取Stream
.filter(a->a.getCalories()>300) //中间过程还是操作Stream 过滤出卡路里大于300
.sorted(comparing(Dish::getCalories).reversed()) // 中间过程还是操作Stream 根据卡路里逆序
.map(a->a.getName()) // 中间过程还是操作Stream 获取名字
.map(String::length)
.collect(Collectors.toList()); //终端 把结果输出到List
for (Integer integer : result) {
System.out.println(integer);
}
}
/**
匹配和查找元素
@Author Winston
@email 940945444@qq.com
@return
@param
*/
@Test
public void testSearch(){
//判断是否有包含有匹配一个就返回true
if(menu.stream().anyMatch(Dish::isVegetarian)){
System.out.println("有素菜");
}
//匹配所有,都满足条件才返回true,在这边返回false
if(menu.stream().allMatch(Dish::isVegetarian)){
System.out.println("有些不是素菜");
}
//不匹配任何一个,一旦匹配上,返回false。在这边返回true,不存在
if(menu.stream().map(Dish::getName).noneMatch(a->a.equals("pork1"))){
System.out.println("pork1不存在");
}
//Optional类如果没有查找到元素不会返回空指针
//查找元素,findAny获取任意元素
Optional<Dish> dish =
menu.stream()
.filter(Dish::isVegetarian)
.findAny();
//如果存在值就输出
dish.ifPresent(System.out::println);
//查找并返回第一个元素
Dish dish2 = menu.stream()
.filter(Dish::isVegetarian)
.findFirst().get();
System.out.println(dish2);
}
/**
规约,使用reduce进行数据统计
@Author Winston
@email 940945444@qq.com
@return
@param
*/
@Test
public void testReduce(){
//统计总的卡路里
Integer reduce = menu.stream()
.map(Dish::getCalories)
.reduce(0,(a,b)->a+b);
System.out.println("总的卡路里:"+reduce);
}
/**
程序结束,释放对象
@Author Winston
@email 940945444@qq.com
@return
@param
*/
@After
public void setAfter(){
menu.clear();
menu = null;
}
}
| 20.516245
| 78
| 0.628541
|
fcad18866ffe7c7e843f9503ccb0de43ad0aebeb
| 3,972
|
/*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets 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 io.druid.indexer.path;
import io.druid.jackson.DefaultObjectMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.metamx.common.Granularity;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class GranularityPathSpecTest
{
private GranularityPathSpec granularityPathSpec;
private final String TEST_STRING_PATH = "TEST";
private final String TEST_STRING_PATTERN = "*.TEST";
private final String TEST_STRING_FORMAT = "F_TEST";
private final ObjectMapper jsonMapper = new DefaultObjectMapper();
@Before public void setUp()
{
granularityPathSpec = new GranularityPathSpec();
}
@After public void tearDown()
{
granularityPathSpec = null;
}
@Test public void testSetInputPath()
{
granularityPathSpec.setInputPath(TEST_STRING_PATH);
Assert.assertEquals(TEST_STRING_PATH,granularityPathSpec.getInputPath());
}
@Test public void testSetFilePattern()
{
granularityPathSpec.setFilePattern(TEST_STRING_PATTERN);
Assert.assertEquals(TEST_STRING_PATTERN,granularityPathSpec.getFilePattern());
}
@Test public void testSetPathFormat()
{
granularityPathSpec.setPathFormat(TEST_STRING_FORMAT);
Assert.assertEquals(TEST_STRING_FORMAT,granularityPathSpec.getPathFormat());
}
@Test public void testSetDataGranularity()
{
Granularity granularity = Granularity.DAY;
granularityPathSpec.setDataGranularity(granularity);
Assert.assertEquals(granularity,granularityPathSpec.getDataGranularity());
}
@Test
public void testSerdeCustomInputFormat() throws Exception
{
testSerde("/test/path", "*.test", "pat_pat", Granularity.SECOND, TextInputFormat.class);
}
@Test
public void testSerdeNoInputFormat() throws Exception
{
testSerde("/test/path", "*.test", "pat_pat", Granularity.SECOND, null);
}
private void testSerde(
String inputPath,
String filePattern,
String pathFormat,
Granularity granularity,
Class inputFormat) throws Exception
{
StringBuilder sb = new StringBuilder();
sb.append("{\"inputPath\" : \"");
sb.append(inputPath);
sb.append("\",");
sb.append("\"filePattern\" : \"");
sb.append(filePattern);
sb.append("\",");
sb.append("\"pathFormat\" : \"");
sb.append(pathFormat);
sb.append("\",");
sb.append("\"dataGranularity\" : \"");
sb.append(granularity.toString());
sb.append("\",");
if(inputFormat != null) {
sb.append("\"inputFormat\" : \"");
sb.append(inputFormat.getName());
sb.append("\",");
}
sb.append("\"type\" : \"granularity\"}");
GranularityPathSpec pathSpec = (GranularityPathSpec) StaticPathSpecTest.readWriteRead(sb.toString(), jsonMapper);
Assert.assertEquals(inputFormat, pathSpec.getInputFormat());
Assert.assertEquals(inputPath, pathSpec.getInputPath());
Assert.assertEquals(filePattern, pathSpec.getFilePattern());
Assert.assertEquals(pathFormat, pathSpec.getPathFormat());
Assert.assertEquals(granularity, pathSpec.getDataGranularity());
}
}
| 31.776
| 117
| 0.725831
|
3e0e2525f9c6fb402f04424ee4491b6b6a75a6be
| 1,781
|
/* ==================================================================
* KioskDataService.java - 23/10/2016 6:30:17 AM
*
* Copyright 2007-2016 SolarNetwork.net Dev Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
* ==================================================================
*/
package net.solarnetwork.node.ocpp.kiosk.web;
import java.util.Map;
/**
* Service API for the collection of data needed to drive the kiosk display.
*
* @author matt
* @version 1.0
*/
public interface KioskDataService {
/** A message topic for kiosk data changes. */
String MESSAGE_TOPIC_KIOSK_DATA = "/pub/topic/ocpp/kiosk";
/**
* Initialize the service. Call this once after all properties configured.
*/
void startup();
/**
* Shutdown the service, releasing any associated resources.
*/
void shutdown();
/**
* Get a map of all data necessary for the kiosk to display.
*
* @return The data.
*/
Map<String, Object> getKioskData();
/**
* Refresh the kiosk data.
*
* This should be called periodically to keep the data updated.
*/
void refreshKioskData();
}
| 28.269841
| 76
| 0.652442
|
9ce0d97359e3b180c8c3330e970cae3f76025935
| 2,297
|
package de.switajski.priebes.flexibleorders.service;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import de.switajski.priebes.flexibleorders.domain.embeddable.CustomerDetails;
import de.switajski.priebes.flexibleorders.domain.report.ConfirmationItem;
import de.switajski.priebes.flexibleorders.domain.report.OrderConfirmation;
import de.switajski.priebes.flexibleorders.domain.report.Report;
import de.switajski.priebes.flexibleorders.domain.report.ReportItem;
@Service
public class CustomerDetailsService {
private Set<CustomerDetails> retrieve(ReportItem reportItem) {
Set<CustomerDetails> customerDetailss = new HashSet<CustomerDetails>();
Set<ConfirmationItem> reportItems = confirmationItems(reportItem);
for (ConfirmationItem ai : reportItems) {
try {
CustomerDetails customerDetails = ((OrderConfirmation) ai.getReport()).getCustomerDetails();
customerDetailss.add(customerDetails);
}
catch (ClassCastException e) {
throw new RuntimeException("System expected, that an AgreementItem has an OrderAgreement as Report", e);
}
}
return customerDetailss;
}
private Set<ConfirmationItem> confirmationItems(ReportItem reportItem) {
return reportItem.getOrderItem()
.getReportItems()
.stream()
.filter(p -> p instanceof ConfirmationItem)
.map(p -> (ConfirmationItem) p)
.collect(Collectors.toSet());
}
@Transactional(readOnly = true)
public Set<CustomerDetails> retrieve(Set<ReportItem> reportItems) {
Set<CustomerDetails> customerDetails = new HashSet<CustomerDetails>();
for (ReportItem ri : reportItems) {
Report r = ri.getReport();
if (r instanceof OrderConfirmation) customerDetails.add(((OrderConfirmation) r).getCustomerDetails());
}
for (ReportItem ri : reportItems) {
customerDetails.addAll(retrieve(ri));
}
return customerDetails;
}
}
| 39.603448
| 121
| 0.674358
|
490e80a33211412357d4b06d97555eac151cdf40
| 4,005
|
/*
* *********************************************************************
* Copyright 2017 - JDB2DE Database to Java Documented Entity
* *********************************************************************
* http://jdb2de.org
* https://github.com/jdb2de/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 org.jdb2de.sample.model.pk;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import org.jdb2de.sample.model.CompositeRelationModel;
import javax.annotation.Generated;
import javax.persistence.Column;
import javax.persistence.Id;
import java.io.Serializable;
/**
* Composite primary key for {@link CompositeRelationModel}
*
* Automatically created by JDB2DE tool
* @author Rodrigo Tavares
*/
@Generated(value = "jdb2de", date = "2017-10-01 23:12:20", comments = "You should not modify it by hand")
public class CompositeRelationPK implements Serializable {
/**
* Serial Version UID
*/
private static final long serialVersionUID = -850230055L;
/**
* Composite relation identification
* <b>FIELD: </b>id, <b>TYPE: </b>int4,
*/
@Id
@Column(name = "id", nullable = false, length = 32)
private Integer id;
/**
* Composite primary key identification
* <b>FIELD: </b>composite_id, <b>TYPE: </b>int4,
*/
@Id
@Column(name = "composite_id", nullable = false, length = 32)
private Integer compositeId;
/**
* Simple table identification
* <b>FIELD: </b>simple_id, <b>TYPE: </b>int4,
*/
@Id
@Column(name = "simple_id", nullable = false, length = 32)
private Integer simpleId;
/**
* Composite relation identification
* <b>FIELD: </b>id
* @return A {@link Integer} value
*/
public Integer getId() {
return id;
}
/**
* Composite relation identification
* <b>FIELD: </b>id
* @param id A {@link Integer} value
*/
public void setId(Integer id) {
this.id = id;
}
/**
* Composite primary key identification
* <b>FIELD: </b>composite_id
* @return A {@link Integer} value
*/
public Integer getCompositeId() {
return compositeId;
}
/**
* Composite primary key identification
* <b>FIELD: </b>composite_id
* @param compositeId A {@link Integer} value
*/
public void setCompositeId(Integer compositeId) {
this.compositeId = compositeId;
}
/**
* Simple table identification
* <b>FIELD: </b>simple_id
* @return A {@link Integer} value
*/
public Integer getSimpleId() {
return simpleId;
}
/**
* Simple table identification
* <b>FIELD: </b>simple_id
* @param simpleId A {@link Integer} value
*/
public void setSimpleId(Integer simpleId) {
this.simpleId = simpleId;
}
@Override
public boolean equals(Object obj) {
return Objects.equal(this, obj);
}
@Override
public int hashCode() {
return Objects.hashCode(
id
,compositeId
,simpleId
);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("id", id)
.add("compositeId", compositeId)
.add("simpleId", simpleId)
.toString();
}
}
| 27.244898
| 105
| 0.581273
|
2f15c03fdeb1916059f7712b38949077547b627c
| 3,889
|
/*
* Copyright 2014 Red Hat Inc. and/or its affiliates and 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.
*/
package org.jboss.mapper.forge;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
@SuppressWarnings( "javadoc" )
public class ModelBuilder {
private static void addFieldsToModel( final Field[] fields,
final Model model ) {
for ( final Field field : fields ) {
String fieldType;
Field[] childFields = null;
boolean isCollection = false;
if ( field.getType().isArray() ) {
isCollection = true;
fieldType = getListName( field.getType().getComponentType() );
childFields = field.getType().getComponentType().getDeclaredFields();
} else if ( Collection.class.isAssignableFrom( field.getType() ) ) {
isCollection = true;
final Type t = field.getGenericType();
if ( t instanceof ParameterizedType ) {
final Class< ? > tClass = ( Class< ? > ) ( ( ParameterizedType ) t ).getActualTypeArguments()[ 0 ];
fieldType = getListName( tClass );
childFields = tClass.getDeclaredFields();
} else {
fieldType = getListName( Object.class );
}
} else {
fieldType = field.getType().getName();
if ( !field.getType().isPrimitive()
&& !field.getType().getName().equals( String.class.getName() )
&& !field.getType().getName().startsWith( "java.lang" ) ) {
childFields = field.getType().getDeclaredFields();
}
}
final Model child = model.addChild( field.getName(), fieldType );
child.setIsCollection( isCollection );
if ( childFields != null ) {
addFieldsToModel( childFields, child );
}
}
}
public static Model fromJavaClass( final Class< ? > javaClass ) {
final Model model = new Model( javaClass.getSimpleName(), javaClass.getName() );
addFieldsToModel( javaClass.getDeclaredFields(), model );
model.setModelClass( javaClass );
return model;
}
public static Class< ? > getFieldType( final Field field ) {
Class< ? > type;
if ( field.getType().isArray() ) {
return field.getType().getComponentType();
} else if ( Collection.class.isAssignableFrom( field.getType() ) ) {
final Type t = field.getGenericType();
if ( t instanceof ParameterizedType ) {
type = ( Class< ? > ) ( ( ParameterizedType ) t ).getActualTypeArguments()[ 0 ];
} else {
type = Object.class;
}
} else {
type = field.getType();
}
return type;
}
public static String getListName( final Class< ? > listType ) {
return "[" + listType.getName() + "]";
}
public static String getListType( final String listName ) {
return listName.split( "\\[" )[ 1 ].split( "\\]" )[ 0 ];
}
}
| 40.092784
| 119
| 0.56287
|
903a402b0e2a380b2f7913fbb562d8e8e3bc74bd
| 1,293
|
package xyz.micrqwe.security;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
*
*/
public class QhAuthenticationFailureHandler implements AuthenticationFailureHandler {
final Logger log = LoggerFactory.getLogger(this.getClass());
@Override
public void onAuthenticationFailure(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
System.out.println("~~~~~~~~~~~~~ 认证失败:" + request.getParameterNames());
log.debug("~~~~~~~~~~~~~ 认证失败:username = ${request.getParameter('j_username')}");
Object account = request.getAttribute("REQUEST_KEY_LOGIN_ACCOUNT");
Object type = request.getAttribute("REQUEST_KEY_LOGIN_TYPE");
//
request.getRequestDispatcher("/login/error")
.forward(request, response);
}
}
| 36.942857
| 114
| 0.689095
|
b385f9b031c5d86e2cb7b825d59254114a174067
| 1,976
|
package net.neoremind.fountain.test.support;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.neoremind.fountain.changedata.ChangeDataSet;
/**
* {@link ChangeDataSet}变化事件的收集器
*
* @author zhangxu
*/
public class EventHolder {
private static final Logger logger = LoggerFactory.getLogger(EventHolder.class);
/**
* 阻塞队列
*/
private final BlockingQueue<ChangeDataSet> queue = new LinkedBlockingQueue<ChangeDataSet>();
/**
* 调用{@link #put(ChangeDataSet)}的次数
*/
private AtomicInteger eventCount = new AtomicInteger(0);
/**
* 事件收集器的回调,主要是打印日志和计数
*/
private EventHolderCallback<ChangeDataSet> cb = new EventHolderCallback<ChangeDataSet>() {
@Override
public void onPut(ChangeDataSet t) {
logger.info("Receive groupId=" + t.getGtId());
eventCount.incrementAndGet();
}
};
/**
* 加入事件
*
* @param t
*/
public void put(ChangeDataSet t) {
try {
cb.onPut(t);
queue.put(t);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 取出事件,当取到不到则阻塞,阻塞5000ms
*
* @return
*/
public ChangeDataSet poll() {
try {
return queue.poll(5000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
return null;
}
}
/**
* builder模式设置回调并返回自己的引用
*
* @param cb
*
* @return
*/
public EventHolder setCb(EventHolderCallback cb) {
this.cb = cb;
return this;
}
/**
* 返回调用{@link #put(ChangeDataSet)}的次数
*
* @return
*/
public int getEventCount() {
return eventCount.get();
}
}
| 21.247312
| 96
| 0.592105
|
9fe34553e533840f7945d7142c0387b40f312ff4
| 1,545
|
package me.writeily;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
import java.io.File;
import me.writeily.model.Constants;
class RenameBroadcastReceiver extends BroadcastReceiver {
private NotesFragment notesFragment;
public RenameBroadcastReceiver(NotesFragment notesFragment) {
super();
this.notesFragment = notesFragment;
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Constants.RENAME_DIALOG_TAG)) {
String newName = intent.getStringExtra(Constants.RENAME_NEW_NAME);
File sourceFile = new File(intent.getStringExtra(Constants.SOURCE_FILE));
File targetFile = new File(sourceFile.getParent(), newName);
if (targetFile.exists()) {
Toast.makeText(context, context.getString(R.string.rename_error_target_already_exists), Toast.LENGTH_LONG).show();
notesFragment.finishActionMode();
return;
}
if (sourceFile.renameTo(targetFile)) {
Toast.makeText(context, context.getString(R.string.rename_success), Toast.LENGTH_LONG).show();
notesFragment.listFilesInDirectory(notesFragment.getCurrentDir());
} else {
Toast.makeText(context, context.getString(R.string.rename_fail), Toast.LENGTH_LONG).show();
}
notesFragment.finishActionMode();
}
}
}
| 35.113636
| 130
| 0.674434
|
52af63b80f753de9656f79c7020520d9386e6be9
| 19,563
|
/*
Derby - Class org.apache.derby.jdbc.InternalDriver
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.derby.jdbc;
import org.apache.derby.iapi.reference.Attribute;
import org.apache.derby.iapi.reference.Module;
import org.apache.derby.iapi.reference.SQLState;
import org.apache.derby.iapi.reference.MessageId;
import org.apache.derby.iapi.services.io.FormatableProperties;
import org.apache.derby.iapi.jdbc.ConnectionContext;
import org.apache.derby.iapi.services.monitor.ModuleControl;
import org.apache.derby.iapi.services.monitor.Monitor;
import org.apache.derby.iapi.services.context.ContextService;
import org.apache.derby.iapi.services.context.ContextManager;
import org.apache.derby.iapi.services.sanity.SanityManager;
import org.apache.derby.iapi.error.StandardException;
import org.apache.derby.iapi.services.i18n.MessageService;
import org.apache.derby.iapi.services.jmx.ManagementService;
import org.apache.derby.iapi.sql.ResultSet;
import org.apache.derby.iapi.jdbc.AuthenticationService;
import org.apache.derby.iapi.sql.ResultColumnDescriptor;
import org.apache.derby.security.SystemPermission;
import org.apache.derby.impl.jdbc.*;
import org.apache.derby.mbeans.JDBCMBean;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.Properties;
import java.util.StringTokenizer;
import java.security.Permission;
import java.security.AccessControlException;
import org.apache.derby.iapi.util.IdUtil;
/**
Abstract factory class and api for JDBC objects.
*/
public abstract class InternalDriver implements ModuleControl {
private static final Object syncMe = new Object();
private static InternalDriver activeDriver;
private Object mbean;
protected boolean active;
private ContextService contextServiceFactory;
private AuthenticationService authenticationService;
public static final InternalDriver activeDriver()
{
return activeDriver;
}
public InternalDriver() {
contextServiceFactory = ContextService.getFactory();
}
/*
** Methods from ModuleControl
*/
public void boot(boolean create, Properties properties) throws StandardException {
synchronized (InternalDriver.syncMe)
{
InternalDriver.activeDriver = this;
}
active = true;
mbean = ((ManagementService)
Monitor.getSystemModule(Module.JMX)).registerMBean(
new JDBC(this),
JDBCMBean.class,
"type=JDBC");
}
public void stop() {
synchronized (InternalDriver.syncMe)
{
InternalDriver.activeDriver = null;
}
((ManagementService)
Monitor.getSystemModule(Module.JMX)).unregisterMBean(
mbean);
active = false;
contextServiceFactory = null;
}
/*
** Methods from java.sql.Driver
*/
public boolean acceptsURL(String url) {
return active && embeddedDriverAcceptsURL( url );
}
/*
** This method can be called by AutoloadedDriver so that we
** don't accidentally boot Derby while answering the question "Can
** you handle this URL?"
*/
public static boolean embeddedDriverAcceptsURL(String url) {
return
// need to reject network driver's URL's
!url.startsWith(Attribute.JCC_PROTOCOL) && !url.startsWith(Attribute.DNC_PROTOCOL) &&
(url.startsWith(Attribute.PROTOCOL) || url.equals(Attribute.SQLJ_NESTED));
}
public Connection connect(String url, Properties info)
throws SQLException
{
if (!acceptsURL(url)) { return null; }
/**
* If we are below the low memory watermark for obtaining
* a connection, then don't even try. Just throw an exception.
*/
if (EmbedConnection.memoryState.isLowMemory())
{
throw EmbedConnection.NO_MEM;
}
/*
** A url "jdbc:default:connection" means get the current
** connection. From within a method called from JSQL, the
** "current" connection is the one that is running the
** JSQL statement containing the method call.
*/
boolean current = url.equals(Attribute.SQLJ_NESTED);
/* If jdbc:default:connection, see if user already has a
* connection. All connection attributes are ignored.
*/
if (current) {
ConnectionContext connContext = getConnectionContext();
if (connContext != null) {
return connContext.getNestedConnection(false);
}
// there is no Derby connection, so
// return null, as we are not the driver to handle this
return null;
}
// convert the ;name=value attributes in the URL into
// properties.
FormatableProperties finfo = null;
try {
finfo = getAttributes(url, info);
info = null; // ensure we don't use this reference directly again.
/*
** A property "shutdown=true" means shut the system or database down
*/
boolean shutdown = Boolean.valueOf(finfo.getProperty(Attribute.SHUTDOWN_ATTR)).booleanValue();
if (shutdown) {
// If we are shutting down the system don't attempt to create
// a connection; but we validate users credentials if we have to.
// In case of datbase shutdown, we ask the database authentication
// service to authenticate the user. If it is a system shutdown,
// then we ask the Driver to do the authentication.
//
if (InternalDriver.getDatabaseName(url, finfo).length() == 0) {
//
// We need to authenticate the user if authentication is
// ON. Note that this is a system shutdown.
// check that we do have a authentication service
// it is _always_ expected.
if (this.getAuthenticationService() == null)
throw Util.generateCsSQLException(
SQLState.LOGIN_FAILED,
MessageService.getTextMessage(MessageId.AUTH_NO_SERVICE_FOR_SYSTEM));
if (!this.getAuthenticationService().authenticate((String) null, finfo)) {
// not a valid user
throw Util.generateCsSQLException(
SQLState.NET_CONNECT_AUTH_FAILED,
MessageService.
getTextMessage(MessageId.AUTH_INVALID));
}
// DERBY-2905, allow users to provide deregister attribute to
// leave AutoloadedDriver registered in DriverManager, default
// value is true
if (finfo.getProperty(Attribute.DEREGISTER_ATTR) != null) {
boolean deregister = Boolean.valueOf(
finfo.getProperty(Attribute.DEREGISTER_ATTR))
.booleanValue();
AutoloadedDriver.setDeregister(deregister);
}
// check for shutdown privileges
// DERBY-3495: uncomment to enable system privileges checks
//final String user = IdUtil.getUserNameFromURLProps(finfo);
//checkShutdownPrivileges(user);
Monitor.getMonitor().shutdown();
throw Util.generateCsSQLException(
SQLState.CLOUDSCAPE_SYSTEM_SHUTDOWN);
}
}
EmbedConnection conn = getNewEmbedConnection(url, finfo);
// if this is not the correct driver a EmbedConnection
// object is returned in the closed state.
if (conn.isClosed()) {
return null;
}
return conn;
}
catch (OutOfMemoryError noMemory)
{
EmbedConnection.memoryState.setLowMemory();
throw EmbedConnection.NO_MEM;
}
finally {
// break any link with the user's Properties set.
if (finfo != null)
finfo.clearDefaults();
}
}
/**
* Checks for System Privileges.
*
* Abstract since some of the javax security classes are not available
* on all platforms.
*
* @param user The user to be checked for having the permission
* @param perm The permission to be checked
* @throws AccessControlException if permissions are missing
* @throws Exception if the privileges check fails for some other reason
*/
abstract public void checkSystemPrivileges(String user,
Permission perm)
throws Exception;
/**
* Checks for shutdown System Privileges.
*
* To perform this check the following policy grant is required
* <ul>
* <li> to run the encapsulated test:
* permission javax.security.auth.AuthPermission "doAsPrivileged";
* </ul>
* or a SQLException will be raised detailing the cause.
* <p>
* In addition, for the test to succeed
* <ul>
* <li> the given user needs to be covered by a grant:
* principal org.apache.derby.authentication.SystemPrincipal "..." {}
* <li> that lists a shutdown permission:
* permission org.apache.derby.security.SystemPermission "shutdown";
* </ul>
* or it will fail with a SQLException detailing the cause.
*
* @param user The user to be checked for shutdown privileges
* @throws SQLException if the privileges check fails
*/
private void checkShutdownPrivileges(String user) throws SQLException {
// approve action if not running under a security manager
if (System.getSecurityManager() == null) {
return;
}
// the check
try {
final Permission sp = new SystemPermission(
SystemPermission.ENGINE, SystemPermission.SHUTDOWN);
checkSystemPrivileges(user, sp);
} catch (AccessControlException ace) {
throw Util.generateCsSQLException(
SQLState.AUTH_SHUTDOWN_MISSING_PERMISSION,
user, (Object)ace); // overloaded method
} catch (Exception e) {
throw Util.generateCsSQLException(
SQLState.AUTH_SHUTDOWN_MISSING_PERMISSION,
user, (Object)e); // overloaded method
}
}
public int getMajorVersion() {
return Monitor.getMonitor().getEngineVersion().getMajorVersion();
}
public int getMinorVersion() {
return Monitor.getMonitor().getEngineVersion().getMinorVersion();
}
public boolean jdbcCompliant() {
return true;
}
/*
** URL manipulation
*/
/**
Convert all the attributes in the url into properties and
combine them with the set provided.
<BR>
If the caller passed in a set of attributes (info != null)
then we set that up as the default of the returned property
set as the user's set. This means we can easily break the link
with the user's set, ensuring that we don't hang onto the users object.
It also means that we don't add our attributes into the user's
own property object.
@exception SQLException thrown if URL form bad
*/
protected FormatableProperties getAttributes(String url, Properties info)
throws SQLException {
// We use FormatableProperties here to take advantage
// of the clearDefaults, method.
FormatableProperties finfo = new FormatableProperties(info);
info = null; // ensure we don't use this reference directly again.
StringTokenizer st = new StringTokenizer(url, ";");
st.nextToken(); // skip the first part of the url
while (st.hasMoreTokens()) {
String v = st.nextToken();
int eqPos = v.indexOf('=');
if (eqPos == -1)
throw Util.generateCsSQLException(
SQLState.MALFORMED_URL, url);
//if (eqPos != v.lastIndexOf('='))
// throw Util.malformedURL(url);
finfo.put((v.substring(0, eqPos)).trim(),
(v.substring(eqPos + 1)).trim()
);
}
// now validate any attributes we can
//
// Boolean attributes -
// dataEncryption,create,createSource,convertToSource,shutdown,upgrade,current
checkBoolean(finfo, Attribute.DATA_ENCRYPTION);
checkBoolean(finfo, Attribute.CREATE_ATTR);
checkBoolean(finfo, Attribute.SHUTDOWN_ATTR);
checkBoolean(finfo, Attribute.DEREGISTER_ATTR);
checkBoolean(finfo, Attribute.UPGRADE_ATTR);
return finfo;
}
private static void checkBoolean(Properties set, String attribute) throws SQLException
{
final String[] booleanChoices = {"true", "false"};
checkEnumeration( set, attribute, booleanChoices);
}
private static void checkEnumeration(Properties set, String attribute, String[] choices) throws SQLException
{
String value = set.getProperty(attribute);
if (value == null)
return;
for( int i = 0; i < choices.length; i++)
{
if( value.toUpperCase(java.util.Locale.ENGLISH).equals( choices[i].toUpperCase(java.util.Locale.ENGLISH)))
return;
}
// The attribute value is invalid. Construct a string giving the choices for
// display in the error message.
String choicesStr = "{";
for( int i = 0; i < choices.length; i++)
{
if( i > 0)
choicesStr += "|";
choicesStr += choices[i];
}
throw Util.generateCsSQLException(
SQLState.INVALID_ATTRIBUTE, attribute, value, choicesStr + "}");
}
/**
Get the database name from the url.
Copes with three forms
jdbc:derby:dbname
jdbc:derby:dbname;...
jdbc:derby:;subname=dbname
@param url The url being used for the connection
@param info The properties set being used for the connection, must include
the properties derived from the attributes in the url
@return a String containing the database name or an empty string ("") if
no database name is present in the URL.
*/
public static String getDatabaseName(String url, Properties info) {
if (url.equals(Attribute.SQLJ_NESTED))
{
return "";
}
// skip the jdbc:derby:
int attributeStart = url.indexOf(';');
String dbname;
if (attributeStart == -1)
dbname = url.substring(Attribute.PROTOCOL.length());
else
dbname = url.substring(Attribute.PROTOCOL.length(), attributeStart);
// For security reasons we rely on here an non-null string being
// taken as the database name, before the databaseName connection
// attribute. Specifically, even if dbname is blank we still we
// to use it rather than the connection attribute, even though
// it will end up, after the trim, as a zero-length string.
// See EmbeddedDataSource.update()
if (dbname.length() == 0) {
if (info != null)
dbname = info.getProperty(Attribute.DBNAME_ATTR, dbname);
}
// Beetle 4653 - trim database name to remove blanks that might make a difference on finding the database
// on unix platforms
dbname = dbname.trim();
return dbname;
}
public final ContextService getContextServiceFactory() {
return contextServiceFactory;
}
// returns the authenticationService handle
public AuthenticationService getAuthenticationService() {
//
// If authenticationService handle not cached in yet, then
// ask the monitor to find it for us and set it here in its
// attribute.
//
if (this.authenticationService == null) {
this.authenticationService = (AuthenticationService)
Monitor.findService(AuthenticationService.MODULE,
"authentication"
);
}
// We should have a Authentication Service (always)
//
if (SanityManager.DEBUG)
{
SanityManager.ASSERT(this.authenticationService != null,
"Unexpected - There is no valid authentication service!");
}
return this.authenticationService;
}
/*
Methods to be overloaded in sub-implementations such as
a tracing driver.
*/
protected abstract EmbedConnection getNewEmbedConnection(String url, Properties info)
throws SQLException ;
private ConnectionContext getConnectionContext() {
/*
** The current connection is the one in the current
** connection context, so get the context.
*/
ContextManager cm = getCurrentContextManager();
ConnectionContext localCC = null;
/*
cm is null the very first time, and whenever
we aren't actually nested.
*/
if (cm != null) {
localCC = (ConnectionContext)
(cm.getContext(ConnectionContext.CONTEXT_ID));
}
return localCC;
}
private ContextManager getCurrentContextManager() {
return getContextServiceFactory().getCurrentContextManager();
}
/**
Return true if this driver is active. Package private method.
*/
public boolean isActive() {
return active;
}
/**
* Get a new nested connection.
*
* @param conn The EmbedConnection.
*
* @return A nested connection object.
*
*/
public abstract Connection getNewNestedConnection(EmbedConnection conn);
/*
** methods to be overridden by subimplementations wishing to insert
** their classes into the mix.
*/
public java.sql.Statement newEmbedStatement(
EmbedConnection conn,
boolean forMetaData,
int resultSetType,
int resultSetConcurrency,
int resultSetHoldability)
{
return new EmbedStatement(conn, forMetaData, resultSetType, resultSetConcurrency,
resultSetHoldability);
}
/**
@exception SQLException if fails to create statement
*/
public abstract java.sql.PreparedStatement newEmbedPreparedStatement(
EmbedConnection conn,
String stmt,
boolean forMetaData,
int resultSetType,
int resultSetConcurrency,
int resultSetHoldability,
int autoGeneratedKeys,
int[] columnIndexes,
String[] columnNames)
throws SQLException;
/**
@exception SQLException if fails to create statement
*/
public abstract java.sql.CallableStatement newEmbedCallableStatement(
EmbedConnection conn,
String stmt,
int resultSetType,
int resultSetConcurrency,
int resultSetHoldability)
throws SQLException;
/**
* Return a new java.sql.DatabaseMetaData instance for this implementation.
@exception SQLException on failure to create.
*/
public DatabaseMetaData newEmbedDatabaseMetaData(EmbedConnection conn,
String dbname) throws SQLException {
return new EmbedDatabaseMetaData(conn,dbname);
}
/**
* Return a new java.sql.ResultSet instance for this implementation.
* @param conn Owning connection
* @param results Top level of language result set tree
* @param forMetaData Is this for meta-data
* @param statement The statement that is creating the SQL ResultSet
* @param isAtomic
* @return a new java.sql.ResultSet
* @throws SQLException
*/
public abstract EmbedResultSet
newEmbedResultSet(EmbedConnection conn, ResultSet results, boolean forMetaData, EmbedStatement statement, boolean isAtomic) throws SQLException;
/**
* Returns a new java.sql.ResultSetMetaData for this implementation
*
* @param columnInfo a ResultColumnDescriptor that stores information
* about the columns in a ResultSet
*/
public EmbedResultSetMetaData newEmbedResultSetMetaData
(ResultColumnDescriptor[] columnInfo) {
return new EmbedResultSetMetaData(columnInfo);
}
}
| 30.519501
| 146
| 0.687062
|
a35270c23fb412789897cb78d7b01613e4ec1709
| 4,159
|
package com.javi.uned.pfgcomposer.kafka.consumers;
import com.javi.uned.pfg.ScoreBuilder;
import com.javi.uned.pfg.exceptions.ExportException;
import com.javi.uned.pfg.io.Export;
import com.javi.uned.pfg.model.ScoreComposite;
import com.javi.uned.pfg.model.Specs;
import com.javi.uned.pfgcomposer.exceptions.MusescoreException;
import com.javi.uned.pfgcomposer.exceptions.SpecsConsumerException;
import com.javi.uned.pfgcomposer.kafka.producers.FileProducer;
import com.javi.uned.pfgcomposer.services.MusescoreService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
@Service
public class RetryXMLConsumer {
private final Logger logger = LoggerFactory.getLogger(RetryXMLConsumer.class);
private static final String TOPIC_COMPOSER_EXECUTION = "melodia.composer.retryxml";
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
@Autowired
private FileProducer fileProducer;
@Autowired
private MusescoreService musescoreService;
@KafkaListener(topics = "melodia.backend.retryxml", groupId = "0", containerFactory = "specsKafkaListenerFactory")
public void consume(Specs specs, @Header(KafkaHeaders.RECEIVED_MESSAGE_KEY) String key) {
File xmlFile = null;
File pdfFile = null;
try{
ScoreComposite scoreComposite = componer(specs, key);
xmlFile = generarXML(scoreComposite, key);
pdfFile = generarPDF(xmlFile, key);
kafkaTemplate.send(TOPIC_COMPOSER_EXECUTION, key, "Terminado!");
logger.info("Composición finalizada. ID={}", key);
} catch (SpecsConsumerException e) {
logger.error("SpecsConsumer.consume: Error al generar partitura", e);
kafkaTemplate.send(TOPIC_COMPOSER_EXECUTION, key, e.getMessage());
} finally { // Clean up
try {
if (xmlFile != null && xmlFile.exists()) Files.delete(xmlFile.toPath());
if (pdfFile != null && pdfFile.exists()) Files.delete(pdfFile.toPath());
} catch (IOException ioe) {
logger.warn("No se ha podido borrar un archivo temporal", ioe);
}
}
}
private ScoreComposite componer(Specs specs, String key) {
kafkaTemplate.send(TOPIC_COMPOSER_EXECUTION, key, "Componiendo");
return ScoreBuilder.getInstance().buildScore(specs);
}
private File generarXML(ScoreComposite scoreComposite, String key) throws SpecsConsumerException {
try{
kafkaTemplate.send(TOPIC_COMPOSER_EXECUTION, key, "Generando fichero .musicxml");
File xmlFile = new File(key+".musicxml");
Export.toXML(scoreComposite, xmlFile);
fileProducer.sendXML(key, xmlFile);
return xmlFile;
} catch (IOException | ExportException e) {
throw new SpecsConsumerException("SpecsConsumer.generarXML: Error al generar XML", e);
}
}
private File generarPDF(File xmlFile, String key) throws SpecsConsumerException {
try{
if(!xmlFile.exists()) throw new SpecsConsumerException("SpecsConsumer.generarPDF: No se ha podido crear el PDF. No existe el archivo " + xmlFile.getAbsolutePath());
kafkaTemplate.send(TOPIC_COMPOSER_EXECUTION, key, "Generando fichero .pdf");
File pdfFile = musescoreService.convertXMLToPDF(xmlFile, key + ".pdf");
fileProducer.sendPDF(key, pdfFile);
return pdfFile;
} catch (MusescoreException e) {
throw new SpecsConsumerException("SpecsConsumer.generarPDF: error al generar PDF", e);
} catch (IOException e) {
throw new SpecsConsumerException("SpecsConsumer.generarPDF: error al guardar PDF", e);
}
}
}
| 44.72043
| 176
| 0.703535
|
8f5b8c256e1871790e2b82c503757534bf32de46
| 2,058
|
/*
Copyright 2017 Erigo Technologies LLC
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 erigo.cttext;
import java.awt.Component;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
/**
*
* Class containing static utility methods.
*
*/
public class Utility {
/**************************************************************************
*
* add()
*
* Add a component to a container in the GUI using the GridBagLayout manager.
*
* This code is from open source DataTurbine class com.rbnb.utility.Utility.
* Covered by Apache 2.0 license.
* Copyright 1997, 2000 Creare Inc, Hanover, N.H.
* All rights reserved.
*
* @author John P. Wilson
*
* @param container
* Container to add Component to
* @param c
* Component to add to the Container
* @param gbl
* GridBagLayout manager to use
* @param gbc
* GridBagConstrains to use to add ther Component
* @param x
* Desired row position of the Component
* @param y
* Desired column position of the Component
* @param w
* Num of columns (width) Component should occupy
* @param h
* Num of rows (height) Component should occupy
*
* @version 10/05/2006
*/
public static void add(Container container, Component c, GridBagLayout gbl, GridBagConstraints gbc, int x, int y, int w, int h) {
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = w;
gbc.gridheight = h;
gbl.setConstraints(c, gbc);
container.add(c);
}
}
| 27.810811
| 130
| 0.656948
|
527ba2f067208749a6306794359f2b0997c7f128
| 6,121
|
/**
* Copyright 2005-2018 Riverside Software
*
* 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.phenix.pct;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.taskdefs.ExecTask;
import org.apache.tools.ant.types.Environment;
import org.apache.tools.ant.types.FileSet;
/**
* Procedure encryption task using xcode utility from Progress
*
* @author <a href="mailto:d.knol@steeg-software.nl">Dick Knol</a>
*/
public class PCTXCode extends PCT {
private List<FileSet> filesets = new ArrayList<>();
private String key = null;
private File destDir = null;
private int tmpLogId = -1;
private File tmpLog = null;
private int filesListId = -1;
private File filesList = null;
private boolean overwrite = false;
private boolean lowercase = false;
/**
* Default constructor
*/
public PCTXCode() {
super();
tmpLogId = PCT.nextRandomInt();
tmpLog = new File(System.getProperty(PCT.TMPDIR), "pct_outp" + tmpLogId + ".log"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
filesListId = PCT.nextRandomInt();
filesList = new File(System.getProperty(PCT.TMPDIR), "xcode" + filesListId + ".input"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
/**
* Sets output directory (-d attribute)
*
* @param destDir File
*/
public void setDestDir(File destDir) {
this.destDir = destDir;
}
/**
* Sets key to be used for encryption (-k attribute)
*
* @param key String
*/
public void setKey(String key) {
this.key = key;
}
/**
* Overwrites files ?
*
* @param overwrite boolean
*/
public void setOverwrite(boolean overwrite) {
this.overwrite = overwrite;
}
/**
* Convert filenames to lowercase (-l attribute)
*
* @param lowercase boolean
*/
public void setLowercase(boolean lowercase) {
this.lowercase = lowercase;
}
/**
* Adds a set of files to encrypt
*
* @param set FileSet
*/
public void addFileset(FileSet set) {
filesets.add(set);
}
/**
* Do the work
*
* @throws BuildException Something went wrong
*/
@Override
public void execute() {
checkDlcHome();
if (destDir == null) {
cleanup();
throw new BuildException(Messages.getString("PCTXCode.4")); //$NON-NLS-1$
}
log(Messages.getString("PCTXCode.5"), Project.MSG_INFO); //$NON-NLS-1$
try {
for (FileSet fs : filesets) {
Task task = createExecTask(fs);
task.execute();
}
cleanup();
} catch (BuildException be) {
cleanup();
throw be;
}
}
private void createFileList(FileSet fs) {
try (FileWriter w = new FileWriter(filesList); BufferedWriter writer = new BufferedWriter(w)) {
for (String str : fs.getDirectoryScanner(getProject()).getIncludedFiles()) {
int j = str.replace(File.separatorChar, '/').lastIndexOf('/');
if (j != -1) {
File f2 = new File(destDir, str.substring(0, j));
if (!f2.exists() && !f2.mkdirs()) {
throw new BuildException(MessageFormat.format(
Messages.getString("PCTXCode.3"), f2.getAbsolutePath())); //$NON-NLS-1$
}
}
File trgFile = new File(destDir, str);
File srcFile = new File(fs.getDir(getProject()), str);
if (!trgFile.exists() || overwrite
|| (srcFile.lastModified() > trgFile.lastModified())) {
log(MessageFormat.format(
Messages.getString("PCTXCode.6"), trgFile.toString()), Project.MSG_VERBOSE); //$NON-NLS-1$
writer.write(str);
writer.newLine();
if (overwrite) {
if (!trgFile.delete())
throw new BuildException(Messages.getString("PCTXCode.7"));
}
}
}
} catch (IOException caught) {
throw new BuildException(caught);
}
}
private Task createExecTask(FileSet fs) {
ExecTask exec = new ExecTask(this);
exec.setDir(fs.getDir(getProject()));
exec.setOutput(tmpLog);
exec.setExecutable(getExecPath("xcode").toString()); //$NON-NLS-1$
Environment.Variable var = new Environment.Variable();
var.setKey("DLC"); //$NON-NLS-1$
var.setValue(getDlcHome().toString());
exec.addEnv(var);
if (key != null) {
exec.createArg().setValue("-k"); //$NON-NLS-1$
exec.createArg().setValue(key);
}
exec.createArg().setValue("-d"); //$NON-NLS-1$
exec.createArg().setValue(destDir.toString());
if (lowercase) {
exec.createArg().setValue("-l"); //$NON-NLS-1$
}
exec.createArg().setValue("-");
createFileList(fs);
exec.setInput(filesList);
return exec;
}
protected void cleanup() {
deleteFile(tmpLog);
deleteFile(filesList);
}
}
| 29.858537
| 137
| 0.570822
|
5fb70cc0563405d5bfdcd3458f8178327ebba16a
| 2,124
|
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2019 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
/*package frc.robot.commands;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import edu.wpi.first.wpilibj2.command.CommandBase;
import frc.robot.Global;
import frc.robot.PIDCalculator;
import frc.robot.subsystems.Hook;
public class HookPID extends CommandBase {
private double error;
private double current;
private double setpoint;
private PIDCalculator hookPID;
private Hook m_hook;
public HookPID(double setpoint, Hook hook) {
// Use addRequirements() here to declare subsystem dependencies.
m_hook = hook;
addRequirements(hook);
this.setpoint = setpoint; //Ticks should be a global constant - MAKE THAT CHANGE
m_hook.HookSpeed(0);
//why does this need to be static in this instance but it doesn't need to be in tankdrive command
hookPID = new PIDCalculator(Global.HOOK_P, 0, 0);
}
// Called when the command is initially scheduled.
@Override
public void initialize() {
}
// Called every time the scheduler runs while the command is scheduled.
@Override
public void execute() {
current = m_hook.getCurrent();
error = setpoint - current;
double currentOutput = hookPID.getOutput(current);
SmartDashboard.putNumber("Current Error", current);
m_hook.HookSpeed(0.5*currentOutput);
}
// Called once the command ends or is interrupted.
@Override
public void end(boolean interrupted) {
m_hook.HookSpeed(0);
//ahhhhhhhhhhhhhhhhhhhhhhhh
}
// Returns true when the command should end.
@Override
public boolean isFinished() {
return Math.abs(error) <= Global.HOOK_TOLERANCE;
}
}
*/
| 29.5
| 101
| 0.627119
|
add652d40f9c8e1a352890c421dd609f5ec07770
| 261
|
package designPatterns.structualPatterns.flyweight.tableTennis.products;
public abstract class TableTennisProduct {
protected int ID;
public TableTennisProduct(int ID) {
this.ID = ID;
}
public int getID() {
return ID;
}
}
| 18.642857
| 72
| 0.67433
|
b320b4a4e611752c2b6e1b82a9c7efae33caddc4
| 1,812
|
package de.agilecoders.wicket.sass;
import java.util.ArrayList;
import java.util.Collection;
import io.bit3.jsass.importer.Import;
import io.bit3.jsass.importer.Importer;
/**
* Importer that tracks nested imports in Sass resources.
*/
class TrackingImporter implements Importer {
/**
* Collection where nested imports are stored.
*/
private final Collection<SassSource> importedSources;
/**
* The scope class used with SassResourceReference.
*/
private final String scopeClass;
/**
* The importer that actually imports Sass sources.
*/
private final Importer delegate;
/**
*
* @param scopeClass The scope class used with SassResourceReference.
* @param delegate The importer that actually imports Sass sources.
*/
public TrackingImporter(String scopeClass, Importer delegate) {
this.scopeClass = scopeClass;
this.delegate = delegate;
this.importedSources = new ArrayList<>();
}
/**
* Returns collection of Sass source that were imported during last compilation.
*
* @return collection of Sass sources imported during last compilation
*/
public Collection<SassSource> getImportedSources() {
return importedSources;
}
@Override
public Collection<Import> apply(String url, Import previous) {
importedSources.clear();
Collection<Import> imports = delegate.apply(url, previous);
if (imports != null && !imports.isEmpty()) {
imports.stream()
.findFirst()
.map(Import::getImportUri)
.ifPresent(importUri ->
this.importedSources.add(new SassSource(importUri.toString(), scopeClass))
);
}
return imports;
}
}
| 27.044776
| 94
| 0.643488
|
9cc98f10ad79eb41259321b5897f3168fcc82976
| 8,435
|
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vcs.changes.ui;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.VcsBundle;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vcs.changes.ChangeListOwner;
import com.intellij.openapi.vcs.changes.LocallyDeletedChange;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.ColoredTreeCellRenderer;
import com.intellij.ui.SimpleTextAttributes;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.MutableTreeNode;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
/**
* @author max
*/
public class ChangesBrowserNode<T> extends DefaultMutableTreeNode {
private SimpleTextAttributes myAttributes;
protected int myCount = -1;
protected int myDirectoryCount = -1;
public static final Object IGNORED_FILES_TAG = new Object() {
public String toString() {
return VcsBundle.message("changes.nodetitle.ignored.files");
}
};
public static final Object LOCKED_FOLDERS_TAG = new Object() {
public String toString() {
return VcsBundle.message("changes.nodetitle.locked.folders");
}
};
public static final Object LOGICALLY_LOCKED_TAG = VcsBundle.message("changes.nodetitle.logicallt.locked.folders");
public static final Object UNVERSIONED_FILES_TAG = new Object() {
public String toString() {
return VcsBundle.message("changes.nodetitle.unversioned.files");
}
};
public static final Object MODIFIED_WITHOUT_EDITING_TAG = new Object() {
public String toString() {
return VcsBundle.message("changes.nodetitle.modified.without.editing");
}
};
public static final Object SWITCHED_FILES_TAG = new Object() {
public String toString() {
return VcsBundle.message("changes.nodetitle.switched.files");
}
};
public static final Object SWITCHED_ROOTS_TAG = new Object() {
public String toString() {
return VcsBundle.message("changes.nodetitle.switched.roots");
}
};
protected ChangesBrowserNode(Object userObject) {
super(userObject);
myAttributes = SimpleTextAttributes.REGULAR_ATTRIBUTES;
}
public static ChangesBrowserNode create(final Project project, @NotNull final LocallyDeletedChange change) {
return new ChangesBrowserLocallyDeletedNode(change, project);
}
public static ChangesBrowserNode create(final Project project, @NotNull Object userObject) {
/*if (userObject instanceof Change) {
return new ChangesBrowserChangeNode(project, (Change) userObject);
}*/
if (userObject instanceof VirtualFile) {
return new ChangesBrowserFileNode(project, (VirtualFile) userObject);
}
if (userObject instanceof FilePath) {
return new ChangesBrowserFilePathNode((FilePath) userObject);
}
/* if (userObject instanceof ChangeList) {
return new ChangesBrowserChangeListNode(project, (ChangeList) userObject);
}*/
if (userObject == IGNORED_FILES_TAG) {
return new ChangesBrowserIgnoredFilesNode(userObject);
}
if (userObject == LOCKED_FOLDERS_TAG) {
return new ChangesBrowserLockedFoldersNode(project, userObject);
}
if (userObject instanceof ChangesBrowserLogicallyLockedFile) {
return (ChangesBrowserNode) userObject;
}
return new ChangesBrowserNode(userObject);
}
@Override
public void insert(MutableTreeNode newChild, int childIndex) {
super.insert(newChild, childIndex);
myCount = -1;
myDirectoryCount = -1;
}
public int getCount() {
if (myCount == -1) {
myCount = 0;
final Enumeration nodes = children();
while (nodes.hasMoreElements()) {
ChangesBrowserNode child = (ChangesBrowserNode)nodes.nextElement();
myCount += child.getCount();
}
}
return myCount;
}
public int getDirectoryCount() {
if (myDirectoryCount == -1) {
myDirectoryCount = isDirectory() ? 1 : 0;
final Enumeration nodes = children();
while (nodes.hasMoreElements()) {
ChangesBrowserNode child = (ChangesBrowserNode)nodes.nextElement();
myDirectoryCount += child.getDirectoryCount();
}
}
return myDirectoryCount;
}
protected boolean isDirectory() {
return false;
}
public List<Change> getAllChangesUnder() {
return getAllObjectsUnder(Change.class);
}
public <T> List<T> getAllObjectsUnder(final Class<T> clazz) {
List<T> changes = new ArrayList<T>();
final Enumeration enumeration = depthFirstEnumeration();
while (enumeration.hasMoreElements()) {
ChangesBrowserNode child = (ChangesBrowserNode)enumeration.nextElement();
final Object value = child.getUserObject();
if (clazz.isAssignableFrom(value.getClass())) {
changes.add((T) value);
}
}
return changes;
}
public List<VirtualFile> getAllFilesUnder() {
List<VirtualFile> files = new ArrayList<VirtualFile>();
final Enumeration enumeration = breadthFirstEnumeration();
while (enumeration.hasMoreElements()) {
ChangesBrowserNode child = (ChangesBrowserNode)enumeration.nextElement();
final Object value = child.getUserObject();
if (value instanceof VirtualFile) {
final VirtualFile file = (VirtualFile)value;
if (file.isValid()) {
files.add(file);
}
}
}
return files;
}
public List<FilePath> getAllFilePathsUnder() {
List<FilePath> files = new ArrayList<FilePath>();
final Enumeration enumeration = breadthFirstEnumeration();
while (enumeration.hasMoreElements()) {
ChangesBrowserNode child = (ChangesBrowserNode)enumeration.nextElement();
final Object value = child.getUserObject();
if (child.isLeaf() && value instanceof FilePath) {
final FilePath file = (FilePath)value;
files.add(file);
}
final FilePath ownPath = child.getMyPath();
if (ownPath != null) {
files.add(ownPath);
}
}
return files;
}
@Nullable
protected FilePath getMyPath() {
return null;
}
public void render(final ChangesBrowserNodeRenderer renderer, final boolean selected, final boolean expanded, final boolean hasFocus) {
renderer.append(userObject.toString(), myAttributes);
appendCount(renderer);
}
protected String getCountText() {
int count = getCount();
int dirCount = getDirectoryCount();
if (dirCount == 0) {
return " " + VcsBundle.message("changes.nodetitle.changecount", count);
}
else if (count == 0 && dirCount > 0) {
return " " + VcsBundle.message("changes.nodetitle.directory.changecount", dirCount);
}
else {
return " " + VcsBundle.message("changes.nodetitle.directory.file.changecount", dirCount, count);
}
}
protected void appendCount(final ColoredTreeCellRenderer renderer) {
final String countText = getCountText();
renderer.append(countText, SimpleTextAttributes.GRAY_ITALIC_ATTRIBUTES);
}
public String toString() {
return getTextPresentation();
}
public String getTextPresentation() {
return userObject == null ? "" : userObject.toString();
}
@Override
public T getUserObject() {
//noinspection unchecked
return (T) userObject;
}
public boolean canAcceptDrop(final ChangeListDragBean dragBean) {
return false;
}
public void acceptDrop(final ChangeListOwner dragOwner, final ChangeListDragBean dragBean) {
}
public int getSortWeight() {
return 8;
}
public int compareUserObjects(final Object o2) {
return 0;
}
public FilePath[] getFilePathsUnder() {
return new FilePath[0];
}
public void setAttributes(SimpleTextAttributes attributes) {
myAttributes = attributes;
}
}
| 31.710526
| 137
| 0.708714
|
76c6141a4b1b32a34e9c4c71998597b59acba554
| 2,462
|
package org.sagebionetworks.repo.model.query.entity;
import java.util.List;
import org.sagebionetworks.repo.model.query.BasicQuery;
import org.sagebionetworks.repo.model.table.TableConstants;
/**
* Model represents an entire entity query including all of the parts.
*
*/
public class QueryModel extends SqlElement {
SelectList select;
Tables from;
ExpressionList where;
SortList sort;
Pagination pagination;
/**
* Build a query model for a given query.
*
* @param query
*/
public QueryModel(BasicQuery query){
IndexProvider indexProvider = new IndexProvider();
// build select
select = new SelectList(query.getSelect(), indexProvider);
// build where
where = new ExpressionList(query.getFilters(), indexProvider);
// build sort
sort = new SortList(query.getSort(), query.isAscending(), indexProvider);
// build the from using the expressions.
from = new Tables(select, where, sort);
pagination = new Pagination(query.getLimit(), query.getOffset());
}
@Override
public void toSql(StringBuilder builder) {
select.toSql(builder);
from.toSql(builder);
where.toSql(builder);
sort.toSql(builder);
pagination.toSql(builder);
}
@Override
public void bindParameters(Parameters parameters) {
from.bindParameters(parameters);
where.bindParameters(parameters);
pagination.bindParameters(parameters);
}
/**
* Create a count query for this model.
*
* @return
*/
public String toCountSql(){
StringBuilder builder = new StringBuilder();
builder.append("SELECT COUNT(*)");
from.toSql(builder);
where.toSql(builder);
return builder.toString();
}
/**
* Create the SQL to get the distinct benefactor IDs for
* this query. The SQL includes any conditions in the original query.
* @return
*/
public String toDistinctBenefactorSql(long limit){
StringBuilder builder = new StringBuilder();
builder.append("SELECT DISTINCT ");
builder.append(TableConstants.ENTITY_REPLICATION_COL_BENEFACTOR_ID);
from.toSql(builder);
where.toSql(builder);
builder.append(" LIMIT ");
builder.append(limit);
return builder.toString();
}
/**
* Is this a select * query?
* @return
*/
public boolean isSelectStar() {
return select.isSelectStar();
}
/**
* Get the where clause.
*
* @return
*/
public ExpressionList getWhereClause(){
return where;
}
}
| 24.137255
| 76
| 0.686028
|
b43d76188ea7bbb99fecf84d803c32444aee22dd
| 3,269
|
/*
Copyright 2018 dm4rnde (dm4rnde@protonmail.com)
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 dm4rnde.tictactoe;
import java.util.List;
public class PatternMatcher {
/**
* Find if there is a match (at least one full row, or at least one full column,
* or at least one full diagonal) for either 'circles' or 'crosses' (whichever
* has the turn).
*
* @param isCrossTurn
* @return
*/
public static boolean checkForMatch(boolean isCrossTurn, List<Box> boxes) {
char[][] c = new char[3][3];
for (Box b : boxes) {
char cr = b.getContainsCross() ? 'c' : 'o';
c[b.getDownPos() - 1][b.getRightPos() - 1] = cr;
}
// Arrays.toString(c);
// Stream.of(c).forEach(r -> System.out.println(Arrays.toString(r)));
if (horizontalMatch(c, isCrossTurn)) {
String cr = isCrossTurn ? "crosses" : "circles";
String msg = String.format("%s won %s", cr, "horizontal");
Loggr.logFine(msg);
return true;
}
if (verticalMatch(c, isCrossTurn)) {
String cr = isCrossTurn ? "crosses" : "circles";
String msg = String.format("%s won %s", cr, "vertical");
Loggr.logFine(msg);
return true;
}
if (diagonalMatch(c, isCrossTurn)) {
String cr = isCrossTurn ? "crosses" : "circles";
String msg = String.format("%s won %s", cr, "diagonal");
Loggr.logFine(msg);
return true;
}
return false;
}
/**
* Having matrix find if symbol 'c' or 'o' fills at least one full diagonal.
*
* @param matrix
* @param checkCrosses
* @return
*/
private static boolean diagonalMatch(char[][] matrix, boolean checkCrosses) {
char cr = checkCrosses ? 'c' : 'o';
if (matrix[0][0] == cr && matrix[1][1] == cr && matrix[2][2] == cr) {
return true;
}
if (matrix[0][2] == cr && matrix[1][1] == cr && matrix[2][0] == cr) {
return true;
}
return false;
}
/**
* Having matrix find if symbol 'c' or 'o' fills at least one full row.
*
* @param matrix
* @param checkCrosses
* @return
*/
private static boolean horizontalMatch(char[][] matrix, boolean checkCrosses) {
char cr = checkCrosses ? 'c' : 'o';
int count = 0;
for (int i = 0; i < 3; i++) {
count = 0;
for (int j = 0; j < 3; j++) {
if (matrix[i][j] == cr) {
count++;
}
}
if (count == 3) {
return true;
}
}
return false;
}
/**
* Having matrix find if symbol 'c' or 'o' fills at least one full column.
*
* @param matrix
* @param checkCrosses
* @return
*/
private static boolean verticalMatch(char[][] matrix, boolean checkCrosses) {
char cr = checkCrosses ? 'c' : 'o';
int count = 0;
for (int i = 0; i < 3; i++) {
count = 0;
for (int j = 0; j < 3; j++) {
if (matrix[j][i] == cr) {
count++;
}
}
if (count == 3) {
return true;
}
}
return false;
}
}
| 24.214815
| 81
| 0.618232
|
d3dd39f8b86d3786c44094a79ffd94b6b6986703
| 10,645
|
/**
* Copyright (C) 2016 Red Hat, 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 io.syndesis.dao.manager;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import javax.annotation.PostConstruct;
import javax.persistence.EntityExistsException;
import javax.persistence.EntityNotFoundException;
import io.syndesis.core.EventBus;
import io.syndesis.core.KeyGenerator;
import io.syndesis.core.SyndesisServerException;
import io.syndesis.dao.init.ModelData;
import io.syndesis.dao.init.ReadApiClientData;
import io.syndesis.model.ChangeEvent;
import io.syndesis.model.Kind;
import io.syndesis.model.ListResult;
import io.syndesis.model.WithId;
import org.infinispan.Cache;
import org.infinispan.manager.CacheContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class DataManager implements DataAccessObjectRegistry {
private static final Logger LOGGER = LoggerFactory.getLogger(DataManager.class.getName());
private final CacheContainer caches;
private final EventBus eventBus;
@Value("${deployment.file:io/syndesis/dao/deployment.json}")
@SuppressWarnings("PMD.ImmutableField") // @Value cannot be applied to final properties
private String dataFileName = "io/syndesis/dao/deployment.json";
@SuppressWarnings("PMD.ImmutableField") // @Value cannot be applied to final properties
@Value("${deployment.load-demo-data:true}")
private boolean loadDemoData = true;
private final List<DataAccessObject<?>> dataAccessObjects = new ArrayList<>();
private final Map<Class<? extends WithId<?>>, DataAccessObject<?>> dataAccessObjectMapping = new ConcurrentHashMap<>();
// Inject mandatory via constructor injection.
@Autowired
public DataManager(CacheContainer caches, List<DataAccessObject<?>> dataAccessObjects, EventBus eventBus) {
this.caches = caches;
this.eventBus = eventBus;
if (dataAccessObjects != null) {
this.dataAccessObjects.addAll(dataAccessObjects);
}
}
@PostConstruct
public void init() {
for (DataAccessObject<?> dataAccessObject : dataAccessObjects) {
registerDataAccessObject(dataAccessObject);
}
}
public void resetDeploymentData() {
if (dataFileName != null) {
loadData(this.dataFileName);
}
if( loadDemoData ) {
loadData("io/syndesis/dao/demo-data.json");
}
}
private void loadData(String file) {
ReadApiClientData reader = new ReadApiClientData();
try {
List<ModelData<?>> mdList = reader.readDataFromFile(file);
for (ModelData<?> modelData : mdList) {
store(modelData);
}
} catch (@SuppressWarnings("PMD.AvoidCatchingGenericException") Exception e) {
throw new IllegalStateException("Cannot read dummy startup data due to: " + e.getMessage(), e);
}
}
public <T extends WithId<T>> void store(ModelData<T> modelData) {
try {
Kind kind = modelData.getKind();
LOGGER.debug("{}:{}", kind, modelData.getDataAsJson());
T entity = modelData.getData();
Optional<String> id = entity.getId();
if (!id.isPresent()) {
LOGGER.warn("Cannot load entity from file since it's missing an id: {}", modelData.toJson());
} else {
WithId<?> prev = null;
try {
prev = this.<T>fetch(kind.getModelClass(), id.get());
} catch (@SuppressWarnings("PMD.AvoidCatchingGenericException") RuntimeException e) {
// Lets try to wipe out the previous record in case
// we are running into something like a schema change.
this.<T>delete(kind.getModelClass(), id.get());
}
if (prev == null) {
create(entity);
} else {
update(entity);
}
}
} catch (@SuppressWarnings("PMD.AvoidCatchingGenericException") Exception e) {
LOGGER.warn("Cannot load entity from file: ", e);
throw SyndesisServerException.launderThrowable(e);
}
}
public <T extends WithId<T>> ListResult<T> fetchAll(Class<T> model, Function<ListResult<T>, ListResult<T>>... operators) {
ListResult<T> result;
if( getDataAccessObject(model)!=null ) {
result = doWithDataAccessObject(model, d -> d.fetchAll());
} else {
Kind kind = Kind.from(model);
Cache<String, T> cache = caches.getCache(kind.getModelName());
result = ListResult.of(cache.values());
}
for (Function<ListResult<T>, ListResult<T>> operator : operators) {
result = operator.apply(result);
}
return result;
}
public <T extends WithId<T>> T fetch(Class<T> model, String id) {
Kind kind = Kind.from(model);
Map<String, T> cache = caches.getCache(kind.getModelName());
T value = cache.get(id);
if ( value == null) {
value = this.<T, T>doWithDataAccessObject(model, d -> d.fetch(id));
if (value != null) {
cache.put(id, value);
}
}
return value;
}
public <T extends WithId<T>> Set<String> fetchIdsByPropertyValue(Class<T> model, String property, String value) {
return doWithDataAccessObject(model, d -> d.fetchIdsByPropertyValue(property, value));
}
public <T extends WithId<T>> T create(final T entity) {
Kind kind = entity.getKind();
Cache<String, T> cache = caches.getCache(kind.getModelName());
Optional<String> id = entity.getId();
String idVal;
final T entityToCreate;
if (!id.isPresent()) {
idVal = KeyGenerator.createKey();
entityToCreate = entity.withId(idVal);
} else {
idVal = id.get();
if (cache.keySet().contains(idVal)) {
throw new EntityExistsException("There already exists a "
+ kind + " with id " + idVal);
}
entityToCreate = entity;
}
this.<T, T>doWithDataAccessObject(kind.getModelClass(), d -> d.create(entityToCreate));
cache.put(idVal, entityToCreate);
broadcast("created", kind.getModelName(), idVal);
return entityToCreate;
}
public <T extends WithId<T>> void update(T entity) {
Optional<String> id = entity.getId();
if (!id.isPresent()) {
throw new EntityNotFoundException("Setting the id on the entity is required for updates");
}
String idVal = id.get();
Kind kind = entity.getKind();
T previous = this.<T, T>doWithDataAccessObject(kind.getModelClass(), d -> d.update(entity));
Map<String, T> cache = caches.getCache(kind.getModelName());
if (!cache.containsKey(idVal) && previous==null) {
throw new EntityNotFoundException("Can not find " + kind + " with id " + idVal);
}
cache.put(idVal, entity);
broadcast("updated", kind.getModelName(), idVal);
//TODO 1. properly merge the data ? + add data validation in the REST Resource
}
public <T extends WithId<T>> boolean delete(Class<T> model, String id) {
if (id == null || id.equals("")) {
throw new EntityNotFoundException("Setting the id on the entity is required for updates");
}
Kind kind = Kind.from(model);
Map<String, WithId<T>> cache = caches.getCache(kind.getModelName());
// Remove it out of the cache
WithId<T> entity = cache.remove(id);
boolean deletedInCache = entity != null;
// And out of the DAO
boolean deletedFromDAO = Boolean.TRUE.equals(doWithDataAccessObject(model, d -> d.delete(id)));
// Return true if the entity was found in any of the two.
if ( deletedInCache || deletedFromDAO ) {
broadcast("deleted", kind.getModelName(), id);
return true;
}
return false;
}
public <T extends WithId<T>> void deleteAll(Class<T> model) {
Kind kind = Kind.from(model);
Map<String, WithId<T>> cache = caches.getCache(kind.getModelName());
cache.clear();
doWithDataAccessObject(model, d -> {
d.deleteAll();
return null;
});
}
@Override
public Map<Class<? extends WithId<?>>, DataAccessObject<?>> getDataAccessObjectMapping() {
return dataAccessObjectMapping;
}
/**
* Perform a simple action if a {@link DataAccessObject} for the specified kind exists.
* This is just a way to avoid, duplicating the dao lookup and checks, which are going to change.
* @param model The model class of the {@link DataAccessObject}.
* @param function The function to perfom on the {@link DataAccessObject}.
* @param <O> The return type.
* @return The outcome of the function.
*/
private <T extends WithId<T>, R> R doWithDataAccessObject(Class<T> model, Function<DataAccessObject<T>, R> function) {
DataAccessObject<T> dataAccessObject = getDataAccessObject(model);
if (dataAccessObject != null) {
return function.apply(dataAccessObject);
}
return null;
}
private void broadcast(String event, String type, String id) {
if( eventBus !=null ) {
eventBus.broadcast("change-event", ChangeEvent.of(event, type, id).toJson());
}
}
public void clearCache() {
for (Kind kind : Kind.values()) {
caches.getCache(kind.modelName).clear();
}
}
}
| 37.22028
| 126
| 0.62527
|
63ff964b3a1b38869bbc3df49e8ccd9f58c292d9
| 987
|
package com.codepath.nytimessearch.activities;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.codepath.nytimessearch.R;
import com.codepath.nytimessearch.models.Article;
public class ArticleActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_article);
Article article = (Article) getIntent().getSerializableExtra("article");
String url = article.getWebUrl();
WebView wvArticle = (WebView) findViewById(R.id.wvArticle);
wvArticle.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
wvArticle.loadUrl(url);
}
}
| 29.909091
| 80
| 0.694022
|
711b17468f33f0e70c77fc27dfb19a15b2d64311
| 5,457
|
/*
* Copyright [2016-2020] [George Papadakis (gpapadis@yahoo.gr)]
*
* 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.scify.jedai.similarityjoins.characterbased;
import gnu.trove.list.TIntList;
import gnu.trove.list.array.TIntArrayList;
import gnu.trove.set.TIntSet;
import gnu.trove.set.hash.TIntHashSet;
import org.scify.jedai.datamodel.Comparison;
import org.scify.jedai.datamodel.EntityProfile;
import org.scify.jedai.datamodel.SimilarityPairs;
import org.scify.jedai.datamodel.joins.IntListPair;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
*
* @author mthanos
*/
public class FastSS extends AbstractCharacterBasedJoin {
private int id;
private final HashMap<String, List<IntListPair>> stringHashIndex;
private final TIntList delPos;
private final TIntSet checkedFlag;
public FastSS(int thr) {
super(thr);
this.checkedFlag = new TIntHashSet();
this.stringHashIndex = new HashMap<>();
this.delPos = new TIntArrayList();
}
@Override
protected SimilarityPairs applyJoin() {
checkedFlag.clear();
delPos.clear();
stringHashIndex.clear();
final List<Comparison> comparisons = processDataset(attributeNameD1, profilesD1);
if (profilesD2 != null) { // Dirty ER
comparisons.addAll(processDataset(attributeNameD2, profilesD2));
}
return getSimilarityPairs(comparisons);
}
private int checkEditDistance(TIntList p1, TIntList p2) {
int i = 0, j = 0, updates = 0;
while (i < p1.size() && j < p2.size()) {
if (p1.get(i) == p2.get(j)) {
updates++;
j++;
i++;
} else if (p1.get(i) < p2.get(j)) {
i++;
} else {
j++;
}
}
return p1.size() + p2.size() - updates;
}
@Override
public String getMethodInfo() {
return getMethodName() + ": it is ideal for short textual values. It associates every value with the set "
+ "of substrings that are produced after deleting a certain number of characters, "
+ "and every other value that shares one or more substrings is considered a candidate match.";
}
@Override
public String getMethodName() {
return "FastSS";
}
private List<Comparison> insertIndex(String attributeValue) {
final TIntList delPos1 = new TIntArrayList(delPos);
List<IntListPair> list = stringHashIndex.computeIfAbsent(attributeValue, k -> new ArrayList<>());
final List<Comparison> executedComparisons = new ArrayList<>();
for (IntListPair p : list) {
if (id == p.getKey()) {
continue;
}
if (isCleanCleanER) {
if (id < datasetDelimiter && p.getKey() < datasetDelimiter) { // both belong to dataset 1
continue;
}
if (datasetDelimiter <= id && datasetDelimiter <= p.getKey()) { // both belong to dataset 2
continue;
}
}
if (checkedFlag.contains(p.getKey())) {
continue;
}
int ed = checkEditDistance(p.getValue(), delPos1);
if (ed <= threshold) {
checkedFlag.add(p.getKey());
final Comparison currentComp = getComparison(id, p.getKey());
currentComp.setUtilityMeasure(1 - (float) ed / threshold);
executedComparisons.add(currentComp);
}
}
final IntListPair kv = new IntListPair(id, delPos1);
list.add(kv);
return executedComparisons;
}
private void performDeletion(String s, int k) {
if (k == 0) {
insertIndex(s);
} else {
for (int pos = (delPos.isEmpty() ? 0 : delPos.get(delPos.size() - 1)); pos < s.length(); pos++) {
delPos.add(pos);
final String newS = s.substring(0, pos) + s.substring(pos + 1);
performDeletion(newS, k - 1);
delPos.removeAt(delPos.size() - 1);
}
}
}
private List<Comparison> processDataset(String attributeName, List<EntityProfile> dataset) {
final List<Comparison> totalComparisons = new ArrayList<>();
for (EntityProfile profile : dataset) {
String nextValue = getAttributeValue(attributeName, profile);
checkedFlag.clear();
totalComparisons.addAll(insertIndex(nextValue));
for (int k = 1; k <= threshold; k++) {
performDeletion((nextValue), k);
}
id++;
}
return totalComparisons;
}
}
| 34.537975
| 115
| 0.577057
|
72ad26d570f77b52acf903472680286bc7cdb930
| 1,788
|
/*
* 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 2012-2018 the original author or authors.
*/
package org.assertj.core.internal;
public final class CommonErrors {
public static NullPointerException arrayOfValuesToLookForIsNull() {
return new NullPointerException(ErrorMessages.arrayOfValuesToLookForIsNull());
}
public static NullPointerException iterableToLookForIsNull() {
return new NullPointerException(ErrorMessages.iterableToLookForIsNull());
}
public static NullPointerException iterableOfValuesToLookForIsNull() {
return new NullPointerException(ErrorMessages.iterableValuesToLookForIsNull());
}
public static IllegalArgumentException arrayOfValuesToLookForIsEmpty() {
return new IllegalArgumentException(ErrorMessages.arrayOfValuesToLookForIsEmpty());
}
public static IllegalArgumentException iterableOfValuesToLookForIsEmpty() {
return new IllegalArgumentException(ErrorMessages.iterableValuesToLookForIsEmpty());
}
public static void wrongElementTypeForFlatExtracting(Object group) {
throw new IllegalArgumentException("Flat extracting expects extracted values to be Iterables or arrays but was a "
+ group.getClass().getSimpleName());
}
private CommonErrors() {}
}
| 39.733333
| 118
| 0.774609
|
b881da35f4a746703c6e8feee5a4eed688144ed0
| 1,210
|
package org.usfirst.frc.team2141.robot.commands;
import org.usfirst.frc.team2141.robot.Robot;
import edu.wpi.first.wpilibj.command.Command;
/**
*
*/
public class ShooterControl extends Command {
public ShooterControl() {
// Use requires() here to declare subsystem dependencies
// eg. requires(chassis);
requires(Robot.shooter);
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
Robot.shooter.setFeederSpeed(.5);
Robot.shooter.setShooterMotorVelocity(15000);
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return false;
}
// Called once after isFinished returns true
protected void end() {
Robot.shooter.setFeederSpeed(0);
Robot.shooter.setShooterMotorVoltage(0);
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
Robot.shooter.setFeederSpeed(0);
Robot.shooter.setShooterMotorVoltage(0);
}
}
| 26.304348
| 79
| 0.68843
|
eeba7ce9bd7e1cc6bf0dc0c96519ee4e8b8194a6
| 2,288
|
package com.shejiaomao.core.http;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.shejiaomao.core.LibConstants;
import com.shejiaomao.core.LibResultCode;
import com.shejiaomao.core.LibRuntimeException;
class FileResponseHandler implements ResponseHandler<File> {
private static final Logger logger = LoggerFactory.getLogger(FileResponseHandler.class);
private File file;
public FileResponseHandler(File file) {
this.file = file;
}
@Override
public File handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
if (file == null) {
throw new LibRuntimeException(LibResultCode.E_PARAM_NULL);
}
return writeToFile(response.getEntity());
}
public File writeToFile(final HttpEntity entity) throws ClientProtocolException, IOException {
if (entity == null) {
throw new LibRuntimeException(LibResultCode.E_PARAM_ERROR);
}
InputStream instream = entity.getContent();
if (instream == null) {
return null;
}
if (entity.getContentLength() > Integer.MAX_VALUE) {
throw new LibRuntimeException(
LibResultCode.E_PARAM_ERROR, "HTTP entity is too large!"
);
}
if (LibConstants.level <= LibConstants.VERBOSE) {
logger.trace("Content Type : {}", entity.getContentType());
}
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
byte[] tmp = new byte[4096];
int l;
while ((l = instream.read(tmp)) != -1) {
fos.write(tmp, 0, l);
}
fos.flush();
} catch (FileNotFoundException e) {
if (LibConstants.isDebug()) logger.debug(e.getMessage(), e);
} finally {
instream.close();
fos.close();
}
return file;
}
}
| 29.333333
| 96
| 0.651224
|
2228d702a2c16dfd891a2f7f83dfcf41e2869491
| 8,111
|
package net.openid.conformance.condition.client;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import net.openid.conformance.condition.Condition.ConditionResult;
import net.openid.conformance.condition.ConditionError;
import net.openid.conformance.logging.TestInstanceEventLog;
import net.openid.conformance.testmodule.Environment;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnitRunner;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(MockitoJUnitRunner.class)
public class AddMTLSEndpointAliasesToEnvironment_UnitTest {
@Spy
private Environment env = new Environment();
@Mock
private TestInstanceEventLog eventLog;
private AddMTLSEndpointAliasesToEnvironment cond;
@Before
public void setUp() throws Exception {
cond = new AddMTLSEndpointAliasesToEnvironment();
cond.setProperties("UNIT-TEST", eventLog, ConditionResult.INFO);
}
@Test
public void testEvaluate_noError() {
JsonObject server = JsonParser.parseString("{"
+ "\"token_endpoint\": \"https://server.example.com/token\","
+ "\"revocation_endpoint\": \"https://server.example.com/revo\","
+ "\"introspection_endpoint\": \"https://server.example.com/introspect\","
+ "\"userinfo_endpoint\": \"https://server.example.com/me\","
+ "\"mtls_endpoint_aliases\": {"
+ "\"token_endpoint\": \"https://mtls.example.com/token\","
+ "\"revocation_endpoint\": \"https://mtls.example.com/revo\","
+ "\"introspection_endpoint\": \"https://mtls.example.com/introspect\""
+ "}}").getAsJsonObject();
env.putObject("server", server);
cond.execute(env);
assertThat(env.getString("server", "mtls_endpoint_aliases.token_endpoint")).isEqualTo(env.getString("token_endpoint"));
assertThat(env.getString("server", "mtls_endpoint_aliases.revocation_endpoint")).isEqualTo(env.getString("revocation_endpoint"));
assertThat(env.getString("server", "mtls_endpoint_aliases.introspection_endpoint")).isEqualTo(env.getString("introspection_endpoint"));
assertThat(env.getString("server", "mtls_endpoint_aliases.only_in_mtsaliases_endpoint")).isEqualTo(env.getString("only_in_mtsaliases_endpoint"));
assertThat(env.getString("server", "userinfo_endpoint")).isEqualTo(env.getString("userinfo_endpoint"));
}
@Test
public void testEvaluate_onlyInMtls() {
JsonObject server = JsonParser.parseString("{"
+ "\"token_endpoint\": \"https://server.example.com/token\","
+ "\"revocation_endpoint\": \"https://server.example.com/revo\","
+ "\"introspection_endpoint\": \"https://server.example.com/introspect\","
+ "\"userinfo_endpoint\": \"https://server.example.com/me\","
+ "\"mtls_endpoint_aliases\": {"
+ "\"token_endpoint\": \"https://mtls.example.com/token\","
+ "\"revocation_endpoint\": \"https://mtls.example.com/revo\","
+ "\"introspection_endpoint\": \"https://mtls.example.com/introspect\","
+ "\"only_in_mtsaliases_endpoint\": \"https://mtls.example.com/onlyinmtlsaliases\""
+ "}}").getAsJsonObject();
env.putObject("server", server);
boolean exception = false;
try {
cond.execute(env);
} catch (ConditionError e) {
exception = true;
}
assertThat(env.getString("server", "mtls_endpoint_aliases.token_endpoint")).isEqualTo(env.getString("token_endpoint"));
assertThat(env.getString("server", "mtls_endpoint_aliases.revocation_endpoint")).isEqualTo(env.getString("revocation_endpoint"));
assertThat(env.getString("server", "mtls_endpoint_aliases.introspection_endpoint")).isEqualTo(env.getString("introspection_endpoint"));
assertThat(env.getString("server", "mtls_endpoint_aliases.only_in_mtsaliases_endpoint")).isEqualTo(env.getString("only_in_mtsaliases_endpoint"));
assertThat(env.getString("server", "userinfo_endpoint")).isEqualTo(env.getString("userinfo_endpoint"));
assertThat(exception);
}
@Test
public void testEvaluate_notPresentMtlsEndpointAliases() {
JsonObject server = JsonParser.parseString("{"
+ "\"token_endpoint\": \"https://server.example.com/token\""
+ "}").getAsJsonObject();
env.putObject("server", server);
cond.execute(env);
assertThat(env.getString("server", "token_endpoint")).isEqualTo(env.getString("token_endpoint"));
}
@Test(expected = ConditionError.class)
public void testEvaluate_missingConfig() {
cond.execute(env);
}
@Test(expected = ConditionError.class)
public void testEvaluate_notObject() {
JsonObject server = JsonParser.parseString("{"
+ "\"token_endpoint\": \"https://server.example.com/token\","
+ "\"revocation_endpoint\": \"https://server.example.com/revo\","
+ "\"introspection_endpoint\": \"https://server.example.com/introspect\","
+ "\"userinfo_endpoint\": \"https://server.example.com/me\","
+ "\"mtls_endpoint_aliases\": \"https://mtls.example.com/token\""
+ "}").getAsJsonObject();
env.putObject("server", server);
cond.execute(env);
}
@Test
public void testEvaluate_authEndpointAliasedError() {
JsonObject server = JsonParser.parseString("{"
+ "\"token_endpoint\": \"https://server.example.com/token\","
+ "\"revocation_endpoint\": \"https://server.example.com/revo\","
+ "\"introspection_endpoint\": \"https://server.example.com/introspect\","
+ "\"userinfo_endpoint\": \"https://server.example.com/me\","
+ "\"mtls_endpoint_aliases\": {"
+ "\"token_endpoint\": \"https://mtls.example.com/token\","
+ "\"revocation_endpoint\": \"https://mtls.example.com/revo\","
+ "\"authorization_endpoint\": \"https://mtls.example.com/auth\","
+ "\"introspection_endpoint\": \"https://mtls.example.com/introspect\""
+ "}}").getAsJsonObject();
env.putObject("server", server);
boolean exception = false;
try {
cond.execute(env);
} catch (ConditionError e) {
exception = true;
}
assertThat(env.getString("server", "mtls_endpoint_aliases.token_endpoint")).isEqualTo(env.getString("token_endpoint"));
assertThat(env.getString("server", "mtls_endpoint_aliases.revocation_endpoint")).isEqualTo(env.getString("revocation_endpoint"));
assertThat(env.getString("server", "mtls_endpoint_aliases.introspection_endpoint")).isEqualTo(env.getString("introspection_endpoint"));
assertThat(env.getString("server", "mtls_endpoint_aliases.only_in_mtsaliases_endpoint")).isEqualTo(env.getString("only_in_mtsaliases_endpoint"));
assertThat(env.getString("server", "userinfo_endpoint")).isEqualTo(env.getString("userinfo_endpoint"));
assertThat(exception);
}
@Test
public void testEvaluate_NotEndpointAliasedError() {
JsonObject server = JsonParser.parseString("{"
+ "\"token_endpoint\": \"https://server.example.com/token\","
+ "\"revocation_endpoint\": \"https://server.example.com/revo\","
+ "\"introspection_endpoint\": \"https://server.example.com/introspect\","
+ "\"userinfo_endpoint\": \"https://server.example.com/me\","
+ "\"mtls_endpoint_aliases\": {"
+ "\"token_endpoint\": \"https://mtls.example.com/token\","
+ "\"revocation_endpoint\": \"https://mtls.example.com/revo\","
+ "\"issuer\": \"https://mtls.example.com/\","
+ "\"introspection_endpoint\": \"https://mtls.example.com/introspect\""
+ "}}").getAsJsonObject();
env.putObject("server", server);
boolean exception = false;
try {
cond.execute(env);
} catch (ConditionError e) {
exception = true;
}
assertThat(env.getString("server", "mtls_endpoint_aliases.token_endpoint")).isEqualTo(env.getString("token_endpoint"));
assertThat(env.getString("server", "mtls_endpoint_aliases.revocation_endpoint")).isEqualTo(env.getString("revocation_endpoint"));
assertThat(env.getString("server", "mtls_endpoint_aliases.introspection_endpoint")).isEqualTo(env.getString("introspection_endpoint"));
assertThat(env.getString("server", "mtls_endpoint_aliases.only_in_mtsaliases_endpoint")).isEqualTo(env.getString("only_in_mtsaliases_endpoint"));
assertThat(env.getString("server", "userinfo_endpoint")).isEqualTo(env.getString("userinfo_endpoint"));
assertThat(exception);
}
}
| 40.555
| 147
| 0.724202
|
612c3e914d92aa5e865896d7dc31740ee4164802
| 3,872
|
package com.github.vcoppe;
import gurobi.GRBException;
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
private static int n = -1;
private static int[] l;
private static int[][] c;
private static final ArrayList<Pair> p = new ArrayList<>(), o = new ArrayList<>(), r = new ArrayList<>();
private static boolean modelAmaral = true;
private static void read(String path) {
try {
Scanner scan = new Scanner(new File(path));
int count = 0;
while (scan.hasNextLine()) {
String line = scan.nextLine();
if (line.startsWith("c")) continue;
String[] tokens = line.split("[\\s,]+");
if (n != -1 && tokens.length != n) continue;
if (n == -1) {
n = Integer.parseInt(tokens[0]);
l = new int[n];
c = new int[n][n];
} else if (count < n) {
for (; count < n; count++) {
l[count] = Integer.parseInt(tokens[count]);
}
} else {
int start = count;
for (; count < start + n; count++) {
c[count/n - 1][count % n] = Integer.parseInt(tokens[count % n]);
}
}
}
scan.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Failed to read input file");
System.exit(0);
}
}
private static void readConstraints(String path) {
try {
Scanner scan = new Scanner(new File(path));
int np = scan.nextInt();
int no = scan.nextInt();
int nr = scan.nextInt();
int a, b;
for (int i=0; i<np; i++) {
a = scan.nextInt();
b = scan.nextInt();
p.add(new Pair(a, b));
}
for (int i=0; i<no; i++) {
a = scan.nextInt();
b = scan.nextInt();
o.add(new Pair(a, b));
}
for (int i=0; i<nr; i++) {
a = scan.nextInt();
b = scan.nextInt();
r.add(new Pair(a, b));
}
scan.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Failed to read constraints file");
System.exit(0);
}
}
public static void main(String[] args) throws GRBException {
if (args.length < 1) {
System.out.println("Arguments needed :\n\tfilename\n\t[--time timeLimit]\n\t[--threads threads]\n\t[--constraints filename]\n\t[--liu]");
return;
}
read(args[0]);
int timeLimit = Integer.MAX_VALUE, threads = 0;
for (int i=1; i<args.length; i++) {
if (args[i].equals("--time")) timeLimit = Integer.parseInt(args[i+1]);
if (args[i].equals("--threads")) threads = Integer.parseInt(args[i+1]);
if (args[i].equals("--constraints")) readConstraints(args[i+1]);
if (args[i].equals("--liu")) modelAmaral = false;
}
if (args[0].contains("Cl")) {
for (int i=0; i<n; i++) {
l[i] += 10;
}
}
Model mip = modelAmaral ? new ModelAmaral(n, l, c, p, o, r) : new ModelLiu(n, l, c, p, o, r);
System.out.println("MIP model created");
System.out.println("Solving...");
mip.solve(timeLimit, threads);
System.out.println("runTime : " + mip.runTime());
System.out.println("objValue : " + mip.objVal());
System.out.println("gap : " + mip.gap());
mip.dispose();
}
}
| 30.976
| 149
| 0.458161
|
8c81424e666d9ae6fecaa9d3bde51cf9625a1de9
| 2,068
|
package yorkpirates.objects;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.math.Vector2;
/**
* Controller for player-controlled ships.
*/
public class PlayerController implements ShipController {
/**
* Calculates the velocity that the corresponding ship should use depending on which keys the player presses.
* @return Vector representing the x and y components of the ship's velocity.
*/
@Override
public Vector2 calculateVelocity() {
Vector2 velocity = new Vector2(0, 0);
if (leftPressed()) {
velocity.x -= 1;
}
if (rightPressed()) {
velocity.x += 1;
}
if (upPressed()) {
velocity.y += 1;
}
if (downPressed()) {
velocity.y -= 1;
}
return velocity.nor();
}
/**
* Returns true if the player presses the key to fire.
*/
@Override
public boolean shouldFire() {
return Gdx.input.isButtonPressed(Input.Buttons.LEFT) ||
Gdx.input.isKeyPressed(Input.Keys.F);
}
/**
* Returns true if the player presses the up arrow key or W.
*/
private boolean upPressed() {
return Gdx.input.isKeyPressed(Input.Keys.UP) || Gdx.input.isKeyPressed(Input.Keys.W);
}
/**
* Returns true if the player presses the left arrow key or A.
*/
private boolean leftPressed() {
return Gdx.input.isKeyPressed(Input.Keys.LEFT) || Gdx.input.isKeyPressed(Input.Keys.A);
}
/**
* Returns true if the player presses the down arrow key or S.
*/
private boolean downPressed() {
return Gdx.input.isKeyPressed(Input.Keys.DOWN) || Gdx.input.isKeyPressed(Input.Keys.S);
}
/**
* Returns true if the player presses the right arrow key or D.
*/
private boolean rightPressed() {
return Gdx.input.isKeyPressed(Input.Keys.RIGHT) || Gdx.input.isKeyPressed(Input.Keys.D);
}
}
| 28.328767
| 114
| 0.589942
|
25ca520ed5cef517a475cbd1ba93d6c659e767ce
| 5,396
|
package top.infra.maven.extension.mavenbuild.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.Properties;
import org.apache.maven.eventspy.EventSpy.Context;
import org.apache.maven.model.InputLocation;
import org.apache.maven.model.Model;
import org.apache.maven.model.Profile;
import org.apache.maven.model.building.ModelProblem;
import org.apache.maven.model.building.ModelProblemCollector;
import org.apache.maven.model.building.ModelProblemCollectorRequest;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.apache.maven.model.profile.ProfileActivationContext;
public abstract class MavenUtils {
public static Optional<Boolean> cmdArgOffline(final Context context) {
return cmdArgOffline(systemProperties(context));
}
public static Optional<Boolean> cmdArgOffline(final Properties systemProperties) {
final String value = systemProperties != null ? systemProperties.getProperty(ENV_MAVEN_CMD_LINE_ARGS) : null;
return Optional.ofNullable(value != null ? value.contains(" -o ") : null);
}
public static Optional<Boolean> cmdArgUpdate(final Context context) {
return cmdArgUpdate(systemProperties(context));
}
public static Optional<Boolean> cmdArgUpdate(final Properties systemProperties) {
final String value = systemProperties != null ? systemProperties.getProperty(ENV_MAVEN_CMD_LINE_ARGS) : null;
return Optional.ofNullable(value != null ? value.contains(" -U ") : null);
}
/**
* Report titled activator problem.
*/
public static void reportProblem(
final String title,
final Exception error,
final Profile profile,
final ProfileActivationContext context,
final ModelProblemCollector problems
) {
final String message = String.format("%s: project='%s' profile='%s'", title, projectName(context), profileId(profile));
registerProblem(message, error, profile.getLocation(""), problems);
}
/**
* Inject new problem in reporter.
*/
private static void registerProblem(
final String message,
final Exception error,
final InputLocation location,
final ModelProblemCollector problems
) {
final ModelProblemCollectorRequest request = problemRequest()
.setMessage(message)
.setException(error)
.setLocation(location);
problems.add(request);
}
/**
* Produce default problem descriptor.
*/
private static ModelProblemCollectorRequest problemRequest() {
return new ModelProblemCollectorRequest(ModelProblem.Severity.ERROR, ModelProblem.Version.BASE);
}
/**
* Extract null-safe profile identity.
*/
public static String profileId(final Profile profile) {
return profile == null || profile.getId() == null ? "" : profile.getId();
}
/**
* Extract optional project name from context.
*/
public static String projectName(final ProfileActivationContext context) {
final String missing = "<missing>";
final File basedir = context.getProjectDirectory();
if (basedir == null) {
return missing;
}
final File pomFile = new File(basedir, "pom.xml");
if (pomFile.exists()) {
final Model model = readMavenModel(pomFile);
final String artifactId = model.getArtifactId();
if (artifactId != null) {
return artifactId;
} else {
return missing;
}
} else {
return basedir.getName();
}
}
public static String settingsSecurityXml() {
final String homeDir = SystemUtils.systemUserHome();
return pathnameInUserHomeDotM2(homeDir, "settings-security.xml");
}
public static String toolchainsXml() {
final String homeDir = SystemUtils.systemUserHome();
return pathnameInUserHomeDotM2(homeDir, "toolchains.xml");
}
private static String pathnameInUserHomeDotM2(final String homeDir, final String filename) {
return Paths.get(homeDir, ".m2", filename).toString();
}
/**
* Fail-safe pom.xml model reader.
*/
private static Model readMavenModel(File pomFile) {
try (final FileInputStream fileInput = new FileInputStream(pomFile)) {
final InputStreamReader fileReader = new InputStreamReader(fileInput, StandardCharsets.UTF_8);
final MavenXpp3Reader pomReader = new MavenXpp3Reader();
return pomReader.read(fileReader);
} catch (final Exception ex) {
return new Model();
}
}
/**
* Extract profile property value.
*/
private static String propertyValue(final Profile profile) {
return profile.getActivation().getProperty().getValue();
}
private static final String ENV_MAVEN_CMD_LINE_ARGS = "env.MAVEN_CMD_LINE_ARGS";
public static Properties systemProperties(final Context context) {
return (Properties) context.getData().get("systemProperties");
}
public static Properties userProperties(final Context context) {
return (Properties) context.getData().get("userProperties");
}
}
| 35.038961
| 127
| 0.677724
|
91bde7c8a62beb5e4b647374e16e2f4b4899877d
| 4,204
|
package com.fr.swift.query.session;
import com.fr.swift.query.builder.QueryBuilder;
import com.fr.swift.query.cache.Cache;
import com.fr.swift.query.info.bean.query.QueryBeanFactory;
import com.fr.swift.query.query.QueryBean;
import com.fr.swift.query.result.SwiftResultSetUtils;
import com.fr.swift.query.session.exception.SessionClosedException;
import com.fr.swift.result.qrs.QueryResultSet;
import com.fr.swift.source.core.MD5Utils;
import com.fr.swift.util.Closable;
import com.fr.swift.util.IoUtil;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* @author yee
* @date 2018/7/17
*/
public class QuerySession implements Session {
private Map<Object, Cache<?>> cache;
private ReentrantReadWriteLock storeLock = new ReentrantReadWriteLock();
private String sessionId;
private boolean close;
private long cacheTimeout;
public QuerySession(long cacheTimeout) {
this.cacheTimeout = cacheTimeout;
cache = new ConcurrentHashMap<Object, Cache<?>>();
sessionId = MD5Utils.getMD5String(new String[]{UUID.randomUUID().toString(), String.valueOf(System.currentTimeMillis())});
}
@Override
public String getSessionId() {
return sessionId;
}
@Override
public QueryResultSet executeQuery(QueryBean queryInfo) throws Exception {
if (isClose()) {
throw new SessionClosedException(sessionId);
}
String queryId = queryInfo.getQueryId();
String jsonString = QueryBeanFactory.queryBean2String(queryInfo);
Cache<QueryResultSet> resultSetCache = (Cache<QueryResultSet>) cache.get(queryId);
if (null != resultSetCache && resultSetCache.get() != null && resultSetCache.get().hasNextPage()) {
resultSetCache.update();
return SwiftResultSetUtils.toSerializable(queryInfo.getQueryType(), resultSetCache.get());
}
QueryResultSet resultSet = query(jsonString);
// 缓存具有本地上下文状态的resultSet
Cache<QueryResultSet> cacheObj = new Cache<QueryResultSet>(resultSet);
cache.put(queryId, cacheObj);
// 取本地resultSet的一页,得到可序列化的resultSet
return SwiftResultSetUtils.toSerializable(queryInfo.getQueryType(), resultSet);
}
protected QueryResultSet query(String jsonString) throws Exception {
return QueryBuilder.buildQuery(jsonString).getQueryResult();
}
@Override
public void close() {
if (close) {
return;
}
close = true;
cleanCache(true);
}
@Override
public boolean isClose() {
return close;
}
@Override
public void cleanCache(boolean force) {
if (null != cache) {
Iterator<Map.Entry<Object, Cache<?>>> iterator = cache.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Object, Cache<?>> entry = iterator.next();
if (force || entry.getValue().getIdle() >= cacheTimeout) {
Object value = entry.getValue().get();
if (value instanceof Closable) {
IoUtil.close((Closable) value);
}
iterator.remove();
}
}
}
}
@Override
public void putObject(Object key, Object value) {
storeLock.writeLock().lock();
try {
cache.put(key, new Cache<Object>(value));
} finally {
storeLock.writeLock().unlock();
}
}
@Override
public Object getObject(Object key) {
storeLock.readLock().lock();
try {
Cache cache = this.cache.get(key);
if (cache != null) {
cache.update();
return cache.get();
}
} finally {
storeLock.readLock().unlock();
}
return null;
}
@Override
public void removeObject(Object key) {
storeLock.writeLock().lock();
try {
cache.remove(key);
} finally {
storeLock.writeLock().unlock();
}
}
}
| 31.609023
| 130
| 0.620599
|
71587282acba60450c1ded8e8021099995114ad3
| 926
|
package jokrey.utilities.morse.input.interpret.morse;
import jokrey.utilities.morse.input.Event;
/**
* Same as EventInterpreterMorse_MinMaxRatio_MinMaxFromEach, but use signal min max for pause calculation also.
* Can help when there are long pauses without input.
*/
public class EventInterpreterMorse_MinMaxRatio_SignalMinMaxForBoth extends EventInterpreterMorse_MinMaxRatio_MinMaxFromEach {
public EventInterpreterMorse_MinMaxRatio_SignalMinMaxForBoth() {
shortLongRatioToTriggerLetterPause = 0.6; //1 will be a word pause or something more insane.
shortLongRatioToTriggerWordPause = 3;
}
@Override protected void preCalculateRuntimeVariables(Event[] preprocessed_events) {
double[] sl_s = Event.getShortestAndLongestSignal(preprocessed_events);
shortest_signal=sl_s[0];
longest_signal=sl_s[1];
shortest_pause=sl_s[0];
longest_pause=sl_s[1];
}
}
| 42.090909
| 125
| 0.769978
|
a759955c64d8ad1bbe2c9c9cb0657a588e423d5d
| 3,682
|
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (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.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is Rhino code, released
* May 6, 1998.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
* provisions of the GPL are applicable instead of those above.
* If you wish to allow use of your version of this file only
* under the terms of the GPL and not to allow others to use your
* version of this file under the NPL, indicate your decision by
* deleting the provisions above and replace them with the notice
* and other provisions required by the GPL. If you do not delete
* the provisions above, a recipient may use your version of this
* file under either the NPL or the GPL.
*/
import org.mozilla.javascript.*;
/**
* Example of controlling the JavaScript execution engine.
*
* We evaluate a script and then manipulate the result.
*
*/
public class Control {
/**
* Main entry point.
*
* Process arguments as would a normal Java program. Also
* create a new Context and associate it with the current thread.
* Then set up the execution environment and begin to
* execute scripts.
*/
public static void main(String[] args)
{
Context cx = Context.enter();
try {
// Set version to JavaScript1.2 so that we get object-literal style
// printing instead of "[object Object]"
cx.setLanguageVersion(Context.VERSION_1_2);
// Initialize the standard objects (Object, Function, etc.)
// This must be done before scripts can be executed.
Scriptable scope = cx.initStandardObjects();
// Now we can evaluate a script. Let's create a new object
// using the object literal notation.
Object result = cx.evaluateString(scope, "obj = {a:1, b:['x','y']}",
"MySource", 1, null);
Scriptable obj = (Scriptable) scope.get("obj", scope);
// Should print "obj == result" (Since the result of an assignment
// expression is the value that was assigned)
System.out.println("obj " + (obj == result ? "==" : "!=") +
" result");
// Should print "obj.a == 1"
System.out.println("obj.a == " + obj.get("a", obj));
Scriptable b = (Scriptable) obj.get("b", obj);
// Should print "obj.b[0] == x"
System.out.println("obj.b[0] == " + b.get(0, b));
// Should print "obj.b[1] == y"
System.out.println("obj.b[1] == " + b.get(1, b));
// Should print {a:1, b:["x", "y"]}
Function fn = (Function) ScriptableObject.getProperty(obj, "toString");
System.out.println(fn.call(cx, scope, obj, new Object[0]));
} finally {
Context.exit();
}
}
}
| 37.571429
| 83
| 0.619772
|
4687f04345bb74c4f945ce16a2a7650c3a08beb6
| 574
|
package com.cyl.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class MyControllerDemo{
@RequestMapping("/hello")
public ModelAndView helloWorld(HttpServletRequest arg0,
HttpServletResponse arg1) throws Exception {
String str="Hello Caiyunlong!";
return new ModelAndView("hello","message",str);
}
}
| 28.7
| 63
| 0.789199
|
a5448f5a4eb3035e29f79ed6e48264cca63b9648
| 1,131
|
package pl.solutions.software.sokolik.bartosz.category.domain;
import lombok.*;
import org.hibernate.envers.AuditTable;
import org.hibernate.envers.Audited;
import org.hibernate.envers.NotAudited;
import pl.solutions.software.sokolik.bartosz.domain.AuditedEntity;
import pl.solutions.software.sokolik.bartosz.movie.domain.Movie;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Data
@Builder
@Audited
@Entity
@Table(name = "categories")
@AuditTable(value = "categories_aud")
@EqualsAndHashCode(callSuper = true, onlyExplicitlyIncluded = true)
@AllArgsConstructor
@NoArgsConstructor
public class Category extends AuditedEntity {
@Id
@SequenceGenerator(name = "category_seq_gen", sequenceName = "category_id_seq", allocationSize = 1, initialValue = 100)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "category_seq_gen")
private Long id;
@Column(name = "name")
private String name;
@NotAudited
@ManyToMany(mappedBy = "categories")
private Set<Movie> movies = new HashSet<>();
public Category(String name) {
this.name = name;
}
}
| 27.585366
| 123
| 0.755084
|
d3ae7bfb4892555cb210c5fbf230037e410bebe0
| 514
|
package wrl.screens;
import wrl.Creature;
import wrl.Item;
/**
* This class extends {@linkplain InventoryBasedScreen}. It allows the player to eat edible items in their inventory.
*
*/
public class EatScreen extends InventoryBasedScreen {
public EatScreen(Creature player) {
super(player);
}
protected String getVerb() {
return "eat";
}
protected boolean isAcceptable(Item item) {
return item.foodValue() != 0;
}
protected Screen use(Item item) {
player.eat(item);
return null;
}
}
| 17.133333
| 117
| 0.708171
|
14b4c766d925b9f42e7154dd5828eab925562bcf
| 1,592
|
package com.zabbix4j.graphprototype;
import com.zabbix4j.ZabbixApiException;
import com.zabbix4j.ZabbixApiTestBase;
import com.zabbix4j.graph.GraphItem;
import org.hamcrest.core.Is;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by Suguru Yajima on 2014/06/02.
*/
public class GraphPrototypeDeleteTest extends ZabbixApiTestBase {
public GraphPrototypeDeleteTest() {
super();
}
@Test
public void testDelete1() throws Exception {
Integer targetId = createDummy();
GraphPrototypeDeleteRequest request = new GraphPrototypeDeleteRequest();
request.addParam(targetId);
GraphPrototypeDeleteResponse response = zabbixApi.graphPrototype().delete(request);
assertNotNull(response);
Integer actualId = response.getResult().getGraphids().get(0);
assertThat(targetId, Is.is(actualId));
}
private Integer createDummy() throws ZabbixApiException {
GraphPrototypeCreateRequest request = new GraphPrototypeCreateRequest();
GraphPrototypeCreateRequest.Params params = request.getParams();
params.setName("Graphprototype delete test");
GraphItem gitem = new GraphItem();
gitem.setColor("00AA00");
gitem.setItemid(23730);
params.addGraphItem(gitem);
params.setHeight(140);
params.setWidth(800);
GraphPrototypeCreateResponse response =zabbixApi.graphPrototype().create(request);
assertNotNull(response);
Integer id = response.getResult().getGraphids().get(0);
return id;
}
}
| 28.945455
| 91
| 0.701005
|
8e47baf6551ca109dca9c18d16e568edcc3ddb87
| 1,159
|
package org.ednovo.gooru.core.api.model;
import javax.persistence.Column;
import javax.persistence.Entity;
@Entity(name="organization")
public class Organization extends Party {
/**
*
*/
private static final long serialVersionUID = -2903580370776228049L;
@Column
private String organizationCode;
private StorageArea s3StorageArea;
private StorageArea nfsStorageArea;
private Organization parentOrganization;
public String getOrganizationCode() {
return organizationCode;
}
public void setOrganizationCode(String organizationCode) {
this.organizationCode = organizationCode;
}
public StorageArea getS3StorageArea() {
return s3StorageArea;
}
public void setS3StorageArea(StorageArea s3StorageArea) {
this.s3StorageArea = s3StorageArea;
}
public StorageArea getNfsStorageArea() {
return nfsStorageArea;
}
public void setNfsStorageArea(StorageArea nfsStorageArea) {
this.nfsStorageArea = nfsStorageArea;
}
public void setParentOrganization(Organization parentOrganization) {
this.parentOrganization = parentOrganization;
}
public Organization getParentOrganization() {
return parentOrganization;
}
}
| 20.333333
| 69
| 0.787748
|
20eecb0db4182b633955adff4e278c615bb069ed
| 569
|
package diaceutics.cucumber.stepdefinitions;
import diaceutics.selenium.pageobject.pages.CollaborationsPage;
import io.cucumber.java.en.Then;
import org.testng.Assert;
public class CollaborationsPageSteps {
private final CollaborationsPage collaborationsPage;
public CollaborationsPageSteps() {
collaborationsPage = new CollaborationsPage();
}
@Then("Collaborations page is opened")
public void collaborationsPageIsOpened() {
Assert.assertTrue(collaborationsPage.isDisplayed(), "Collaborations page should be opened");
}
}
| 27.095238
| 100
| 0.768014
|
d173b3a9b41b02a0da21b99f5cdeadf0f76dea36
| 1,569
|
package com.kingyzll.tablayoutdemo;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.kingyzll.tablayoutdemo.Adapter.MainAdapter;
import java.util.ArrayList;
import java.util.List;
public class MainFragment extends Fragment {
private View view;
private TabLayout tabLayout;
private ViewPager viewPager;
private String[] title={"kingyz","ll"};
private List<Fragment> fragments;
private MainAdapter adapter;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_main,container,false);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
tabLayout = view.findViewById(R.id.main_tab_layout);
viewPager = view.findViewById(R.id.main_view_pager);
fragments = new ArrayList<>();
fragments.add(new FragmentMainPage1());
fragments.add(new FragmentMainPage2());
adapter = new MainAdapter(getChildFragmentManager(),fragments,title);
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
}
}
| 31.38
| 132
| 0.746335
|
ac63c81b803d662a34a4189a4dbd178fcde48962
| 3,924
|
/*
* Copyright (C) 2006-2011 by Olivier Chafik (http://ochafik.com)
*
* 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.ochafik.swing.ui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Paint;
import javax.swing.JComponent;
import javax.swing.JProgressBar;
import javax.swing.plaf.ProgressBarUI;
import com.ochafik.util.listenable.Pair;
public class SimplisticProgressBarUI extends ProgressBarUI {
Dimension preferredSize;
static boolean useGradients;
static {
useGradients = System.getProperty("ochafik.swing.ui.useGradients", "true").equals("true");
};
public SimplisticProgressBarUI(Dimension preferredSize) {
this.preferredSize = preferredSize;
}
@Override
public Dimension getPreferredSize(JComponent c) {
Insets in = c.getInsets();
return new Dimension(preferredSize.width + in.left + in.right, preferredSize.height + in.top + in.bottom);
}
@Override
public void installUI(JComponent c) {
c.setOpaque(false);
}
static Color brighter(Color color) {
float[] hsb = Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null);
float deltaS = 0 , deltaB = 0.1f;//05f;
return Color.getHSBColor(hsb[0], hsb[1]-deltaS, hsb[2]+deltaB);
}
static Pair<Color,Color> darkerBrighter(Color color) {
float[] hsb = Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null);
float deltaS = 0 , deltaB = 0.1f;//05f;
return new Pair<Color,Color>(Color.getHSBColor(hsb[0], hsb[1]+deltaS, hsb[2]-deltaB),Color.getHSBColor(hsb[0], hsb[1]-deltaS, hsb[2]+deltaB));
}
GradientPaint cachedPaint;
Color cachedBaseColor;
int cachedBarWidth;
@Override
public void paint(Graphics g, JComponent c) {
Graphics2D g2d = (Graphics2D)g;
JProgressBar bar = (JProgressBar)c;
Dimension size = bar.getSize();
Insets in = bar.getInsets();
double p = bar.getPercentComplete();
Color color = bar.getForeground();
int x = in.left, y = in.top, w = size.width - in.left - in.right, h = size.height - in.top - in.bottom;
int barWidth = p < 0.5 ? (int)Math.ceil((w-2) * p) : (int)((w-2) * p);
Paint oldPaint = null;
if (useGradients) {
GradientPaint paint = cachedPaint;
if (cachedBaseColor == null || !cachedBaseColor.equals(color) || cachedBarWidth != barWidth) {
Pair<Color,Color> darkerBrighter = darkerBrighter(cachedBaseColor = color);
cachedBarWidth = barWidth;
paint = cachedPaint = new GradientPaint(x+1,y, darkerBrighter.getSecond(), x+barWidth, y, darkerBrighter.getFirst());
}
oldPaint = g2d.getPaint();
g2d.setPaint(paint);
} else {
g2d.setColor(color);
}
g2d.fillRect(x+1, y, barWidth+1, h);
if (useGradients) {
g2d.setPaint(oldPaint);
g2d.setColor(color);
}
g2d.setColor(color);
g2d.drawRect(x, y, w, h);
}
}
| 34.421053
| 144
| 0.720693
|
18f50ac84cbae97b626b89c278750a264cc3ba71
| 2,551
|
/*
Copyright 2017-2019 VMware, Inc.
SPDX-License-Identifier: BSD-2-Clause
*/
/**
*
*
* @author Hal
*/
package com.vmware.weathervane.auction.service;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vmware.weathervane.auction.data.model.AttendanceRecord;
import com.vmware.weathervane.auction.data.repository.event.AttendanceRecordRepository;
import com.vmware.weathervane.auction.rest.representation.AttendanceRecordRepresentation;
import com.vmware.weathervane.auction.rest.representation.CollectionRepresentation;
import com.vmware.weathervane.auction.service.liveAuction.LiveAuctionServiceConstants;
/**
* @author Hal
*
*/
public class AttendanceServiceImpl implements AttendanceService {
private static final Logger logger = LoggerFactory.getLogger(AttendanceServiceImpl.class);
@Inject
AttendanceRecordRepository attendanceRecordRepository;
public AttendanceServiceImpl() {
}
@Override
public CollectionRepresentation<AttendanceRecordRepresentation> getAttendanceRecordsForUser(long userId,
Date fromDate, Date toDate, Integer page, Integer pageSize) {
Integer realPage = LiveAuctionServiceConstants.getCollectionPage(page);
Integer realPageSize = LiveAuctionServiceConstants
.getCollectionPageSize(pageSize);
logger.info("AttendanceServiceImpl::getAttendanceRecordsForUser page = " + realPage + ", pageSize = "
+ realPageSize);
List<AttendanceRecord> queryResults = null;
if (fromDate == null)
if (toDate == null)
queryResults = attendanceRecordRepository.findByUserId(userId);
else
queryResults = attendanceRecordRepository.findByUserIdAndTimestampLessThanEqual(userId, toDate);
else
if (toDate == null)
queryResults = attendanceRecordRepository.findByUserIdAndTimestampGreaterThanEqual(userId, fromDate);
else
queryResults = attendanceRecordRepository.findByUserIdAndTimestampBetween(userId, fromDate, toDate);
List<AttendanceRecordRepresentation> liveAttendanceRecords =
queryResults.stream().limit(realPageSize)
.map(r -> new AttendanceRecordRepresentation(r)).collect(Collectors.toList());
CollectionRepresentation<AttendanceRecordRepresentation> colRep = new CollectionRepresentation<AttendanceRecordRepresentation>();
colRep.setPage(realPage);
colRep.setPageSize(realPageSize);
colRep.setTotalRecords(realPageSize.longValue());
colRep.setResults(liveAttendanceRecords);
return colRep;
}
}
| 32.291139
| 131
| 0.801254
|
36ed92f9c8565ae5adec90a474059a26e0264915
| 5,230
|
/*
* Copyright (c) 2015 Andrew Coates
*
* 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.datalorax.populace.core.populate.instance;
import com.google.common.testing.EqualsTester;
import com.google.common.testing.NullPointerTester;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.mockito.Mockito.*;
public class DefaultTypeInstanceFactoryTest {
private final Class<List> baseType = List.class;
private final Class<ArrayList> defaultType = ArrayList.class;
private InstanceFactory concreteFactory;
private InstanceFactories instanceFactories;
private DefaultTypeInstanceFactory factory;
private Object parent;
@BeforeMethod
public void setUp() throws Exception {
concreteFactory = mock(InstanceFactory.class);
parent = mock(Object.class);
instanceFactories = mock(InstanceFactories.class);
factory = new DefaultTypeInstanceFactory(baseType, defaultType, concreteFactory);
}
@Test
public void shouldReturnNullIfRequestedTypeNotSubtypeOfDefaultType() throws Exception {
// When:
final String instance = factory.createInstance(String.class, null, null);
// Then:
assertThat(instance, is(nullValue()));
}
@Test
public void shouldReturnNullIfDefaultTypeNotCompatibleWithRequestedType() throws Exception {
// Given:
final ArrayList expected = mock(ArrayList.class);
when(concreteFactory.createInstance(ArrayList.class, parent, instanceFactories)).thenReturn(expected);
// When:
final List instance = factory.createInstance(AbstractSequentialList.class, parent, instanceFactories);
// Then:
assertThat(instance, is(nullValue()));
}
@Test
public void shouldDelegateToConcreteFactoryForConcreteTypes() throws Exception {
// When:
factory.createInstance(Vector.class, parent, instanceFactories);
// Then:
verify(concreteFactory).createInstance(Vector.class, parent, instanceFactories);
}
@Test
public void shouldUseConcreteFactoryToCreateDefaultType() throws Exception {
// When:
factory.createInstance(List.class, parent, instanceFactories);
// Then:
verify(concreteFactory).createInstance(defaultType, parent, instanceFactories);
}
@Test
public void shouldReturnInstanceFromConcreteFactoryForConcreteTypes() throws Exception {
// Given:
final Vector expected = mock(Vector.class);
when(concreteFactory.createInstance(Vector.class, parent, instanceFactories)).thenReturn(expected);
// When:
final Vector instance = factory.createInstance(Vector.class, parent, instanceFactories);
// Then:
assertThat(instance, is(expected));
}
@Test
public void shouldReturnInstanceFromConcreteFactoryForNonConcreteTypes() throws Exception {
// Given:
final ArrayList expected = mock(ArrayList.class);
when(concreteFactory.createInstance(ArrayList.class, parent, instanceFactories)).thenReturn(expected);
// When:
final List instance = factory.createInstance(List.class, parent, instanceFactories);
// Then:
assertThat(instance, is(expected));
}
@Test
public void shouldTestEqualsAndHashCode() throws Exception {
final Class<Map> baseType = Map.class;
final Class<HashMap> defaultType = HashMap.class;
final InstanceFactory concreteFactory = mock(InstanceFactory.class, "1");
final InstanceFactory concreteFactory2 = mock(InstanceFactory.class, "2");
new EqualsTester()
.addEqualityGroup(
new DefaultTypeInstanceFactory(baseType, defaultType, concreteFactory),
new DefaultTypeInstanceFactory(baseType, defaultType, concreteFactory))
.addEqualityGroup(
new DefaultTypeInstanceFactory(HashMap.class, defaultType, concreteFactory))
.addEqualityGroup(
new DefaultTypeInstanceFactory(baseType, TreeMap.class, concreteFactory))
.addEqualityGroup(
new DefaultTypeInstanceFactory(baseType, defaultType, concreteFactory2))
.testEquals();
}
@Test
public void shouldThrowNPEsOnConstructorParams() throws Exception {
new NullPointerTester()
.setDefault(InstanceFactory.class, mock(InstanceFactory.class))
.testAllPublicConstructors(DefaultTypeInstanceFactory.class);
}
}
| 37.357143
| 110
| 0.710134
|
1af2a633b1922c46db2e5f3ccca10f8dbf166553
| 2,443
|
/**
* Copyright (C) 2014 OpenTravel Alliance (info@opentravel.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opentravel.schemacompiler.codegen.impl;
import org.opentravel.schemacompiler.codegen.util.XsdCodegenUtils;
import org.opentravel.schemacompiler.transform.util.BaseTransformer;
/**
* Base class for all <code>ObjectTransformer</code> implementations that are part of the code generation subsystem.
*
* @param <S> the source type of the object transformation
* @param <T> the target type of the object transformation
* @author S. Livezey
*/
public abstract class AbstractCodegenTransformer<S, T> extends BaseTransformer<S,T,CodeGenerationTransformerContext> {
/**
* Returns the sub-folder location (relative to the target output folder) where built-in schemas should be stored
* during the code generation process. If no sub-folder location is specified by the code generation context, this
* method will return an empty string, indicating that built-ins schemas should be saved in the same target output
* folder as the user-defined library/service output.
*
* @return String
*/
protected String getBuiltInSchemaOutputLocation() {
return XsdCodegenUtils.getBuiltInSchemaOutputLocation( context.getCodegenContext() );
}
/**
* Returns the sub-folder location (relative to the target output folder) where legacy schemas should be stored
* during the code generation process. If no sub-folder location is specified by the code generation context, this
* method will return an empty string, indicating that legacy schemas should be saved in the same target output
* folder as the user-defined library/service output.
*
* @return String
*/
protected String getLegacySchemaOutputLocation() {
return XsdCodegenUtils.getLegacySchemaOutputLocation( context.getCodegenContext() );
}
}
| 43.625
| 118
| 0.745804
|
009b97b7d6c86ee6fc9ac0dfda20926c465b42e4
| 2,436
|
/**
*
*/
package dev.projects.math.kernel.function;
import dev.projects.math.kernel.base.DenseVector;
import dev.projects.utils.exception.LoggableException;
/**
* @author vyn
*
*/
public abstract class AbstractScalarDifferentiableFunction extends AbstractScalarFunction
{
private boolean isGradientCacheActual = false;
private long gradientComputeCount = 0;
private DenseVector cachedGrad;
protected AbstractScalarDifferentiableFunction(int variablesCount) throws LoggableException {
super(variablesCount);
cachedGrad = DenseVector.getInstance(variablesCount);
}
protected AbstractScalarDifferentiableFunction(DenseVector variables) throws LoggableException {
this(variables.getSize());
setVariables(variables);
}
public long getGradientComputeCount()
{
return gradientComputeCount;
}
@Override
public void reset() throws LoggableException {
super.reset();
gradientComputeCount = 0;
setVariables(DenseVector.getRandomizedVector(getVariablesCount(), 1.0));
}
public void setVariables(DenseVector variables) throws LoggableException {
super.setVariables(variables);
deactivateGradientCache();
}
public DenseVector getCachedGradient() {
return cachedGrad.deepCopy();
}
public DenseVector computeGradient(DenseVector variables) throws LoggableException
{
setVariables(variables);
return computeGradient();
}
public DenseVector computeGradient() throws LoggableException
{
DenseVector grad= getCachedGradient();
if (!isGradientCacheActual)
{
grad= actualComputeGradient();
incGradComputeCount();
setGradientCache(grad);
activateGradCache();
}
return grad;
}
protected abstract DenseVector actualComputeGradient() throws LoggableException;
protected void activateGradCache()
{
isGradientCacheActual = true;
}
protected void deactivateGradientCache() {
isGradientCacheActual = false;
}
private void incGradComputeCount()
{
gradientComputeCount++;
}
private void setGradientCache(DenseVector cachedGrad)
{
this.cachedGrad = cachedGrad.deepCopy();
}
}
| 24.36
| 101
| 0.658456
|
76c04cfa492575500a52e1970e9b308db3ac5d7c
| 1,278
|
package com.github.volodya_lombrozo.conventional_commit_linter.git;
import com.github.volodya_lombrozo.conventional_commit_linter.commit.FakeCommit;
import org.junit.Test;
import static org.junit.Assert.*;
public class GitCommitTest {
@Test
public void message() {
final String message = "message";
final GitCommit commit = new GitCommit(message);
final String actual = commit.message();
assertEquals(message, actual);
}
@Test
public void testToString() {
final GitCommit commit = new GitCommit("message");
final String actual = commit.toString();
assertEquals("GitCommit[message='message']", actual);
}
@Test
public void testEquals() {
final GitCommit commit = new GitCommit("f");
assertEquals(commit, commit);
assertNotEquals(new GitCommit("m"), null);
assertEquals(new GitCommit("m"), new GitCommit("m"));
assertNotEquals(new GitCommit("m1"), new GitCommit("m2"));
}
@Test
public void testHashCode() {
final GitCommit first = new GitCommit("m1");
final GitCommit second = new GitCommit("m2");
assertNotEquals(0, first.hashCode());
assertNotEquals(first.hashCode(), second.hashCode());
}
}
| 28.4
| 80
| 0.65493
|
962a0767d49584ddf6edc4b36bd058e1ccd8d68f
| 197
|
package io.whileaway.forgetcmd.util;
import lombok.Data;
@Data
public class Result<A> {
private Integer status;
private String message;
private A data;
private String redirect;
}
| 16.416667
| 36
| 0.720812
|
fe2837f7ca1ddd6ef9960090abc228e1a9f6cc3b
| 2,846
|
package de.micromata.merlin.excel;
import de.micromata.merlin.Definitions;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
class ExcelChecksumTest {
private Logger log = LoggerFactory.getLogger(ExcelChecksumTest.class);
@Test
void xssfChecksumTest() throws FileNotFoundException, IOException {
Workbook poiWorkbook = new XSSFWorkbook();
ExcelWorkbook workbook = new ExcelWorkbook(poiWorkbook);
createAndCheck(workbook);
}
@Test
void hssfChecksumTest() throws FileNotFoundException, IOException {
Workbook poiWorkbook = new HSSFWorkbook();
ExcelWorkbook workbook = new ExcelWorkbook(poiWorkbook);
createAndCheck(workbook);
}
private void createAndCheck(ExcelWorkbook workbook) throws IOException {
ExcelSheet sheet = workbook.createOrGetSheet("Sheet 1");
ExcelRow row = sheet.createRow();
row.createCells("cell 1", "cell 2");
long checksum = ExcelChecksum.buildChecksum(workbook.getPOIWorkbook());
assertEquals(-1, ExcelChecksum.readChecksum(workbook.getPOIWorkbook()));
ExcelChecksum.writeChecksum(workbook.getPOIWorkbook(), checksum);
assertEquals(checksum, ExcelChecksum.readChecksum(workbook.getPOIWorkbook()));
String fileSuffix = workbook.getPOIWorkbook() instanceof XSSFWorkbook ? "xlsx" : "xls";
File file = new File(Definitions.OUTPUT_DIR, "Checksum." + fileSuffix);
log.info("Writing checksum Excel file: " + file.getAbsolutePath());
workbook.getPOIWorkbook().write(new FileOutputStream(file));
workbook = new ExcelWorkbook(file);
assertEquals(checksum, ExcelChecksum.readChecksum(workbook.getPOIWorkbook()));
workbook.createOrGetSheet("Sheet 2");
long newChecksum = ExcelChecksum.buildChecksum(workbook.getPOIWorkbook());
assertNotEquals(checksum, newChecksum);
checksum = newChecksum;
Cell cell = workbook.getSheet("Sheet 1").getRow(0).getRow().getCell(0);
cell.setCellValue("New value");
assertNotEquals(checksum, newChecksum = ExcelChecksum.buildChecksum(workbook.getPOIWorkbook()));
checksum = newChecksum;
workbook.createOrGetSheet("Sheet 2").createRow().createCells("test");
assertNotEquals(checksum, newChecksum = ExcelChecksum.buildChecksum(workbook.getPOIWorkbook()));
}
}
| 43.784615
| 104
| 0.734013
|
9ff93c8642111dac8beace2355ae5eb92cd482fa
| 3,464
|
package org.csi.rastreamento.correios.manager;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.csi.rastreamento.correios.entidade.Evento;
import org.csi.rastreamento.correios.util.Constantes;
public class DhlRastreio implements Rastreio {
@Override
public List<Evento> obterEventos(String codigoObjeto, String user, String password, String wsdl) {
List<Evento> eventos = new ArrayList<Evento>();
try {
eventos = obterEventosWsdl(codigoObjeto, user, password, wsdl);
} catch (Exception e) {
e.printStackTrace();
}
return eventos;
}
public static void main(String[] args) {
new DhlRastreio().obterEventos("6481267225", "v62_UBLbvmydcY", "Zvnk7OzOcy", "https://xmlpitest-ea.dhl.com/XMLShippingServlet?isUTF8Support=true");
}
private List<Evento> obterEventosWsdl(String codigo, String user, String password, String wsdl) throws Exception {
String clientRequestXML = Constantes.XML_DHL.replace("{SITEID}", user).replace("{PASSWORD}", password).replace("{AWBNUMBER}", codigo);
boolean useUtf8 = wsdl.contains("isUTF8Support");
URL servletURL = new URL(wsdl);
HttpURLConnection conn = null;
conn = (HttpURLConnection) servletURL.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
if(useUtf8) {
conn.setRequestProperty("Accept-Charset", "UTF-8");
}
String len = Integer.toString(clientRequestXML.getBytes().length);
conn.setRequestProperty("Content-Length", len);
conn.setRequestProperty("futureDate", "false");
conn.connect();
OutputStreamWriter wr = null;
if(useUtf8) {
wr = new OutputStreamWriter(conn.getOutputStream(), "UTF8");
} else {
wr = new OutputStreamWriter(conn.getOutputStream());
}
wr.write(clientRequestXML);
wr.flush();
wr.close();
InputStreamReader isr = null;
if(useUtf8) {
isr = new InputStreamReader(conn.getInputStream(),"UTF8");
} else {
isr = new InputStreamReader(conn.getInputStream());
}
BufferedReader rd = new BufferedReader(isr);
StringBuilder result = new StringBuilder();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line).append("\n");
}
List<Evento> events = new ArrayList<>();
Pattern pattern = Pattern.compile("<ShipmentEvent>(.*?)<\\/ShipmentEvent>");
Matcher matcher = pattern.matcher(result.toString().replace("\n", ""));
Pattern patternDescription = Pattern.compile("(<Description>)(.*?)(<\\/Description>)");
while(matcher.find()) {
String description = "";
String title = "";
String eventStr = matcher.group();
Matcher matcherDescription = patternDescription.matcher(eventStr);
if(matcherDescription.find()) {
description = matcherDescription.group(2).replaceAll("\\s+", " ");
matcherDescription.find();
title = matcherDescription.group(2);
}
events.add(new Evento(title, description));
}
rd.close();
isr.close();
return events;
}
@Override
public String getTokenUsuario() {
return "DHL_USUARIO";
}
@Override
public String getTokenSenha() {
return "DHL_SENHA";
}
@Override
public String getTokenWsdl() {
return "DHL_WSDL";
}
}
| 30.385965
| 149
| 0.71709
|
2ba0bcbf1af17b4809f3873e152875f5fac94692
| 10,744
|
/*
* Copyright (C) 2014-2018 D3X Systems - All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.d3x.morpheus.reference.algebra;
import java.util.Optional;
import java.util.function.Function;
import com.d3x.morpheus.array.Array;
import com.d3x.morpheus.frame.DataFrame;
import com.d3x.morpheus.frame.DataFrameException;
import com.d3x.morpheus.jama.CholeskyDecomposition;
import com.d3x.morpheus.jama.EigenDecomposition;
import com.d3x.morpheus.jama.LUDecomposition;
import com.d3x.morpheus.jama.Matrix;
import com.d3x.morpheus.jama.QRDecomposition;
import com.d3x.morpheus.jama.SingularValueDecomposition;
import com.d3x.morpheus.range.Range;
import com.d3x.morpheus.util.LazyValue;
/**
* An implementation of the DataFrameAlgebra interface that uses JAMA
*
* @param <R> the row key type
* @param <C> the column key type
*
* <p><strong>This is open source software released under the <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2.0 License</a></strong></p>
*
* @see <a href="http://math.nist.gov/javanumerics/jama/">JAMA</a>
* @author Xavier Witdouck
*/
class XDataFrameAlgebraJama<R,C> extends XDataFrameAlgebra<R,C> {
/**
* Constructor
* @param frame the frame reference
*/
XDataFrameAlgebraJama(DataFrame<R,C> frame) {
super(frame);
}
@Override
public Decomposition decomp() {
return new Decomp(frame());
}
@Override
public DataFrame<Integer,Integer> inverse() throws DataFrameException {
try {
final Matrix matrix = toMatrix(frame());
final Matrix inverse = matrix.inverse();
return toDataFrame(inverse);
} catch (Exception ex) {
throw new DataFrameException("Failed to compute inverse of DataFrame", ex);
}
}
@Override
public DataFrame<Integer,Integer> solve(DataFrame<?,?> rhs) throws DataFrameException {
try {
final Matrix b = toMatrix(rhs);
final Matrix a = toMatrix(frame());
final Matrix x = a.solve(b);
return toDataFrame(x);
} catch (Exception ex) {
throw new DataFrameException("Failed to solve AX=B for frames", ex);
}
}
/**
* Returns a Morpheus DataFrame representation of a JAMA matrix
* @param matrix the JAMA matrix
* @return the Morpheus DataFrame
*/
private DataFrame<Integer,Integer> toDataFrame(Matrix matrix) {
final Range<Integer> rowKeys = Range.of(0, matrix.getRowDimension());
final Range<Integer> colKeys = Range.of(0, matrix.getColumnDimension());
return DataFrame.ofDoubles(rowKeys, colKeys, v -> {
final int i = v.rowOrdinal();
final int j = v.colOrdinal();
return matrix.get(i, j);
});
}
/**
* Returns a JAMA matrix representation of the Morpheus DataFrame
* @param frame the DataFrame reference
* @return the JAMA matrix
*/
private Matrix toMatrix(DataFrame<?,?> frame) {
final Matrix matrix = new Matrix(frame.rowCount(), frame.colCount());
frame.forEachValue(v -> {
final int i = v.rowOrdinal();
final int j = v.colOrdinal();
final double value = v.getDouble();
matrix.set(i, j, value);
});
return matrix;
}
/**
* The Decomposition implementation for Apache Library
*/
private class Decomp implements Decomposition {
private DataFrame<?,?> frame;
/**
* Constructor
* @param frame the frame reference
*/
Decomp(DataFrame<?,?> frame) {
this.frame = frame;
}
@Override
public <T> Optional<T> lud(Function<LUD, Optional<T>> handler) {
return handler.apply(new XLUD(toMatrix(frame)));
}
@Override
public <T> Optional<T> qrd(Function<QRD, Optional<T>> handler) {
return handler.apply(new XQRD(toMatrix(frame)));
}
@Override
public <T> Optional<T> evd(Function<EVD, Optional<T>> handler) {
return handler.apply(new XEVD(toMatrix(frame)));
}
@Override
public <T> Optional<T> svd(Function<SVD, Optional<T>> handler) {
return handler.apply(new XSVD(toMatrix(frame)));
}
@Override
public <T> Optional<T> cd(Function<CD, Optional<T>> handler) {
return handler.apply(new XCD(toMatrix(frame)));
}
}
/**
* An implementation of LU Decomposition using the Apache Library
*/
private class XLUD implements LUD {
private LUDecomposition lud;
private LazyValue<DataFrame<Integer,Integer>> l;
private LazyValue<DataFrame<Integer,Integer>> u;
private LazyValue<DataFrame<Integer,Integer>> p;
/**
* Constructor
* @param matrix the matrix to decompose
*/
private XLUD(Matrix matrix) {
this.lud = new LUDecomposition(matrix);
this.l = LazyValue.of(() -> toDataFrame(lud.getL()));
this.u = LazyValue.of(() -> toDataFrame(lud.getU()));
this.p = LazyValue.of(() -> toDataFrame(null));
}
@Override
public double det() {
return lud.det();
}
@Override
public boolean isNonSingular() {
return lud.isNonsingular();
}
@Override
public DataFrame<Integer,Integer> getL() {
return l.get();
}
@Override
public DataFrame<Integer,Integer> getU() {
return u.get();
}
@Override
public DataFrame<Integer,Integer> getP() {
return p.get();
}
@Override
public DataFrame<Integer,Integer> solve(DataFrame<?,?> rhs) {
final Matrix b = toMatrix(rhs);
final Matrix result = lud.solve(b);
return toDataFrame(result);
}
}
/**
* An implementation of an QR Decomposition using the Apache Library
*/
private class XQRD implements QRD {
private QRDecomposition qrd;
private LazyValue<DataFrame<Integer,Integer>> q;
private LazyValue<DataFrame<Integer,Integer>> r;
/**
* Constructor
* @param matrix the input matrix
*/
XQRD(Matrix matrix) {
this.qrd = new QRDecomposition(matrix);
this.q = LazyValue.of(() -> toDataFrame(qrd.getQ()));
this.r = LazyValue.of(() -> toDataFrame(qrd.getR()));
}
@Override
public DataFrame<Integer,Integer> getR() {
return r.get();
}
@Override
public DataFrame<Integer,Integer> getQ() {
return q.get();
}
@Override
public DataFrame<Integer,Integer> solve(DataFrame<?,?> rhs) {
final Matrix b = toMatrix(rhs);
final Matrix result = qrd.solve(b);
return toDataFrame(result);
}
}
/**
* An implementation of an Eigenvalue Decomposition using the Apache Library
*/
private class XEVD implements EVD {
private Array<Double> eigenValues;
private DataFrame<Integer,Integer> d;
private DataFrame<Integer,Integer> v;
/**
* Constructor
* @param matrix the input matrix
*/
XEVD(Matrix matrix) {
final EigenDecomposition evd = new EigenDecomposition(matrix);
this.d = toDataFrame(evd.getD());
this.v = toDataFrame(evd.getV());
this.eigenValues = Array.of(evd.getRealEigenvalues());
}
@Override
public Array<Double> getEigenvalues() {
return eigenValues;
}
@Override
public DataFrame<Integer,Integer> getD() {
return d;
}
@Override
public DataFrame<Integer,Integer> getV() {
return v;
}
}
/**
* An implementation of Singular Value Decomposition using the Apache Library
*/
private class XSVD implements SVD {
private int rank;
private Array<Double> singularValues;
private DataFrame<Integer,Integer> u;
private DataFrame<Integer,Integer> v;
private DataFrame<Integer,Integer> s;
/**
* Constructor
* @param x the input matrix
*/
XSVD(Matrix x) {
final SingularValueDecomposition svd = new SingularValueDecomposition(x);
this.rank = svd.rank();
this.u = toDataFrame(svd.getU());
this.v = toDataFrame(svd.getV());
this.s = toDataFrame(svd.getS());
this.singularValues = Array.of(svd.getSingularValues());
}
@Override
public final int rank() {
return rank;
}
@Override
public final DataFrame<Integer,Integer> getU() {
return u;
}
@Override
public final DataFrame<Integer,Integer> getV() {
return v;
}
@Override
public final DataFrame<Integer,Integer> getS() {
return s;
}
@Override
public final Array<Double> getSingularValues() {
return singularValues;
}
}
/**
* An implementation of Cholesky Decomposition using the Apache Library
*/
private class XCD implements CD {
private CholeskyDecomposition cd;
private LazyValue<DataFrame<Integer,Integer>> l;
/**
* Constructor
* @param matrix the input matrix
*/
XCD(Matrix matrix) {
this.cd = new CholeskyDecomposition(matrix);
this.l = LazyValue.of(() -> toDataFrame(cd.getL()));
}
@Override
public DataFrame<Integer,Integer> getL() {
return l.get();
}
@Override
public DataFrame<Integer,Integer> solve(DataFrame<?,?> rhs) {
final Matrix b = toMatrix(rhs);
final Matrix result = cd.solve(b);
return toDataFrame(result);
}
}
}
| 29.037838
| 150
| 0.583675
|
b29e99d7f05537133aeef9e7292343b27066fdbb
| 548
|
package models;
import models.type.WebappType;
import play.db.ebean.Model;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import java.util.List;
/**
* User: k16wire
* Date: 15. 2. 15.
* Time: 오후 9:09
*/
@Entity
public class Webapp extends Model{
@Id
public Long id;
public String name;
public WebappType webappType;
@OneToMany(mappedBy = "webapp", cascade = CascadeType.ALL)
public List<WebappContainer> webappContainerList;
}
| 20.296296
| 62
| 0.735401
|
5c991df6e163cb352603e74867371037a8473ab6
| 708
|
package tools.gnzlz.database.query;
import tools.gnzlz.database.query.builder.IWhere;
import tools.gnzlz.database.query.builder.Query;
import tools.gnzlz.database.query.builder.data.GWhere;
public class Where extends Query<Where> implements IWhere<Where>{
private Where() {}
public static Where newI() {
return new Where();
}
/***************************
* where
***************************/
private GWhere dWhere;
@Override
public GWhere gWhere() {
if(dWhere == null) dWhere = new GWhere(null);
return dWhere;
}
@Override
public Where type() {
return this;
}
@Override
public String query() {
return generate().toString();
}
}
| 19.135135
| 66
| 0.611582
|
04c7bf17023caeb178d102ad1bdcd4de9fe48f31
| 2,335
|
/*
* 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.knox.gateway.util;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.junit.Test;
public class CollectionUtilsTest {
private final Comparator<Integer> integerComparator = Comparator.naturalOrder();
@Test
public void shouldReturnFalseWhenCheckingIfCollectionIsSortedAndGivenCollectionIsNull() throws Exception {
assertFalse(CollectionUtils.isSorted(null, integerComparator));
}
@Test
public void shouldReturnTrueWhenCheckingIfCollectionIsSortedAndGivenCollectionIsEmpty() throws Exception {
assertTrue(CollectionUtils.isSorted(Collections.emptyList(), integerComparator));
}
@Test
public void shouldReturnTrueWhenCheckingIfCollectionIsSortedAndGivenCollectionHasOneElement() throws Exception {
final List<Integer> list = Arrays.asList(1);
assertTrue(CollectionUtils.isSorted(list, integerComparator));
}
@Test
public void shouldReturnTrueWhenCheckingIfCollectionIsSortedAndGivenCollectionIsSorted() throws Exception {
final List<Integer> list = Arrays.asList(1, 2, 5, 8, 9);
assertTrue(CollectionUtils.isSorted(list, integerComparator));
}
@Test
public void shouldReturnFalseWhenCheckingIfCollectionIsSortedAndGivenCollectionIsNotSorted() throws Exception {
final List<Integer> list = Arrays.asList(1, 5, 2, 8, 9);
assertFalse(CollectionUtils.isSorted(list, integerComparator));
}
}
| 37.66129
| 114
| 0.784154
|
a2f86f42ecc5f5188f20da9b4fb92d7a4866dffb
| 68
|
package com.LimoB.util.files.impl;
public class StorageFolder {
}
| 11.333333
| 34
| 0.764706
|
28e899ba97fa4ff341025c7ee344e1f293ddee5d
| 206
|
public enum OrderType {
CASH_ON_DELIVERY(1),
ONLINE(0.9);
private double factor;
OrderType(double factor)
{
this.factor = factor;
}
public double getFactor()
{
return factor;
}
}
| 12.117647
| 26
| 0.645631
|
c28ac689dedd08931b665209d701d422d77417a7
| 642
|
package com.ducetech.app.dao;
import com.ducetech.app.model.ScheduleInfoUser;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface ScheduleInfoUserDAO {
ScheduleInfoUser selectById(Long id);
List<ScheduleInfoUser> selectByModel(String modelId);
ScheduleInfoUser selectByModelAndWeek(@Param("modelId") String modelId, @Param("weekNumber") int weekNumber);
void insert(ScheduleInfoUser scheduleInfoUser);
void deleteById(Long id);
ScheduleInfoUser selectByModelAndUser(@Param("modelId")String modelId, @Param("userId")String userId);
void updateWeekNumber(ScheduleInfoUser u);
}
| 32.1
| 113
| 0.785047
|
c2e53d881a372b0d734021a027180287f5d12da1
| 16,631
|
/*
* Copyright 2013-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch;
import static org.assertj.core.api.Assertions.*;
import static org.elasticsearch.index.query.QueryBuilders.*;
import static org.springframework.data.elasticsearch.utils.IdGenerator.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import org.springframework.data.elasticsearch.annotations.InnerField;
import org.springframework.data.elasticsearch.annotations.MultiField;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration;
import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest;
import org.springframework.data.elasticsearch.utils.IndexInitializer;
import org.springframework.lang.Nullable;
import org.springframework.test.context.ContextConfiguration;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Artur Konczak
* @author Peter-Josef Meisch
* @author Mark Paluch
*/
@SpringIntegrationTest
@ContextConfiguration(classes = { ElasticsearchRestTemplateConfiguration.class })
public class NestedObjectTests {
@Autowired private ElasticsearchOperations operations;
private final List<Class<?>> entityClasses = Arrays.asList(Book.class, Person.class, PersonMultipleLevelNested.class);
@BeforeEach
public void before() {
entityClasses.stream().map(operations::indexOps).forEach(IndexInitializer::init);
}
@AfterEach
void tearDown() {
entityClasses.forEach(clazz -> operations.indexOps(clazz).delete());
}
@Test
public void shouldIndexInitialLevelNestedObject() {
List<Car> cars = new ArrayList<>();
Car saturn = new Car();
saturn.setName("Saturn");
saturn.setModel("SL");
Car subaru = new Car();
subaru.setName("Subaru");
subaru.setModel("Imprezza");
Car ford = new Car();
ford.setName("Ford");
ford.setModel("Focus");
cars.add(saturn);
cars.add(subaru);
cars.add(ford);
Person foo = new Person();
foo.setName("Foo");
foo.setId("1");
foo.setCar(cars);
Car car = new Car();
car.setName("Saturn");
car.setModel("Imprezza");
Person bar = new Person();
bar.setId("2");
bar.setName("Bar");
bar.setCar(Collections.singletonList(car));
List<IndexQuery> indexQueries = new ArrayList<>();
IndexQuery indexQuery1 = new IndexQuery();
indexQuery1.setId(foo.getId());
indexQuery1.setObject(foo);
IndexQuery indexQuery2 = new IndexQuery();
indexQuery2.setId(bar.getId());
indexQuery2.setObject(bar);
indexQueries.add(indexQuery1);
indexQueries.add(indexQuery2);
IndexCoordinates index = IndexCoordinates.of("test-index-person");
operations.bulkIndex(indexQueries, index);
operations.indexOps(Person.class).refresh();
QueryBuilder builder = nestedQuery("car",
boolQuery().must(termQuery("car.name", "saturn")).must(termQuery("car.model", "imprezza")), ScoreMode.None);
Query searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build();
SearchHits<Person> persons = operations.search(searchQuery, Person.class, index);
assertThat(persons).hasSize(1);
}
@Test
public void shouldIndexMultipleLevelNestedObject() {
// given
List<IndexQuery> indexQueries = createPerson();
// when
operations.bulkIndex(indexQueries, IndexCoordinates.of("test-index-person-multiple-level-nested"));
operations.indexOps(PersonMultipleLevelNested.class).refresh();
// then
PersonMultipleLevelNested personIndexed = operations.get("1", PersonMultipleLevelNested.class,
IndexCoordinates.of("test-index-person-multiple-level-nested"));
assertThat(personIndexed).isNotNull();
}
@Test
public void shouldIndexMultipleLevelNestedObjectWithIncludeInParent() {
// given
List<IndexQuery> indexQueries = createPerson();
// when
operations.bulkIndex(indexQueries, IndexCoordinates.of("test-index-person-multiple-level-nested"));
// then
Map<String, Object> mapping = operations.indexOps(PersonMultipleLevelNested.class).getMapping();
assertThat(mapping).isNotNull();
Map<String, Object> propertyMap = (Map<String, Object>) mapping.get("properties");
assertThat(propertyMap).isNotNull();
Map bestCarsAttributes = (Map) propertyMap.get("bestCars");
assertThat(bestCarsAttributes.get("include_in_parent")).isNotNull();
}
@Test
public void shouldSearchUsingNestedQueryOnMultipleLevelNestedObject() {
// given
List<IndexQuery> indexQueries = createPerson();
// when
IndexCoordinates index = IndexCoordinates.of("test-index-person-multiple-level-nested");
operations.bulkIndex(indexQueries, index);
operations.indexOps(PersonMultipleLevelNested.class).refresh();
// then
BoolQueryBuilder builder = boolQuery();
builder.must(nestedQuery("girlFriends", termQuery("girlFriends.type", "temp"), ScoreMode.None)).must(
nestedQuery("girlFriends.cars", termQuery("girlFriends.cars.name", "Ford".toLowerCase()), ScoreMode.None));
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build();
SearchHits<PersonMultipleLevelNested> personIndexed = operations.search(searchQuery,
PersonMultipleLevelNested.class, index);
assertThat(personIndexed).isNotNull();
assertThat(personIndexed.getTotalHits()).isEqualTo(1);
assertThat(personIndexed.getSearchHit(0).getContent().getId()).isEqualTo("1");
}
private List<IndexQuery> createPerson() {
PersonMultipleLevelNested person1 = new PersonMultipleLevelNested();
person1.setId("1");
person1.setName("name");
Car saturn = new Car();
saturn.setName("Saturn");
saturn.setModel("SL");
Car subaru = new Car();
subaru.setName("Subaru");
subaru.setModel("Imprezza");
Car car = new Car();
car.setName("Saturn");
car.setModel("Imprezza");
Car ford = new Car();
ford.setName("Ford");
ford.setModel("Focus");
GirlFriend permanent = new GirlFriend();
permanent.setName("permanent");
permanent.setType("permanent");
permanent.setCars(Arrays.asList(saturn, subaru));
GirlFriend temp = new GirlFriend();
temp.setName("temp");
temp.setType("temp");
temp.setCars(Arrays.asList(car, ford));
person1.setGirlFriends(Arrays.asList(permanent, temp));
IndexQuery indexQuery1 = new IndexQuery();
indexQuery1.setId(person1.getId());
indexQuery1.setObject(person1);
PersonMultipleLevelNested person2 = new PersonMultipleLevelNested();
person2.setId("2");
person2.setName("name");
person2.setGirlFriends(Collections.singletonList(permanent));
IndexQuery indexQuery2 = new IndexQuery();
indexQuery2.setId(person2.getId());
indexQuery2.setObject(person2);
List<IndexQuery> indexQueries = new ArrayList<>();
indexQueries.add(indexQuery1);
indexQueries.add(indexQuery2);
return indexQueries;
}
@Test
public void shouldSearchBooksForPersonInitialLevelNestedType() {
// given
List<Car> cars = new ArrayList<>();
Car saturn = new Car();
saturn.setName("Saturn");
saturn.setModel("SL");
Car subaru = new Car();
subaru.setName("Subaru");
subaru.setModel("Imprezza");
Car ford = new Car();
ford.setName("Ford");
ford.setModel("Focus");
cars.add(saturn);
cars.add(subaru);
cars.add(ford);
Book java = new Book();
java.setId("1");
java.setName("java");
Author javaAuthor = new Author();
javaAuthor.setId("1");
javaAuthor.setName("javaAuthor");
java.setAuthor(javaAuthor);
Book spring = new Book();
spring.setId("2");
spring.setName("spring");
Author springAuthor = new Author();
springAuthor.setId("2");
springAuthor.setName("springAuthor");
spring.setAuthor(springAuthor);
Person foo = new Person();
foo.setName("Foo");
foo.setId("1");
foo.setCar(cars);
foo.setBooks(Arrays.asList(java, spring));
Car car = new Car();
car.setName("Saturn");
car.setModel("Imprezza");
Person bar = new Person();
bar.setId("2");
bar.setName("Bar");
bar.setCar(Collections.singletonList(car));
List<IndexQuery> indexQueries = new ArrayList<>();
IndexQuery indexQuery1 = new IndexQuery();
indexQuery1.setId(foo.getId());
indexQuery1.setObject(foo);
IndexQuery indexQuery2 = new IndexQuery();
indexQuery2.setId(bar.getId());
indexQuery2.setObject(bar);
indexQueries.add(indexQuery1);
indexQueries.add(indexQuery2);
IndexCoordinates index = IndexCoordinates.of("test-index-person");
operations.bulkIndex(indexQueries, index);
operations.indexOps(Person.class).refresh();
// when
QueryBuilder builder = nestedQuery("books", boolQuery().must(termQuery("books.name", "java")), ScoreMode.None);
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build();
SearchHits<Person> persons = operations.search(searchQuery, Person.class, index);
// then
assertThat(persons).hasSize(1);
}
@Test // DATAES-73
public void shouldIndexAndSearchMapAsNestedType() {
// given
Book book1 = new Book();
Book book2 = new Book();
book1.setId(nextIdAsString());
book1.setName("testBook1");
book2.setId(nextIdAsString());
book2.setName("testBook2");
Map<Integer, Collection<String>> map1 = new HashMap<>();
map1.put(1, Arrays.asList("test1", "test2"));
Map<Integer, Collection<String>> map2 = new HashMap<>();
map2.put(1, Arrays.asList("test3", "test4"));
book1.setBuckets(map1);
book2.setBuckets(map2);
List<IndexQuery> indexQueries = new ArrayList<>();
IndexQuery indexQuery1 = new IndexQuery();
indexQuery1.setId(book1.getId());
indexQuery1.setObject(book1);
IndexQuery indexQuery2 = new IndexQuery();
indexQuery2.setId(book2.getId());
indexQuery2.setObject(book2);
indexQueries.add(indexQuery1);
indexQueries.add(indexQuery2);
// when
IndexCoordinates index = IndexCoordinates.of("test-index-book-nested-objects");
operations.bulkIndex(indexQueries, index);
operations.indexOps(Book.class).refresh();
// then
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(nestedQuery("buckets", termQuery("buckets.1", "test3"), ScoreMode.None)).build();
SearchHits<Book> books = operations.search(searchQuery, Book.class, index);
assertThat(books.getSearchHits()).hasSize(1);
assertThat(books.getSearchHit(0).getContent().getId()).isEqualTo(book2.getId());
}
@Document(indexName = "test-index-book-nested-objects")
static class Book {
@Nullable
@Id private String id;
@Nullable private String name;
@Nullable
@Field(type = FieldType.Object) private Author author;
@Nullable
@Field(type = FieldType.Nested) private Map<Integer, Collection<String>> buckets = new HashMap<>();
@Nullable
@MultiField(mainField = @Field(type = FieldType.Text, analyzer = "whitespace"),
otherFields = { @InnerField(suffix = "prefix", type = FieldType.Text, analyzer = "stop",
searchAnalyzer = "standard") }) private String description;
@Nullable
public String getId() {
return id;
}
public void setId(@Nullable String id) {
this.id = id;
}
@Nullable
public String getName() {
return name;
}
public void setName(@Nullable String name) {
this.name = name;
}
@Nullable
public Author getAuthor() {
return author;
}
public void setAuthor(@Nullable Author author) {
this.author = author;
}
@Nullable
public Map<Integer, Collection<String>> getBuckets() {
return buckets;
}
public void setBuckets(@Nullable Map<Integer, Collection<String>> buckets) {
this.buckets = buckets;
}
@Nullable
public String getDescription() {
return description;
}
public void setDescription(@Nullable String description) {
this.description = description;
}
}
@Document(indexName = "test-index-person")
static class Person {
@Nullable
@Id private String id;
@Nullable private String name;
@Nullable
@Field(type = FieldType.Nested) private List<Car> car;
@Nullable
@Field(type = FieldType.Nested, includeInParent = true) private List<Book> books;
@Nullable
public String getId() {
return id;
}
public void setId(@Nullable String id) {
this.id = id;
}
@Nullable
public String getName() {
return name;
}
public void setName(@Nullable String name) {
this.name = name;
}
@Nullable
public List<Car> getCar() {
return car;
}
public void setCar(@Nullable List<Car> car) {
this.car = car;
}
@Nullable
public List<Book> getBooks() {
return books;
}
public void setBooks(@Nullable List<Book> books) {
this.books = books;
}
}
static class Car {
@Nullable private String name;
@Nullable private String model;
@Nullable
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Nullable
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
@Document(indexName = "test-index-person-multiple-level-nested")
static class PersonMultipleLevelNested {
@Nullable
@Id private String id;
@Nullable private String name;
@Nullable
@Field(type = FieldType.Nested) private List<GirlFriend> girlFriends;
@Nullable
@Field(type = FieldType.Nested) private List<Car> cars;
@Nullable
@Field(type = FieldType.Nested, includeInParent = true) private List<Car> bestCars;
@Nullable
public String getId() {
return id;
}
public void setId(@Nullable String id) {
this.id = id;
}
@Nullable
public String getName() {
return name;
}
public void setName(@Nullable String name) {
this.name = name;
}
@Nullable
public List<GirlFriend> getGirlFriends() {
return girlFriends;
}
public void setGirlFriends(@Nullable List<GirlFriend> girlFriends) {
this.girlFriends = girlFriends;
}
@Nullable
public List<Car> getCars() {
return cars;
}
public void setCars(@Nullable List<Car> cars) {
this.cars = cars;
}
@Nullable
public List<Car> getBestCars() {
return bestCars;
}
public void setBestCars(@Nullable List<Car> bestCars) {
this.bestCars = bestCars;
}
}
static class GirlFriend {
@Nullable private String name;
@Nullable private String type;
@Nullable
@Field(type = FieldType.Nested) private List<Car> cars;
@Nullable
public String getName() {
return name;
}
public void setName(@Nullable String name) {
this.name = name;
}
@Nullable
public String getType() {
return type;
}
public void setType(@Nullable String type) {
this.type = type;
}
@Nullable
public List<Car> getCars() {
return cars;
}
public void setCars(@Nullable List<Car> cars) {
this.cars = cars;
}
}
static class Author {
@Nullable private String id;
@Nullable private String name;
@Nullable
public String getId() {
return id;
}
public void setId(@Nullable String id) {
this.id = id;
}
@Nullable
public String getName() {
return name;
}
public void setName(@Nullable String name) {
this.name = name;
}
}
}
| 26.314873
| 119
| 0.726475
|
c75241e6281b322c0ff5ae644b8585685c11861e
| 4,961
|
/*
* 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 food;
import static com.sun.faces.util.CollectionsUtils.map;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
@ManagedBean
@ViewScoped
public class DropdownView implements Serializable {
private Map<String,Map<String,String>> data = new HashMap<String, Map<String,String>>();
private String icecream;
private String price;
private Map<String,String> icecreams;
private Map<String,String> prices;
private String drink;
private Map<String,String> drinks;
@PostConstruct
public void init() {
icecreams = new HashMap<String, String>();
icecreams.put("Alumni Swirl", "Alumni Swirl");
icecreams.put("Bars", "Bars");
icecreams.put("Cones", "Cones");
icecreams.put("Chocolate Eclair", "Chocolate Eclair");
icecreams.put("Sandwiches", "Sandwiches");
icecreams.put("Strawberry", "Strawberry");
icecreams.put("Vanila King Cone", "Vanila King Cone");
Map<String,String> map = new HashMap<String, String>();
map.put("50", "50");
map.put("40", "40");
map.put("30", "30");
data.put("Alumni Swirl", map);
String key=map.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue,Map.Entry::getKey)).get("Alumni Swirl");
System.out.println(key);
Map<String,String> map1 = new HashMap<String, String>();
map1.put("100", "100");
map1.put("80", "80");
map1.put("70", "70");
data.put("Bars", map1);
Map<String,String> map2 = new HashMap<String, String>();
map2.put("60", "60");
map2.put("40", "40");
map2.put("20", "20");
data.put("Cones", map2);
Map<String,String> map3 = new HashMap<String, String>();
map3.put("90", "90");
map3.put("60", "60");
map3.put("30", "30");
data.put("Chocolate Eclair", map3);
Map<String,String> map4 = new HashMap<String, String>();
map4.put("120", "120");
map4.put("80", "80");
map4.put("50", "50");
data.put("Sandwiches", map4);
Map<String,String> map5 = new HashMap<String, String>();
map5.put("150", "150");
map5.put("80", "80");
map5.put("40", "40");
data.put("Strawberry", map5);
Map<String,String> map6 = new HashMap<String, String>();
map6.put("110", "110");
map6.put("60", "60");
map6.put("30", "30");
data.put("Vanila King Cone", map6);
}
public String getDrink() {
return drink;
}
public void setDrink(String drink) {
this.drink = drink;
}
public Map<String, String> getDrinks() {
return drinks;
}
public void setDrinks(Map<String, String> drinks) {
this.drinks = drinks;
}
public Map<String, Map<String, String>> getData() {
return data;
}
public Map<String, String> getIcecreams() {
return icecreams;
}
public void setIcecreams(Map<String, String> icecreams) {
this.icecreams = icecreams;
}
public Map<String, String> getPrices() {
return prices;
}
public void setPrices(Map<String, String> prices) {
this.prices = prices;
}
public String getIcecream() {
return icecream;
}
public void setIcecream(String icecream) {
this.icecream = icecream;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public void onFoodChange() {
if(icecream !=null && !icecream.equals(""))
prices = data.get(icecream);
else
prices= new HashMap<String, String>();
}
public String display() {
FacesMessage msg;
if(price != null && icecream != null)
{
if(price != null && drink != null)
{
msg = new FacesMessage("Selected", price + " of " +drink);
// return "Buy.xhtml";
}
msg = new FacesMessage("Selected", price + " of " +icecream);
return "Buy.xhtml";
}
else{
msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Invalid", "Icecream and drinks is not selected.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
return null;
}
}
| 26.529412
| 122
| 0.571457
|
1ed6233f3cf3e0e76bb3a4883afbdd87b5be8d1e
| 1,967
|
//
// Copyright (C) 2006 United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration
// (NASA). All Rights Reserved.
//
// This software is distributed under the NASA Open Source Agreement
// (NOSA), version 1.3. The NOSA has been approved by the Open Source
// Initiative. See the file NOSA-1.3-JPF at the top of the distribution
// directory tree for the complete NOSA document.
//
// THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF ANY
// KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT
// LIMITED TO, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO
// SPECIFICATIONS, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR
// A PARTICULAR PURPOSE, OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT
// THE SUBJECT SOFTWARE WILL BE ERROR FREE, OR ANY WARRANTY THAT
// DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE SUBJECT SOFTWARE.
//
package java.lang.ref;
/**
* MJI model class for java.lang.ref.Reference library abstraction
* we model this so that we can rely on our WeakRefence implementation
*/
public abstract class Reference<T> {
/**
* the object we reference
* NOTE: this has to be the *first* field, or we break WeakReference handling in
* the garbage collection!!
*/
T ref;
/** the optional queue for us */
ReferenceQueue<? super T> queue;
/** link to enqueue w/o additional memory requirements */
Reference<T> next;
Reference (T r) {
ref = r;
}
Reference (T r, ReferenceQueue<? super T> q) {
ref = r;
queue = q;
}
/** is the referenced object enqueued */
public boolean isEnqueued () {
// <2do>
return false;
}
/** clear, but do not enqueue the referenced object */
public void clear () {
ref = null;
}
/** add the referenced object to its queue */
public void enqueue () {
}
/** return the referenced object */
public T get () {
return ref;
}
}
| 28.507246
| 82
| 0.6909
|
173531b9d0c0b46466f84d0a16628ca471b32488
| 2,980
|
/*
* 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.example.application.data.entity;
import com.example.application.data.AbstractEntity;
import javax.persistence.CascadeType;
import javax.persistence.ManyToOne;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.validation.constraints.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
/**
*
* @author Leinier
*/
@Data
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@ToString(onlyExplicitlyIncluded = true)
@Entity
@Table(name = "Profesores")
public class Profesor extends AbstractEntity {
@EqualsAndHashCode.Include
@ToString.Include
@NotEmpty
@NotBlank(message = "El campo no debe estar vacío")
@Pattern(regexp = "^[a-zA-ZÀ-ÿ\\u00f1\\u00d1]+(\\s*[a-zA-ZÀ-ÿ\\u00f1\\u00d1]*)*[a-zA-ZÀ-ÿ\\u00f1\\u00d1]+$", message = "Datos incorrectos, solo letras") //0 combinaciones de letras 0 o mas veces incluyendo espacios
@Size(message = "Mínimo 2 caracteres y máximo 100", min = 2, max = 100)
@Column(name = "nombre", nullable = false)
private String nombre;
@NotEmpty
@NotBlank(message = "El campo no debe estar vacío")
@Pattern(regexp = "^[a-zA-ZÀ-ÿ\\u00f1\\u00d1]+(\\s*[a-zA-ZÀ-ÿ\\u00f1\\u00d1]*)*[a-zA-ZÀ-ÿ\\u00f1\\u00d1]+$", message = "Datos incorrectos, solo letras") //0 combinaciones de letras 0 o mas veces incluyendo espacios
@Size(message = "Mínimo 3 caracteres y máximo 100", min = 3, max = 100)
@Column(name = "apellidos", nullable = false)
private String apellidos;
@NotNull(message = "campo vacío")
@OneToOne(optional = false, cascade = CascadeType.ALL)
private User user;
@Email
@NotEmpty
@NotBlank(message = "El campo no debe estar vacío")
@Pattern(regexp = "^([a-zA-Z]+[a-zA-Z0-9_\\.]+)*[a-zA-Z0-9]+(@uci\\.cu)$", message = "Por favor escriba un correo válido")
@Column(name = "email", nullable = false, unique = true)
private String email;
@NotEmpty
@NotBlank(message = "El campo no debe estar vacío")
@Pattern(regexp = "^[A-Z][0-9]+$", message = "Solapín incorrecto")
@Size(message = "Mínimo 7 caracteres y máximo 7 ", min = 7, max = 7)
@Column(name = "solapin", nullable = false, unique = true)
private String solapin;
@NotNull(message = "debe elegir un campo")
@JoinColumn(name = "a_id",nullable = false, updatable = false)
@ManyToOne()
private Area a;
public String getStringNombreApellidos() {
return getNombre() + " " + getApellidos();
}
}
| 34.252874
| 218
| 0.700336
|
217b40be63e3f4d0ba773baa5b0860358139bef6
| 2,438
|
package com.danielkueffer.filehosting.persistence.dao.impl;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.Query;
import com.danielkueffer.filehosting.persistence.dao.AbstractDao;
import com.danielkueffer.filehosting.persistence.dao.FileDao;
import com.danielkueffer.filehosting.persistence.model.UploadFile;
import com.danielkueffer.filehosting.persistence.model.User;
/**
* The file DAO implementation
*
* @author dkueffer
*
*/
@Stateless
public class FileDaoImpl extends AbstractDao<UploadFile> implements FileDao {
/**
* Get files by user
*/
@SuppressWarnings("unchecked")
@Override
public List<UploadFile> getFilesByUser(User user) {
Query q = this.getEm().createQuery(
"SELECT u FROM UploadFile u WHERE u.user = :qUser");
q.setParameter("qUser", user);
return q.getResultList();
}
/**
* Get files by user under the parent directory
*/
@SuppressWarnings("unchecked")
@Override
public List<UploadFile> getFilesByUser(User user, int parent) {
Query q = this
.getEm()
.createQuery(
"SELECT u FROM UploadFile u WHERE u.user = :qUser AND u.parent = :qParent");
q.setParameter("qUser", user);
q.setParameter("qParent", parent);
return q.getResultList();
}
/**
* Get a single file by user
*/
@SuppressWarnings("unchecked")
@Override
public List<UploadFile> getSingleFileByUser(String filePath, User user) {
Query q = this
.getEm()
.createQuery(
"SELECT u FROM UploadFile u WHERE u.user = :qUser AND u.path = :qPath");
q.setParameter("qUser", user);
q.setParameter("qPath", filePath);
return q.getResultList();
}
/**
* Get a single file by user and parent
*/
@SuppressWarnings("unchecked")
@Override
public List<UploadFile> getSingleFileByUserAndParent(String filePath,
User user, int parent) {
Query q = this
.getEm()
.createQuery(
"SELECT u FROM UploadFile u WHERE u.user = :qUser AND u.path = :qPath AND u.parent = :qParent");
q.setParameter("qUser", user);
q.setParameter("qPath", filePath);
q.setParameter("qParent", parent);
return q.getResultList();
}
/**
* Get files by parent folder
*/
@SuppressWarnings("unchecked")
@Override
public List<UploadFile> getFilesByParent(int parent) {
Query q = this.getEm().createQuery(
"SELECT u FROM UploadFile u WHERE u.parent = :qParent");
q.setParameter("qParent", parent);
return q.getResultList();
}
}
| 23.442308
| 102
| 0.705496
|
17bd0426954f57903a994b16e863750a1f9f0240
| 2,694
|
/*
* Copyright 2017-2021 EPAM Systems, Inc. (https://www.epam.com/)
*
* 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.epam.pipeline.entity.user;
import com.epam.pipeline.entity.cloud.credentials.CloudProfileCredentialsEntity;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.io.Serializable;
import java.util.List;
@Getter
@Setter
@EqualsAndHashCode
@AllArgsConstructor
@Entity
@Table(name = "role", schema = "pipeline")
public class Role implements StorageContainer, Serializable {
public static final String ROLE_PREFIX = "ROLE_";
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "role_generator")
@SequenceGenerator(name="role_generator", sequenceName = "s_role", schema = "pipeline")
private Long id;
private String name;
private boolean predefined;
private boolean userDefault;
private Long defaultStorageId;
private Long defaultProfileId;
@Transient
private Boolean blocked;
@ManyToMany
@JoinTable(
name = "cloud_profile_credentials_role",
schema = "pipeline",
inverseJoinColumns = { @JoinColumn(name = "cloud_profile_credentials_id") },
joinColumns = { @JoinColumn(name = "role_id") }
)
private List<CloudProfileCredentialsEntity> cloudProfiles;
public Role() {
this.predefined = false;
this.userDefault = false;
}
public Role(String name) {
this();
this.name = name;
}
public Role(Long id, String name) {
this(name);
this.id = id;
}
@Override
public Long getDefaultStorageId() {
return defaultStorageId;
}
@Override
public String toString() {
return name;
}
}
| 26.94
| 91
| 0.714922
|
3747508905b935a2c11c6087f9da1de4209a144d
| 186
|
package com.jn.agileway.ssh.client.impl.sshj;
import com.jn.agileway.ssh.client.AbstractSshConnectionConfig;
public class SshjConnectionConfig extends AbstractSshConnectionConfig {
}
| 23.25
| 71
| 0.844086
|
2cb99ed7230cd2a2f9d96a23f29f28e36628c104
| 4,228
|
/*
* 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.isis.extensions.secman.jdo.seed.scripts;
import org.apache.isis.applib.services.appfeat.ApplicationFeatureId;
import org.apache.isis.commons.collections.Can;
import org.apache.isis.core.security.authentication.logout.LogoutMenu;
import org.apache.isis.extensions.secman.api.SecmanConfiguration;
import org.apache.isis.extensions.secman.api.permission.ApplicationPermissionMode;
import org.apache.isis.extensions.secman.api.permission.ApplicationPermissionRule;
import lombok.val;
/**
* Role for regular users of the security module, providing the ability to lookup their user account using the
* {@link org.apache.isis.extensions.secman.model.dom.user.MeService}, and for viewing and maintaining their user details.
*
* @since 2.0 {@index}
*/
public class IsisExtSecmanRegularUserRoleAndPermissions extends AbstractRoleAndPermissionsFixtureScript {
public IsisExtSecmanRegularUserRoleAndPermissions(SecmanConfiguration configBean) {
super(configBean.getRegularUserRoleName(), "Regular user of the security module");
}
@Override
protected void execute(ExecutionContext executionContext) {
val allowViewing = Can.of(
ApplicationFeatureId.newType("isis.ext.secman.ApplicationUser"),
ApplicationFeatureId.newMember("isis.ext.secman.ApplicationRole", "name"),
ApplicationFeatureId.newMember("isis.ext.secman.ApplicationRole", "description")
);
val allowChanging = Can.of(
ApplicationFeatureId.newMember(LogoutMenu.OBJECT_TYPE, "logout"),
ApplicationFeatureId.newMember("isis.ext.secman.MeService", "me"),
ApplicationFeatureId.newMember("isis.ext.secman.ApplicationUser", "updateName"),
ApplicationFeatureId.newMember("isis.ext.secman.ApplicationUser", "updatePassword"),
ApplicationFeatureId.newMember("isis.ext.secman.ApplicationUser", "updateEmailAddress"),
ApplicationFeatureId.newMember("isis.ext.secman.ApplicationUser", "updatePhoneNumber"),
ApplicationFeatureId.newMember("isis.ext.secman.ApplicationUser", "updateFaxNumber")
);
val vetoViewing = Can.of(
ApplicationFeatureId.newMember("isis.ext.secman.ApplicationUser", "filterPermissions"),
ApplicationFeatureId.newMember("isis.ext.secman.ApplicationUser", "resetPassword"),
ApplicationFeatureId.newMember("isis.ext.secman.ApplicationUser", "lock"), // named 'enable' in the UI
ApplicationFeatureId.newMember("isis.ext.secman.ApplicationUser", "unlock"), // named 'disable' in the UI
ApplicationFeatureId.newMember("isis.ext.secman.ApplicationUser", "addRole"),
ApplicationFeatureId.newMember("isis.ext.secman.ApplicationUser", "removeRoles")
);
newPermissions(
ApplicationPermissionRule.ALLOW,
ApplicationPermissionMode.VIEWING,
allowViewing);
newPermissions(
ApplicationPermissionRule.ALLOW,
ApplicationPermissionMode.CHANGING,
allowChanging);
newPermissions(
ApplicationPermissionRule.VETO,
ApplicationPermissionMode.VIEWING,
vetoViewing);
}
}
| 48.045455
| 122
| 0.697729
|
9421c8e364dc44f719a5f667e552ea07f207c436
| 1,665
|
package org.jboss.bakery.data.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.Table;
import org.apache.commons.lang.ObjectUtils;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Index;
@Entity
@NamedQueries({
@javax.persistence.NamedQuery(name = "Chocolate.getChocolateByOrigin", query = "select k from Chocolate k where k.origin = :origin") })
@GenericGenerator(name = "ChocolateGen", strategy = "sequence", parameters = {
@org.hibernate.annotations.Parameter(name = "sequence", value = "CHOCOLATE_SEQ") })
@Table(name = "CHOCOLATE")
public class Chocolate extends EdibleEntity {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "ChocolateGen")
@Column(name = "ID")
private Integer id;
@Column(name = "ORIGIN", length = 9, nullable = false, unique = true)
@Index(name = "ID_CHOCOLATE_ORIGIN", columnNames = { "ORIGIN" })
private String origin;
public int hashCode() {
return 31 * 948382 + (getId() == null ? 0 : getId().hashCode());
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Chocolate)) {
return false;
}
Chocolate other = (Chocolate) obj;
return (getId() != null) && (ObjectUtils.equals(getId(), other.getId()));
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getOrigin() {
return this.origin;
}
public void setOrigin(String origin) {
this.origin = origin;
}
}
| 26.015625
| 137
| 0.715315
|
479f94086e57e456af3e34bfb70da483673909f9
| 1,060
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.process;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.openapi.application.ApplicationManager;
import org.jetbrains.annotations.NotNull;
public abstract class ProcessHandlerFactory {
public static ProcessHandlerFactory getInstance() {
return ApplicationManager.getApplication().getService(ProcessHandlerFactory.class);
}
/**
* Returns a new instance of the {@link OSProcessHandler}.
*/
@NotNull
public abstract OSProcessHandler createProcessHandler(@NotNull GeneralCommandLine commandLine) throws ExecutionException;
/**
* Returns a new instance of the {@link OSProcessHandler} which is aware of ANSI coloring output.
*/
@NotNull
public abstract OSProcessHandler createColoredProcessHandler(@NotNull GeneralCommandLine commandLine) throws ExecutionException;
}
| 37.857143
| 140
| 0.803774
|
5f7548916720ad311ccdc547eeb00f214278de98
| 1,187
|
package uk.gov.dvsa.motr.web.mapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.gov.dvsa.motr.web.render.TemplateEngine;
import javax.inject.Inject;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import static java.util.Collections.emptyMap;
import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;
/**
* Executes when no other error handler was executed.
*/
@Provider
public class UnhandledExceptionMapper implements ExceptionMapper<Throwable> {
private static final Logger logger = LoggerFactory.getLogger(UnhandledExceptionMapper.class);
private final TemplateEngine renderer;
@Inject
public UnhandledExceptionMapper(TemplateEngine renderer) {
this.renderer = renderer;
}
@Override
public Response toResponse(Throwable exception) {
logger.error("Unhandled error!", exception);
String content = renderer.render("error/internal-error", emptyMap());
return Response.status(INTERNAL_SERVER_ERROR)
.header("Content-type", "text/html")
.entity(content)
.build();
}
}
| 26.977273
| 97
| 0.723673
|
000d3d2c06699b2b363ec8fe334c614e20c9df58
| 1,045
|
package com.estafet.blockchain.demo.console.ui.selenium.tests.rates;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.estafet.blockchain.demo.pages.lib.home.HomePage;
import com.estafet.blockchain.demo.pages.lib.rate.UpdateExchangeRatePage;
public class ITUpdateExchangeRatePageTest {
UpdateExchangeRatePage updateExchangeRatePage;
@Before
public void before() throws Exception {
updateExchangeRatePage = new HomePage().clickExchangeRatesMenuItem().getItems().get(0).clickEditLink();
}
@After
public void after() throws Exception {
updateExchangeRatePage.close();
}
@Test
public void testCurrency() {
assertEquals("USD", updateExchangeRatePage.getCurrency());
}
@Test
public void testRate() {
assertEquals(250, updateExchangeRatePage.getRate(), 0);
}
@Test
public void testSave() {
updateExchangeRatePage.setRate(450);
assertTrue(updateExchangeRatePage.clickSaveButton().isLoaded());
}
}
| 24.302326
| 106
| 0.737799
|
b380de0019d07d9250d844c87c7bd269cc327b7f
| 2,950
|
package com.alibaba.cola.command;
import com.alibaba.cola.dto.Command;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.exception.framework.ExceptionHandlerFactory;
import com.alibaba.cola.logger.Logger;
import com.alibaba.cola.logger.LoggerFactory;
import com.google.common.collect.FluentIterable;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class CommandInvocation{
private static Logger logger = LoggerFactory.getLogger(CommandInvocation.class);
@Setter
private CommandExecutorI commandExecutor;
@Setter
private Iterable<CommandInterceptorI> preInterceptors;
@Setter
private Iterable<CommandInterceptorI> postInterceptors;
@Autowired
private CommandHub commandHub;
public CommandInvocation() {
}
public CommandInvocation(CommandExecutorI commandExecutor, List<CommandInterceptorI> preInterceptors,
List<CommandInterceptorI> postInterceptors){
this.commandExecutor = commandExecutor;
this.preInterceptors = preInterceptors;
this.postInterceptors = postInterceptors;
}
public Response invoke(Command command) {
Response response = null;
try {
preIntercept(command);
response = commandExecutor.execute(command);
}
catch(Exception e){
response = getResponseInstance(command);
response.setSuccess(false);
ExceptionHandlerFactory.getExceptionHandler().handleException(command, response, e);
}
finally {
//make sure post interceptors performs even though exception happens
postIntercept(command, response);
}
return response;
}
private void postIntercept(Command command, Response response) {
try {
for (CommandInterceptorI postInterceptor : FluentIterable.from(postInterceptors).toSet()) {
postInterceptor.postIntercept(command, response);
}
}
catch(Exception e){
logger.error("postInterceptor error:"+e.getMessage(), e);
}
}
private void preIntercept(Command command) {
for (CommandInterceptorI preInterceptor : FluentIterable.from(preInterceptors).toSet()) {
preInterceptor.preIntercept(command);
}
}
private Response getResponseInstance(Command cmd) {
Class responseClz = commandHub.getResponseRepository().get(cmd.getClass());
try {
return (Response) responseClz.newInstance();
} catch (Exception e) {
return new Response();
}
}
}
| 32.777778
| 105
| 0.688136
|
8a62524aa2bcdf46996d258eefa2fa4527893c78
| 8,893
|
package io.polyglotted.elastic.search;
import io.polyglotted.elastic.search.Aggregation.AggregationType;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import org.elasticsearch.join.aggregations.Children;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.SingleBucketAggregation;
import org.elasticsearch.search.aggregations.bucket.filter.Filter;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.aggregations.bucket.nested.Nested;
import org.elasticsearch.search.aggregations.bucket.nested.ReverseNested;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.avg.Avg;
import org.elasticsearch.search.aggregations.metrics.cardinality.Cardinality;
import org.elasticsearch.search.aggregations.metrics.max.Max;
import org.elasticsearch.search.aggregations.metrics.min.Min;
import org.elasticsearch.search.aggregations.metrics.stats.Stats;
import org.elasticsearch.search.aggregations.metrics.stats.extended.ExtendedStats;
import org.elasticsearch.search.aggregations.metrics.sum.Sum;
import org.elasticsearch.search.aggregations.metrics.valuecount.ValueCount;
import java.util.List;
import static io.polyglotted.elastic.search.Aggregation.aggregationBuilder;
import static java.util.Objects.requireNonNull;
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public enum AggsConverter {
AggMax {
@Override Aggregation.Builder getWith(String label, org.elasticsearch.search.aggregations.Aggregation agg) {
return aggregationBuilder().label(label).type(AggregationType.Max).value("Max", ((Max) agg).getValue());
}
},
AggMin {
@Override Aggregation.Builder getWith(String label, org.elasticsearch.search.aggregations.Aggregation agg) {
return aggregationBuilder().label(label).type(AggregationType.Min).value("Min", ((Min) agg).getValue());
}
},
AggSum {
@Override Aggregation.Builder getWith(String label, org.elasticsearch.search.aggregations.Aggregation agg) {
return aggregationBuilder().label(label).type(AggregationType.Sum).value("Sum", ((Sum) agg).getValue());
}
},
AggAvg {
@Override Aggregation.Builder getWith(String label, org.elasticsearch.search.aggregations.Aggregation agg) {
return aggregationBuilder().label(label).type(AggregationType.Avg).value("Avg", ((Avg) agg).getValue());
}
},
AggCount {
@Override Aggregation.Builder getWith(String label, org.elasticsearch.search.aggregations.Aggregation agg) {
return aggregationBuilder().label(label).type(AggregationType.Count).value("Count", ((ValueCount) agg).getValue());
}
},
AggCardinality {
@Override Aggregation.Builder getWith(String label, org.elasticsearch.search.aggregations.Aggregation agg) {
return aggregationBuilder().label(label).type(AggregationType.Cardinality).value("Cardinality", ((Cardinality) agg).getValue());
}
},
AggExtStatistics {
@Override Aggregation.Builder getWith(String label, org.elasticsearch.search.aggregations.Aggregation agg) {
return getStats(label, AggregationType.ExtStatistics, (ExtendedStats) agg);
}
},
AggStatistics {
@Override Aggregation.Builder getWith(String label, org.elasticsearch.search.aggregations.Aggregation agg) {
return getStats(label, AggregationType.Statistics, (Stats) agg);
}
},
AggTerm {
@Override Aggregation.Builder getWith(String label, org.elasticsearch.search.aggregations.Aggregation agg) {
Terms terms = (Terms) agg;
Aggregation.Builder builder = aggregationBuilder().label(label).type(AggregationType.Term)
.param("docCountError", terms.getDocCountError()).param("sumOfOtherDocs", terms.getSumOfOtherDocCounts());
addMultiBucketAgg(builder, terms.getBuckets());
return builder;
}
},
AggDateHistogram {
@Override Aggregation.Builder getWith(String label, org.elasticsearch.search.aggregations.Aggregation agg) {
Histogram histogram = (Histogram) agg;
Aggregation.Builder builder = aggregationBuilder().label(label).type(AggregationType.DateHistogram);
addMultiBucketAgg(builder, histogram.getBuckets());
return builder;
}
},
AggFilter {
@Override Aggregation.Builder getWith(String label, org.elasticsearch.search.aggregations.Aggregation agg) {
Aggregation.Builder builder = aggregationBuilder().label(label).type(AggregationType.Filter);
return addSingleBucketChildren(label, builder, (Filter) agg);
}
},
AggChildren {
@Override Aggregation.Builder getWith(String label, org.elasticsearch.search.aggregations.Aggregation agg) {
Aggregation.Builder builder = aggregationBuilder().label(label).type(AggregationType.Children);
return addSingleBucketChildren(label, builder, (Children) agg);
}
},
AggNested {
@Override Aggregation.Builder getWith(String label, org.elasticsearch.search.aggregations.Aggregation agg) {
Aggregation.Builder builder = aggregationBuilder().label(label).type(AggregationType.Nested);
return addSingleBucketChildren(label, builder, (Nested) agg);
}
},
AggReverseNested {
@Override Aggregation.Builder getWith(String label, org.elasticsearch.search.aggregations.Aggregation agg) {
Aggregation.Builder builder = aggregationBuilder().label(label).type(AggregationType.ReverseNested);
return addSingleBucketChildren(label, builder, (ReverseNested) agg);
}
};
abstract Aggregation.Builder getWith(String label, org.elasticsearch.search.aggregations.Aggregation agg);
static Aggregation.Builder detectAgg(org.elasticsearch.search.aggregations.Aggregation agg) {
AggsConverter converter = null;
if (agg instanceof Max) { converter = AggMax; }
else if (agg instanceof Min) { converter = AggMin; }
else if (agg instanceof Sum) { converter = AggSum; }
else if (agg instanceof Avg) { converter = AggAvg; }
else if (agg instanceof ValueCount) { converter = AggCount; }
else if (agg instanceof Cardinality) { converter = AggCardinality; }
else if (agg instanceof ExtendedStats) { converter = AggExtStatistics; }
else if (agg instanceof Stats) { converter = AggStatistics; }
else if (agg instanceof Terms) { converter = AggTerm; }
else if (agg instanceof Histogram) { converter = AggDateHistogram; }
else if (agg instanceof Filter) { converter = AggFilter; }
else if (agg instanceof Children) { converter = AggChildren; }
else if (agg instanceof Nested) { converter = AggNested; }
else if (agg instanceof ReverseNested) { converter = AggReverseNested; }
return requireNonNull(converter, "unable to detect " + agg.getName() + ":" + agg.getClass()).getWith(agg.getName(), agg);
}
private static Aggregation.Builder addSingleBucketChildren(String label, Aggregation.Builder builder, SingleBucketAggregation single) {
Bucket.Builder bucket = builder.bucketBuilder().key(label).count(single.getDocCount());
for (org.elasticsearch.search.aggregations.Aggregation child : single.getAggregations()) { bucket.aggregation(detectAgg(child));}
return builder;
}
private static void addMultiBucketAgg(Aggregation.Builder builder, List<? extends MultiBucketsAggregation.Bucket> buckets) {
for (MultiBucketsAggregation.Bucket bucket : buckets) {
Bucket.Builder buckBldr = builder.bucketBuilder().key(bucket.getKeyAsString())
.value(bucket.getKey()).count(bucket.getDocCount());
if (bucket.getAggregations() == null) continue;
for (org.elasticsearch.search.aggregations.Aggregation child : bucket.getAggregations()) { buckBldr.aggregation(detectAgg(child)); }
}
}
private static Aggregation.Builder getStats(String label, AggregationType aggregationType, Stats stats) {
Aggregation.Builder builder = aggregationBuilder().label(label).type(aggregationType).value("Count", stats.getCount())
.value("Max", stats.getMax()).value("Min", stats.getMin()).value("Avg", stats.getAvg()).value("Sum", stats.getSum());
if(stats instanceof ExtendedStats) {
ExtendedStats estats = (ExtendedStats) stats;
builder.value("SumOfSquares", estats.getSumOfSquares()).value("StdDeviation", estats.getStdDeviation())
.value("Variance", estats.getVariance());
}
return builder;
}
}
| 55.930818
| 144
| 0.714832
|
1632ab6710a90129424a24b06aeb0e55ed6f3ded
| 26,066
|
package io.elastic.jdee1;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonString;
import javax.json.JsonValue;
import javax.swing.table.DefaultTableModel;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.jdedwards.system.xml.XMLRequest;
public class Utils {
private static final Logger logger = LoggerFactory.getLogger(Utils.class);
private Document XMLDoc;
private Document XMLResponseDoc;
private Document XMLServer;
public static final String CFG_USER = "user";
public static final String CFG_PASSWORD = "password";
public static final String CFG_ENV = "environment";
public static final String CFG_FUNCTION = "function"; // function name for verification @ creds
public static final String CFG_SERVER = "server";
public static final String CFG_PORT = "port";
public static final String SESSION = "session";
public static final String FUNCTION_NAME = "name"; // function name @ runtime processing
public static final String ERROR_MESSAGE = "error_message";
public static final String ERROR_CODE = "error_code";
public static final String RESULT = "result";
public static final String PT_SESSION = "pt_session"; // passthrough session value
/* keys below for verifyCredentials action only */
public static final String CFG_USER_FUNC = "userFunc";
public static final String CFG_PASSWORD_FUNC = "passwordFunc";
public static final String CFG_ENV_FUNC = "environmentFunc";
public static final String CFG_FUNCTION_FUNC = "functionFunc"; // function name for verification @ creds
public static final String CFG_SERVER_FUNC = "serverFunc";
public static final String CFG_PORT_FUNC = "portFunc";
HashMap<Integer, String> errorReturnCodes = new HashMap<Integer, String>() {{
put(1, "root XML element is not a jdeRequest or jdeResponse.");
put(2,
"jdeRequest user identification unknown. Check the user, pwd and environment attributes.");
put(3, "XML Parse error at line.");
put(4, "Fatal XML Parse error at line.");
put(5, "Error during parser initialization, server not configured correctly.");
put(6, "Unknown parse error.");
put(7, "Request session attribute is invalid.");
put(8, "Request type attribute is invalid.");
put(9, "Request type attribute not given.");
put(10,
"Request session attribute is invalid, referenced process 'processid' no longer exists.");
put(11, "jdeRequest child element is invalid or unknown.");
put(12,
"Environment 'Env name' could not be initialized for user, check user, pwd and environment attribute values.");
put(13, "jdeXMLRequest parameter invalid");
put(14, "Connection to OneWorld failed");
put(15, "jdeXMLRequest send failed");
put(16, "jdeXMLResponse receive failed");
put(17, "jdeXMLResponse memory allocation failed");
put(99, "invalid BSFN Name");
}};
public String session = "";
public Boolean executed = false;
public String returnCode = "-1";
public String errors = "";
String[] columnNames = new String[]{"Parameter", "Input Value", "Output Value"};
Object[][] Parameters = new Object[][]{{"", "", ""}};
public DefaultTableModel BSFNParmsModel = new DefaultTableModel(Parameters, columnNames);
private String getSessionIDFromXMLDocument(Document doc) {
String ret = null;
try {
NodeList returncodelist = doc.getElementsByTagName("jdeResponse");
Node returncode = returncodelist.item(0);
NamedNodeMap attributes = returncode.getAttributes();
Node att = attributes.getNamedItem("session");
ret = att.getNodeValue();
} catch (Exception var7) {
ret = "";
}
return ret;
}
public JsonObject getTemplate_actionPerformed(final JsonObject config, final JsonObject snapshot,
final JsonObject body) {
JsonObjectBuilder properties = Json.createObjectBuilder();
JsonObjectBuilder field = Json.createObjectBuilder();
JsonObjectBuilder result = Json.createObjectBuilder();
executed = false;
String response = "";
String function = getFunction(config, snapshot, body);
logger.info("Function: {}", function);
if (function.compareTo("") != 0) {
clearBSFNModel();
errors = "";
Node node = null;
logger.info("Config: {}", config.toString());
try {
node = createTemplateRequestXMLDocument(config, snapshot, body);
} catch (ParserConfigurationException var12) {
errors = "Failed to create XML document for get template.\n" + var12.toString();
logger.info("Error: {}", errors);
properties.add(Utils.ERROR_CODE, returnCode);
properties.add(Utils.ERROR_MESSAGE, errors);
properties.add(Utils.RESULT, result.build());
return properties.build();
}
try {
response = executeXMLRequest(config, node);
} catch (Exception var11) {
errors = "Failed to Execute XML request for get template.\n" + var11.toString();
logger.info("Error: {}", errors);
properties.add(Utils.ERROR_CODE, returnCode);
properties.add(Utils.ERROR_MESSAGE, errors);
properties.add(Utils.RESULT, result.build());
return properties.build();
}
try {
XMLDoc = convertStringToXMLDocument(response);
} catch (Exception var10) {
errors = "Failed to convert response to XML document.\n" + var10.toString();
logger.info("Error: {}", errors);
properties.add(Utils.ERROR_CODE, returnCode);
properties.add(Utils.ERROR_MESSAGE, errors);
properties.add(Utils.RESULT, result.build());
return properties.build();
}
String ret = getReturnCodeFromXMLDocument(XMLDoc);
if (ret.compareTo("99") == 0) {
errors = "Failed to retrieve template\n";
showTemplateErrorMessage(XMLDoc);
} else {
NodeList parms = XMLDoc.getElementsByTagName("param");
for (int i = 0; i < parms.getLength(); ++i) {
NamedNodeMap attributes = parms.item(i).getAttributes();
Node x = attributes.getNamedItem("name");
String[] row = new String[]{x.getNodeValue(), "", ""};
String name = x.getNodeValue();
field.add("title", name)
.add("type", "string");
properties.add(name, field);
BSFNParmsModel.addRow(row);
}
executed = true;
}
}
return properties.build();
}
private String executeXMLRequest(final JsonObject config, Node node)
throws UnsupportedEncodingException, IOException {
String request = convertXMLDocumentToString(node);
final String server = getServer(config, null);
final String port = getPort(config, null);
XMLRequest xml = new XMLRequest(server, Integer.parseInt(port), request);
return xml.execute();
}
private Node createTemplateRequestXMLDocument(final JsonObject config, final JsonObject snapshot,
final JsonObject body)
throws ParserConfigurationException {
Node node = null;
final String user = getUser(config, snapshot);
final String password = getPassword(config, snapshot);
final String environment = getEnv(config, snapshot);
final String function = getFunction(config, snapshot, body);
DocumentBuilder Builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document Doc = Builder.newDocument();
Element element = Doc.createElement("jdeRequest");
element.setAttribute("type", "callmethod");
element.setAttribute("user", user);
element.setAttribute("pwd", password);
element.setAttribute("environment", environment);
element.setAttribute("session", session);
Doc.appendChild(element);
Element element2 = Doc.createElement("callMethodTemplate");
element2.setAttribute("app", "");
element2.setAttribute("name", function);
element.appendChild(element2);
return Doc;
}
private String getReturnCodeFromXMLDocument(Document doc) {
String ret = null;
try {
NodeList returncodelist = doc.getElementsByTagName("returnCode");
Node returncode = returncodelist.item(0);
NamedNodeMap attributes = returncode.getAttributes();
Node att = attributes.getNamedItem("code");
ret = att.getNodeValue();
} catch (Exception var7) {
ret = "";
}
return ret;
}
private Document convertStringToXMLDocument(String XML)
throws ParserConfigurationException, SAXException, IOException {
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(XML));
doc = db.parse(is);
return doc;
}
private String convertXMLDocumentToString(Node node) {
try {
Source source = new DOMSource(node);
StringWriter stringWriter = new StringWriter();
Result result = new StreamResult(stringWriter);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.transform(source, result);
return stringWriter.getBuffer().toString();
} catch (Exception var7) {
return var7.toString();
}
}
private void clearBSFNModel() {
int j = BSFNParmsModel.getRowCount();
for (int i = 0; i < j; ++i) {
BSFNParmsModel.removeRow(0);
}
}
private void showTemplateErrorMessage(Document doc) {
String ret = null;
try {
NodeList returncodelist = doc.getElementsByTagName("returnCode");
Node returncode = returncodelist.item(0);
ret = returncode.getFirstChild().getNodeValue();
} catch (Exception var5) {
ret = "";
}
errors = ret;
}
public JsonObject jbExecute_actionPerformed(JsonObject config, JsonObject body,
JsonObject snapshot)
throws ParserConfigurationException, IOException, SAXException, NumberFormatException {
errors = "";
String ret;
String pt_session;
JsonObjectBuilder properties = Json.createObjectBuilder();
JsonObjectBuilder field = Json.createObjectBuilder();
JsonObjectBuilder result = Json.createObjectBuilder();
getTemplate_actionPerformed(config, snapshot, body);
StringBuilder keys = new StringBuilder();
StringBuilder values = new StringBuilder();
StringBuilder setString = new StringBuilder();
int indexParam = 0;
if (body != null) {
for (Map.Entry<String, JsonValue> entry : body.entrySet()) {
if (entry.getValue().toString().compareTo("") != 0) {
setParameterValue(entry.getKey().toString(), ((JsonString) entry.getValue()).getString());
}
}
}
setCredentialsInXMLDocument(config, snapshot, body, false);
String response = null;
try {
response = executeXMLRequest(config, XMLDoc);
} catch (IOException var13) {
errors = "Failed to Execute XMLRequest for function call.\n" + var13.toString();
properties.add(Utils.ERROR_CODE, returnCode);
properties.add(Utils.ERROR_MESSAGE, errors);
properties.add(Utils.RESULT, result.build());
return properties.build();
}
try {
XMLResponseDoc = convertStringToXMLDocument(response);
} catch (Exception var12) {
errors = "Failed to Execute XMLRequest for function call.\n" + var12.toString();
var12.printStackTrace();
properties.add(Utils.ERROR_CODE, returnCode);
properties.add(Utils.ERROR_MESSAGE, errors);
properties.add(Utils.RESULT, result.build());
return properties.build();
}
ret = getReturnCodeFromXMLDocument(XMLResponseDoc);
returnCode = ret;
logger.info("Response: {}", response);
logger.info("returnCode: {}", returnCode);
if (!returnCode.equals("") && (Integer.parseInt(returnCode) == 7
|| Integer.parseInt(returnCode) == 10)) {
logger.info("Session is invalid. Error message: \"{}\". Try to get a new session",
errorReturnCodes.get(Integer.parseInt(returnCode)));
setCredentialsInXMLDocument(config, snapshot, body, true);
response = null;
try {
response = executeXMLRequest(config, XMLDoc);
} catch (IOException var13) {
errors = "Failed to Execute XMLRequest for function call.\n" + var13.toString();
properties.add(Utils.ERROR_CODE, returnCode);
properties.add(Utils.ERROR_MESSAGE, errors);
properties.add(Utils.RESULT, result.build());
return properties.build();
}
try {
XMLResponseDoc = convertStringToXMLDocument(response);
} catch (Exception var12) {
errors = "Failed to Execute XMLRequest for function call.\n" + var12.toString();
var12.printStackTrace();
properties.add(Utils.ERROR_CODE, returnCode);
properties.add(Utils.ERROR_MESSAGE, errors);
properties.add(Utils.RESULT, result.build());
return properties.build();
}
ret = getReturnCodeFromXMLDocument(XMLResponseDoc);
returnCode = ret;
}
Node node = null;
logger.info("Session: {}", session);
if (!returnCode.equals("") && Integer.parseInt(returnCode) > 0) {
errors = errorReturnCodes.get(Integer.parseInt(returnCode));
logger.info("Error: {} - {}", returnCode, errors);
NodeList errors = XMLResponseDoc.getElementsByTagName("error");
if (errors.getLength() > 0) {
for (int i = 0; i < errors.getLength(); ++i) {
node = errors.item(i);
String errorMessage = node.getTextContent();
NamedNodeMap attributes = node.getAttributes();
Node x = attributes.getNamedItem("code");
String errorCode = x.getNodeValue();
Node textNode = null;
properties.add(ERROR_CODE, errorCode);
properties.add(ERROR_MESSAGE, errorMessage);
properties.add(RESULT, Json.createObjectBuilder().build());
return properties.build();
}
}
}
pt_session = getSessionIDFromXMLDocument(XMLResponseDoc);
NodeList parms = XMLResponseDoc.getElementsByTagName("param");
for (int i = 0; i < parms.getLength(); ++i) {
node = parms.item(i);
NamedNodeMap attributes = node.getAttributes();
Node x = attributes.getNamedItem("name");
String parmname = x.getNodeValue();
Node textNode = null;
if ((textNode = node.getFirstChild()) != null) {
int index = getParameterIndexByName(parmname);
if (index != -1) {
BSFNParmsModel.setValueAt(textNode.getNodeValue(), index, 2);
String name = x.getNodeValue();
field.add("title", name)
.add("type", "string");
result.add(name, textNode.getNodeValue());
}
}
}
properties.add(Utils.PT_SESSION, pt_session);
properties.add(Utils.SESSION, (session != null && !session.isEmpty()) ? session : getSession(snapshot, body));
properties.add(Utils.ERROR_CODE, returnCode);
properties.add(Utils.ERROR_MESSAGE, "");
properties.add(Utils.RESULT, result.build());
XMLResponseDoc.getElementsByTagName("jdeResponse");
displayBSFNErrors(XMLResponseDoc);
return properties.build();
}
public void setParameterValue(String key, String value) {
NodeList parms = XMLDoc.getElementsByTagName("param");
for (int i = 0, len = parms.getLength(); i < len; i++) {
Element elm = (Element) parms.item(i);
if (elm.getAttribute("name").contains(key)) {
Node node = parms.item(i);
Node textNode = null;
if ((textNode = node.getFirstChild()) == null) {
textNode = XMLDoc.createTextNode(value);
node.appendChild(textNode);
}
if (textNode != null) {
textNode.setNodeValue(value);
}
}
}
}
private void setCredentialsInXMLDocument(JsonObject config, JsonObject snapshot, JsonObject body,
boolean resetSession) throws DOMException {
NodeList requestlist;
try {
requestlist = XMLDoc.getElementsByTagName("jdeRequest");
} catch (Exception err) {
throw new RuntimeException("Connection to the instance failed");
}
Node request = requestlist.item(0);
String user = getUser(config, snapshot);
String password = getPassword(config, snapshot);
String env = getEnv(config, snapshot);
String session = (resetSession) ? "" : getSession(snapshot, body);
try {
NamedNodeMap attributes = request.getAttributes();
Node att = attributes.getNamedItem(Utils.CFG_USER);
att.setNodeValue(user);
att = attributes.getNamedItem("pwd");
att.setNodeValue(password);
att = attributes.getNamedItem(Utils.CFG_ENV);
att.setNodeValue(env);
att = attributes.getNamedItem(Utils.SESSION);
att.setNodeValue(session);
} catch (Exception var6) {
var6.printStackTrace();
}
}
private int getParameterIndexByName(String parmname) {
for (int i = 0; i < this.BSFNParmsModel.getRowCount(); ++i) {
String parm = null;
parm = (String) this.BSFNParmsModel.getValueAt(i, 0);
if (parm.compareTo(parmname) == 0) {
return i;
}
}
return -1;
}
private void displayBSFNErrors(Document doc) {
String codestring = "";
String message = "";
try {
NodeList errorlist = doc.getElementsByTagName("error");
for (int i = 0; i < errorlist.getLength(); ++i) {
Node error = errorlist.item(i);
NamedNodeMap attributes = error.getAttributes();
Node code = attributes.getNamedItem("code");
if (code != null) {
codestring = code.getNodeValue();
}
message = error.getFirstChild().getNodeValue();
errors += codestring + " - " + message + "\n";
}
} catch (Exception var9) {
errors += "Failed to get error";
}
}
public static String documentToString(Document doc) {
try {
StringWriter sw = new StringWriter();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.transform(new DOMSource(doc), new StreamResult(sw));
return sw.toString();
} catch (Exception ex) {
throw new RuntimeException("Error converting to String", ex);
}
}
public void addAttribute(Document doc, String name, String value) {
Element root = doc.getDocumentElement();
Element person = (Element) root.getFirstChild();
person.setAttribute(name, value);
}
public static JsonObject removeProperty(JsonObject origin, String key) {
JsonObjectBuilder builder = Json.createObjectBuilder();
Integer index = 0;
for (Map.Entry<String, JsonValue> entry : origin.entrySet()) {
if (entry.getKey().equals(key)) {
continue;
} else {
builder.add(entry.getKey(), entry.getValue());
}
}
return builder.build();
}
public static String getNonNullString(final JsonObject config, final String key) {
Object value = "";
try {
Set<Entry<String, JsonValue>> kvPairs = config.entrySet();
for (Map.Entry<String, JsonValue> kvPair : kvPairs) {
if (kvPair.getKey().equals(key)) {
value = config.get(key);
}
}
} catch (NullPointerException e) {
logger.info("key {} doesn't have any mapping: {}", key, e);
e.printStackTrace();
} catch (ClassCastException e) {
logger.info("key {} doesn't have any mapping: {}", key, e);
e.printStackTrace();
}
return value.toString().replaceAll("\"", "");
}
private static String getRequiredNonEmptyString(final JsonObject config, final String key,
final String message) {
final String value = config.getString(key);
if (value == null || value.isEmpty()) {
throw new RuntimeException(message);
}
return value;
}
private static String getUser(JsonObject config, JsonObject snapshot) {
String user = "";
if (snapshot.containsKey(CFG_USER)
&& Utils.getNonNullString(snapshot, CFG_USER).length() != 0) {
user = snapshot.getString(CFG_USER);
} else if (config.containsKey(CFG_USER)
&& Utils.getNonNullString(config, CFG_USER).length() != 0) {
user = config.getString(CFG_USER);
}
if (config.containsKey(CFG_USER_FUNC)
&& Utils.getNonNullString(config, CFG_USER_FUNC).length() != 0) {
user = config.getString(CFG_USER_FUNC);
}
if (user.length() == 0) {
throw new RuntimeException("Username is required");
}
return user;
}
private static String getPassword(JsonObject config, JsonObject snapshot) {
String password = "";
if (snapshot.containsKey(CFG_PASSWORD)
&& Utils.getNonNullString(snapshot, CFG_PASSWORD).length() != 0) {
password = snapshot.getString(CFG_PASSWORD);
} else if (config.containsKey(CFG_PASSWORD)
&& Utils.getNonNullString(config, CFG_PASSWORD).length() != 0) {
password = config.getString(CFG_PASSWORD);
}
if (config.containsKey(CFG_PASSWORD_FUNC)
&& Utils.getNonNullString(config, CFG_PASSWORD_FUNC).length() != 0) {
password = config.getString(CFG_PASSWORD_FUNC);
}
if (password.length() == 0) {
throw new RuntimeException("Password is required");
}
return password;
}
private static String getEnv(JsonObject config, JsonObject snapshot) {
String env = "";
if (snapshot.containsKey(CFG_ENV)
&& Utils.getNonNullString(snapshot, CFG_ENV).length() != 0) {
env = snapshot.getString(CFG_ENV);
} else if (config.containsKey(CFG_ENV)
&& Utils.getNonNullString(config, CFG_ENV).length() != 0) {
env = config.getString(CFG_ENV);
}
if (config.containsKey(CFG_ENV_FUNC)
&& Utils.getNonNullString(config, CFG_ENV_FUNC).length() != 0) {
env = config.getString(CFG_ENV_FUNC);
}
if (env.length() == 0) {
throw new RuntimeException("Environment is required");
}
return env;
}
private static String getFunction(JsonObject config, JsonObject snapshot, JsonObject body) {
String function = "";
if (snapshot.containsKey(CFG_FUNCTION)
&& Utils.getNonNullString(snapshot, CFG_FUNCTION).length() != 0) {
function = snapshot.getString(CFG_FUNCTION);
} else if (config.containsKey(FUNCTION_NAME)
&& Utils.getNonNullString(config, FUNCTION_NAME).length() != 0) {
function = config.getString(FUNCTION_NAME);
} else if (config.containsKey(CFG_FUNCTION)
&& Utils.getNonNullString(config, CFG_FUNCTION).length() != 0) {
function = config.getString(CFG_FUNCTION);
}
if (config.containsKey(CFG_FUNCTION_FUNC)
&& Utils.getNonNullString(config, CFG_FUNCTION_FUNC).length() != 0) {
function = config.getString(CFG_FUNCTION_FUNC);
}
if (function.length() == 0) {
throw new RuntimeException("Function is required");
}
return function;
}
private static String getServer(JsonObject config, JsonObject snapshot) {
String server = "";
if (snapshot != null && snapshot.containsKey(CFG_SERVER)
&& Utils.getNonNullString(snapshot, CFG_SERVER).length() != 0) {
server = snapshot.getString(CFG_SERVER);
} else if (config.containsKey(CFG_SERVER)
&& Utils.getNonNullString(config, CFG_SERVER).length() != 0) {
server = config.getString(CFG_SERVER);
}
if (config.containsKey(CFG_SERVER_FUNC)
&& Utils.getNonNullString(config, CFG_SERVER_FUNC).length() != 0) {
server = config.getString(CFG_SERVER_FUNC);
}
if (server.length() == 0 ) {
throw new RuntimeException("Server is required");
}
return server;
}
private static String getPort(JsonObject config, JsonObject snapshot) {
String port = "";
if (snapshot != null && snapshot.containsKey(CFG_PORT)
&& Utils.getNonNullString(snapshot, CFG_PORT).length() != 0) {
port = snapshot.getString(CFG_PORT);
} else if (config.containsKey(CFG_PORT)
&& Utils.getNonNullString(config, CFG_PORT).length() != 0) {
port = config.getString(CFG_PORT);
}
if (config.containsKey(CFG_PORT_FUNC)
&& Utils.getNonNullString(config, CFG_PORT_FUNC).length() != 0) {
port = config.getString(CFG_PORT_FUNC);
}
if (port.length() == 0) {
throw new RuntimeException("Port is required");
}
return port;
}
private static String getSession(JsonObject snapshot, JsonObject body) {
String session = "";
if (snapshot.containsKey(SESSION)
&& Utils.getNonNullString(snapshot, SESSION).length() != 0) {
session = snapshot.getString(SESSION);
}
if (body!= null && body.containsKey(PT_SESSION)
&& Utils.getNonNullString(body, PT_SESSION).length() != 0) {
session = body.getString(PT_SESSION);
}
return session;
}
}
| 35.706849
| 119
| 0.668687
|
acc3658daf7909c6391a456e55769992e1d75747
| 67
|
interface A {
}
class C implements A {
public interface B {}
}
| 11.166667
| 25
| 0.641791
|
0d47855d7fc36f745fbc8c085b8268facb1eebed
| 10,725
|
/* See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* Esri Inc. 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 com.esri.gpt.framework.sql;
import com.esri.gpt.framework.collection.StringSet;
import com.esri.gpt.framework.util.LogUtil;
import com.esri.gpt.framework.util.Val;
import java.util.logging.Level;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
/**
* Configuration reference for a database.
* <p>
* The reference usually represents a JNDI based connection.
* It can also represent a direct connection (driver/url/user/pwd), but this
* is usually limited to a non-production environment.
*/
public final class DatabaseReference {
// class variables =============================================================
// instance variables ==========================================================
private String _directDriver = "";
private String _directPassword = "";
private String _directUrl = "";
private String _directUsername = "";
private boolean _isJndiBased = true;
private DataSource _jndiDataSource = null;
private String _jndiName = "";
private String _refName = "";
private StringSet _tags = new StringSet();
// constructors ================================================================
/** Default constructor. */
public DatabaseReference() {}
// properties ==================================================================
/**
* Gets the driver class name for a direct database reference.
* @return the database driver class name
*/
public String getDirectDriverClassName() {
return _directDriver;
}
/**
* Sets the driver class name for a direct database reference.
* @param driver the database driver class name
*/
public void setDirectDriverClassName(String driver) {
_directDriver = Val.chkStr(driver);
}
/**
* Gets the password for a direct database reference.
* @return the password
*/
public String getDirectPassword() {
return _directPassword;
}
/**
* Sets the password for a direct database reference.
* @param password the password
*/
public void setDirectPassword(String password) {
_directPassword = password;
}
/**
* Gets the URL for a direct database reference.
* @return the database url
*/
public String getDirectUrl() {
return _directUrl;
}
/**
* Sets the URL for a direct database reference.
* @param url the database url
*/
public void setDirectUrl(String url) {
_directUrl = Val.chkStr(url);
}
/**
* Gets the username for a direct database reference.
* @return the username
*/
public String getDirectUsername() {
return _directUsername;
}
/**
* Sets the username for a direct database reference.
* @param username the username
*/
public void setDirectUsername(String username) {
_directUsername = Val.chkStr(username);
}
/**
* Gets the JNDI based reference status.
* @return <b>true</b> if this reference is JNDI based
*/
public boolean getIsJndiBased() {
return _isJndiBased;
}
/**
* Sets the JNDI based reference status.
* @param isJndiBased <b>true</b> if this reference is JNDI based
*/
public void setIsJndiBased(boolean isJndiBased) {
_isJndiBased = isJndiBased;
}
/**
* Gets the JNDI based DataSource for the reference.
* @return the data source
* @throws NamingException if a JNDI naming exception occurs
*/
protected DataSource getJndiDataSource()
throws NamingException {
if (_jndiDataSource == null) {
_jndiDataSource = openJndiDataSource(getJndiName());
}
return _jndiDataSource;
}
/**
* Gets the name for a JNDI based database reference.
* @return the JNDI name
*/
public String getJndiName() {
return _jndiName;
}
/**
* Sets the name for a JNDI based database reference.
* @param jndiName the JNDI name
*/
public void setJndiName(String jndiName) {
_jndiName = Val.chkStr(jndiName);
}
/**
* Gets the label for the database reference.
* @return the reference label
*/
protected String getReferenceLabel() {
if (getIsJndiBased()) {
return getReferenceName()+", jndiName: "+getJndiName();
} else {
return getReferenceName()+", url: "+getDirectUrl();
}
}
/**
* Gets the name for the database reference.
* @return the name
*/
public String getReferenceName() {
return _refName;
}
/**
* Sets the name for the database reference.
* @param referenceName the reference name
*/
public void setReferenceName(String referenceName) {
_refName = Val.chkStr(referenceName);
}
/**
* Gets the tags associated with the reference.
* @return the associated tags
*/
public StringSet getTags() {
return _tags;
}
// methods =====================================================================
/**
* Closes a JDBC connection.
* <br/>Executes the close() method against the JDBC connection.
* @param con the connection to close
*/
public void closeConnection(Connection con) {
if (con != null) {
try {
if (!con.isClosed()) {
LogUtil.getLogger().fine("Closing connection for "+getReferenceLabel());
con.close();
}
} catch (Exception e) {
String sMsg = "Unable to close connection for "+getReferenceLabel();
LogUtil.getLogger().log(Level.SEVERE,sMsg,e);
}
}
}
/**
* Makes a JDBC connection from based upon the configuration of the database reference.
* @return the JDBC connection
* @throws ClassNotFoundException if the database driver class was not found
* @throws NamingException if a JNDI naming exception occurs
* @throws SQLException if an SQL exception occurs while establishing the connection
*/
public Connection openConnection()
throws ClassNotFoundException, NamingException, SQLException {
Connection con = null;
String sMsg;
// obtain the connection
sMsg = "Opening connection for "+getReferenceLabel();
LogUtil.getLogger().finer(sMsg);
if (getIsJndiBased()) {
con = openJndiConnection();
} else {
con = openDirectConnection();
}
if (con != null) {
con.setAutoCommit(true);
}
// log information about the connection obtained
try {
//System.err.println(con.getMetaData().getDatabaseMajorVersion());
//System.err.println(con.getMetaData().getDatabaseMinorVersion());
//System.err.println(con.getMetaData().supportsGetGeneratedKeys());
sMsg = "Connection opened for "+getReferenceLabel();
sMsg += ", productName: "+con.getMetaData().getDatabaseProductName();
sMsg += ", driver: "+con.getMetaData().getDriverName();
sMsg += " "+con.getMetaData().getDriverVersion();
LogUtil.getLogger().fine(sMsg);
} catch (Exception e2) {
LogUtil.getLogger().log(Level.WARNING,"Unable to determine connection metaData",e2);
}
return con;
}
/**
* Opens a direct JDBC connection based upon the driver, url, username and password.
* @return the JDBC connection
* @throws ClassNotFoundException if the database driver class was not found
* @throws SQLException if an SQL exception occurs while establishing the connection
*/
protected Connection openDirectConnection()
throws ClassNotFoundException, SQLException {
Class.forName(getDirectDriverClassName());
return DriverManager.getConnection(
getDirectUrl(),getDirectUsername(),getDirectPassword());
}
/**
* Opens a JDBC connection from the JNDI DataSource associated with the JNDI name.
* @return the JDBC connection
* @throws NamingException if a JNDI naming exception occurs
* @throws SQLException if an SQL exception occurs while establishing the connection
*/
protected Connection openJndiConnection()
throws NamingException, SQLException {
DataSource dataSource = getJndiDataSource();
return dataSource.getConnection();
}
/**
* Opens the DataSource associated with the JNDI name.
* @param jndiName the associated JNDI name
* @return the associated data source
* @throws NamingException if a JNDI naming exception occurs
*/
protected DataSource openJndiDataSource(String jndiName)
throws NamingException {
DataSource dataSource = null;
InitialContext initContext = new InitialContext();
try {
dataSource = (DataSource)initContext.lookup(jndiName);
} catch (NamingException e1) {
try {
dataSource = (DataSource)initContext.lookup("java:comp/env/"+jndiName);
} catch (NamingException e2) {
Context envContext = (Context)initContext.lookup("java:comp/env");
dataSource = (DataSource)envContext.lookup(jndiName);
}
}
return dataSource;
}
/**
* Tests the connection associated with the database reference.
* <br/>A connection is opened, then immediately closed.
*/
protected void testConnection() {
LogUtil.getLogger().finer("Testing connection for "+getReferenceLabel());
Connection con = null;
try {
con = openConnection();
} catch (Throwable t) {
LogUtil.getLogger().log(Level.SEVERE,"Connection test failed.",t);
} finally {
closeConnection(con);
}
}
/**
* Returns a string representation of this object.
* @return the string
*/
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(getClass().getName()).append(" (\n");
sb.append(" name=").append(getReferenceName()).append("\n");
if (getIsJndiBased()) {
sb.append(" jndiName=").append(getJndiName()).append("\n");
} else {
sb.append(" driver=").append(getDirectDriverClassName()).append("\n");
sb.append(" url=").append(getDirectUrl()).append("\n");
sb.append(" username=").append(getDirectUsername()).append("\n");
sb.append(" password=").append(getDirectPassword()).append("\n");
}
sb.append(" referenceTags=").append(getTags()).append("\n");
sb.append(") ===== end ").append(getClass().getName());
return sb.toString();
}
}
| 31.086957
| 89
| 0.670396
|
925afb5453c60ebd148b8fc6621ca7a9e883edb9
| 1,364
|
package homework.day01;
import java.util.Random;
import java.util.Scanner;
/**
* 生成一个4位验证码(数字和字母的组合)
* 然后输出到控制台并提示用户输入该验证码,只要用户输入正确(无论大小写都算),
* 就输出:验证码正确,否则输出:验证码错误
*
*
* 验证码如何生成?
* 思路导向填空:
* 1:要先确定生成的内容范围(列出所有可以出现的字符):
* abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXY3456789
* 01 ... length-1
*
* 2:先思考如何生成其中的一个字符呢?
* 2.1:确定怎么保存这些可以出现的字符:
*
* 2.2:怎么能随机抽选一个
*
* 3:既然可以生成一个,如何做到生成4个或更多个?
*
* 4:怎么在生成这些字符的过程中将他们组成一个字符串?
*
* 5:获取到用户输入的字符串后怎么与之比较,要利用到哪些字符串操作?
*
*
* @author Xiloer
*
*/
public class Test06 {
public static void main(String[] args) {
String chs = "abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXY3456789";
Random random = new Random();
int length = chs.length();
StringBuilder buf = new StringBuilder(4);
//生成4位验证码
buf.append(chs.charAt(random.nextInt(length)))
.append(chs.charAt(random.nextInt(length)))
.append(chs.charAt(random.nextInt(length)))
.append(chs.charAt(random.nextInt(length)));
//将生成的验证码转换为 String类型, 为了后续调用忽略大小写比较做准备
String code = buf.toString();
System.out.println(code);
Scanner in = new Scanner(System.in);
System.out.print("输入你的验证码:");
String input = in.nextLine();
if(code.equalsIgnoreCase(input)){
System.out.println("验证码一致");
}else{
System.out.println("验证码错误!");
}
}
}
| 20.666667
| 73
| 0.664223
|
10fc23ca7353f5b912b0fd70ade616e146b4621a
| 1,989
|
package com.socket.pad.paddemo.Utils;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import com.github.mikephil.charting.animation.ChartAnimator;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.interfaces.dataprovider.LineDataProvider;
import com.github.mikephil.charting.renderer.LineChartRenderer;
import com.github.mikephil.charting.utils.MPPointD;
import com.github.mikephil.charting.utils.Transformer;
import com.github.mikephil.charting.utils.Utils;
import com.github.mikephil.charting.utils.ViewPortHandler;
import java.util.ArrayList;
import java.util.List;
public class CustomLineChartRenderer extends LineChartRenderer {
private List<String> pressValues = new ArrayList<>();
public CustomLineChartRenderer(LineDataProvider chart, ChartAnimator animator, ViewPortHandler viewPortHandler) {
super(chart, animator, viewPortHandler);
}
@Override
public void drawValues(Canvas c) {
super.drawValues(c);
Paint paint =new Paint(Paint.ANTI_ALIAS_FLAG);//抗锯齿画笔
paint.setTextSize(Utils.convertDpToPixel(8));//设置字体大小
paint.setColor(Color.BLACK);
for (int i = 0,size = pressValues.size();i<size;i++){
LineDataSet lineDataSet = (LineDataSet) mChart.getLineData().getDataSets().get(i);
Transformer trans =mChart.getTransformer(lineDataSet.getAxisDependency());
String label = lineDataSet.getLabel();
MPPointD minPoint = trans.getPixelForValues(lineDataSet.getValues().get(lineDataSet.getValues().size()-1).getX(),lineDataSet.getValues().get(lineDataSet.getValues().size()-1).getY());
float x = (float)minPoint.x;
float y = (float)minPoint.y;
c.drawText(pressValues.get(i),x + Utils.convertDpToPixel(10),y + Utils.convertDpToPixel(3),paint);
}
}
public void addPressValue(String press){
pressValues.add(press);
}
}
| 39.78
| 195
| 0.731021
|
5e2b57dfa4a3dd0d5f6400e44c705bb85dfc261b
| 278
|
package br.com.treinamento.cleanarch.dataprovider.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import br.com.treinamento.cleanarch.dataprovider.entity.ClienteTable;
public interface ClienteRepository extends JpaRepository<ClienteTable, Long> {
}
| 30.888889
| 78
| 0.852518
|
95a983d82aa010bb261a41e67b48a8b0c5363a9f
| 2,529
|
package org.innovateuk.ifs.project.financechecks.workflow.financechecks.configuration;
import org.innovateuk.ifs.project.finance.resource.FundingRulesEvent;
import org.innovateuk.ifs.project.finance.resource.FundingRulesState;
import org.innovateuk.ifs.workflow.WorkflowStateMachineListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.statemachine.config.EnableStateMachineFactory;
import org.springframework.statemachine.config.StateMachineConfigurerAdapter;
import org.springframework.statemachine.config.builders.StateMachineConfigurationConfigurer;
import org.springframework.statemachine.config.builders.StateMachineStateConfigurer;
import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer;
import java.util.EnumSet;
import static org.innovateuk.ifs.project.finance.resource.FundingRulesEvent.*;
import static org.innovateuk.ifs.project.finance.resource.FundingRulesState.*;
/**
* Describes the workflow for the Funding Rules Approval process.
*/
@Configuration
@EnableStateMachineFactory(name = "fundingRulesStateMachineFactory")
public class FundingRulesWorkflow extends StateMachineConfigurerAdapter<FundingRulesState, FundingRulesEvent> {
@Override
public void configure(StateMachineConfigurationConfigurer<FundingRulesState, FundingRulesEvent> config) throws Exception {
config.withConfiguration().listener(new WorkflowStateMachineListener<>());
}
@Override
public void configure(StateMachineStateConfigurer<FundingRulesState, FundingRulesEvent> states) throws Exception {
states.withStates()
.initial(REVIEW)
.states(EnumSet.of(REVIEW, APPROVED));
}
@Override
public void configure(StateMachineTransitionConfigurer<FundingRulesState, FundingRulesEvent> transitions) throws Exception {
transitions
.withExternal()
.source(REVIEW)
.event(PROJECT_CREATED)
.target(REVIEW)
.and()
.withExternal()
.source(REVIEW)
.event(FUNDING_RULES_UPDATED)
.target(REVIEW)
.and()
.withExternal()
.source(REVIEW)
.event(FUNDING_RULES_APPROVED)
.target(APPROVED)
.and()
.withExternal()
.source(APPROVED)
.event(FUNDING_RULES_UPDATED)
.target(REVIEW);
}
}
| 40.142857
| 128
| 0.714512
|
52c305a6056e04a076de8ed0964621a28ef0cffd
| 1,503
|
/*
* Copyright © 2016 Cask Data, 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 co.cask.cdap.etl.batch.mapreduce;
import co.cask.cdap.api.dataset.lib.KeyValue;
import co.cask.cdap.api.mapreduce.MapReduceTaskContext;
import java.util.Map;
/**
* Writes to multiple named outputs.
*
* @param <KEY_OUT> the output key type
* @param <VAL_OUT> the output value type
*/
public class MultiOutputWriter<KEY_OUT, VAL_OUT> extends OutputWriter<KEY_OUT, VAL_OUT> {
// sink name -> outputs for that sink
private final Map<String, SinkOutput> sinkOutputs;
public MultiOutputWriter(MapReduceTaskContext<KEY_OUT, VAL_OUT> context, Map<String, SinkOutput> sinkOutputs) {
super(context);
this.sinkOutputs = sinkOutputs;
}
public void write(String sinkName, KeyValue<KEY_OUT, VAL_OUT> output) throws Exception {
for (String outputName : sinkOutputs.get(sinkName).getSinkOutputs()) {
context.write(outputName, output.getKey(), output.getValue());
}
}
}
| 33.4
| 113
| 0.739854
|
35a6e783b076d9bb246255345aa7964c49137719
| 816
|
/*
* I_Directory_Administration
* REST Schnittstelle zur Pflege der Verzeichniseinträge. Über diese Schnittstelle können Verzeichniseinträge inklusive Zertifikaten erzeugt, aktualisiert und gelöscht werden. Die Administration von Fachdaten erfolgt über Schnittstelle I_Directory_Application_Maintenance und wird durch die Fachanwendungen durchgeführt. Lesender Zugriff auf die Fachdaten ist mit Operation getDirectoryEntries in vorliegender Schnittstelle möglich.
*
* The version of the OpenAPI document: 1.6.3
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package de.gematik.ti.epa.vzd.client.invoker.auth;
public enum OAuthFlow {
accessCode, implicit, password, application
}
| 42.947368
| 432
| 0.805147
|
ec6c3e88f6523e412549f9232411229d20b26073
| 7,554
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.storageimportexport.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
/** Contains information about the Microsoft datacenter to which the drives should be shipped. */
@Fluent
public final class ShippingInformation {
@JsonIgnore private final ClientLogger logger = new ClientLogger(ShippingInformation.class);
/*
* The name of the recipient who will receive the hard drives when they are
* returned.
*/
@JsonProperty(value = "recipientName")
private String recipientName;
/*
* The first line of the street address to use when returning the drives.
*/
@JsonProperty(value = "streetAddress1")
private String streetAddress1;
/*
* The second line of the street address to use when returning the drives.
*/
@JsonProperty(value = "streetAddress2")
private String streetAddress2;
/*
* The city name to use when returning the drives.
*/
@JsonProperty(value = "city")
private String city;
/*
* The state or province to use when returning the drives.
*/
@JsonProperty(value = "stateOrProvince")
private String stateOrProvince;
/*
* The postal code to use when returning the drives.
*/
@JsonProperty(value = "postalCode")
private String postalCode;
/*
* The country or region to use when returning the drives.
*/
@JsonProperty(value = "countryOrRegion")
private String countryOrRegion;
/*
* Phone number of the recipient of the returned drives.
*/
@JsonProperty(value = "phone")
private String phone;
/*
* Additional shipping information for customer, specific to datacenter to
* which customer should send their disks.
*/
@JsonProperty(value = "additionalInformation", access = JsonProperty.Access.WRITE_ONLY)
private String additionalInformation;
/**
* Get the recipientName property: The name of the recipient who will receive the hard drives when they are
* returned.
*
* @return the recipientName value.
*/
public String recipientName() {
return this.recipientName;
}
/**
* Set the recipientName property: The name of the recipient who will receive the hard drives when they are
* returned.
*
* @param recipientName the recipientName value to set.
* @return the ShippingInformation object itself.
*/
public ShippingInformation withRecipientName(String recipientName) {
this.recipientName = recipientName;
return this;
}
/**
* Get the streetAddress1 property: The first line of the street address to use when returning the drives.
*
* @return the streetAddress1 value.
*/
public String streetAddress1() {
return this.streetAddress1;
}
/**
* Set the streetAddress1 property: The first line of the street address to use when returning the drives.
*
* @param streetAddress1 the streetAddress1 value to set.
* @return the ShippingInformation object itself.
*/
public ShippingInformation withStreetAddress1(String streetAddress1) {
this.streetAddress1 = streetAddress1;
return this;
}
/**
* Get the streetAddress2 property: The second line of the street address to use when returning the drives.
*
* @return the streetAddress2 value.
*/
public String streetAddress2() {
return this.streetAddress2;
}
/**
* Set the streetAddress2 property: The second line of the street address to use when returning the drives.
*
* @param streetAddress2 the streetAddress2 value to set.
* @return the ShippingInformation object itself.
*/
public ShippingInformation withStreetAddress2(String streetAddress2) {
this.streetAddress2 = streetAddress2;
return this;
}
/**
* Get the city property: The city name to use when returning the drives.
*
* @return the city value.
*/
public String city() {
return this.city;
}
/**
* Set the city property: The city name to use when returning the drives.
*
* @param city the city value to set.
* @return the ShippingInformation object itself.
*/
public ShippingInformation withCity(String city) {
this.city = city;
return this;
}
/**
* Get the stateOrProvince property: The state or province to use when returning the drives.
*
* @return the stateOrProvince value.
*/
public String stateOrProvince() {
return this.stateOrProvince;
}
/**
* Set the stateOrProvince property: The state or province to use when returning the drives.
*
* @param stateOrProvince the stateOrProvince value to set.
* @return the ShippingInformation object itself.
*/
public ShippingInformation withStateOrProvince(String stateOrProvince) {
this.stateOrProvince = stateOrProvince;
return this;
}
/**
* Get the postalCode property: The postal code to use when returning the drives.
*
* @return the postalCode value.
*/
public String postalCode() {
return this.postalCode;
}
/**
* Set the postalCode property: The postal code to use when returning the drives.
*
* @param postalCode the postalCode value to set.
* @return the ShippingInformation object itself.
*/
public ShippingInformation withPostalCode(String postalCode) {
this.postalCode = postalCode;
return this;
}
/**
* Get the countryOrRegion property: The country or region to use when returning the drives.
*
* @return the countryOrRegion value.
*/
public String countryOrRegion() {
return this.countryOrRegion;
}
/**
* Set the countryOrRegion property: The country or region to use when returning the drives.
*
* @param countryOrRegion the countryOrRegion value to set.
* @return the ShippingInformation object itself.
*/
public ShippingInformation withCountryOrRegion(String countryOrRegion) {
this.countryOrRegion = countryOrRegion;
return this;
}
/**
* Get the phone property: Phone number of the recipient of the returned drives.
*
* @return the phone value.
*/
public String phone() {
return this.phone;
}
/**
* Set the phone property: Phone number of the recipient of the returned drives.
*
* @param phone the phone value to set.
* @return the ShippingInformation object itself.
*/
public ShippingInformation withPhone(String phone) {
this.phone = phone;
return this;
}
/**
* Get the additionalInformation property: Additional shipping information for customer, specific to datacenter to
* which customer should send their disks.
*
* @return the additionalInformation value.
*/
public String additionalInformation() {
return this.additionalInformation;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
}
}
| 29.857708
| 118
| 0.66521
|
598d5dfc8ccaeb5e540530423e4c66e3fea08b5d
| 928
|
package org.phoenix.leetcode.learn.binarytree;
public class Problem12_LowestCommonAncestor {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) return null;
// if p or q value equals root
if (root.val == p.val || root.val == q.val) {
return root;
}
// Recur for left & right
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
// left & right both are not null
if (left != null && right != null) {
return root;
}
// return left if left is not null
return left != null ? left : right;
}
//Definition for a binary tree node.
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
}
| 28.121212
| 81
| 0.563578
|
190b6a0c9f4db14b8ff539d34627412fef4f3803
| 8,750
|
package me.joeleoli.fairfight.player;
import lombok.Getter;
import lombok.Setter;
import me.joeleoli.fairfight.FairFight;
import me.joeleoli.fairfight.check.impl.aimassist.*;
import me.joeleoli.fairfight.check.impl.autoclicker.*;
import me.joeleoli.fairfight.check.impl.badpackets.*;
import me.joeleoli.fairfight.check.impl.inventory.*;
import me.joeleoli.fairfight.check.impl.killaura.*;
import me.joeleoli.fairfight.check.impl.velocity.VelocityA;
import me.joeleoli.fairfight.check.ICheck;
import me.joeleoli.fairfight.check.impl.fly.FlyA;
import me.joeleoli.fairfight.check.impl.fly.FlyB;
import me.joeleoli.fairfight.check.impl.fly.FlyC;
import me.joeleoli.fairfight.check.impl.range.RangeA;
import me.joeleoli.fairfight.check.impl.scaffold.ScaffoldA;
import me.joeleoli.fairfight.check.impl.scaffold.ScaffoldB;
import me.joeleoli.fairfight.check.impl.scaffold.ScaffoldC;
import me.joeleoli.fairfight.check.impl.step.StepA;
import me.joeleoli.fairfight.check.impl.timer.TimerA;
import me.joeleoli.fairfight.check.impl.velocity.VelocityB;
import me.joeleoli.fairfight.check.impl.velocity.VelocityC;
import me.joeleoli.fairfight.check.impl.wtap.WTapA;
import me.joeleoli.fairfight.check.impl.wtap.WTapB;
import me.joeleoli.fairfight.client.ClientType;
import me.joeleoli.fairfight.client.EnumClientType;
import me.joeleoli.fairfight.util.CustomLocation;
import net.minecraft.server.v1_8_R3.BlockPosition;
import java.lang.reflect.Constructor;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
@Setter @Getter public final class PlayerData {
private static final Map<Class<? extends ICheck>, Constructor<? extends ICheck>> CONSTRUCTORS;
public static final Class<? extends ICheck>[] CHECKS;
private final Map<UUID, List<CustomLocation>> recentPlayerPackets;
private final Map<ICheck, Set<Long>> checkViolationTimes;
private final Map<Class<? extends ICheck>, ICheck> checkMap;
private final Map<Integer, Long> keepAliveTimes;
private final Map<ICheck, Double> checkVlMap;
private final Set<BlockPosition> fakeBlocks = new HashSet<>();
private final Set<CustomLocation> teleportLocations;
private Map<String, String> forgeMods;
private StringBuilder sniffedPacketBuilder;
private CustomLocation lastMovePacket;
private ClientType client;
private UUID lastTarget;
private String randomBanReason;
private double randomBanRate;
private boolean randomBan;
private boolean allowTeleport;
private boolean inventoryOpen;
private boolean setInventoryOpen;
private boolean sendingVape;
private boolean attackedSinceVelocity;
private boolean underBlock;
private boolean sprinting;
private boolean inLiquid;
private boolean instantBreakDigging;
private boolean fakeDigging;
private boolean onGround;
private boolean sniffing;
private boolean onStairs;
private boolean onCarpet;
private boolean placing;
private boolean banning;
private boolean digging;
private boolean inWeb;
private boolean onIce;
private boolean wasUnderBlock;
private boolean wasOnGround;
private boolean wasInLiquid;
private boolean wasInWeb;
private double lastGroundY;
private double velocityX;
private double velocityY;
private double velocityZ;
private long lastDelayedMovePacket;
private long lastAnimationPacket;
private long lastAttackPacket;
private long lastVelocity;
private long ping;
private int velocityH;
private int velocityV;
private int lastCps;
private int movementsSinceIce;
private int movementsSinceUnderBlock;
public PlayerData() {
this.recentPlayerPackets = new HashMap<>();
this.checkViolationTimes = new HashMap<>();
this.checkMap = new HashMap<>();
this.keepAliveTimes = new HashMap<>();
this.checkVlMap = new HashMap<>();
this.teleportLocations = Collections.newSetFromMap(new ConcurrentHashMap<CustomLocation, Boolean>());
this.sniffedPacketBuilder = new StringBuilder();
this.client = EnumClientType.VANILLA;
FairFight.getInstance().getServer().getScheduler().runTaskAsynchronously(FairFight.getInstance(), () -> {
PlayerData.CONSTRUCTORS.keySet().stream().map(o -> (Class<? extends ICheck>) o).forEach(check -> {
Constructor<? extends ICheck> constructor = PlayerData.CONSTRUCTORS.get(check);
try {
this.checkMap.put(check, constructor.newInstance(this));
} catch (Exception ex) {
ex.printStackTrace();
}
});
});
}
public <T extends ICheck> T getCheck(final Class<T> clazz) {
return (T) this.checkMap.get(clazz);
}
public CustomLocation getLastPlayerPacket(final UUID playerUUID, final int index) {
final List<CustomLocation> customLocations = this.recentPlayerPackets.get(playerUUID);
if (customLocations != null && customLocations.size() > index) {
return customLocations.get(customLocations.size() - index);
}
return null;
}
public void addPlayerPacket(final UUID playerUUID, final CustomLocation customLocation) {
List<CustomLocation> customLocations = this.recentPlayerPackets.get(playerUUID);
if (customLocations == null) {
customLocations = new ArrayList<>();
}
if (customLocations.size() == 20) {
customLocations.remove(0);
}
customLocations.add(customLocation);
this.recentPlayerPackets.put(playerUUID, customLocations);
}
public void addTeleportLocation(final CustomLocation teleportLocation) {
this.teleportLocations.add(teleportLocation);
}
public boolean allowTeleport(final CustomLocation teleportLocation) {
for (final CustomLocation customLocation : this.teleportLocations) {
final double delta = Math.pow(teleportLocation.getX() - customLocation.getX(), 2.0) +
Math.pow(teleportLocation.getZ() - customLocation.getZ(), 2.0);
if (delta <= 0.005) {
this.teleportLocations.remove(customLocation);
return true;
}
}
return false;
}
public double getCheckVl(final ICheck check) {
if (!this.checkVlMap.containsKey(check)) {
this.checkVlMap.put(check, 0.0);
}
return this.checkVlMap.get(check);
}
public void setCheckVl(double vl, final ICheck check) {
if (vl < 0.0) {
vl = 0.0;
}
this.checkVlMap.put(check, vl);
}
public boolean keepAliveExists(final int id) {
return this.keepAliveTimes.containsKey(id);
}
public long getKeepAliveTime(final int id) {
return this.keepAliveTimes.get(id);
}
public void removeKeepAliveTime(final int id) {
this.keepAliveTimes.remove(id);
}
public void addKeepAliveTime(final int id) {
this.keepAliveTimes.put(id, System.currentTimeMillis());
}
public int getViolations(final ICheck check, final Long time) {
final Set<Long> timestamps = this.checkViolationTimes.get(check);
if (timestamps != null) {
int violations = 0;
for (final long timestamp : timestamps) {
if (System.currentTimeMillis() - timestamp <= time) {
++violations;
}
}
return violations;
}
return 0;
}
public void addViolation(final ICheck check) {
Set<Long> timestamps = this.checkViolationTimes.get(check);
if (timestamps == null) {
timestamps = new HashSet<>();
}
timestamps.add(System.currentTimeMillis());
this.checkViolationTimes.put(check, timestamps);
}
static {
CHECKS = new Class[]{
AimAssistA.class, AimAssistB.class, AimAssistC.class, AimAssistD.class,
AimAssistE.class,
AutoClickerA.class, AutoClickerB.class, AutoClickerC.class, AutoClickerD.class,
AutoClickerE.class, AutoClickerF.class, AutoClickerG.class, AutoClickerH.class,
AutoClickerI.class, AutoClickerJ.class, AutoClickerK.class, AutoClickerK.class,
AutoClickerL.class,
BadPacketsA.class, BadPacketsB.class, BadPacketsC.class, BadPacketsD.class,
BadPacketsE.class, BadPacketsF.class, BadPacketsG.class, BadPacketsH.class,
BadPacketsI.class, BadPacketsJ.class, BadPacketsK.class, BadPacketsL.class,
FlyA.class, FlyB.class, FlyC.class,
InventoryA.class, InventoryB.class, InventoryC.class, InventoryD.class,
InventoryE.class, InventoryF.class, InventoryG.class,
KillAuraA.class, KillAuraB.class, KillAuraC.class, KillAuraD.class,
KillAuraE.class, KillAuraF.class, KillAuraG.class, KillAuraH.class,
KillAuraI.class, KillAuraJ.class, KillAuraK.class, KillAuraL.class,
KillAuraM.class, KillAuraN.class, KillAuraO.class, KillAuraP.class,
KillAuraQ.class, KillAuraR.class, KillAuraS.class,
RangeA.class,
TimerA.class,
VelocityA.class, VelocityB.class, VelocityC.class,
WTapA.class, WTapB.class,
ScaffoldA.class, ScaffoldB.class, ScaffoldC.class,
StepA.class,
};
CONSTRUCTORS = new ConcurrentHashMap<>();
for (final Class<? extends ICheck> check : PlayerData.CHECKS) {
try {
PlayerData.CONSTRUCTORS.put(check, check.getConstructor(PlayerData.class));
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
}
| 32.527881
| 107
| 0.762057
|
dc48212a4ff9812c0cfd5d9beabd68dd80c89a64
| 1,477
|
package com.hcy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
/**
* 基础电商推广服务
* 1. 生成最优价商品海报
* 2. 海报含带推广邀请码
*/
public abstract class NetMall {
protected Logger logger = LoggerFactory.getLogger(NetMall.class);
// 用户ID
String uId;
// 用户密码
String uPwd;
public NetMall(String uId, String uPwd) {
this.uId = uId;
this.uPwd = uPwd;
}
/**
* 生成商品推广海报
*
* @param skuUrl 商品地址(京东、淘宝、当当)
* @return 海报图片base64位信息
*/
public String generateGoodsPoster(String skuUrl) {
// 1. 验证登录
if (!login(uId, uPwd)) {
return null;
}
// 2. 爬虫商品
Map<String, String> reptile = reptile(skuUrl);
// 3. 组装海报
return createBase64(reptile);
}
/**
* 模拟登录
* @author HCY
* @since 2021/4/25 1:14 下午
* @param uId:
* @param uPwd:
* @return java.lang.Boolean
*/
protected abstract Boolean login(String uId, String uPwd);
/**
* 爬虫提取商品信息(登录后的优惠价格)
* @author HCY
* @since 2021/4/25 1:14 下午
* @param skuUrl:
* @return java.util.Map<java.lang.String,java.lang.String>
*/
protected abstract Map<String, String> reptile(String skuUrl);
/**
* 生成商品海报信息
* @author HCY
* @since 2021/4/25 1:16 下午
* @param goodsInfo:
* @return java.lang.String
*/
protected abstract String createBase64(Map<String, String> goodsInfo);
}
| 20.232877
| 74
| 0.574814
|
39048845e8451db41b4d06cde80dbed0e49771f9
| 3,215
|
package br.com.engebras.controller;
/**
* @author Adalberto
* dt. criação: 13/06/2016
*/
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import java.util.List;
import br.com.engebras.model.entities.Contrato;
import br.com.engebras.filter.ContratoFilter;
import br.com.engebras.model.dao.HibernateDAO;
import br.com.engebras.model.dao.InterfaceDAO;
import br.com.engebras.util.FacesContextUtil;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceException;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Order;
@ManagedBean(name="mbPesquisaContrato")
@ViewScoped
public class MbPesquisaContrato implements Serializable {
private static final long serialVersionUID = 1L;
private EntityManager manager;
public ContratoFilter filtro;
private List<Contrato> contratosFiltrados;
private Contrato contrato = new Contrato();
public MbPesquisaContrato(){
filtro = new ContratoFilter();
}
private InterfaceDAO<Contrato> contratoDAO(){
InterfaceDAO<Contrato> contratoDAO = new HibernateDAO<Contrato>(Contrato.class, FacesContextUtil.getRequestSession());
return contratoDAO;
}
public void deleteContrato(){
contratoDAO().remove(contrato);
pesquisar();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Registro excluído com sucesso !!!",""));
}
public void pesquisar(){
contratosFiltrados = filtrados(filtro);
}
public List<Contrato> filtrados(ContratoFilter filtro){
Session session = FacesContextUtil.getRequestSession();
Criteria criteria = session.createCriteria(Contrato.class);
if (filtro.getNr_crd() != null && filtro.getNr_crd() > 0 ){
criteria.add(Restrictions.eq("nr_crd", filtro.getNr_crd()));
}
return criteria.addOrder(Order.asc("nr_crd")).list();
}
public EntityManager getManager() {
return manager;
}
public void setManager(EntityManager manager) {
this.manager = manager;
}
public ContratoFilter getFiltro() {
return filtro;
}
public void setFiltro(ContratoFilter filtro) {
this.filtro = filtro;
}
public List<Contrato> getContratosFiltrados() {
return contratosFiltrados;
}
public void setContratosFiltrados(List<Contrato> contratosFiltrados) {
this.contratosFiltrados = contratosFiltrados;
}
public Contrato getContrato() {
return contrato;
}
public void setContrato(Contrato contrato) {
this.contrato = contrato;
}
}
| 29.227273
| 146
| 0.689891
|
ba679bc367104129f46267caa00abb034482931b
| 2,320
|
/*
* Copyright (c) 2014. Vlad Ilyushchenko
*
* 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.nfsdb.journal.net;
import com.nfsdb.journal.JournalKey;
import com.nfsdb.journal.PartitionType;
import com.nfsdb.journal.model.Quote;
import com.nfsdb.journal.net.model.IndexedJournalKey;
import com.nfsdb.journal.net.protocol.commands.SetKeyRequestConsumer;
import com.nfsdb.journal.net.protocol.commands.SetKeyRequestProducer;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class SetKeyTest {
private MockByteChannel channel;
@Before
public void setUp() throws Exception {
channel = new MockByteChannel();
}
@Test
public void testProducerConsumer() throws Exception {
SetKeyRequestProducer producer = new SetKeyRequestProducer();
SetKeyRequestConsumer consumer = new SetKeyRequestConsumer();
IndexedJournalKey key = new IndexedJournalKey(0, new JournalKey<>(Quote.class, "loc1", PartitionType.DAY, 100, true));
producer.setValue(key);
producer.write(channel);
consumer.read(channel);
Assert.assertEquals(key, consumer.getValue());
IndexedJournalKey key2 = new IndexedJournalKey(1, new JournalKey<>(Quote.class, "longer_location", PartitionType.DAY, 1000, true));
producer.setValue(key2);
producer.write(channel);
consumer.reset();
consumer.read(channel);
Assert.assertEquals(key2, consumer.getValue());
IndexedJournalKey key3 = new IndexedJournalKey(2, new JournalKey<>(Quote.class, "shorter_loc", PartitionType.DAY, 1000, true));
producer.setValue(key3);
producer.write(channel);
consumer.reset();
consumer.read(channel);
Assert.assertEquals(key3, consumer.getValue());
}
}
| 36.25
| 139
| 0.719397
|
79aef4b6816c09a5c2f98cab1284ec6c598d3407
| 1,932
|
/*
* Copyright (c) 2016—2017 Andrei Tomashpolskiy and individual 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 bt.torrent.selector;
import bt.data.LocalBitfield;
import bt.data.PeerBitfield;
import bt.torrent.PieceStatistics;
import java.util.BitSet;
import java.util.stream.IntStream;
/**
* Decorator that applies a filter to the selector stream.
*
* @since 1.1
*/
public class ValidatingSelector {
private final LocalBitfield localBitfield;
private final BitSet piecesToSkip; // nullable
private final PieceSelector delegate;
/**
* Creates a filtering selector.
*
* @param piecesToSkip The relevant pieces to download
* @param delegate Delegate selector
* @since 1.1
*/
public ValidatingSelector(LocalBitfield localBitfield, BitSet piecesToSkip, PieceSelector delegate) {
this.localBitfield = localBitfield;
this.piecesToSkip = piecesToSkip.isEmpty() ? null : piecesToSkip;
this.delegate = delegate;
}
public IntStream getNextPieces(PeerBitfield peerBitfield, PieceStatistics pieceStatistics) {
BitSet relevantChunks = peerBitfield.getBitmask();
if (piecesToSkip != null)
relevantChunks.andNot(this.piecesToSkip);
localBitfield.removeVerifiedPiecesFromBitset(relevantChunks);
return delegate.getNextPieces(relevantChunks, pieceStatistics);
}
}
| 32.2
| 105
| 0.728261
|
630611ebfb692251e13e8797db94785f8cb4bf78
| 236
|
package src.main.java.org.teachingextentions.logo.utils.ApprovalUtils.general;
public class NotImplementedException extends Exception {
/**
*
*/
private static final long serialVersionUID = 5269165537235260411L;
}
| 19.666667
| 78
| 0.745763
|
ba28033ad41b0ceae6bc8a997a017d9a880fbe70
| 2,524
|
package de.fhg.aisec.secunity.rest;
import java.util.HashSet;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import org.openrdf.model.IRI;
import org.openrdf.query.BindingSet;
import de.fhg.aisec.secunity.db.TripleStore;
@Path("institutions") //TODO support filters
public class Institutions {
@GET
@Produces("application/json; charset=UTF-8")
public Response getInstitutions(@QueryParam(value = "limit") String limit, @QueryParam(value = "offset") String offset
, @QueryParam(value = "wlocfirst") String withlocfirst) {
HashSet<String> data = new HashSet<String>();
// build SPARQL query
StringBuilder sb = new StringBuilder();
for (String ns: TripleStore.getInstance().getNamespaces()) {
sb.append("PREFIX ");
sb.append(TripleStore.getInstance().getPrefix(ns));
sb.append(": <");
sb.append(ns);
sb.append(">\n");
}
// If this parameter is set the locations with lat or lng set are returned first so that the number of gecoding queries can
// be reduced. But depending on the query this may be replaced when a filtering is used for the retrieval of the insstitution names
if(withlocfirst != null){
sb.append("SELECT ?s ");
sb.append("WHERE { ");
sb.append(" ?s rdf:type <"+TripleStore.DEFAULT_NS+"Organisation> .");
sb.append(" OPTIONAL {?s su:loc_lat ?lat} .");
sb.append(" OPTIONAL {?s su:loc_lng ?lng}");
sb.append("} ");
sb.append("ORDER BY DESC (?lat) DESC (?lng)");
}else{
sb.append("SELECT ?s ");
sb.append("WHERE { ");
sb.append(" ?s rdf:type <"+TripleStore.DEFAULT_NS+"Organisation> .");
sb.append("} ");
sb.append("ORDER BY ASC(?s)");
}
if (limit != null) { // Enforce max. limit even when not given
sb.append(" LIMIT " + limit);
}
if (limit != null && offset !=null) {
sb.append(" OFFSET " + offset);
}
String query = sb.toString();
System.out.println(query);
List<BindingSet> res = TripleStore.getInstance().querySPARQLTuples(query, false);
for (BindingSet bs:res) {
if (bs.getValue("s") instanceof IRI) {
IRI subjIRI = (IRI) bs.getValue("s");
String institution = TripleStore.getInstance().getPrefix(subjIRI.getNamespace()) + ":" + subjIRI.getLocalName();
data.add(institution);
} else {
System.out.println("Unkown type " + bs.getValue("s"));
}
}
return Response.ok().entity(Entity.json(data)).build();
}
}
| 33.653333
| 133
| 0.673534
|
f82a5cc008250d479b928e3c4a2d901aa596323e
| 277
|
package org.apache.batik.w3c.dom;
public interface Window {
Window getParent();
Location getLocation();
}
/* Location: /mnt/r/ConTenDoViewer.jar!/org/apache/batik/w3c/dom/Window.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
| 21.307692
| 90
| 0.65343
|
d4827f8938f88b0ae56e0c54de38eb0379588066
| 2,443
|
package org.openecomp.sdc.be.auditing.impl.category;
import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
import org.openecomp.sdc.be.resources.data.auditing.CategoryEvent;
import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
public class AuditCategoryEventFactory extends AuditBaseEventFactory {
private static final String LOG_STR = "ACTION = \"%s\" MODIFIER = \"%s\" CATEGORY_NAME = \"%s\" SUB_CATEGORY_NAME = \"%s\"" +
" GROUPING_NAME = \"%s\" RESOURCE_TYPE = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
private final CategoryEvent event;
private AuditCategoryEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String modifier, String categoryName,
String subCategoryName, String groupingName, String resourceType) {
super(action);
event = new CategoryEvent(getAction().getName(), commonFields, modifier, categoryName,
subCategoryName, groupingName, resourceType);
}
public AuditCategoryEventFactory(AuditingActionEnum action, CommonAuditData commonFields, User modifier,
String categoryName, String subCategoryName, String groupingName, String resourceType) {
this(action, commonFields, buildUserName(modifier), categoryName, subCategoryName, groupingName, resourceType);
}
public AuditCategoryEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String modifier, String categoryName,
String subCategoryName, String groupingName, String resourceType, String timestamp) {
this(action, commonFields, modifier, categoryName, subCategoryName, groupingName, resourceType);
event.setTimestamp1(timestamp);
}
@Override
public String getLogPattern() {
return LOG_STR;
}
@Override
public String[] getLogMessageParams() {
return new String[] {event.getAction(), event.getModifier(), event.getCategoryName(), event.getSubCategoryName(),
event.getGroupingName(), event.getResourceType(), event.getStatus(), event.getDesc()};
}
@Override
public AuditingGenericEvent getDbEvent() {
return event;
}
}
| 46.09434
| 132
| 0.709783
|
8b1cbdb9cb41bb021030a8ca79d2b833b7fa19e9
| 754
|
package com.taobao.metamorphosis.network;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.taobao.gecko.core.buffer.IoBuffer;
public class FetchCommandTest {
@Test
public void test_encode(){
String version = "2.1";
String topic = "test";
String group = "pingwei-test";
int partition = 2;
long offset = 1000;
int maxSize = 1024;
int opaque = 1023;
long time = System.currentTimeMillis();
FetchCommand fc = new FetchCommand(version, topic, group, partition, offset, maxSize, opaque, time);
IoBuffer buf = fc.encode();
assertEquals(0, buf.position());
assertEquals("fetch 2.1 test pingwei-test 2 1000 1024 1023 " + time +"\r\n", new String(buf.array()));
}
}
| 25.133333
| 105
| 0.676393
|
351f82b8482f9a5adce9c736a91636e0bd618f16
| 1,207
|
package com.github.alexivchenko.examples.spring.cloud.kafka.message.rest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
@Slf4j
@RestController
@EnableBinding(Source.class)
@SpringBootApplication
public class MessageRestApplication {
private final Source source;
public MessageRestApplication(Source source) {
this.source = source;
}
public static void main(String[] args) {
SpringApplication.run(MessageRestApplication.class, args);
}
@PostMapping
public void publishMessage(@RequestBody String message) {
log.info("publishing message: \"{}\"", message);
source.output().send(MessageBuilder.withPayload(message).build());
}
}
| 34.485714
| 74
| 0.787075
|
9dad1741c916d575c5c16d558cda9ceceea901e0
| 877
|
package com.github.flow.dto;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
public class HistoricProcessInstanceDTO {
@ApiModelProperty("历史流程实例ID")
private String id;
@ApiModelProperty("历史流程实例的业务id")
private String businessKey;
@ApiModelProperty("历史流程实例名称")
private String name;
@ApiModelProperty("历史流程实例开始ID")
private String startActivityId;
@ApiModelProperty("历史流程实例结束ID")
private String endActivityId;
@ApiModelProperty("历史流程实例开始时间")
private String startTime;
@ApiModelProperty("历史流程实例结束时间")
private String endTime;
@ApiModelProperty("流程是否结束")
private Boolean isEnded;
@ApiModelProperty("流程定义ID")
private String processDefinitionId;
@ApiModelProperty("流程定义KEY")
private String processDefinitionKey;
@ApiModelProperty("流程部署ID")
private String deploymentId;
}
| 29.233333
| 47
| 0.744584
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.