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
95938a4f496cb1be7d635284f1118b57e70b83c4
1,046
package com.delmar.sysSettings.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.delmar.core.dao.CoreDao; import com.delmar.core.service.impl.CoreServiceImpl; import com.delmar.sysSettings.dao.SysSettingsValuesDao; import com.delmar.sysSettings.model.SysSettingsValues; import com.delmar.sysSettings.service.SysSettingsValuesService; @Service("SysSettingsValuesService") public class SysSettingsValuesServiceImpl extends CoreServiceImpl<SysSettingsValues> implements SysSettingsValuesService{ @Autowired SysSettingsValuesDao sysSettingsValuesDao; /** * 保存或更新. */ public SysSettingsValues saveOrUpdate(SysSettingsValues sysSettingsValues) { if (sysSettingsValues.getId() == null) { sysSettingsValuesDao.insert(sysSettingsValues); } else { sysSettingsValuesDao.update(sysSettingsValues); } return sysSettingsValues; } @Override protected CoreDao<SysSettingsValues> getCoreDao() { return sysSettingsValuesDao; } }
27.526316
121
0.808795
f38bb1b00df72c58985a13cbf51fffdc0391734a
7,322
package org.jeecg.modules.message.service.impl; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.jeecg.common.api.dto.message.MessageDTO; import org.jeecg.common.exception.JeecgBootException; import org.jeecg.common.system.api.ISysBaseAPI; import org.jeecg.common.util.oConvertUtils; import org.jeecg.modules.base.entity.CmsComment; import org.jeecg.modules.base.mapper.CmsCommentMapper; import org.jeecg.modules.base.service.ICmsCommentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @Description: 评论表 * @Author: jeecg-boot * @Date: 2021-03-18 * @Version: V1.0 */ @Service public class CmsCommentServiceImpl extends ServiceImpl<CmsCommentMapper, CmsComment> implements ICmsCommentService { @Autowired private ISysBaseAPI sysBaseAPI; @Override public void addCmsComment(CmsComment cmsComment) { if (oConvertUtils.isEmpty(cmsComment.getPid())) { cmsComment.setPid(ICmsCommentService.ROOT_PID_VALUE); } else { //如果当前节点父ID不为空 则设置父节点的hasChildren 为1 CmsComment parent = baseMapper.selectById(cmsComment.getPid()); if (parent != null && !"1".equals(parent.getHasChild())) { parent.setHasChild("1"); baseMapper.updateById(parent); } } baseMapper.insert(cmsComment); // 发送站内消息 MessageDTO messageDTO = new MessageDTO(cmsComment.getCreateBy(), cmsComment.getReceive(), String.format("%s回复", cmsComment.getTitle()), cmsComment.getContent()); sysBaseAPI.sendSysAnnouncement(messageDTO); } @Override public void updateCmsComment(CmsComment cmsComment) { CmsComment entity = this.getById(cmsComment.getId()); if (entity == null) { throw new JeecgBootException("未找到对应实体"); } String old_pid = entity.getPid(); String new_pid = cmsComment.getPid(); if (!old_pid.equals(new_pid)) { updateOldParentNode(old_pid); if (oConvertUtils.isEmpty(new_pid)) { cmsComment.setPid(ICmsCommentService.ROOT_PID_VALUE); } if (!ICmsCommentService.ROOT_PID_VALUE.equals(cmsComment.getPid())) { baseMapper.updateTreeNodeStatus(cmsComment.getPid(), ICmsCommentService.HASCHILD); } } baseMapper.updateById(cmsComment); } @Override @Transactional(rollbackFor = Exception.class) public void deleteCmsComment(String id) throws JeecgBootException { //查询选中节点下所有子节点一并删除 id = this.queryTreeChildIds(id); if (id.indexOf(",") > 0) { StringBuffer sb = new StringBuffer(); String[] idArr = id.split(","); for (String idVal : idArr) { if (idVal != null) { CmsComment cmsComment = this.getById(idVal); String pidVal = cmsComment.getPid(); //查询此节点上一级是否还有其他子节点 List<CmsComment> dataList = baseMapper.selectList(new QueryWrapper<CmsComment>().eq("pid", pidVal).notIn("id", Arrays.asList(idArr))); if ((dataList == null || dataList.size() == 0) && !Arrays.asList(idArr).contains(pidVal) && !sb.toString().contains(pidVal)) { //如果当前节点原本有子节点 现在木有了,更新状态 sb.append(pidVal).append(","); } } } //批量删除节点 baseMapper.deleteBatchIds(Arrays.asList(idArr)); //修改已无子节点的标识 String[] pidArr = sb.toString().split(","); for (String pid : pidArr) { this.updateOldParentNode(pid); } } else { CmsComment cmsComment = this.getById(id); if (cmsComment == null) { throw new JeecgBootException("未找到对应实体"); } updateOldParentNode(cmsComment.getPid()); baseMapper.deleteById(id); } } @Override public List<CmsComment> queryTreeListNoPage(QueryWrapper<CmsComment> queryWrapper) { List<CmsComment> dataList = baseMapper.selectList(queryWrapper); List<CmsComment> mapList = new ArrayList<>(); for (CmsComment data : dataList) { String pidVal = data.getPid(); //递归查询子节点的根节点 if (pidVal != null && !"0".equals(pidVal)) { CmsComment rootVal = this.getTreeRoot(pidVal); if (rootVal != null && !mapList.contains(rootVal)) { mapList.add(rootVal); } } else { if (!mapList.contains(data)) { mapList.add(data); } } } return mapList; } @Override public List<CmsComment> listVo(CmsComment cmsComment) { return baseMapper.queryList(cmsComment); } /** * 根据所传pid查询旧的父级节点的子节点并修改相应状态值 * * @param pid */ private void updateOldParentNode(String pid) { if (!ICmsCommentService.ROOT_PID_VALUE.equals(pid)) { Integer count = baseMapper.selectCount(new QueryWrapper<CmsComment>().eq("pid", pid)); if (count == null || count <= 1) { baseMapper.updateTreeNodeStatus(pid, ICmsCommentService.NOCHILD); } } } /** * 递归查询节点的根节点 * * @param pidVal * @return */ private CmsComment getTreeRoot(String pidVal) { CmsComment data = baseMapper.selectById(pidVal); if (data != null && !"0".equals(data.getPid())) { return this.getTreeRoot(data.getPid()); } else { return data; } } /** * 根据id查询所有子节点id * * @param ids * @return */ private String queryTreeChildIds(String ids) { //获取id数组 String[] idArr = ids.split(","); StringBuffer sb = new StringBuffer(); for (String pidVal : idArr) { if (pidVal != null) { if (!sb.toString().contains(pidVal)) { if (sb.toString().length() > 0) { sb.append(","); } sb.append(pidVal); this.getTreeChildIds(pidVal, sb); } } } return sb.toString(); } /** * 递归查询所有子节点 * * @param pidVal * @param sb * @return */ private StringBuffer getTreeChildIds(String pidVal, StringBuffer sb) { List<CmsComment> dataList = baseMapper.selectList(new QueryWrapper<CmsComment>().eq("pid", pidVal)); if (dataList != null && dataList.size() > 0) { for (CmsComment tree : dataList) { if (!sb.toString().contains(tree.getId())) { sb.append(",").append(tree.getId()); } this.getTreeChildIds(tree.getId(), sb); } } return sb; } }
35.033493
169
0.577438
1089c408c7cfaf065f457abf8ce3a4514638530d
3,984
package budgetbuddy.model; import static budgetbuddy.testutil.Assert.assertThrows; import static budgetbuddy.testutil.ruleutil.TypicalRules.EQUAL4090_INAMT_SCRIPT; import static budgetbuddy.testutil.ruleutil.TypicalRules.FOOD_DESC_FOOD; import static budgetbuddy.testutil.ruleutil.TypicalRules.LESS10_INAMT_SWITCH; import static budgetbuddy.testutil.ruleutil.TypicalRules.RULE_LIST; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Collections; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import budgetbuddy.commons.core.index.Index; import budgetbuddy.model.rule.Rule; import budgetbuddy.model.rule.exceptions.RuleNotFoundException; import budgetbuddy.testutil.TypicalIndexes; import budgetbuddy.testutil.ruleutil.RuleBuilder; import budgetbuddy.testutil.ruleutil.TypicalActions; public class RuleManagerTest { private RuleManager ruleManager = new RuleManager(); @BeforeEach public void cleanUp_setSampleData() { ruleManager = new RuleManager(); ruleManager.addRule(FOOD_DESC_FOOD); } @Test public void constructor_noArguments_isEmptyList() { ruleManager = new RuleManager(); assertEquals(Collections.emptyList(), ruleManager.getRules()); } @Test public void constructor_nullRules_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> new RuleManager(null)); } @Test public void getRules_modifyList_throwsUnsupportedOperationException() { assertThrows(UnsupportedOperationException.class, () -> ruleManager.getRules().remove(0)); } @Test public void getRule_nullIndex_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> ruleManager.getRule(null)); } @Test public void getRule_indexBeyondListSize_throwsRuleNotFoundException() { assertThrows(RuleNotFoundException.class, () -> ruleManager.getRule( Index.fromZeroBased(ruleManager.getRuleCount()))); } @Test public void hasRule_ruleNotInRuleList_returnsFalse() { assertFalse(ruleManager.hasRule(LESS10_INAMT_SWITCH)); } @Test public void hasRule_nullRule_returnsFalse() { assertFalse(ruleManager.hasRule(null)); } @Test public void editRule_validIndexValidRule_editedRuleReplacesTargetRule() { Index targetIndex = TypicalIndexes.INDEX_FIRST_ITEM; Rule targetRule = ruleManager.getRule(targetIndex); Rule editedRule = new RuleBuilder(targetRule).withAction(TypicalActions.SWITCH_DIRECT).build(); ruleManager.editRule(targetIndex, editedRule); assertEquals(editedRule, ruleManager.getRule(targetIndex)); } @Test public void deleteLoan_validIndex_loanDeletedFromList() { Index targetIndex = TypicalIndexes.INDEX_FIRST_ITEM; Rule targetRule = ruleManager.getRule(targetIndex); ruleManager.deleteRule(targetIndex); assertTrue(ruleManager.getRules().stream().noneMatch(loan -> loan.equals(targetRule))); } @Test public void equals() { // same values -> returns true RuleManager ruleManagerCopy = new RuleManager(ruleManager.getRules()); assertEquals(ruleManagerCopy, ruleManager); // same object -> returns true assertEquals(ruleManager, ruleManager); // null -> returns false assertNotEquals(null, ruleManager); // different types -> returns false assertNotEquals(0, ruleManager); // different rules -> returns false ruleManager = new RuleManager(RULE_LIST); RuleManager ruleManagerAlt = new RuleManager(); ruleManagerAlt.addRule(EQUAL4090_INAMT_SCRIPT); assertNotEquals(ruleManagerAlt, ruleManager); } }
34.947368
103
0.73996
60c7087e1873145f3b6934bdfa25f05c2fecd249
12,030
package com.sudwood.betterhoppers.tileentities; import java.util.List; import com.sudwood.betterhoppers.TransferHelper; import com.sudwood.betterhoppers.blocks.BlockBetterHopper; import net.minecraft.command.IEntitySelector; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.world.World; import net.minecraftforge.common.ForgeDirection; public class TileEntityFasterHopper extends TileEntityBetterHopper implements IInventory { protected ItemStack[] inventory = new ItemStack[5]; private String inventoryName; public int numTransfered = 1; public void readFromNBT(NBTTagCompound par1NBTTagCompound) { super.readFromNBT(par1NBTTagCompound); NBTTagList nbttaglist = par1NBTTagCompound.getTagList("Items"); this.inventory = new ItemStack[this.getSizeInventory()]; for (int i = 0; i < nbttaglist.tagCount(); ++i) { NBTTagCompound nbttagcompound1 = (NBTTagCompound)nbttaglist.tagAt(i); byte b0 = nbttagcompound1.getByte("Slot"); if (b0 >= 0 && b0 < this.inventory.length) { this.inventory[b0] = ItemStack.loadItemStackFromNBT(nbttagcompound1); } } } /** * Writes a tile entity to NBT. */ public void writeToNBT(NBTTagCompound par1NBTTagCompound) { super.writeToNBT(par1NBTTagCompound); NBTTagList nbttaglist = new NBTTagList(); for (int i = 0; i < this.inventory.length; ++i) { if (this.inventory[i] != null) { NBTTagCompound nbttagcompound1 = new NBTTagCompound(); nbttagcompound1.setByte("Slot", (byte)i); this.inventory[i].writeToNBT(nbttagcompound1); nbttaglist.appendTag(nbttagcompound1); } } par1NBTTagCompound.setTag("Items", nbttaglist); } @Override public void updateEntity() { if(!worldObj.isRemote && BlockBetterHopper.getIsBlockNotPoweredFromMetadata(this.blockMetadata)) { if(inventory[0]!=null || inventory[1]!=null || inventory[2]!=null || inventory[3]!=null || inventory[4]!=null) pushItem(); if((inventory[0] ==null || inventory[0].stackSize<64) || (inventory[1] ==null || inventory[1].stackSize<64) || (inventory[2] ==null || inventory[2].stackSize<64) || (inventory[3] ==null || inventory[3].stackSize<64) || (inventory[4] ==null || inventory[4].stackSize<64)) { pullItem(); } } } public boolean putItemInThisInventory(ItemStack stack) { int[] slot = null; if(stack!=null) { slot = TransferHelper.checkSpace(xCoord, yCoord, zCoord, stack, worldObj, 0); if(slot!=null) { if(slot[1] == 0) { inventory[slot[0]] = stack.copy(); this.onInventoryChanged(); return true; } if(slot[1] == 1) { inventory[slot[0]].stackSize += stack.stackSize; this.onInventoryChanged(); return true; } } } return false; } public void pullItem() { int[] slot = TransferHelper.getFirstStackThatFits(xCoord, yCoord+ForgeDirection.UP.offsetY, zCoord, inventory, worldObj, numTransfered); if(slot!= null) { try { IInventory tile = (IInventory) worldObj.getBlockTileEntity(xCoord, yCoord+ForgeDirection.UP.offsetY, zCoord); if(slot[1] == 0) { inventory[slot[2]] = tile.getStackInSlot(slot[0]).copy(); inventory[slot[2]].stackSize = numTransfered; this.onInventoryChanged(); if(tile.getStackInSlot(slot[0]).stackSize == numTransfered) { tile.setInventorySlotContents(slot[0], null); } else { ItemStack stack = tile.getStackInSlot(slot[0]).copy(); stack.stackSize-=numTransfered; tile.setInventorySlotContents(slot[0], stack); } tile.onInventoryChanged(); } if(slot[1] == 1) { ItemStack stackish = tile.getStackInSlot(slot[0]).copy(); stackish.stackSize = numTransfered; if(slot[3]!= 0) { stackish.stackSize = slot[3]; } System.out.println(stackish.stackSize); if(this.inventory[slot[2]].stackSize<64) this.inventory[slot[2]].stackSize += stackish.stackSize; this.onInventoryChanged(); if(tile.getStackInSlot(slot[0]).stackSize == stackish.stackSize) { tile.setInventorySlotContents(slot[0], null); } else { ItemStack stack = tile.getStackInSlot(slot[0]).copy(); stack.stackSize-=stackish.stackSize; tile.setInventorySlotContents(slot[0], stack); } tile.onInventoryChanged(); } } catch(Exception e) { } } } public void pushItem() { int sideAttached = BlockBetterHopper.getDirectionFromMetadata(this.blockMetadata) ^ 1; int[] slot = null; for(int i = 0; i < inventory.length; i++) { if(inventory[i]!=null) { IInventory transfer = null; switch(BlockBetterHopper.getDirectionFromMetadata(this.blockMetadata)) { case 0: //down slot = TransferHelper.checkSpace(xCoord+ForgeDirection.DOWN.offsetX, yCoord+ForgeDirection.DOWN.offsetY, zCoord+ForgeDirection.DOWN.offsetZ, new ItemStack(inventory[i].getItem(), numTransfered, inventory[i].getItemDamage()), worldObj, sideAttached); try { transfer = (IInventory) worldObj.getBlockTileEntity(xCoord+ForgeDirection.DOWN.offsetX, yCoord+ForgeDirection.DOWN.offsetY, zCoord+ForgeDirection.DOWN.offsetZ); } catch(Exception e) { } break; case 2: //North slot = TransferHelper.checkSpace(xCoord+ForgeDirection.NORTH.offsetX, yCoord+ForgeDirection.NORTH.offsetY, zCoord+ForgeDirection.NORTH.offsetZ, new ItemStack(inventory[i].getItem(), numTransfered, inventory[i].getItemDamage()), worldObj, sideAttached); try { transfer = (IInventory) worldObj.getBlockTileEntity(xCoord+ForgeDirection.NORTH.offsetX, yCoord+ForgeDirection.NORTH.offsetY, zCoord+ForgeDirection.NORTH.offsetZ); } catch(Exception e) { }break; case 3: //south slot = TransferHelper.checkSpace(xCoord+ForgeDirection.SOUTH.offsetX, yCoord+ForgeDirection.SOUTH.offsetY, zCoord+ForgeDirection.SOUTH.offsetZ, new ItemStack(inventory[i].getItem(), numTransfered, inventory[i].getItemDamage()), worldObj, sideAttached); try { transfer = (IInventory) worldObj.getBlockTileEntity(xCoord+ForgeDirection.SOUTH.offsetX, yCoord+ForgeDirection.SOUTH.offsetY, zCoord+ForgeDirection.SOUTH.offsetZ); } catch(Exception e) { } break; case 4: //west slot = TransferHelper.checkSpace(xCoord+ForgeDirection.WEST.offsetX, yCoord+ForgeDirection.WEST.offsetY, zCoord+ForgeDirection.WEST.offsetZ, new ItemStack(inventory[i].getItem(), numTransfered, inventory[i].getItemDamage()), worldObj, sideAttached); try { transfer = (IInventory) worldObj.getBlockTileEntity(xCoord+ForgeDirection.WEST.offsetX, yCoord+ForgeDirection.WEST.offsetY, zCoord+ForgeDirection.WEST.offsetZ); } catch(Exception e) { } break; case 5: //east slot = TransferHelper.checkSpace(xCoord+ForgeDirection.EAST.offsetX, yCoord+ForgeDirection.EAST.offsetY, zCoord+ForgeDirection.EAST.offsetZ, new ItemStack(inventory[i].getItem(), numTransfered, inventory[i].getItemDamage()), worldObj, sideAttached); try { transfer = (IInventory) worldObj.getBlockTileEntity(xCoord+ForgeDirection.EAST.offsetX, yCoord+ForgeDirection.EAST.offsetY, zCoord+ForgeDirection.EAST.offsetZ); } catch(Exception e) { } break; } if(slot!=null && transfer!= null) { if(slot[1] == 0) { ItemStack stack = inventory[i].copy(); stack.stackSize = numTransfered; transfer.setInventorySlotContents(slot[0], stack); transfer.onInventoryChanged(); if(inventory[i].stackSize == numTransfered) { inventory[i] = null; this.onInventoryChanged(); return; } inventory[i].stackSize-=numTransfered; this.onInventoryChanged(); return; } if(slot[1] == 1 && transfer.getStackInSlot(slot[0]).stackSize < transfer.getInventoryStackLimit()) { ItemStack stack = inventory[i].copy(); if(slot[2]!=0) stack.stackSize = slot[2]+transfer.getStackInSlot(slot[0]).stackSize; else stack.stackSize = numTransfered+transfer.getStackInSlot(slot[0]).stackSize; transfer.setInventorySlotContents(slot[0], stack); transfer.onInventoryChanged(); if(inventory[i].stackSize == numTransfered) { inventory[i] = null; this.onInventoryChanged(); return; } inventory[i].stackSize-=numTransfered; this.onInventoryChanged(); return; } } } } } @Override public int getSizeInventory() { // TODO Auto-generated method stub return inventory.length; } @Override public ItemStack getStackInSlot(int i) { // TODO Auto-generated method stub return inventory[i]; } @Override public ItemStack decrStackSize(int i, int j) { if (this.inventory[i] != null) { ItemStack itemstack; if (this.inventory[i].stackSize <= j) { itemstack = this.inventory[i]; this.inventory[i] = null; return itemstack; } else { itemstack = this.inventory[i].splitStack(j); if (this.inventory[i].stackSize == 0) { this.inventory[i] = null; } return itemstack; } } else { return null; } } @Override public ItemStack getStackInSlotOnClosing(int i) { if (this.inventory[i] != null) { ItemStack itemstack = this.inventory[i]; this.inventory[i] = null; return itemstack; } else { return null; } } @Override public void setInventorySlotContents(int i, ItemStack itemstack) { this.inventory[i] = itemstack; if (itemstack != null && itemstack.stackSize > this.getInventoryStackLimit()) { itemstack.stackSize = this.getInventoryStackLimit(); } } @Override public String getInvName() { return "Faster Hopper"; } @Override public boolean isInvNameLocalized() { // TODO Auto-generated method stub return true; } @Override public int getInventoryStackLimit() { // TODO Auto-generated method stub return 64; } @Override public boolean isUseableByPlayer(EntityPlayer par1EntityPlayer) { return this.worldObj.getBlockTileEntity(this.xCoord, this.yCoord, this.zCoord) != this ? false : par1EntityPlayer.getDistanceSq((double)this.xCoord + 0.5D, (double)this.yCoord + 0.5D, (double)this.zCoord + 0.5D) <= 64.0D; } @Override public void openChest() {} @Override public void closeChest() {} @Override public boolean isItemValidForSlot(int i, ItemStack itemstack) { // TODO Auto-generated method stub return true; } }
31.328125
277
0.615628
bd7d64be64a9144eb3d6c6beea7f4a96953a6d97
12,279
/* * Copyright (C) 2017 - present Instructure, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.instructure.pandautils.discussions; import android.content.Context; import android.text.TextUtils; import com.instructure.canvasapi2.models.DiscussionEntry; import com.instructure.canvasapi2.models.RemoteFile; import com.instructure.canvasapi2.utils.DateHelper; import com.instructure.canvasapi2.utils.FileUtils; import com.instructure.canvasapi2.utils.Pronouns; import com.instructure.pandautils.R; import com.instructure.pandautils.utils.Const; import com.instructure.pandautils.utils.ProfileUtils; import java.util.Locale; @Deprecated public class DiscussionEntryHTMLHelper { private static final String NO_PIC = "images/dotted_pic.png"; private static final String ASSETS = "file:///android_asset"; public static final String ASSET_IMAGES = "file:///android_asset"; private static final String DRAWABLE = "file:///android_res/drawable"; private static final String ATTACHMENT_ICON = "https://du11hjcvx0uqb.cloudfront.net/dist/images/inst_tree/file_types/page_white_picture-94db8424e5.png"; private static String getContentHTML(DiscussionEntry discussionEntry, String message) { if (message == null || message.equals("null")) { return ""; } else { StringBuilder html = new StringBuilder(); html.append("<div class=\"width\">"); html.append(message); for(RemoteFile attachment : discussionEntry.getAttachments()){ if (!attachment.getHiddenForUser() && !discussionEntry.getDeleted()) { html.append("<div class=\"nowrap\">"); html.append(String.format("<img class=\"attachment_img\" src=\"" + ATTACHMENT_ICON + "\" /> <a class=\"attachment_link\" href=\"%s\">%s</a>", attachment.getUrl(), attachment.getDisplayName())); html.append("</div>"); } } html.append("</div>"); return html.toString(); } } private static String getClickListener(int index) { if (index == -1) { return ""; } return " onClick=\"onPressed('" + index + "')\""; } private static String getReplyListener(long index) { return " onClick=\"onReplyPressed('" + index + "')\""; } private static String getLikeListener(long index) { if(index == -1) { return ""; } return " onClick=\"onLikePressed('" + index + "')\""; } public static String getUnreadCountHtmlLabel(Context context, DiscussionEntry discussionEntry) { if (discussionEntry.getUnreadChildren() > 0) { return String.format("<div class=\"is_unread\" id=\"is_unread_%d\">%s</div>", discussionEntry.getId(), formatUnreadCount(context, discussionEntry.getUnreadChildren())); } else { if(discussionEntry.getUnread()) { return String.format("<div class=\"is_unread\" id=\"is_unread_%d\">%s</div>", discussionEntry.getId(), context.getString(R.string.discussion_unread)); } return ""; } } public static String getCommentsCountHtmlLabel(Context context, DiscussionEntry discussionEntry, int subEntryCount) { return String.format("<div class=\"comments\" id =\"comments_%d\">%s</div>",discussionEntry.getId(), formatCommentsCount(context, subEntryCount)); } public static String getHTML(DiscussionEntry discussionEntry, Context context, int index, String deletedString, String colorString, boolean shouldAllowRating, boolean canReply, int currentRatingForUser, String likeString, int subEntryCount) { return getHTML(discussionEntry, context, index, deletedString, colorString, false, shouldAllowRating, canReply, currentRatingForUser, likeString, subEntryCount); } /** * Here we replace html with data, fun... */ public static String getHTML(DiscussionEntry discussionEntry, Context context, int index, String deletedString, String colorString, boolean isForbidden, boolean shouldAllowRating, boolean canReply, int currentRatingForUser, String likeString, int subEntryCount) { String unread = getUnreadCountHtmlLabel(context, discussionEntry); String comments = getCommentsCountHtmlLabel(context, discussionEntry, subEntryCount); String listener = getClickListener(index); String replyListener = getReplyListener(index); String likeListener = getLikeListener(index); String avatarUrl = ""; String avatarVisibility = "display: block;"; String title = ""; String date = ""; String message = discussionEntry.getMessage("<p>" + deletedString + "</p>"); String content = getContentHTML(discussionEntry, message); String status = discussionEntry.getUnread() ? "unread_message" : "read_message"; String classString = "parent"; String displayInitials = ""; String borderString = ""; String reply = formatReplyText(context, canReply); String userId; String detailsWrapperStyle = "display: block;"; //Prevents the topic from appearing as deleted if the editorId was not set if(index == -1 && discussionEntry.getUserId() == 0) { userId = Integer.toString(index); } else { if(discussionEntry.getUserId() == 0 && discussionEntry.getEditorId() != 0) { userId = Long.toString(discussionEntry.getEditorId()); } else { userId = Long.toString(discussionEntry.getUserId()); } } String forbiddenHtml = isForbidden ? getForbiddenHtml(context.getString(R.string.forbidden)) : ""; if (index >= 0) { classString = "child"; } if (discussionEntry.getDeleted()) { avatarUrl = "background: " + colorString + " url(\"file:///android_res/drawable/ic_default_avatar.png\");"; if(discussionEntry.getAuthor() != null && !TextUtils.isEmpty(discussionEntry.getAuthor().getDisplayName())) { String name = Pronouns.html( discussionEntry.getAuthor().getDisplayName(), discussionEntry.getAuthor().getPronouns() ); title = String.format(Locale.getDefault(), context.getString(R.string.deleted_by), name); } else { title = deletedString; } content = reply = comments = likeString = ""; detailsWrapperStyle = "display: none;"; avatarVisibility = "display: none;"; } else { if (discussionEntry.getAuthor() != null) { if(!isEmptyImage(discussionEntry.getAuthor().getAvatarImageUrl())){ avatarUrl = "background-image:url(" + discussionEntry.getAuthor().getAvatarImageUrl() + ");"; borderString = "border: 0px solid " + colorString + ";"; }else { avatarUrl = "background: transparent;"; displayInitials = ProfileUtils.getUserInitials(discussionEntry.getAuthor().getDisplayName()); } }else { avatarUrl = "background: " + colorString + " url(\"file:///android_res/drawable/ic_default_avatar.png\");"; borderString = "border: 0px solid " + colorString + ";"; } if (discussionEntry.getAuthor() != null && discussionEntry.getAuthor().getDisplayName() != null) { title = Pronouns.html( discussionEntry.getAuthor().getDisplayName(), discussionEntry.getAuthor().getPronouns() ); } else if (discussionEntry.getDescription() != null) { //Graded discussion. title = discussionEntry.getDescription(); } //if title is still null set it to an empty string if(title == null) { title = ""; } //Check if we can like, replay, and if there are comments if(discussionEntry.getTotalChildren() == 0 && !canReply && !shouldAllowRating) { //Hide detailsWrapper detailsWrapperStyle = "display: none;"; } } if (discussionEntry.getUpdatedAt() != null) { date = DateHelper.getDateTimeString(context, discussionEntry.getUpdatedDate()); } return (FileUtils.getAssetsFile(context, "discussion_html_template.html") .replace("__BORDER_STRING__", borderString) .replace("__COLOR__", "background: " + colorString + ";") .replace("__LISTENER_HTML__", listener) .replace("__LIKE_LISTENER__", likeListener) .replace("__REPLY_LISTENER__", replyListener) .replace("__AVATAR_URL__", avatarUrl) .replace("__AVATAR_VISIBILITY__", avatarVisibility) .replace("__TITLE__", title) .replace("__DATE__", date) .replace("__LIKES_TEXT__", likeString) .replace("__UNREAD_COUNT__", unread) .replace("__CONTENT_HTML__", content) .replace("__CLASS__", classString) .replace("__STATUS__", status) .replace("__FORBIDDEN__", forbiddenHtml) .replace("__HEADER_ID__", Long.toString(discussionEntry.getId())) .replace("__ENTRY_ID__", Long.toString(discussionEntry.getId())) .replace("__USER_ID__", userId) .replace("__USER_INITIALS__", displayInitials) .replace("__REPLY_TEXT__", reply) .replace("__COMMENTS_COUNT__", comments) .replace("__DETAILS_WRAPPER__", detailsWrapperStyle) .replace("__INDEX__", Integer.toString(index)) .replace("__READ_STATE__", getReadState(discussionEntry))); } public static String getReadState(DiscussionEntry discussionEntry) { return discussionEntry.getUnread() ? "unread" : "read"; } /* * Displays text to the user when they have to post before viewing replies */ private static String getForbiddenHtml(String forbiddenText) { return String.format("<div class=\"forbidden\"><p>%s</p></div>", forbiddenText); } public static boolean isEmptyImage(String avatarURL){ if(TextUtils.isEmpty(avatarURL)) return true; return avatarURL.contains(NO_PIC) || avatarURL.contains(Const.PROFILE_URL); } private static String formatCommentsCount(Context context, int count) { if(count == 0) { return ""; } else if(count > 1) { return String.format(Locale.getDefault(), context.getString(R.string.word_space_word), String.valueOf(count), context.getString(R.string.discussion_responses)); } else { return String.format(Locale.getDefault(), context.getString(R.string.word_space_word), String.valueOf(count), context.getString(R.string.discussion_response)); } } private static String formatUnreadCount(Context context, int count) { if(count == 0) { return ""; } else { return String.format(Locale.getDefault(), context.getString(R.string.word_space_word), String.valueOf(count), context.getString(R.string.discussion_unread)); } } private static String formatReplyText(Context context, boolean canReply) { if(canReply) { return String.format("<div class=\"reply\">%s</div>", context.getString(R.string.discussion_reply)); } return ""; } }
47.045977
267
0.625947
fcef574b02dae2bb11994b0cad2e76c0672ffaf7
5,415
package com.roku.dvp; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.util.concurrent.BlockingQueue; import android.util.Log; public final class Transmitter implements Runnable { private static final String LOG_PREFIX = "Transmitter"; private static final String QUIT_MARK = "__quit__"; public Transmitter(BlockingQueue<Transmission> queue, StatusListener listener) { mQueue = queue; mListener = listener; mAddress = null; mPort = 0; mSocket = new Socket(); mThread = new Thread(this); int priority = mThread.getPriority()+1; mThread.setPriority(priority); setStatus(StatusListener.DISCONNECTED); } private void go() { if (checkConnect()) mThread.start(); } public void stop() { checkClose(); if (mThread != null && mThread.isAlive()) { try { mQueue.put(new Transmission(QUIT_MARK)); mThread.join(); } catch (InterruptedException e) { // throw on destruction } } } public void destroy() { stop(); mThread = null; } private boolean checkConnect() { boolean connected = false; synchronized (mSocket) { connected = mSocket.isConnected() && !mSocket.isOutputShutdown(); if (!connected && isTargeted()) { setStatus(StatusListener.PENDING); Log.i(LOG_PREFIX,"connecting to "+mAddress.toString()+":"+Integer.toString(mPort)); try { mSocket.connect(new InetSocketAddress(mAddress,mPort)); connected = mSocket.isConnected(); Log.i(LOG_PREFIX,(connected?"connected":"not connected")+" to "+mAddress.toString()+":"+mPort); mSocket.setTcpNoDelay(true); mRequestStream = mSocket.getOutputStream(); mResponseStream = mSocket.getInputStream(); } catch (IOException e) { Log.i(LOG_PREFIX,"connect error, "+e.toString()); } setStatus(connected ? StatusListener.SUCCESS : StatusListener.FAILED); } } return connected; } private void checkClose() { try { synchronized (mSocket) { if (mRequestStream!=null) { mRequestStream.close(); mRequestStream = null; } if (mResponseStream!=null) { mResponseStream.close(); mResponseStream = null; } if (mSocket.isConnected()) { mSocket.close(); setStatus(StatusListener.DISCONNECTED); } } } catch (IOException e) { Log.i(LOG_PREFIX,"close error, "+e.toString()); } setStatus(StatusListener.DISCONNECTED); } public final void setTarget(InetAddress address, int port) { synchronized (mSocket) { if (update(address, port)) { stop(); go(); } } } private boolean isTargeted() { return mAddress!=null && mPort>0; } private boolean update(InetAddress address, int port) { boolean changed = mAddress==null || !mAddress.equals(address) || mPort!=port; if (changed) { mAddress = address; mPort = port; } return changed; } protected void finalize() throws Throwable { destroy(); super.finalize(); } public void run() { mQueue.clear(); // skip old events (might be for diff target) while (true) { Transmission t = null; try { t = mQueue.take(); } catch (InterruptedException e) { // nothing to do here } if (t == null) continue; if (t.packet.equals(QUIT_MARK)) return; postHttp(t); } } public void setListener(StatusListener listener) { mListener = listener; sendStatus(); } private byte[] postHttp(final Transmission t) { byte[] result = null; StringBuffer request = new StringBuffer(); request.append("POST /"+t.packet+" HTTP/1.1\n\n"); try { synchronized (mSocket) { if (checkConnect()) { mRequestStream.write(request.toString().getBytes()); mRequestStream.flush(); Log.i(LOG_PREFIX, "transmission: "+request+ " lag " + Long.toString(System.currentTimeMillis()-t.timestamp)); consumeResponse(); } else Log.i(LOG_PREFIX,"not connected"); } } catch (IOException e) { result = null; Log.i(LOG_PREFIX,"transmit error, "+e.toString()); } return result; } private void consumeResponse() { // This might read nothing, a partial response, a whole response, or parts of more than one response try { synchronized (mSocket) { int length = mResponseStream.available(); if (length>0) { byte[] result = new byte[length]; int total = 0, read = 0; do { read = mResponseStream.read(result, total, length-total); total += read; } while (read>0 && total<length); } } } catch (IOException e) { Log.i(LOG_PREFIX,"response error, "+e.toString()); } } private void setStatus(int status) { mStatus = status; sendStatus(); } private void sendStatus() { mListener.statusChanged(mStatus); } private int mStatus; private StatusListener mListener; private Thread mThread; private final BlockingQueue<Transmission> mQueue; private Socket mSocket; private InetAddress mAddress; private int mPort; private OutputStream mRequestStream; private InputStream mResponseStream; }
28.350785
119
0.628809
8183aca39a31da90e8560ad8c5dab6c06b0b8ef2
470
package br.com.contabancaria.modulos; import javax.persistence.*; @Entity public class Cliente { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String nome; @JoinColumn(unique = true) //Anotação para restringir associação do elemento conta com mais de um cliente @OneToOne private Conta conta; public Cliente(String nome, Conta conta){ this.nome = nome; this.conta = conta; } }
19.583333
109
0.685106
4d3f3bb8bc36b7a308b6ddedd7ff6c04f7176a2e
309
package edu.pku.gg.pokemonbutton; /** * Created by Gg on 2016/10/12. */ public enum PokemonType { NORMAL, FIRE, FIGHTING, WATER, FLYING, GRASS, POSITION, ELECTRIC, GROUND, PSYCHIC, ROCK, ICE, BUG, DRAGON, GHOST, DARK, STEEL, FAIRY }
11.884615
33
0.543689
a688219cd6ee08c017de3dd7845ba672b1e0f126
154
package com.seydanurdemir.model; import java.util.ArrayList; public class Geometry{ public String type; public ArrayList<Double> coordinates; }
17.111111
41
0.766234
5814e7f83f237a3d0a87bd14408788288a4ae0b5
245
package test; /** * This is the local interface for TestingSession enterprise bean. */ public interface TestingSessionLocal extends javax.ejb.EJBLocalObject, test.TestingSessionLocalBusiness { String testBusinessMethod1(); }
17.5
105
0.75102
59434d0f47b4aeda588b5d9238394f9e5fa196ea
1,323
package datamodel.ex1.entity.validation; import datamodel.ex1.entity.Location; import datamodel.ex1.entity.Person; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import java.util.regex.Matcher; import java.util.regex.Pattern; // tag::validator[] public class ValidPassportNumberValidator implements ConstraintValidator<ValidPassportNumber, Person> { @Override public boolean isValid(Person person, ConstraintValidatorContext context) { // <1> if (person == null) return false; if (person.getLocation() == null || person.getPassportNumber() == null) return false; return doPassportNumberFormatCheck(person.getLocation(), person.getPassportNumber()); } // end::validator[] private boolean doPassportNumberFormatCheck(Location location, String passportNumber) { // dumb check that ensures that passport number is not empty and // contains only digits and spaces after trimming trailing and leading spaces Pattern pat = Pattern.compile("(^[\\d\\s]+$)", Pattern.CASE_INSENSITIVE); Matcher mat = pat.matcher(passportNumber.trim()); return (passportNumber.trim().length() > 0) && mat.find(); } // tag::validator[] } // end::validator[]
37.8
91
0.699169
af5f934ab3912dade13c89ea8d64788e63e8edcc
1,408
package src; import becker.robots.*; /* CS1A: Assignment 1: Part 2 - What's wrong with this code. The program is supposed to make jo perform diving acrobatics - but it's not yet working. Find, document, and correct all the errors in the code and get jo into the pool. */ public class A1_Part_2 extends Object { public static void main(String[] args) { // Create the robot on the diving board... City bothell = new City(); Robot jo = new Robot(bothell, 0, 1, Direction.NORTH, 0); //pool new Wall(bothell, 2, 3, Direction.EAST); new Wall(bothell, 2, 3, Direction.SOUTH); new Wall(bothell, 2, 3, Direction.WEST); new Thing(bothell, 2, 3); //diving board new Wall(bothell, 1, 1, Direction.SOUTH); new Wall(bothell, 2,1, Direction.WEST); new Wall(bothell, 3, 1, Direction.WEST); // jo first leaps off the board, turns right, moves beyond the diving board, // faces downwards, goes to the bottom of the pool (without crashing), and // then faces upwards. jo.turnLeft(); jo.turnLeft(); jo.turnLeft(); jo.move(); jo.move(); jo.turnLeft(); jo.turnLeft(); jo.turnLeft(); // Dive jo, DIVE! jo.move(); jo.move(); jo.turnLeft(); jo.turnLeft(); } }
27.607843
89
0.571023
e8236f15b0e1b95fbc8453a46db2c96165ce219b
3,613
/* */ package org.springframework.http.client; /* */ /* */ import java.io.IOException; /* */ import java.io.OutputStream; /* */ import java.net.HttpURLConnection; /* */ import java.net.URI; /* */ import java.net.URISyntaxException; /* */ import org.springframework.http.HttpHeaders; /* */ import org.springframework.lang.Nullable; /* */ import org.springframework.util.StreamUtils; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ final class SimpleStreamingClientHttpRequest /* */ extends AbstractClientHttpRequest /* */ { /* */ private final HttpURLConnection connection; /* */ private final int chunkSize; /* */ @Nullable /* */ private OutputStream body; /* */ private final boolean outputStreaming; /* */ /* */ SimpleStreamingClientHttpRequest(HttpURLConnection connection, int chunkSize, boolean outputStreaming) { /* 53 */ this.connection = connection; /* 54 */ this.chunkSize = chunkSize; /* 55 */ this.outputStreaming = outputStreaming; /* */ } /* */ /* */ /* */ /* */ public String getMethodValue() { /* 61 */ return this.connection.getRequestMethod(); /* */ } /* */ /* */ /* */ public URI getURI() { /* */ try { /* 67 */ return this.connection.getURL().toURI(); /* */ } /* 69 */ catch (URISyntaxException ex) { /* 70 */ throw new IllegalStateException("Could not get HttpURLConnection URI: " + ex.getMessage(), ex); /* */ } /* */ } /* */ /* */ /* */ protected OutputStream getBodyInternal(HttpHeaders headers) throws IOException { /* 76 */ if (this.body == null) { /* 77 */ if (this.outputStreaming) { /* 78 */ long contentLength = headers.getContentLength(); /* 79 */ if (contentLength >= 0L) { /* 80 */ this.connection.setFixedLengthStreamingMode(contentLength); /* */ } else { /* */ /* 83 */ this.connection.setChunkedStreamingMode(this.chunkSize); /* */ } /* */ } /* 86 */ SimpleBufferingClientHttpRequest.addHeaders(this.connection, headers); /* 87 */ this.connection.connect(); /* 88 */ this.body = this.connection.getOutputStream(); /* */ } /* 90 */ return StreamUtils.nonClosing(this.body); /* */ } /* */ /* */ /* */ protected ClientHttpResponse executeInternal(HttpHeaders headers) throws IOException { /* */ try { /* 96 */ if (this.body != null) { /* 97 */ this.body.close(); /* */ } else { /* */ /* 100 */ SimpleBufferingClientHttpRequest.addHeaders(this.connection, headers); /* 101 */ this.connection.connect(); /* */ /* 103 */ this.connection.getResponseCode(); /* */ } /* */ /* 106 */ } catch (IOException iOException) {} /* */ /* */ /* 109 */ return new SimpleClientHttpResponse(this.connection); /* */ } /* */ } /* Location: /home/kali/ctf/htb/fatty-10.10.10.174/ftp/fatty-client.jar!/org/springframework/http/client/SimpleStreamingClientHttpRequest.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
30.880342
156
0.496263
8580be0b986a318e2dbff1ed8f23db566293f8a5
837
package treino.basicoavancado.InterfaceGrafica; import java.awt.*; import javax.swing.*; public class RadioButton extends JFrame { JRadioButton masculino = new JRadioButton("Masculino", true); JRadioButton feminino = new JRadioButton("Feminino"); // Resolver o problema de os dois serem marcados ao mesmo tempo ButtonGroup grupo = new ButtonGroup(); public RadioButton() { setLayout(new FlowLayout()); add(masculino); add(feminino); grupo.add(masculino); grupo.add(feminino); setTitle("Mateus"); setSize(600, 400); setLocationRelativeTo(null); setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public static void main(String[] args) { new RadioButton(); } }
24.617647
67
0.64994
3f063c1dc39b08accbdca06d5c8e1f6725f4d584
769
package com.baidu.mapp.tp.bean.auth; import lombok.Data; /** * @description: 小程序基础信息修改次数 * @author: chenhaonan02 * @create: 2021-10-25 11:29 **/ @Data public class AppInfoModifyCount { /** * 名称已使用修改次数 */ private Integer nameModifyUsed; /** * 名称修改次数总额度 */ private Integer nameModifyQuota; /** * 简介已使用修改次数 */ private Integer signatureModifyUsed; /** * 简介修改次数总额度 */ private Integer signatureModifyQuota; /** * 头像已使用修改次数 */ private Integer imageModifyUsed; /** * 头像修改次数总额度 */ private Integer imageModifyQuota; /** * 类目已使用修改次数 */ private Integer categoryModifyUsed; /** * 类目修改次数总额度 */ private Integer categoryModifyQuota; }
17.088889
41
0.592978
1f3ad47c82ede3dc4896d6837a089bae20623a6c
231
package com.example.springbootdynamodb; public class UniquePrimaryKeyConstraintViolationException extends RuntimeException { public UniquePrimaryKeyConstraintViolationException(String message) { super(message); } }
33
84
0.813853
d581b490af8a2a6370a41200e11d98f1eb8898e6
117
package gw.specContrib.generics; public interface BeanPopulator2<T extends CharSequence> { void execute(T Bean); }
23.4
57
0.794872
859094266561367ec9f59150d832ceebdbedbfae
1,322
package com.lhc.ocat.mobileplatform.domain.dto; import com.lhc.ocat.mobileplatform.domain.dos.ApplicationDO; import com.lhc.ocat.mobileplatform.domain.dos.MenuDO; import lombok.Data; import lombok.EqualsAndHashCode; import org.springframework.beans.BeanUtils; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * @author lhc * @date 2019-11-23 23:34 */ @Data @EqualsAndHashCode public class Menu implements Comparable<Menu>{ private String id; private String parentId; private Integer orderNum; private Integer type; private String name; private String icon; private String href; private String description; private List<Menu> children = new ArrayList<>(); public static final String ROOT_PARENT_ID = "0"; static public Menu toMenu(MenuDO menuDO) { Menu menu = new Menu(); BeanUtils.copyProperties(menuDO, menu); menu.setId(String.valueOf(menuDO.getId())); menu.setParentId(String.valueOf(menuDO.getParentId())); return menu; } @Override public int compareTo(Menu o) { if (Objects.isNull(o)) { return -1; } if (Objects.isNull(this.getOrderNum())) { return 1; } return this.getOrderNum().compareTo(o.getOrderNum()); } }
25.921569
63
0.676248
ccf841a74eb0ca3c3163851209fe32692e62c46b
949
package page16.q1589; import java.util.Scanner; import java.util.TreeSet; public class Main { private static class Key implements Comparable{ private int index; private double time; public Key(int index, int c, int v) { this.index = index; this.time = (double)c / v; } @Override public int compareTo(Object o) { Key k = (Key)o; double diff = this.time - k.time; if(diff < 0) return 1; else if(diff > 0) return -1; return k.index - this.index; } } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(), i = 1; TreeSet<Key> s = new TreeSet<Key>(); while(n-- > 0) { s.add(new Key(i++, in.nextInt(), in.nextInt())); } StringBuilder sb = new StringBuilder(); for(Key k : s.descendingSet()) sb.append(' ').append(k.index); System.out.println(sb.substring(1)); } }
21.568182
54
0.581665
bc76319c0aa45ae0054da8b36e797686f30a2ba0
4,038
package stork.scheduler; import stork.core.server.*; import stork.util.*; import stork.feather.*; import stork.util.*; import java.util.*; import java.util.concurrent.*; /** * Maintains a set of all {@code Job}s and handles ordering {@code Job} for * execution. This class implements a {@code Set} interface so its state can be * restored after restarting the system. {@code Job}s enter the system via the * {@link #add(Job)} method, which handles filtering and other bookkeeping. * Subclasses need only implement the {@link #schedule(Job)} method and any * data structures necessary to support the scheduling of {@code Job}s. */ public abstract class Scheduler implements Set<Job> { // All jobs known by the system, indexed by UUID. private transient HashMap<UUID,Job> jobs = new HashMap<UUID,Job>(); // Jobs added before start() has been called. private transient List<Job> pending = new LinkedList<Job>(); /** * Schedule {@code job} to be executed. The scheduler implementation need * only find a time to schedule the job based on whatever scheduling policy * the schedule implements. This will be called again automatically if a job * fails and it still has more attempts remaining. */ protected abstract void schedule(Job job); /** * The server this scheduler belongs to. Subclasses should not override this. */ public Server server() { return null; } /** * Add a job and schedule it if necessary. This will always either return * {@code true} or throw a {@code RuntimeException}. */ public final synchronized boolean add(Job job) { if (contains(job)) throw new RuntimeException("Job is already scheduled."); jobs.put(job.uuid(), job); job.scheduler = this; // If we're still waiting for start() to be called, add it to the pending // list. if (pending != null) pending.add(job); else doSchedule(job); return true; } private void doSchedule(Job job) { if (job.canBeScheduled()) try { job.status(JobStatus.scheduled); schedule(job); } catch (RuntimeException e) { job.status(JobStatus.failed, e.getMessage()); } } /** * Call this to indicate that the server state has been finalized and jobs * may begin being scheduled. */ public final synchronized void start() { for (Job job : pending) doSchedule(job); pending = null; } public final boolean addAll(Collection<? extends Job> jobs) { if (jobs.isEmpty()) return false; for (Job job : jobs) add(job); return true; } /** Jobs cannot be removed. */ public void clear() { throw new UnsupportedOperationException(); } public final boolean contains(Object o) { if (o instanceof Job) return contains((Job) o); return false; } public final boolean contains(Job job) { return jobs.containsKey(job.uuid()); } public final boolean containsAll(Collection<?> c) { for (Object o : c) if (!contains(c)) return false; return true; } public final boolean equals(Object o) { if (!(o instanceof Scheduler)) return false; return containsAll((Scheduler) o); } /** Get a {@code Job} by its UUID. */ public final Job get(UUID uuid) { return jobs.get(uuid); } public final int hashCode() { return jobs.hashCode(); } public final boolean isEmpty() { return jobs.isEmpty(); } public final Iterator<Job> iterator() { return jobs.values().iterator(); } public final boolean remove(Object o) { throw new UnsupportedOperationException(); } public final boolean removeAll(Collection<?> c) { throw new UnsupportedOperationException(); } public final boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException(); } public final int size() { return jobs.size(); } public final Object[] toArray() { return jobs.values().toArray(new Job[size()]); } public final <T> T[] toArray(T[] a) { return jobs.values().toArray(a); } }
26.220779
79
0.665428
ed0396026abc5a0b2aa221bf3b2f744964bde00a
2,765
/* * Copyright 2018 ConsenSys AG. * * 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 tech.pegasys.pantheon.ethereum.p2p.discovery.internal; import static org.assertj.core.api.Assertions.assertThat; import tech.pegasys.pantheon.util.bytes.BytesValue; import java.util.Random; import org.junit.Test; public class PeerDiscoveryControllerDistanceCalculatorTest { @Test public void distanceZero() { final byte[] id = new byte[64]; new Random().nextBytes(id); assertThat(PeerTable.distance(BytesValue.wrap(id), BytesValue.wrap(id))).isEqualTo(0); } @Test public void distance1() { final BytesValue id1 = BytesValue.fromHexString("0x8f19400000"); final BytesValue id2 = BytesValue.fromHexString("0x8f19400001"); assertThat(PeerTable.distance(id1, id2)).isEqualTo(1); } @Test public void distance2() { final BytesValue id1 = BytesValue.fromHexString("0x8f19400000"); final BytesValue id2 = BytesValue.fromHexString("0x8f19400002"); assertThat(PeerTable.distance(id1, id2)).isEqualTo(2); } @Test public void distance3() { final BytesValue id1 = BytesValue.fromHexString("0x8f19400000"); final BytesValue id2 = BytesValue.fromHexString("0x8f19400004"); assertThat(PeerTable.distance(id1, id2)).isEqualTo(3); } @Test public void distance9() { final BytesValue id1 = BytesValue.fromHexString("0x8f19400100"); final BytesValue id2 = BytesValue.fromHexString("0x8f19400000"); assertThat(PeerTable.distance(id1, id2)).isEqualTo(9); } @Test public void distance40() { final BytesValue id1 = BytesValue.fromHexString("0x8f19400000"); final BytesValue id2 = BytesValue.fromHexString("0x0f19400000"); assertThat(PeerTable.distance(id1, id2)).isEqualTo(40); } @Test(expected = AssertionError.class) public void distance40_differentLengths() { final BytesValue id1 = BytesValue.fromHexString("0x8f19400000"); final BytesValue id2 = BytesValue.fromHexString("0x0f1940000099"); assertThat(PeerTable.distance(id1, id2)).isEqualTo(40); } @Test public void distanceZero_emptyArrays() { final BytesValue id1 = BytesValue.EMPTY; final BytesValue id2 = BytesValue.EMPTY; assertThat(PeerTable.distance(id1, id2)).isEqualTo(0); } }
34.135802
118
0.739602
fe1c1b81ac7ec73b8e4fc987ae70a784d18dbb2b
385
package factory.simplefactory; import factory.simplefactory.apple.Apple; public class TestSimpleFactory { public static void main(String[] args) { SimpleFactory factory = new SimpleFactory(); Apple red = factory.createApple("red"); red.eat(); System.out.println(); Apple green = factory.createApple("green"); green.eat(); } }
24.0625
52
0.646753
34e57533cb993002a0a1b6c30cc0dd4a79e2ce58
1,665
package com.reandroid.lib.arsc.decoder; import com.reandroid.lib.arsc.value.ResValueBag; import java.util.HashSet; import java.util.Set; public class ResourceNameStore implements ResourceNameProvider { private final Set<ResourceNameProvider> resourceNameProviders; public ResourceNameStore(){ this.resourceNameProviders=new HashSet<>(); } public void addResourceNameProvider(ResourceNameProvider provider){ if(provider!=null){ resourceNameProviders.add(provider); } } public Set<ResourceNameProvider> getResourceNameProviders(){ return resourceNameProviders; } @Override public String getResourceFullName(int resId, boolean includePackageName) { for(ResourceNameProvider provider:this.resourceNameProviders){ String name=provider.getResourceFullName(resId, includePackageName); if(name!=null){ return name; } } return null; } @Override public String getResourceName(int resId, boolean includePackageName) { for(ResourceNameProvider provider:this.resourceNameProviders){ String name=provider.getResourceName(resId, includePackageName); if(name!=null){ return name; } } return null; } @Override public ResValueBag getAttributeBag(int resId) { for(ResourceNameProvider provider:this.resourceNameProviders){ ResValueBag resValueBag=provider.getAttributeBag(resId); if(resValueBag!=null){ return resValueBag; } } return null; } }
31.415094
80
0.658859
93f3c38216d2017376f5f18dccdd2d4e364e544c
437
package tetris.factories; import tetris.panel.AbsPanel; public class PanelFactory { public static AbsPanel getPanel(String panelName){ try { return (AbsPanel) Class.forName("tetris.panel." + panelName).newInstance(); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { e.printStackTrace(); } System.err.println("Class tetris.panel." + panelName +" Not Found!"); return null; } }
24.277778
86
0.732265
f7dbc7ecd23c8ef8b87bdc225c8c388fb953029e
1,101
package com.walmartlabs.concord.common.form; /*- * ***** * Concord * ----- * Copyright (C) 2017 - 2019 Walmart 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. * ===== */ import io.takari.bpm.form.FormValidatorLocale; import io.takari.bpm.model.form.FormField; public interface ConcordFormValidatorLocale extends FormValidatorLocale { /** * Expected a date value. * * @param formId * @param field * @param idx * @param value * @return */ String expectedDate(String formId, FormField field, Integer idx, Object value); }
28.230769
83
0.689373
7e9e3bcbb1904b81751ff45ae26210eef71f837a
449
package org.jeecg.modules.party_building.service; import com.baomidou.mybatisplus.extension.service.IService; import org.jeecg.modules.party_building.entity.DataInformationFile; import java.util.List; /** * @Description: data_information_file * @Author: jeecg-boot * @Date: 2020-07-02 * @Version: V1.0 */ public interface IDataInformationFileService extends IService<DataInformationFile> { List<String> listByRelatedId(String id); }
23.631579
84
0.781737
c919798e17a8b35ed4902b42599b92554016c54e
1,501
package net.redbear.board.controller.model.product; import android.content.Intent; import android.util.Log; import net.redbear.board.controller.model.pin.Pin; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; /** * Created by dong on 3/23/16. */ public class Board { protected List<Pin> pinList; protected Board(){ pinList = new ArrayList<>(); } public int getPinAmount(){ return pinList.size(); } public Pin getPin(int pinNum){ return pinList.get(pinNum); } public boolean isPinModeIDE(int pinNum){ return pinList.get(pinNum).getPinMode() == Common.PIN_MODE_IDE; } public ArrayList<Integer> getPinModeSupport(int pinNum){ return pinList.get(pinNum).getSupportPinNumMode(); } public void notifyPinData(int pin,int pinMode,int value){ for(Pin p : pinList){ if (p.getPinNum() == pin){ p.setPinMode(pinMode); p.setValue(value); } } } public void resetAll(){ for(Pin p : pinList){ if (p.getPinMode() != Common.PIN_MODE_DISABLE){ p.setPinMode(Common.PIN_MODE_IDE); p.setValue(0); } } } public int getPinViewNum(int pin){ for(Pin p : pinList){ if (p.getPinNum() == pin){ return p.getPinViewNum(); } } return -1; } }
20.847222
71
0.576282
f4a4c7dd0a9019c08e97fadcdf455ffb1272bd15
630
package timeflow.data.db.filter; import timeflow.data.db.Act; import timeflow.data.db.Field; public class MissingValueFilter extends ActFilter { private Field field; private boolean text, array, number; public MissingValueFilter(Field field) { this.field=field; text=field.getType()==String.class; array=field.getType()==String[].class; number=field.getType()==Double.class; } @Override public boolean accept(Act act) { Object o=act.get(field); return o==null || number && Double.isNaN(((Double)o).doubleValue()) || text && "".equals(o) || array && ((String[])o).length==0; } }
22.5
60
0.674603
4b76423f14946eedab3abb1dfc79857df6e3e7c3
4,665
package controllers; import static akka.pattern.Patterns.ask; import java.util.List; import java.util.concurrent.CompletionStage; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import javax.inject.Inject; import com.avaje.ebean.Ebean; import com.avaje.ebean.Query; import actors.CategoryActorProtocol; import models.Category; import models.Product; import models.User; import play.data.Form; import play.data.FormFactory; import play.mvc.Controller; import play.mvc.Result; import play.mvc.Security; import scala.compat.java8.FutureConverters; import views.*; import views.html.*; import views.formdata.*; /** *Login Controller: *--------------------- * * This class handles the access to the system by interacting with the Secured class (app/controllers/Secured.java) * All the methods in this class are returning the requests in the typical way that Play Framework does, that is * returning a Result object. Internally, Play framework does this calls asynchronously with the use of CompletionStage * and that behaviour is shown in the controllers : ProductController and CategoryController. * * Also the use of Lists are handled using the Java Collections Framework and Generics. * * @author joana * */ public class LoginController extends Controller{ @Inject FormFactory formFactory; private AtomicInteger usersCounter; @Inject public LoginController(FormFactory formFactory, AtomicInteger usersCounter){ this.formFactory = formFactory; this.usersCounter = usersCounter; } public AtomicInteger getUsersCounter() { return usersCounter; } public void setUsersCounter(AtomicInteger usersCounter) { this.usersCounter = usersCounter; } /** * Provides the Index page. * @return The Index page. */ public Result index(String idcategory) { Category c = new Category(); List<Category> lc = c.find.all(); String idString = idcategory; if (idcategory == null) { idString="1"; } Category category = new Category(); category = Category.find.byId(Integer.parseInt(idcategory)); if (category == null){ Query<Category> cat = Ebean.createQuery(Category.class, "limit 1"); List<Category> list = cat.findList(); category = list.get(0); } else{ category.setId(Integer.parseInt(idString)); } List<Product> productList = Product.find.where().eq("idcategory", category.getId()).findList(); return ok(index.render("Home", Secured.isLoggedIn(ctx()), Secured.getUserInfo(ctx()), lc, productList)); } /** * Provides the Login page (only to unauthenticated users). * @return The Login page. */ public Result login() { if (Secured.isLoggedIn(ctx())){ return redirect(routes.LoginController.home()); } else{ Form<LoginFormData> formData = formFactory.form(LoginFormData.class); return ok(login.render("Login", Secured.isLoggedIn(ctx()), Secured.getUserInfo(ctx()), formData)); } } /** * Processes a login form submission from an unauthenticated user. * First we bind the HTTP POST data to an instance of LoginFormData. * The binding process will invoke the LoginFormData.vrunalidate() method. * If errors are found, re-render the page, displaying the error data. * If errors not found, render the page with the good data. * @return The index page with the results of validation. */ public Result postLogin() { Form<LoginFormData> formData = formFactory.form(LoginFormData.class); LoginFormData loginData = formData.bindFromRequest().get(); List<User> users = User.find.where().eq("email", loginData.email).eq("pwd", loginData.password).findList(); if (!users.isEmpty()){ session().clear(); session("email", loginData.email); usersCounter.incrementAndGet(); return redirect(routes.LoginController.home()); } else{ flash("error", "Login credentials not valid."); return redirect(routes.LoginController.login()); } } /** * Logs out (only for authenticated users) and returns them to the Index page. * @return A redirect to the Index page. */ @Security.Authenticated(Secured.class) public Result logout() { usersCounter.decrementAndGet(); session().clear(); return redirect(routes.LoginController.index("1")); } /** * Provides the Home page to the category list of products (only to authenticated users). * @return The category home page. */ @Security.Authenticated(Secured.class) public Result home() { List<Category> categories = Category.find.all(); if (usersCounter.get()==0) { usersCounter.incrementAndGet(); } return ok(home.render("Home", Secured.isLoggedIn(ctx()), Secured.getUserInfo(ctx()), categories, usersCounter.get())); } }
29.15625
120
0.728403
60caa8377f5afeb00223e7fbbf6f942e8cfe0b14
462
package dev.hephaestus.automotion.common.block.entity; import dev.hephaestus.automotion.common.AutomotionBlocks; import net.minecraft.block.BlockState; import net.minecraft.block.entity.BlockEntity; import net.minecraft.util.math.BlockPos; public class EntityDetectorBlockEntity extends BlockEntity { public EntityDetectorBlockEntity(BlockPos pos, BlockState state) { super(AutomotionBlocks.BASIC_ENTITY_DETECTOR_BLOCK_ENTITY, pos, state); } }
35.538462
79
0.820346
b16564c73d58f54067a492d945c290232c6e5b3b
13,554
package kam.hazelrigg; import edu.stanford.nlp.pipeline.StanfordCoreNLP; import kam.hazelrigg.readers.*; import org.apache.commons.cli.ParseException; import org.junit.BeforeClass; import org.junit.Test; import org.junit.rules.ExpectedException; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.Properties; import static org.junit.Assert.*; public class WillowTest { final private ExpectedException e = ExpectedException.none(); @BeforeClass public static void setUp() { Willow.pipeline = createPipeline(); try { BatchRunner.passCommandLine(Willow.getCommandLine(new String[]{""})); } catch (ParseException e1) { e1.printStackTrace(); } } @Test public void stringDoesNotEqualFreqmap() { FreqMap one; one = new FreqMap(); one.increaseFreq("test"); assertFalse(one.equals("test")); } @Test public void freqmapsAreEqual() { FreqMap one; one = new FreqMap(); one.increaseFreq("test"); one.increaseFreq("best"); FreqMap two = new FreqMap(); two.increaseFreq("test"); two.increaseFreq("best"); assertTrue(one.equals(two)); } @Test public void freqmapsAreNotEqual() { FreqMap one; one = new FreqMap(); one.increaseFreq("test"); FreqMap two = new FreqMap(); one.increaseFreq("toast"); assertFalse(one.equals(two)); } @Test public void getsTitleFromText() { Book test = getTestBook(); test.setTitleFromText(); assertEquals("2 B R 0 2 B", test.getTitle()); } @Test public void getsNameFromText() { Book test = getTestBook(); test.setTitleFromText(); assertEquals("2 B R 0 2 B by Kurt Vonnegut", test.getName()); } @Test(expected = NullPointerException.class) public void nullReadFileTest() { Book test = new Book(); test.readText(false); } @Test public void setTitleFakeFileTest() { e.expect(FileNotFoundException.class); Book test = new Book(); Path fakePath = Paths.get("thiscouldntbearealfileifitwantedtobe.okay"); test.setPath(fakePath); test.readText(false); } @Test public void shouldGetIsGutenberg() { Book test = getTestBook(); test.setTitleFromText(); BookStats stats = test.getStats(); assertTrue(stats.isGutenberg()); } @Test public void shouldGetIsNotGutenberg() { Book test = getTestBook("test2.txt"); test.setTitleFromText(); BookStats stats = test.getStats(); assertFalse(stats.isGutenberg()); } @Test public void shouldGetIsGutenbergVariant() { Book test = getTestBook("test3.txt"); test.setTitleFromText(); BookStats stats = test.getStats(); assertTrue(stats.isGutenberg()); } @Test public void shouldReadText() { Book test = getTestBook(); assertTrue(test.readText(false)); } @Test public void shouldBeMissingFile() { Book test = new Book(); test.setPath(Paths.get("whoops, nothing here")); assertFalse(test.readText(false)); } @Test public void createsSubdirectoryBook() { Book test = new Book("dir"); assertEquals("dir", test.getSubdirectory()); } @Test public void createsTXT() { Book test = getTestBook(); test.readText(false); OutputWriter ow = new OutputWriter(test); boolean wroteTxt = ow.writeTxt(); assertTrue(wroteTxt); } @Test public void createsJSON() { Book test = getTestBook(); test.readText(false); OutputWriter ow = new OutputWriter(test); assertTrue(ow.writeJson()); } @Test public void createsCSV() { Book test = getTestBook(); test.readText(false); OutputWriter ow = new OutputWriter(test); assertTrue(ow.writeCsv()); } @Test public void createsPartsOfSpeechChart() { Book test = getTestBook(); test.readText(false); OutputWriter ow = new OutputWriter(test); assertTrue(ow.makePartsOfSpeechGraph()); } @Test public void createsSyllableDistributionChart() { Book test = getTestBook(); test.readText(false); OutputWriter ow = new OutputWriter(test); assertTrue(ow.makeSyllableDistributionGraph()); } @Test public void getsCorrectWordCount() throws ParseException { Runner testEconomyRunner = new Runner(getTestPath(), getTestPath()); testEconomyRunner.setCommandLine(Willow.getCommandLine(new String[]{"-eo"})); testEconomyRunner.run(); Book test = testEconomyRunner.getBook(); BookStats stats = test.getStats(); assertEquals(2672, stats.getWordCount()); } @Test public void getsCorrectNouns() { Book test = getTestBook(); test.readText(false); BookStats stats = test.getStats(); assertEquals(363, stats.getPartsOfSpeech().get("Noun, singular or mass")); } @Test public void getsNovelLength() { Book test = getTestBook("test4.txt"); test.readText(false); BookStats stats = test.getStats(); assertEquals("novel", stats.getClassifiedLength()); } @Test public void getsSentenceCount() { Book test = getTestBook(); test.readText(false); BookStats stats = test.getStats(); assertEquals(261, stats.getSentenceCount()); } @Test public void getsMonosyllabic() { Book test = getTestBook(); test.readText(false); BookStats stats = test.getStats(); assertEquals(1769, stats.getMonosyllablic()); } @Test public void getsPolysyllabic() { Book test = getTestBook(); test.readText(false); BookStats stats = test.getStats(); assertEquals(905, stats.getPolysyllablic()); } @Test public void isDifficult() { Book test = getTestBook("difficult.txt"); test.readText(false); BookStats stats = test.getStats(); assertEquals("difficult", stats.getEasyDifficult()); } @Test public void getsGradeLevel() { Book test = getTestBook("Obama.txt"); test.readText(false); BookStats stats = test.getStats(); assertEquals("10th to 12th grade", stats.classifyKincaidScore(stats.getFleschKincaidScore())); } @Test public void runBatchSetOfFiles() throws IOException { BatchRunner.clear(); BatchRunner.startRunners(getTestPath("dir"), 3); ArrayList<Runner> runners = BatchRunner.getRunners(); ArrayList<String> realPaths = new ArrayList<>(); realPaths.add("test.txt"); realPaths.add("test2.txt"); realPaths.add("test3.txt"); ArrayList<String> paths = new ArrayList<>(); for (Runner runner : runners) { paths.add(runner.getBook().getPath().getFileName().toString()); } Collections.sort(paths); assertEquals(realPaths, paths); } @Test(expected = IOException.class) public void runNullFolder() throws IOException { BatchRunner.startRunners(getTestPath(null), 1); } @Test public void batchRunnerSingleFile() throws IOException { BatchRunner.clear(); BatchRunner.startRunners(getTestPath(), 1); assertEquals(1, BatchRunner.getRunners().size()); } @Test public void runnerCreatesResults() throws ParseException { Runner runner = new Runner(getTestPath(), getTestPath()); runner.setCommandLine(Willow.getCommandLine(new String[]{"-o"})); runner.run(); assertTrue(runner.getBook().hasResults(false, false)); } @Test(expected = IOException.class) public void batchRunnerNullFile() throws IOException { BatchRunner.clear(); BatchRunner.startRunners(getTestPath("notarealfile"), 0); } @Test(expected = UnsupportedOperationException.class) public void batchRunnerNoConstructor() { new BatchRunner(); } @Test(expected = UnsupportedOperationException.class) public void willowNoConstructor() { new Willow(); } // Text Readers @Test public void economyModeGetsCorrectWordCounts() throws ParseException { Runner testEconomyRunner = new Runner(getTestPath(), getTestPath()); testEconomyRunner.setCommandLine(Willow.getCommandLine(new String[]{"-oe"})); testEconomyRunner.run(); Book test = testEconomyRunner.getBook(); BookStats stats = test.getStats(); long wordCount = stats.getWordCount(); assertEquals(2672, wordCount); } @Test public void getsEconomyTextReader() { Book test = getTestBook(); test.readText(true); assertTrue(test.getTextReader() instanceof EconomyTextReader); } @Test public void getsPlainTextReader() { Book test = getTestBook(); test.readText(false); assertTrue(test.getTextReader() instanceof PlainTextReader); } @Test public void getsPdfTextReader() { Book test = getTestBook("test.pdf"); test.readText(false); assertTrue(test.getTextReader() instanceof PdfTextReader); } @Test public void getsDocTextReader() { Book test = getTestBook("TestWordDoc.doc"); test.readText(false); assertTrue(test.getTextReader() instanceof DocTextReader); } @Test public void getsDocxTextReader() { Book test = getTestBook("demo.docx"); test.readText(false); assertTrue(test.getTextReader() instanceof DocxTextReader); } @Test public void plainTextIOException() { e.expect(IOException.class); Book test = new Book(); PlainTextReader reader = new PlainTextReader(); reader.setBook(test); reader.setPath(Paths.get("")); reader.readText(); } @Test public void pdfReaderIOException() { e.expect(IOException.class); Book test = new Book(); PdfTextReader reader = new PdfTextReader(); reader.setBook(test); reader.setPath(Paths.get("")); reader.readText(); } @Test public void economyIOException() { e.expect(IOException.class); Book test = new Book(); EconomyTextReader reader = new EconomyTextReader(); reader.setBook(test); reader.setPath(Paths.get("")); reader.readText(); } @Test public void economyScratchException() { e.expect(IOException.class); Book test = new Book(); EconomyTextReader reader = new EconomyTextReader(); reader.setBook(test); reader.setPath(Paths.get("")); reader.readText(); } @Test public void docxIOException() { e.expect(IOException.class); Book test = new Book(); DocxTextReader reader = new DocxTextReader(); reader.setBook(test); reader.setPath(Paths.get("")); reader.readText(); } @Test public void docIOException() { e.expect(IOException.class); Book test = new Book(); DocTextReader reader = new DocTextReader(); reader.setBook(test); reader.setPath(Paths.get("")); reader.readText(); } @Test public void runnerRunsFlags() throws ParseException { Runner runner = new Runner(getTestPath(), getTestPath()); runner.setCommandLine(Willow.getCommandLine(new String[]{"-jicoe"})); runner.run(); Book tester = runner.getBook(); assertTrue(tester.hasResults(true, true)); } @Test(expected = IllegalArgumentException.class) public void willowPrintsHelp() { Willow.main(new String[]{"-o"}); } @Test public void willowNotRealPath() { e.expect(IOException.class); Willow.main(new String[]{"areallylongnamethatisnotanactualdirectory"}); } @Test public void willowParseException() { e.expect(ParseException.class); Willow.main(new String[]{"-xyz", ""}); } @Test public void willowRuns() { BatchRunner.clear(); Willow.main(new String[]{"-ot", "3", "src/test/resources/dir"}); assertEquals(3, BatchRunner.getRunners().size()); } private static StanfordCoreNLP createPipeline() { Properties properties = new Properties(); properties.put("annotators", "tokenize, ssplit, pos, lemma"); properties.put("tokenize.options", "untokenizable=noneDelete"); return new StanfordCoreNLP(properties); } private static Book getTestBook() { Book book = new Book(); book.setPath(getTestPath()); book.setTitleFromText(); return book; } private static Book getTestBook(String path) { Book book = new Book(); book.setPath(getTestPath(path)); book.setTitleFromText(); return book; } private static Path getTestPath() { return new File("src/test/resources/test.txt").toPath(); } private static Path getTestPath(String path) { return new File("src/test/resources/" + path).toPath(); } }
28.296451
102
0.619448
ad287c2d668a6c16cd63e83ce55a19c4d4509aa4
3,462
/* * File : RegisterServlet.java * Authors : Antoine Drabble & Guillaume Serneels * Last Modified : 21.10.2016 */ package com.heig.amt.webapp.web; import com.heig.amt.webapp.services.UserServiceLocal; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.ejb.DuplicateKeyException; import javax.ejb.EJB; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * This Servlet relies on the UserService EJB to provide the user registering * feature to our web service. * * @author Antoine Drabble antoine.drabble@heig-vd.ch * @author Guillaume Serneels guillaume.serneels@heig-vd.ch */ public class RegisterServlet extends HttpServlet { @EJB private UserServiceLocal userService; // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * Show the register page. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("id", request.getSession().getAttribute("id")); request.getRequestDispatcher("/WEB-INF/pages/register.jsp").forward(request, response); } /** * Handles the HTTP <code>POST</code> method. * Tries to register the user with the given POST parameters. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { long id = userService.create(request.getParameter("username"), request.getParameter("password"), request.getParameter("email"), request.getParameter("firstname"), request.getParameter("lastname")); request.getSession().setAttribute("id", id); response.sendRedirect(request.getContextPath() + "/users"); } catch (DuplicateKeyException e) { request.setAttribute("error", e.getMessage()); request.getRequestDispatcher("/WEB-INF/pages/register.jsp").forward(request, response); }catch (Exception e) { Logger.getLogger(LoginServlet.class.getName()).log(Level.SEVERE, e.getMessage(), e); String message; // If there is an error in the POST parameters if (e.getCause() != null && e.getCause().getClass().getSimpleName().equals(IllegalArgumentException.class.getSimpleName())) { message = e.getCause().getMessage(); } // Otherwise send internal server error message else { message = "Internal server error!"; } request.setAttribute("error", message); request.getRequestDispatcher("/WEB-INF/pages/register.jsp").forward(request, response); } } }
39.340909
137
0.669266
c7a85cf0aac15183b4c84a6e29e09546e9558d09
976
package com.gq.mediaplayer; public class TrackBean { private String subtitleName; private String audioName; private int index; public int getType() { return type; } public void setType(int type) { this.type = type; } private int type; public String getSubtitleColor() { return subtitleColor; } public void setSubtitleColor(String subtitleColor) { this.subtitleColor = subtitleColor; } private String subtitleColor; public String getAudioName() { return audioName; } public void setAudioName(String audioName) { this.audioName = audioName; } public String getSubtitleName() { return subtitleName; } public void setSubtitleName(String subtitleName) { this.subtitleName = subtitleName; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } }
18.769231
56
0.626025
b609895a6367ffa2e18b9b890215cf37286da428
964
package com.example.homework.entity.order9th; public class RecommendManager { private RecommendCloth[] rCloth; private RecommendBook[] rBook; private final int CHOOSENUM = 3; private int serviceCode; public RecommendManager(int TOTAL, int MAX, int serviceCode){ this.serviceCode = serviceCode; randomRecommend(); } //recommendProduct를 실행 하면 랜덤 추천 상품이 MAX개 나오도록 만들자 //전역 변수를 사용해서 1번 상품(의류)나 2번 상품(책)이 나오게 해볼까 //쓰레드는 필요없고 상속까진 잘 활용하면 좋을 것 같다. public void randomRecommend(){ switch(serviceCode){ //일반 배열이 아니라 MAP 배열을 쓰고 싶음... case ProductNumber.CLOTH: rCloth = new RecommendCloth[CHOOSENUM]; //총 3개짜리 배열 선언 break; case ProductNumber.BOOK: rBook = new RecommendBook[CHOOSENUM]; break; } //세 개를 뽑는 반복문은 어디에 들어가면 좋나... //상품 중 3개를 뽑는 반복문이 들어있는 클래스를 상품 클래스들이 상속받게 만들까? } }
27.542857
70
0.60166
412c122329390d3b12613cf2083b8c79d3c3c1ca
527
package lombok.ast.pg; import lombok.Getter; @Getter public class Ternary extends Expression<Ternary> { private Expression<?> test; private Expression<?> ifTrue; private Expression<?> ifFalse; public Ternary(Expression<?> test, Expression<?> ifTrue, Expression<?> ifFalse) { this.test = test; this.ifTrue = ifTrue; this.ifFalse = ifFalse; } @Override public <RETURN_TYPE, PARAMETER_TYPE> RETURN_TYPE accept(ASTVisitor<RETURN_TYPE, PARAMETER_TYPE> v, PARAMETER_TYPE p) { return v.visitTernary(this, p); } }
23.954545
119
0.73814
d5eba9af51fefc4be8aeb04e2ad9c378d7f2628e
2,748
package com.covid19.rest; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpRequest; import org.springframework.http.HttpStatus; import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.ClientHttpResponse; import org.springframework.util.StreamUtils; import lombok.extern.slf4j.Slf4j; @Slf4j public class OutboundRequestInterceptor implements ClientHttpRequestInterceptor { @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { log.info("RestTemplate Request: URI={}, Headers={}, Body={}", request.getURI(), request.getHeaders(), new String(body)); ClientHttpResponse response = new BufferingClientHttpResponseWrapper(execution.execute(request, body)); StringBuilder inputStringBuilder = new StringBuilder(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody(), "UTF-8")); String line = bufferedReader.readLine(); while (line != null) { inputStringBuilder.append(line); inputStringBuilder.append('\n'); line = bufferedReader.readLine(); } log.info("RestTemplate Response: StatusCode={} {}, Headers={}, Body={}", response.getStatusCode(), response.getStatusText(), response.getHeaders(), inputStringBuilder.toString()); return response; } private static class BufferingClientHttpResponseWrapper implements ClientHttpResponse { private final ClientHttpResponse response; private byte[] body; BufferingClientHttpResponseWrapper(ClientHttpResponse response) { this.response = response; } @Override public HttpStatus getStatusCode() throws IOException { return this.response.getStatusCode(); } @Override public int getRawStatusCode() throws IOException { return this.response.getRawStatusCode(); } @Override public String getStatusText() throws IOException { return this.response.getStatusText(); } @Override public HttpHeaders getHeaders() { return this.response.getHeaders(); } @Override public InputStream getBody() throws IOException { if (this.body == null) { this.body = StreamUtils.copyToByteArray(this.response.getBody()); } return new ByteArrayInputStream(this.body); } @Override public void close() { this.response.close(); } } }
29.234043
89
0.729622
37e6e8ddc46789105b358c9ea9eaaed71556e2b6
3,720
/** * Copyright (c) 2012, Hadyn Richard * * 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 net.scapeemulator.game.model.pathfinding; /** * Created by Hadyn Richard */ public final class Tile { /** * The flags for each of the traversals. */ public static final int /* Each of the flags for walls */ WALL_NORTH = 0x1, WALL_SOUTH = 0x2, WALL_EAST = 0x4, WALL_WEST = 0x8, WALL_NORTH_EAST = 0x10, WALL_NORTH_WEST = 0x20, WALL_SOUTH_EAST = 0x40, WALL_SOUTH_WEST = 0x80, /* Each of the occupant flags for both impenetrable and normal */ OCCUPANT = 0x8000, IMPENETRABLE_OCCUPANT = 0x10000, /* Each of the impenetrable wall flags, meaning projectiles cannot fly over these */ IMPENETRABLE_WALL_NORTH = 0x100, IMPENETRABLE_WALL_SOUTH = 0x200, IMPENETRABLE_WALL_EAST = 0x400, IMPENETRABLE_WALL_WEST = 0x800, IMPENETRABLE_WALL_NORTH_EAST = 0x800, IMPENETRABLE_WALL_NORTH_WEST = 0x1000, IMPENETRABLE_WALL_SOUTH_EAST = 0x2000, IMPENETRABLE_WALL_SOUTH_WEST = 0x4000, /* The other flags */ BLOCKED = 0x20000, BRIDGE = 0x40000, NONE = 0x0; /** * The flags for the tile. */ private int flags; /** * Constructs a new {@link Tile}; */ public Tile() { this(NONE); } /** * Constructs a new {@link Tile}; */ public Tile(int flags) { this.flags = flags; } /** * Sets a flag for the tile. */ public void set(int flag) { flags |= flag; } /** * Unsets a flag for the tile. */ public void unset(int flag) { flags &= 0xffff - flag; } /** * Gets if a flag is active. * @param flag The flag to check for if it is active. * @return If the flag is active. */ public boolean isActive(int flag) { return (flags & flag) != 0; } /** * Gets if a flag is inactive. * @param flag The flag to check for if it is inactive. * @return If the flag is inactive. */ public boolean isInactive(int flag) { return (flags & flag) == 0; } /** * Gets the flags for the tile. */ public int flags() { return flags; } }
34.12844
113
0.569892
0d76d298aff3f79c51b9f46da9980edb4f9d7e92
12,173
/******************************************************************************* "FreePastry" Peer-to-Peer Application Development Substrate Copyright 2002-2007, Rice University. Copyright 2006-2007, Max Planck Institute for Software Systems. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of Rice University (RICE), Max Planck Institute for Software Systems (MPI-SWS) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. This software is provided by RICE, MPI-SWS and the contributors on an "as is" basis, without any representations or warranties of any kind, express or implied including, but not limited to, representations or warranties of non-infringement, merchantability or fitness for a particular purpose. In no event shall RICE, MPI-SWS or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage. *******************************************************************************/ package org.mpisws.p2p.transport.table; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Map; import org.mpisws.p2p.transport.ErrorHandler; import org.mpisws.p2p.transport.MessageCallback; import org.mpisws.p2p.transport.MessageRequestHandle; import org.mpisws.p2p.transport.P2PSocket; import org.mpisws.p2p.transport.SocketCallback; import org.mpisws.p2p.transport.SocketRequestHandle; import org.mpisws.p2p.transport.TransportLayer; import org.mpisws.p2p.transport.TransportLayerCallback; import org.mpisws.p2p.transport.util.BufferReader; import org.mpisws.p2p.transport.util.BufferWriter; import org.mpisws.p2p.transport.util.DefaultErrorHandler; import org.mpisws.p2p.transport.util.Serializer; import org.mpisws.p2p.transport.util.SocketRequestHandleImpl; import rice.Continuation; import rice.environment.Environment; import rice.environment.logging.Logger; import rice.p2p.commonapi.Cancellable; import rice.p2p.util.rawserialization.SimpleInputBuffer; import rice.p2p.util.rawserialization.SimpleOutputBuffer; /** * @author Jeff Hoye * */ public class TableTransprotLayerImpl<Identifier, Key, Value> implements TableTransportLayer<Identifier, Key, Value>, TransportLayerCallback<Identifier, ByteBuffer> { public static final byte PASSTHROUGH = 0; public static final byte REQUEST = 1; public static final byte RESPONSE_SUCCESS = 2; public static final byte RESPONSE_FAILED = 3; /** * Could just be a hashTable */ protected TableStore<Key, Value> knownValues; protected TransportLayerCallback<Identifier, ByteBuffer> callback; protected TransportLayer<Identifier, ByteBuffer> tl; protected Serializer<Key> keySerializer; protected Serializer<Value> valueSerializer; protected ErrorHandler<Identifier> errorHandler; protected Logger logger; /** * * @param iSerializer * @param cSerializer * @param tableStore should be pre-populated with any persistent or initial values * @param tl * @param env */ public TableTransprotLayerImpl(Serializer<Key> iSerializer, Serializer<Value> cSerializer, TableStore<Key, Value> tableStore, TransportLayer<Identifier, ByteBuffer> tl, Environment env) { this.keySerializer = iSerializer; this.valueSerializer = cSerializer; this.knownValues = tableStore; this.tl = tl; this.logger = env.getLogManager().getLogger(getClass(), null); this.errorHandler = new DefaultErrorHandler<Identifier>(this.logger); } /** * REQUEST, int requestId, Key */ public Cancellable requestValue(final Identifier source, final Key principal, final Continuation<Value, Exception> c, Map<String, Object> options) { if (logger.level <= Logger.FINE) logger.log("requestValue("+source+","+principal+")"); if (knownValues.containsKey(principal)) { if (c != null) c.receiveResult(knownValues.get(principal)); return null; } if (logger.level <= Logger.FINER) logger.log("requestValue("+source+","+principal+") opening socket"); return tl.openSocket(source, new SocketCallback<Identifier>() { public void receiveResult(SocketRequestHandle<Identifier> cancellable, P2PSocket<Identifier> sock) { try { SimpleOutputBuffer sob = new SimpleOutputBuffer(); keySerializer.serialize(principal,sob); SimpleOutputBuffer sob2 = new SimpleOutputBuffer(); sob2.writeByte(REQUEST); // here, we are allocating the space for the size value sob2.writeInt(sob.getWritten()); sob2.write(sob.getBytes()); new BufferWriter<Identifier>(sob2.getByteBuffer(), sock, new Continuation<P2PSocket<Identifier>, Exception>() { public void receiveException(Exception exception) { c.receiveException(exception); } public void receiveResult(P2PSocket<Identifier> result) { new BufferReader<Identifier>(result,new Continuation<ByteBuffer, Exception>() { public void receiveResult(ByteBuffer result) { try { SimpleInputBuffer sib = new SimpleInputBuffer(result); byte response = sib.readByte(); switch(response) { case RESPONSE_SUCCESS: Value value = valueSerializer.deserialize(sib); if (logger.level <= Logger.FINER) logger.log("requestValue("+source+","+principal+") got value "+value); knownValues.put(principal, value); c.receiveResult(value); break; case RESPONSE_FAILED: c.receiveException(new UnknownValueException(source, principal)); break; default: c.receiveException(new IllegalStateException("Unknown response:"+response)); break; } } catch (Exception ioe) { c.receiveException(ioe); } } public void receiveException(Exception exception) { c.receiveException(exception); } }); } },false); } catch (IOException ioe) { c.receiveException(ioe); } } public void receiveException(SocketRequestHandle<Identifier> s, Exception ex) { c.receiveException(ex); } }, options); } public SocketRequestHandle<Identifier> openSocket(Identifier i, final SocketCallback<Identifier> deliverSocketToMe, Map<String, Object> options) { final SocketRequestHandleImpl<Identifier> ret = new SocketRequestHandleImpl<Identifier>(i,options,logger); ret.setSubCancellable(tl.openSocket(i, new SocketCallback<Identifier>() { public void receiveException(SocketRequestHandle<Identifier> s, Exception ex) { deliverSocketToMe.receiveException(ret, ex); } public void receiveResult(SocketRequestHandle<Identifier> cancellable, P2PSocket<Identifier> sock) { ByteBuffer writeMe = ByteBuffer.allocate(1); writeMe.put(PASSTHROUGH); writeMe.clear(); new BufferWriter<Identifier>(writeMe, sock, new Continuation<P2PSocket<Identifier>, Exception>() { public void receiveException(Exception exception) { deliverSocketToMe.receiveException(ret, exception); } public void receiveResult(P2PSocket<Identifier> result) { deliverSocketToMe.receiveResult(ret, result); } }, false); } }, options)); return ret; } public void incomingSocket(final P2PSocket<Identifier> sock) throws IOException { if (logger.level <= Logger.FINEST) logger.log("incomingSocket() from "+sock); new BufferReader<Identifier>(sock,new Continuation<ByteBuffer, Exception>() { public void receiveResult(ByteBuffer result) { byte type = result.get(); if (logger.level <= Logger.FINEST) logger.log("incomingSocket() from "+sock+" "+type); switch (type) { case PASSTHROUGH: try { callback.incomingSocket(sock); } catch (IOException ioe) { errorHandler.receivedException(sock.getIdentifier(), ioe); } return; case REQUEST: handleValueRequest(sock); return; default: errorHandler.receivedUnexpectedData(sock.getIdentifier(), new byte[] {type}, 0, sock.getOptions()); sock.close(); } } public void receiveException(Exception exception) { errorHandler.receivedException(sock.getIdentifier(), exception); } },1); } public void handleValueRequest(final P2PSocket<Identifier> sock) { if (logger.level <= Logger.FINER) logger.log("handleValueRequest() from "+sock); new BufferReader<Identifier>(sock,new Continuation<ByteBuffer, Exception>() { public void receiveResult(ByteBuffer result) { try { SimpleInputBuffer sib = new SimpleInputBuffer(result); Key principal = keySerializer.deserialize(sib); ByteBuffer writeMe; if (knownValues.containsKey(principal)) { SimpleOutputBuffer sob = new SimpleOutputBuffer(); sob.writeByte(RESPONSE_SUCCESS); valueSerializer.serialize(knownValues.get(principal), sob); writeMe = sob.getByteBuffer(); } else { writeMe = ByteBuffer.allocate(1); writeMe.put(RESPONSE_FAILED); writeMe.clear(); } new BufferWriter<Identifier>(writeMe,sock,null); } catch (Exception ioe) { errorHandler.receivedException(sock.getIdentifier(), ioe); sock.close(); } } public void receiveException(Exception exception) { errorHandler.receivedException(sock.getIdentifier(), exception); } }); } public boolean hasKey(Key i) { return knownValues.containsKey(i); } public void acceptMessages(boolean b) { tl.acceptMessages(b); } public void acceptSockets(boolean b) { tl.acceptSockets(b); } public Identifier getLocalIdentifier() { return tl.getLocalIdentifier(); } public MessageRequestHandle<Identifier, ByteBuffer> sendMessage(Identifier i, ByteBuffer m, MessageCallback<Identifier, ByteBuffer> deliverAckToMe, Map<String, Object> options) { return tl.sendMessage(i, m, deliverAckToMe, options); } public void setCallback( TransportLayerCallback<Identifier, ByteBuffer> callback) { this.callback = callback; } public void setErrorHandler(ErrorHandler<Identifier> handler) { this.errorHandler = handler; } public void destroy() { tl.destroy(); } public void messageReceived(Identifier i, ByteBuffer m, Map<String, Object> options) throws IOException { callback.messageReceived(i, m, options); } }
37.2263
189
0.658753
31b0a97b1ac93fb090e758f546e9590038075163
15,430
/* * This file is generated by jOOQ. */ package io.cattle.platform.core.model.tables.records; import io.cattle.platform.core.model.DynamicSchema; import io.cattle.platform.core.model.tables.DynamicSchemaTable; import io.cattle.platform.db.jooq.utils.TableRecordJaxb; import java.util.Date; import java.util.Map; import javax.annotation.Generated; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.jooq.Field; import org.jooq.Record1; import org.jooq.Record13; import org.jooq.Row13; import org.jooq.impl.UpdatableRecordImpl; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.9.3" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) @Entity @Table(name = "dynamic_schema", schema = "cattle") public class DynamicSchemaRecord extends UpdatableRecordImpl<DynamicSchemaRecord> implements TableRecordJaxb, Record13<Long, String, Long, String, String, String, String, Date, Map<String,Object>, String, String, Long, Date>, DynamicSchema { private static final long serialVersionUID = 1052968725; /** * Setter for <code>cattle.dynamic_schema.id</code>. */ @Override public void setId(Long value) { set(0, value); } /** * Getter for <code>cattle.dynamic_schema.id</code>. */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", unique = true, nullable = false, precision = 19) @Override public Long getId() { return (Long) get(0); } /** * Setter for <code>cattle.dynamic_schema.name</code>. */ @Override public void setName(String value) { set(1, value); } /** * Getter for <code>cattle.dynamic_schema.name</code>. */ @Column(name = "name", length = 255) @Override public String getName() { return (String) get(1); } /** * Setter for <code>cattle.dynamic_schema.account_id</code>. */ @Override public void setAccountId(Long value) { set(2, value); } /** * Getter for <code>cattle.dynamic_schema.account_id</code>. */ @Column(name = "account_id", precision = 19) @Override public Long getAccountId() { return (Long) get(2); } /** * Setter for <code>cattle.dynamic_schema.kind</code>. */ @Override public void setKind(String value) { set(3, value); } /** * Getter for <code>cattle.dynamic_schema.kind</code>. */ @Column(name = "kind", nullable = false, length = 255) @Override public String getKind() { return (String) get(3); } /** * Setter for <code>cattle.dynamic_schema.uuid</code>. */ @Override public void setUuid(String value) { set(4, value); } /** * Getter for <code>cattle.dynamic_schema.uuid</code>. */ @Column(name = "uuid", unique = true, nullable = false, length = 128) @Override public String getUuid() { return (String) get(4); } /** * Setter for <code>cattle.dynamic_schema.description</code>. */ @Override public void setDescription(String value) { set(5, value); } /** * Getter for <code>cattle.dynamic_schema.description</code>. */ @Column(name = "description", length = 1024) @Override public String getDescription() { return (String) get(5); } /** * Setter for <code>cattle.dynamic_schema.state</code>. */ @Override public void setState(String value) { set(6, value); } /** * Getter for <code>cattle.dynamic_schema.state</code>. */ @Column(name = "state", nullable = false, length = 128) @Override public String getState() { return (String) get(6); } /** * Setter for <code>cattle.dynamic_schema.created</code>. */ @Override public void setCreated(Date value) { set(7, value); } /** * Getter for <code>cattle.dynamic_schema.created</code>. */ @Column(name = "created") @Override public Date getCreated() { return (Date) get(7); } /** * Setter for <code>cattle.dynamic_schema.data</code>. */ @Override public void setData(Map<String,Object> value) { set(8, value); } /** * Getter for <code>cattle.dynamic_schema.data</code>. */ @Column(name = "data", length = 65535) @Override public Map<String,Object> getData() { return (Map<String,Object>) get(8); } /** * Setter for <code>cattle.dynamic_schema.parent</code>. */ @Override public void setParent(String value) { set(9, value); } /** * Getter for <code>cattle.dynamic_schema.parent</code>. */ @Column(name = "parent", length = 255) @Override public String getParent() { return (String) get(9); } /** * Setter for <code>cattle.dynamic_schema.definition</code>. */ @Override public void setDefinition(String value) { set(10, value); } /** * Getter for <code>cattle.dynamic_schema.definition</code>. */ @Column(name = "definition", length = 16777215) @Override public String getDefinition() { return (String) get(10); } /** * Setter for <code>cattle.dynamic_schema.service_id</code>. */ @Override public void setServiceId(Long value) { set(11, value); } /** * Getter for <code>cattle.dynamic_schema.service_id</code>. */ @Column(name = "service_id", precision = 19) @Override public Long getServiceId() { return (Long) get(11); } /** * Setter for <code>cattle.dynamic_schema.removed</code>. */ @Override public void setRemoved(Date value) { set(12, value); } /** * Getter for <code>cattle.dynamic_schema.removed</code>. */ @Column(name = "removed") @Override public Date getRemoved() { return (Date) get(12); } // ------------------------------------------------------------------------- // Primary key information // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public Record1<Long> key() { return (Record1) super.key(); } // ------------------------------------------------------------------------- // Record13 type implementation // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public Row13<Long, String, Long, String, String, String, String, Date, Map<String,Object>, String, String, Long, Date> fieldsRow() { return (Row13) super.fieldsRow(); } /** * {@inheritDoc} */ @Override public Row13<Long, String, Long, String, String, String, String, Date, Map<String,Object>, String, String, Long, Date> valuesRow() { return (Row13) super.valuesRow(); } /** * {@inheritDoc} */ @Override public Field<Long> field1() { return DynamicSchemaTable.DYNAMIC_SCHEMA.ID; } /** * {@inheritDoc} */ @Override public Field<String> field2() { return DynamicSchemaTable.DYNAMIC_SCHEMA.NAME; } /** * {@inheritDoc} */ @Override public Field<Long> field3() { return DynamicSchemaTable.DYNAMIC_SCHEMA.ACCOUNT_ID; } /** * {@inheritDoc} */ @Override public Field<String> field4() { return DynamicSchemaTable.DYNAMIC_SCHEMA.KIND; } /** * {@inheritDoc} */ @Override public Field<String> field5() { return DynamicSchemaTable.DYNAMIC_SCHEMA.UUID; } /** * {@inheritDoc} */ @Override public Field<String> field6() { return DynamicSchemaTable.DYNAMIC_SCHEMA.DESCRIPTION; } /** * {@inheritDoc} */ @Override public Field<String> field7() { return DynamicSchemaTable.DYNAMIC_SCHEMA.STATE; } /** * {@inheritDoc} */ @Override public Field<Date> field8() { return DynamicSchemaTable.DYNAMIC_SCHEMA.CREATED; } /** * {@inheritDoc} */ @Override public Field<Map<String,Object>> field9() { return DynamicSchemaTable.DYNAMIC_SCHEMA.DATA; } /** * {@inheritDoc} */ @Override public Field<String> field10() { return DynamicSchemaTable.DYNAMIC_SCHEMA.PARENT; } /** * {@inheritDoc} */ @Override public Field<String> field11() { return DynamicSchemaTable.DYNAMIC_SCHEMA.DEFINITION; } /** * {@inheritDoc} */ @Override public Field<Long> field12() { return DynamicSchemaTable.DYNAMIC_SCHEMA.SERVICE_ID; } /** * {@inheritDoc} */ @Override public Field<Date> field13() { return DynamicSchemaTable.DYNAMIC_SCHEMA.REMOVED; } /** * {@inheritDoc} */ @Override public Long value1() { return getId(); } /** * {@inheritDoc} */ @Override public String value2() { return getName(); } /** * {@inheritDoc} */ @Override public Long value3() { return getAccountId(); } /** * {@inheritDoc} */ @Override public String value4() { return getKind(); } /** * {@inheritDoc} */ @Override public String value5() { return getUuid(); } /** * {@inheritDoc} */ @Override public String value6() { return getDescription(); } /** * {@inheritDoc} */ @Override public String value7() { return getState(); } /** * {@inheritDoc} */ @Override public Date value8() { return getCreated(); } /** * {@inheritDoc} */ @Override public Map<String,Object> value9() { return getData(); } /** * {@inheritDoc} */ @Override public String value10() { return getParent(); } /** * {@inheritDoc} */ @Override public String value11() { return getDefinition(); } /** * {@inheritDoc} */ @Override public Long value12() { return getServiceId(); } /** * {@inheritDoc} */ @Override public Date value13() { return getRemoved(); } /** * {@inheritDoc} */ @Override public DynamicSchemaRecord value1(Long value) { setId(value); return this; } /** * {@inheritDoc} */ @Override public DynamicSchemaRecord value2(String value) { setName(value); return this; } /** * {@inheritDoc} */ @Override public DynamicSchemaRecord value3(Long value) { setAccountId(value); return this; } /** * {@inheritDoc} */ @Override public DynamicSchemaRecord value4(String value) { setKind(value); return this; } /** * {@inheritDoc} */ @Override public DynamicSchemaRecord value5(String value) { setUuid(value); return this; } /** * {@inheritDoc} */ @Override public DynamicSchemaRecord value6(String value) { setDescription(value); return this; } /** * {@inheritDoc} */ @Override public DynamicSchemaRecord value7(String value) { setState(value); return this; } /** * {@inheritDoc} */ @Override public DynamicSchemaRecord value8(Date value) { setCreated(value); return this; } /** * {@inheritDoc} */ @Override public DynamicSchemaRecord value9(Map<String,Object> value) { setData(value); return this; } /** * {@inheritDoc} */ @Override public DynamicSchemaRecord value10(String value) { setParent(value); return this; } /** * {@inheritDoc} */ @Override public DynamicSchemaRecord value11(String value) { setDefinition(value); return this; } /** * {@inheritDoc} */ @Override public DynamicSchemaRecord value12(Long value) { setServiceId(value); return this; } /** * {@inheritDoc} */ @Override public DynamicSchemaRecord value13(Date value) { setRemoved(value); return this; } /** * {@inheritDoc} */ @Override public DynamicSchemaRecord values(Long value1, String value2, Long value3, String value4, String value5, String value6, String value7, Date value8, Map<String,Object> value9, String value10, String value11, Long value12, Date value13) { value1(value1); value2(value2); value3(value3); value4(value4); value5(value5); value6(value6); value7(value7); value8(value8); value9(value9); value10(value10); value11(value11); value12(value12); value13(value13); return this; } // ------------------------------------------------------------------------- // FROM and INTO // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public void from(DynamicSchema from) { setId(from.getId()); setName(from.getName()); setAccountId(from.getAccountId()); setKind(from.getKind()); setUuid(from.getUuid()); setDescription(from.getDescription()); setState(from.getState()); setCreated(from.getCreated()); setData(from.getData()); setParent(from.getParent()); setDefinition(from.getDefinition()); setServiceId(from.getServiceId()); setRemoved(from.getRemoved()); } /** * {@inheritDoc} */ @Override public <E extends DynamicSchema> E into(E into) { into.from(this); return into; } // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- /** * Create a detached DynamicSchemaRecord */ public DynamicSchemaRecord() { super(DynamicSchemaTable.DYNAMIC_SCHEMA); } /** * Create a detached, initialised DynamicSchemaRecord */ public DynamicSchemaRecord(Long id, String name, Long accountId, String kind, String uuid, String description, String state, Date created, Map<String,Object> data, String parent, String definition, Long serviceId, Date removed) { super(DynamicSchemaTable.DYNAMIC_SCHEMA); set(0, id); set(1, name); set(2, accountId); set(3, kind); set(4, uuid); set(5, description); set(6, state); set(7, created); set(8, data); set(9, parent); set(10, definition); set(11, serviceId); set(12, removed); } }
21.671348
241
0.542709
9c0badd254a6efc513a29547316bb75ecddb8193
842
package book.jeepatterns.dao; import java.time.LocalDate; import java.util.Arrays; import java.util.Set; import java.util.stream.Collectors; import book.jeepatterns.model.Professor; public class ProfessorDAO { private static Set<Professor> professors; static { Professor p1 = new Professor ("professor a", LocalDate.of (2001, 03, 22)), p2 = new Professor ("professor b", LocalDate.of (1994, 07, 05)), p3 = new Professor ("professor c", LocalDate.of (1985, 10, 12)), p4 = new Professor ("professor cv", LocalDate.of (2005, 07, 17)); professors = Arrays .stream (new Professor[]{p1, p2, p3, p4}) .collect (Collectors.toSet()); } public Professor findByName (String name) { return professors .stream() .filter(p->p.getName().equals(name)) .findAny() .get(); } }
25.515152
77
0.655582
5310e4c0308e4342156d32ba4eca7ce34e766f1b
391
import org.xbib.settings.SettingsLoader; import org.xbib.settings.datastructures.yaml.YamlSettingsLoader; module org.xbib.settings.datastructures.yaml { exports org.xbib.settings.datastructures.yaml; requires transitive org.xbib.settings.datastructures; requires org.xbib.datastructures.yaml.tiny; uses SettingsLoader; provides SettingsLoader with YamlSettingsLoader; }
35.545455
64
0.810742
19beae95e58f3258a0b171bba18289d590f898cb
385
/* * 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.github.jittagornp.fluentquery; /** * * @author jitta * @param <T> */ public interface TransactionCallback<T> { T execute(TransactionContext context); }
21.388889
80
0.672727
de4ab3f7745b386a84dfecc96381af40c687ed7d
2,648
/* Copyright 2009, 2012 predic8 GmbH, www.predic8.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.predic8.membrane.core.interceptor; import java.io.StringWriter; import java.net.InetAddress; import java.net.UnknownHostException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Required; import com.googlecode.jatl.Html; import com.predic8.membrane.annot.MCAttribute; import com.predic8.membrane.annot.MCElement; import com.predic8.membrane.core.exchange.Exchange; import com.predic8.membrane.core.http.Header; import com.predic8.membrane.core.http.MimeType; import com.predic8.membrane.core.http.Response; @MCElement(name="counter") public class CountInterceptor extends AbstractInterceptor { private static Logger log = LoggerFactory.getLogger(CountInterceptor.class.getName()); private int counter; public CountInterceptor() { name = "Count Interceptor"; } @Override public Outcome handleRequest(Exchange exc) throws Exception { log.debug(""+ (++counter) +". request received."); exc.setResponse(Response.ok().header(Header.CONTENT_TYPE, MimeType.TEXT_HTML_UTF8).body(getPage()).build()); return Outcome.RETURN; } private String getPage() throws UnknownHostException { StringWriter writer = new StringWriter(); new Html(writer) {{ html(); head(); title().text(name).end(); end(); body(); h1().text(name+"("+InetAddress.getLocalHost().getHostAddress()+")").end(); p().text("This site is generated by a simple interceptor that counts how often this site was requested.").end(); p().text("Request count: "+counter).end(); endAll(); done(); } }; return writer.toString(); } @Override public String getDisplayName() { return "Counter: " + super.getDisplayName(); } /** * @description Sets the name that will be displayed on the web page. * @example Mock Node 1 */ @Required @MCAttribute(attributeName="name") @Override public void setDisplayName(String name) { if (name.startsWith("Counter: ")) super.setDisplayName(name.substring(9)); else super.setDisplayName(name); } }
29.422222
115
0.738671
a534160cd85ed984b206a7d27cbef45a2acb22af
2,867
package org.wrkr.clb.services.security.impl; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; import org.wrkr.clb.model.user.User; import org.wrkr.clb.repo.user.UserRepo; import org.wrkr.clb.services.BaseServiceTest; import org.wrkr.clb.services.security.SecurityService; public class SecurityServiceTest extends BaseServiceTest { private static final String privateUserEmail = "private_user@test.com"; private static final String privateUserUsername = privateUserEmail; private static final String publicUserEmail = "public_user@test.com"; private static final String publicUserUsername = publicUserEmail; private static final String disabledUserEmail = "disabled_user@test.com"; private static final String disabledUserUsername = disabledUserEmail; @Autowired private UserRepo userRepo; @Autowired private SecurityService securityService; @Rule public ExpectedException expectedException = ExpectedException.none(); @Before public void beforeTest() throws Exception { saveUser(privateUserEmail, privateUserUsername, DEFAULT_USER_PASSWORD); saveUser(publicUserEmail, publicUserUsername, DEFAULT_USER_PASSWORD); saveUser(disabledUserEmail, disabledUserUsername); } @After public void afterTest() { testRepo.clearTable(User.class); } @Test public void test_enabledUserIsAuthenticated() { User enabledUser = userRepo.getByUsername(privateUserUsername); securityService.isAuthenticated(enabledUser); } @Test public void test_disabledUserIsNotAuthenticated() { expectedException.expect(AuthenticationCredentialsNotFoundException.class); User disabledUser = userRepo.getByUsername(disabledUserUsername); securityService.isAuthenticated(disabledUser); } @Test public void test_nullUserIsNotAuthenticated() { expectedException.expect(AuthenticationCredentialsNotFoundException.class); securityService.isAuthenticated(null); } @Test public void test_userCanReadPublicUserProfile() { User publicUser = userRepo.getByUsername(publicUserUsername); User otherUser = userRepo.getByUsername(privateUserUsername); securityService.authzCanReadUserProfile(otherUser, publicUser.getId()); } @Test public void test_userCanReadPrivateUserProfile() { User privateUser = userRepo.getByUsername(privateUserUsername); User otherUser = userRepo.getByUsername(publicUserUsername); securityService.authzCanReadUserProfile(otherUser, privateUser.getId()); } }
33.337209
94
0.764213
4606b6d0c2107babcf11086f04d630379e2c2a50
286
package dsx.bcv.server.data.repositories; import dsx.bcv.server.data.models.Role; import org.springframework.data.repository.CrudRepository; import java.util.Optional; public interface RoleRepository extends CrudRepository<Role, Long> { Optional<Role> findByName(String name); }
26
68
0.807692
533bb35ac692ebcc9ead8186d697aa55a3ac1624
733
package org.hyojeong.stdmgt.model; public class UpdateHisory { int pid; String memo; String updateDate; public int getPid() { return pid; } public void setPid(int pid) { this.pid = pid; } public String getMemo() { return memo; } public void setMemo(String memo) { this.memo = memo; } public String getUpdateDate() { return updateDate; } public void setUpdateDate(String updateDate) { this.updateDate = updateDate; } @Override public String toString() { return "UpdateHisory [pid=" + pid + ", memo=" + memo + ", updateDate=" + updateDate + "]"; } public UpdateHisory(int pid, String memo, String updateDate) { super(); this.pid = pid; this.memo = memo; this.updateDate = updateDate; } }
19.289474
92
0.672578
4e75519abe36c843fdb2d0ffce9e134686671410
302
package org.nix.domain.entity.dto; import org.springframework.stereotype.Repository; /** * Create by zhangpe0312@qq.com on 2018/3/11. * * 用于返回前端所需信息的返回接口 */ @Repository public interface ResultDto{ /** * 返回需要的dto组装类 * @return */ ResultDto resultDto(Object... objects); }
14.380952
49
0.668874
098cd5e90ecf1b2609beecddc07b09e814e7c92f
1,503
package com.apchernykh.todo.atleap.sample.network.retrofit; import com.apchernykh.todo.atleap.sample.BuildConfig; import com.apchernykh.todo.atleap.sample.Constants; import com.fasterxml.jackson.databind.ObjectMapper; import retrofit.RestAdapter; import retrofit.converter.JacksonConverter; @SuppressWarnings("SameParameterValue") public class RetrofitHelper { public static RestAdapter.Builder createApiGithubRestAdapter(RestAdapter.Builder builder) { return createApiTodoRestAdapter(builder) .setErrorHandler(new NetworkErrorHandler()) .setRequestInterceptor(new AuthRequestInterceptor()); } public static RestAdapter.Builder createApiTodoRestAdapter(RestAdapter.Builder builder) { return createBaseRestAdapter(builder) .setEndpoint(Constants.TODO_API_BASE_URL); } public static RestAdapter.Builder createTodoRestAdapterForAuth(RestAdapter.Builder builder) { return createBaseRestAdapter(builder).setEndpoint(Constants.TODO_API_BASE_URL); } private static RestAdapter.Builder createBaseRestAdapter(RestAdapter.Builder builder) { if (builder == null) builder = new RestAdapter.Builder(); builder.setConverter(new JacksonConverter(new ObjectMapper())); if (BuildConfig.DEBUG) { builder.setLogLevel(RestAdapter.LogLevel.FULL); } else { builder.setLogLevel(RestAdapter.LogLevel.NONE); } return builder; } }
34.953488
97
0.7332
f175b105fc455f4bee25a4349935c556d8a21fc1
6,683
/** * Copyright 2017 Syncleus, Inc. * with portions copyright 2004-2017 Bo Zimmerman * * 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.syncleus.aethermud.game.WebMacros; import com.syncleus.aethermud.game.Common.interfaces.AbilityComponent; import com.syncleus.aethermud.game.core.CMLib; import com.syncleus.aethermud.web.interfaces.HTTPRequest; import com.syncleus.aethermud.web.interfaces.HTTPResponse; import java.util.List; public class ComponentPieceNext extends StdWebMacro { @Override public String name() { return "ComponentPieceNext"; } @Override public boolean isAdminMacro() { return true; } @Override public String runMacro(HTTPRequest httpReq, String parm, HTTPResponse httpResp) { final java.util.Map<String, String> parms = parseParms(parm); final String compID = httpReq.getUrlParameter("COMPONENT"); if (compID == null) return " @break@"; final String fixedCompID = compID.replace(' ', '_').toUpperCase(); if (!httpReq.isUrlParameter(fixedCompID + "_PIECE_CONNECTOR_1")) { final List<AbilityComponent> set = CMLib.ableComponents().getAbilityComponents(compID); if (set != null) { int index = 1; for (final AbilityComponent A : set) { httpReq.addFakeUrlParameter(fixedCompID + "_PIECE_MASK_" + index, A.getMaskStr()); if (A.getType() == AbilityComponent.CompType.STRING) httpReq.addFakeUrlParameter(fixedCompID + "_PIECE_STRING_" + index, A.getStringType()); else httpReq.addFakeUrlParameter(fixedCompID + "_PIECE_STRING_" + index, Long.toString(A.getLongType())); httpReq.addFakeUrlParameter(fixedCompID + "_PIECE_AMOUNT_" + index, Integer.toString(A.getAmount())); httpReq.addFakeUrlParameter(fixedCompID + "_PIECE_CONNECTOR_" + index, A.getConnector().toString()); httpReq.addFakeUrlParameter(fixedCompID + "_PIECE_LOCATION_" + index, A.getLocation().toString()); httpReq.addFakeUrlParameter(fixedCompID + "_PIECE_TYPE_" + index, A.getType().toString()); httpReq.addFakeUrlParameter(fixedCompID + "_PIECE_CONSUMED_" + index, A.isConsumed() ? "on" : ""); index++; } } else { httpReq.addFakeUrlParameter(fixedCompID + "_PIECE_MASK_1", ""); httpReq.addFakeUrlParameter(fixedCompID + "_PIECE_STRING_1", "item name"); httpReq.addFakeUrlParameter(fixedCompID + "_PIECE_AMOUNT_1", "1"); httpReq.addFakeUrlParameter(fixedCompID + "_PIECE_CONNECTOR_1", "AND"); httpReq.addFakeUrlParameter(fixedCompID + "_PIECE_LOCATION_1", "INVENTORY"); httpReq.addFakeUrlParameter(fixedCompID + "_PIECE_TYPE_1", "STRING"); httpReq.addFakeUrlParameter(fixedCompID + "_PIECE_CONSUMED_1", "on"); } } else { int oldIndex = 1; int newIndex = 1; while (httpReq.isUrlParameter(fixedCompID + "_PIECE_CONNECTOR_" + oldIndex)) { final String type = httpReq.getUrlParameter(fixedCompID + "_PIECE_CONNECTOR_" + oldIndex); if ((type.length() > 0) && (!type.equalsIgnoreCase("DELETE"))) { if (newIndex != oldIndex) { httpReq.addFakeUrlParameter(fixedCompID + "_PIECE_MASK_" + newIndex, httpReq.getUrlParameter(fixedCompID + "_PIECE_MASK_" + oldIndex)); httpReq.addFakeUrlParameter(fixedCompID + "_PIECE_STRING_" + newIndex, httpReq.getUrlParameter(fixedCompID + "_PIECE_STRING_" + oldIndex)); httpReq.addFakeUrlParameter(fixedCompID + "_PIECE_AMOUNT_" + newIndex, httpReq.getUrlParameter(fixedCompID + "_PIECE_AMOUNT_" + oldIndex)); httpReq.addFakeUrlParameter(fixedCompID + "_PIECE_CONNECTOR_" + newIndex, httpReq.getUrlParameter(fixedCompID + "_PIECE_CONNECTOR_" + oldIndex)); httpReq.addFakeUrlParameter(fixedCompID + "_PIECE_LOCATION_" + newIndex, httpReq.getUrlParameter(fixedCompID + "_PIECE_LOCATION_" + oldIndex)); httpReq.addFakeUrlParameter(fixedCompID + "_PIECE_TYPE_" + newIndex, httpReq.getUrlParameter(fixedCompID + "_PIECE_TYPE_" + oldIndex)); httpReq.addFakeUrlParameter(fixedCompID + "_PIECE_CONSUMED_" + newIndex, httpReq.getUrlParameter(fixedCompID + "_PIECE_CONSUMED_" + oldIndex)); } newIndex++; } oldIndex++; } httpReq.removeUrlParameter(fixedCompID + "_PIECE_MASK_" + newIndex); httpReq.removeUrlParameter(fixedCompID + "_PIECE_STRING_" + newIndex); httpReq.removeUrlParameter(fixedCompID + "_PIECE_AMOUNT_" + newIndex); httpReq.removeUrlParameter(fixedCompID + "_PIECE_CONNECTOR_" + newIndex); httpReq.removeUrlParameter(fixedCompID + "_PIECE_LOCATION_" + newIndex); httpReq.removeUrlParameter(fixedCompID + "_PIECE_TYPE_" + newIndex); httpReq.removeUrlParameter(fixedCompID + "_PIECE_CONSUMED_" + newIndex); } final String last = httpReq.getUrlParameter("COMPONENTPIECE"); if (parms.containsKey("RESET")) { if (last != null) httpReq.removeUrlParameter("COMPONENTPIECE"); return ""; } String lastID = ""; for (int index = 1; httpReq.isUrlParameter(fixedCompID + "_PIECE_CONNECTOR_" + index); index++) { final String id = Integer.toString(index); if ((last == null) || ((last.length() > 0) && (last.equals(lastID)) && (!id.equalsIgnoreCase(lastID)))) { httpReq.addFakeUrlParameter("COMPONENTPIECE", id); return ""; } lastID = id; } httpReq.addFakeUrlParameter("COMPONENTPIECE", ""); if (parms.containsKey("EMPTYOK")) return "<!--EMPTY-->"; return " @break@"; } }
56.159664
169
0.633249
69f7539007ea206076d6f0580d647f52da57bc14
2,225
/* * Copyright 2020-present huanglei.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.huanglei.nail.okhttp; import okhttp3.OkHttpClient; import org.huanglei.nail.NailOption; import java.net.URL; import java.util.concurrent.ConcurrentHashMap; public class NailHttpClientHelper { private static ConcurrentHashMap<String, OkHttpClient> clients = new ConcurrentHashMap<>(); public static OkHttpClient getOkHttpClient(final String host, final int port, NailOption option) throws Exception { String key; if (option.getProxy() != null && !option.getProxy().isEmpty()) { URL url = new URL(option.getProxy()); key = getClientKey(url.getHost(), url.getPort()); } else { key = getClientKey(host, port); } OkHttpClient client = clients.get(key); if (client == null) { client = createOkHttpClient(option); clients.put(key, client); } return client; } private static OkHttpClient createOkHttpClient(NailOption option) { NailHttpClientBuilder builder = new NailHttpClientBuilder(); return builder .showLog(option.isShowLog()) .connectTimeout(option.getConnectTimeout()) .readTimeout(option.getReadTimeout()) .connectionPool(option.getMaxIdleConns()) .isIgnoreSSL(option.isIgnoreSSL()) .certificate(option.getCertInputStream(), option.getCertPassword()) .proxy(option.getProxy()) .build(); } private static String getClientKey(String host, int port) { return String.format("%s:%d", host, port); } }
35.31746
119
0.658876
750912d1f02069c5197e5aef6b2e2f8b07de609c
11,299
/* * Copyright (c) 2008-2011, Piccolo2D project, http://piccolo2d.org * Copyright (c) 1998-2008, University of Maryland * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided * that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the * distribution. * * None of the name of the University of Maryland, the name of the Piccolo2D project, or the names of its * contributors may be used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.piccolo2d.util; import java.awt.AlphaComposite; import java.awt.Composite; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.font.FontRenderContext; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import org.piccolo2d.PCamera; /** * <b>PPaintContext</b> is used by piccolo nodes to paint themselves on the * screen. PPaintContext wraps a Graphics2D to implement painting. * <P> * * @version 1.0 * @author Jesse Grosjean */ public class PPaintContext { /** Used for lowering quality of rendering when requested. */ public static final int LOW_QUALITY_RENDERING = 0; /** Used for improving quality of rendering when requested. */ public static final int HIGH_QUALITY_RENDERING = 1; /** Font context to use while in low quality rendering. */ public static final FontRenderContext RENDER_QUALITY_LOW_FRC = new FontRenderContext(null, false, true); /** Font context to use while in high quality rendering. */ public static final FontRenderContext RENDER_QUALITY_HIGH_FRC = new FontRenderContext(null, true, true); /** Used while calculating scale at which rendering is occurring. */ private static final double[] PTS = new double[4]; /** PaintContext is associated with this graphics context. */ private final Graphics2D graphics; /** Used while computing transparency. */ protected PStack compositeStack; /** Used to optimize clipping region. */ protected PStack clipStack; /** Tracks clipping region in local coordinate system. */ protected PStack localClipStack; /** Stack of cameras through which the node being painted is being viewed. */ protected PStack cameraStack; /** Stack of transforms being applied to the drawing context. */ protected PStack transformStack; /** The current render quality that all rendering should be done in. */ protected int renderQuality; /** * Creates a PPaintContext associated with the given graphics context. * * @param graphics graphics context to associate with this paint context */ public PPaintContext(final Graphics2D graphics) { this.graphics = graphics; compositeStack = new PStack(); clipStack = new PStack(); localClipStack = new PStack(); cameraStack = new PStack(); transformStack = new PStack(); renderQuality = HIGH_QUALITY_RENDERING; Shape clip = graphics.getClip(); if (clip == null) { clip = new PBounds(-Integer.MAX_VALUE / 2, -Integer.MAX_VALUE / 2, Integer.MAX_VALUE, Integer.MAX_VALUE); graphics.setClip(clip); } localClipStack.push(clip.getBounds2D()); } /** * Returns the graphics context associated with this paint context. * * @return graphics context associated with this paint context */ public Graphics2D getGraphics() { return graphics; } /** * Returns the clipping region in the local coordinate system applied by * graphics. * * @return clipping region in the local coordinate system applied by * graphics */ public Rectangle2D getLocalClip() { return (Rectangle2D) localClipStack.peek(); } /** * Returns scale of the current graphics context. By calculating how a unit * segment gets transformed after transforming it by the graphics context's * transform. * * @return scale of the current graphics context's transformation */ public double getScale() { // x1, y1, x2, y2 PTS[0] = 0; PTS[1] = 0; PTS[2] = 1; PTS[3] = 0; graphics.getTransform().transform(PTS, 0, PTS, 0, 2); return Point2D.distance(PTS[0], PTS[1], PTS[2], PTS[3]); } /** * Pushes the camera onto the camera stack. * * @param aCamera camera to push onto the stack */ public void pushCamera(final PCamera aCamera) { cameraStack.push(aCamera); } /** * Removes the camera at the top of the camera stack. * * @since 1.3 */ public void popCamera() { cameraStack.pop(); } /** * Returns the camera at the top of the camera stack, or null if stack is * empty. * * @return topmost camera on camera stack or null if stack is empty */ public PCamera getCamera() { return (PCamera) cameraStack.peek(); } /** * Pushes the given clip to the pain context. * * @param clip clip to be pushed */ public void pushClip(final Shape clip) { final Shape currentClip = graphics.getClip(); clipStack.push(currentClip); graphics.clip(clip); final Rectangle2D newLocalClip = clip.getBounds2D(); Rectangle2D.intersect(getLocalClip(), newLocalClip, newLocalClip); localClipStack.push(newLocalClip); } /** * Removes the topmost clipping region from the clipping stack. * * @param clip not used in this method */ public void popClip(final Shape clip) { final Shape newClip = (Shape) clipStack.pop(); graphics.setClip(newClip); localClipStack.pop(); } /** * Pushes the provided transparency onto the transparency stack if * necessary. If the transparency is fully opaque, then it does nothing. * * @param transparency transparency to be pushed onto the transparency stack */ public void pushTransparency(final float transparency) { if (transparency == 1.0f) { return; } final Composite current = graphics.getComposite(); float currentAlaph = 1.0f; compositeStack.push(current); if (current instanceof AlphaComposite) { currentAlaph = ((AlphaComposite) current).getAlpha(); } final AlphaComposite newComposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, currentAlaph * transparency); graphics.setComposite(newComposite); } /** * Removes the topmost transparency if the given transparency is not opaque * (1f). * * @param transparency transparency to be popped */ public void popTransparency(final float transparency) { if (transparency == 1.0f) { return; } final Composite c = (Composite) compositeStack.pop(); graphics.setComposite(c); } /** * Pushed the provided transform onto the transform stack if it is not null. * * @param transform will be pushed onto the transform stack if not null */ public void pushTransform(final PAffineTransform transform) { if (transform != null) { final Rectangle2D newLocalClip = (Rectangle2D) getLocalClip().clone(); transform.inverseTransform(newLocalClip, newLocalClip); transformStack.push(graphics.getTransform()); localClipStack.push(newLocalClip); graphics.transform(transform); } } /** * Pops the topmost Transform from the top of the transform if the passed in * transform is not null. * * @param transform transform that should be at the top of the stack */ public void popTransform(final PAffineTransform transform) { if (transform != null) { graphics.setTransform((AffineTransform) transformStack.pop()); localClipStack.pop(); } } /** * Return the render quality used by this paint context. * * @return the current render quality */ public int getRenderQuality() { return renderQuality; } /** * Set the rendering hints for this paint context. The render quality is * most often set by the rendering PCanvas. Use PCanvas.setRenderQuality() * and PCanvas.setInteractingRenderQuality() to set these values. * * @param requestedQuality supports PPaintContext.HIGH_QUALITY_RENDERING or * PPaintContext.LOW_QUALITY_RENDERING */ public void setRenderQuality(final int requestedQuality) { renderQuality = requestedQuality; switch (renderQuality) { case HIGH_QUALITY_RENDERING: setRenderQualityToHigh(); break; case LOW_QUALITY_RENDERING: setRenderQualityToLow(); break; default: throw new RuntimeException("Quality must be either HIGH_QUALITY_RENDERING or LOW_QUALITY_RENDERING"); } } private void setRenderQualityToLow() { graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED); graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); } private void setRenderQualityToHigh() { graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); } }
35.984076
117
0.678467
4d717c1a51d26eb72fff54647b43ba469ca86f80
708
package com.miniprofiler; import static org.junit.Assert.*; import org.junit.Test; import java.time.Instant; public class InstantOffsetTest { private Instant now = Instant.now(); private Instant later = now.plusMillis(1); @Test public void testInstantOffset() { InstantOffset offset = new InstantOffset(now, later); assertEquals(now, offset.getStart()); assertEquals(later, offset.getOffset()); } @Test(expected = IllegalArgumentException.class) public void testInvalidOffset() { new InstantOffset(later, now); } @Test public void testEqualInstants() { new InstantOffset(now, now); // Expect no exception. } }
23.6
61
0.666667
777f14c8252f611235900f5b9ed8fb99b7002484
6,916
/* * This file is part of ELKI: * Environment for Developing KDD-Applications Supported by Index-Structures * * Copyright (C) 2019 * ELKI Development Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.lmu.ifi.dbs.elki.math.statistics.dependence; import java.util.Collection; import java.util.Iterator; import de.lmu.ifi.dbs.elki.math.MathUtil; import de.lmu.ifi.dbs.elki.utilities.datastructures.arraylike.NumberArrayAdapter; import de.lmu.ifi.dbs.elki.utilities.datastructures.arrays.IntegerArrayQuickSort; /** * Abstract base class for dependence measures. * * @author Erich Schubert * @since 0.7.0 */ public abstract class AbstractDependenceMeasure implements DependenceMeasure { /** * Clamp values to a given minimum and maximum. * * @param value True value * @param min Minimum * @param max Maximum * @return {@code value}, unless smaller than {@code min} or larger than * {@code max}. */ protected static double clamp(double value, double min, double max) { return value < min ? min : value > max ? max : value; } /** * Compute ranks of all objects, normalized to [0;1] * (where 0 is the smallest value, 1 is the largest). * * @param adapter Data adapter * @param data Data array * @param len Length of data * @return Array of scores */ protected static <A> double[] computeNormalizedRanks(final NumberArrayAdapter<?, A> adapter, final A data, int len) { // Sort the objects: int[] s1 = sortedIndex(adapter, data, len); final double norm = .5 / (len - 1); double[] ret = new double[len]; for(int i = 0; i < len;) { final int start = i++; final double val = adapter.getDouble(data, s1[start]); while(i < len && adapter.getDouble(data, s1[i]) <= val) { i++; } final double score = (start + i - 1) * norm; for(int j = start; j < i; j++) { ret[s1[j]] = score; } } return ret; } /** * Compute ranks of all objects, ranging from 1 to len. * * Ties are given the average rank. * * @param adapter Data adapter * @param data Data array * @param len Length of data * @return Array of scores */ protected static <A> double[] ranks(final NumberArrayAdapter<?, A> adapter, final A data, int len) { return ranks(adapter, data, sortedIndex(adapter, data, len)); } /** * Compute ranks of all objects, ranging from 1 to len. * * Ties are given the average rank. * * @param adapter Data adapter * @param data Data array * @param idx Data index * @return Array of scores */ protected static <A> double[] ranks(final NumberArrayAdapter<?, A> adapter, final A data, int[] idx) { final int len = idx.length; double[] ret = new double[len]; for(int i = 0; i < len;) { final int start = i++; final double val = adapter.getDouble(data, idx[start]); // Include ties: while(i < len && adapter.getDouble(data, idx[i]) <= val) { i++; } final double score = (start + i - 1) * .5 + 1; for(int j = start; j < i; j++) { ret[idx[j]] = score; } } return ret; } /** * Build a sorted index of objects. * * @param adapter Data adapter * @param data Data array * @param len Length of data * @return Sorted index */ protected static <A> int[] sortedIndex(final NumberArrayAdapter<?, A> adapter, final A data, int len) { int[] s1 = MathUtil.sequence(0, len); IntegerArrayQuickSort.sort(s1, (x, y) -> Double.compare(adapter.getDouble(data, x), adapter.getDouble(data, y))); return s1; } /** * Discretize a data set into equi-width bin numbers. * * @param adapter Data adapter * @param data Data array * @param len Length of data * @param bins Number of bins * @return Array of bin numbers [0;bin[ */ protected static <A> int[] discretize(NumberArrayAdapter<?, A> adapter, A data, final int len, final int bins) { double min = adapter.getDouble(data, 0), max = min; for(int i = 1; i < len; i++) { double v = adapter.getDouble(data, i); if(v < min) { min = v; } else if(v > max) { max = v; } } final double scale = (max > min) ? bins / (max - min) : 1; int[] discData = new int[len]; for(int i = 0; i < len; i++) { int bin = (int) Math.floor((adapter.getDouble(data, i) - min) * scale); discData[i] = bin < 0 ? 0 : bin >= bins ? bins - 1 : bin; } return discData; } /** * Index into the serialized array. * * @param x Column * @param y Row * @return Index in serialized array */ protected static int index(int x, int y) { assert (x < y) : "Only lower triangle is allowed."; return ((y * (y - 1)) >> 1) + x; } /** * Validate the length of the two data sets (must be the same, and non-zero) * * @param adapter1 First data adapter * @param data1 First data set * @param adapter2 Second data adapter * @param data2 Second data set * @param <A> First array type * @param <B> Second array type */ protected static <A, B> int size(NumberArrayAdapter<?, A> adapter1, A data1, NumberArrayAdapter<?, B> adapter2, B data2) { final int len = adapter1.size(data1); if(len != adapter2.size(data2)) { throw new IllegalArgumentException("Array sizes do not match!"); } if(len == 0) { throw new IllegalArgumentException("Empty array!"); } return len; } /** * Validate the length of the two data sets (must be the same, and non-zero) * * @param adapter Data adapter * @param data Data sets * @param <A> First array type */ protected static <A> int size(NumberArrayAdapter<?, A> adapter, Collection<? extends A> data) { if(data.size() < 2) { throw new IllegalArgumentException("Need at least two axes to compute dependence measures."); } Iterator<? extends A> iter = data.iterator(); final int len = adapter.size(iter.next()); while(iter.hasNext()) { if(len != adapter.size(iter.next())) { throw new IllegalArgumentException("Array sizes do not match!"); } } if(len == 0) { throw new IllegalArgumentException("Empty array!"); } return len; } }
31.436364
124
0.626374
e338b501804eb4357894fffe6554acedb35bb1d5
11,791
package de.ellpeck.prettypipes.terminal; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ListMultimap; import de.ellpeck.prettypipes.PrettyPipes; import de.ellpeck.prettypipes.Registry; import de.ellpeck.prettypipes.Utility; import de.ellpeck.prettypipes.misc.EquatableItemStack; import de.ellpeck.prettypipes.misc.ItemEquality; import de.ellpeck.prettypipes.network.NetworkItem; import de.ellpeck.prettypipes.network.NetworkLocation; import de.ellpeck.prettypipes.network.PipeNetwork; import de.ellpeck.prettypipes.packets.PacketGhostSlot; import de.ellpeck.prettypipes.packets.PacketHandler; import de.ellpeck.prettypipes.pipe.PipeTileEntity; import de.ellpeck.prettypipes.terminal.containers.CraftingTerminalContainer; import net.minecraft.block.BlockState; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.inventory.container.Container; import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompoundNBT; import net.minecraft.util.Direction; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.Style; import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TranslationTextComponent; import net.minecraftforge.items.ItemHandlerHelper; import net.minecraftforge.items.ItemStackHandler; import org.apache.commons.lang3.mutable.MutableInt; import javax.annotation.Nullable; import java.util.*; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; public class CraftingTerminalTileEntity extends ItemTerminalTileEntity { public final ItemStackHandler craftItems = new ItemStackHandler(9) { @Override protected void onContentsChanged(int slot) { for (PlayerEntity playerEntity : CraftingTerminalTileEntity.this.getLookingPlayers()) playerEntity.openContainer.onCraftMatrixChanged(null); } }; public final ItemStackHandler ghostItems = new ItemStackHandler(9); public CraftingTerminalTileEntity() { super(Registry.craftingTerminalTileEntity); } public ItemStack getRequestedCraftItem(int slot) { ItemStack stack = this.craftItems.getStackInSlot(slot); if (!stack.isEmpty()) return stack; return this.ghostItems.getStackInSlot(slot); } public boolean isGhostItem(int slot) { return this.craftItems.getStackInSlot(slot).isEmpty() && !this.ghostItems.getStackInSlot(slot).isEmpty(); } public void setGhostItems(ListMultimap<Integer, ItemStack> stacks) { this.updateItems(); for (int i = 0; i < this.ghostItems.getSlots(); i++) { List<ItemStack> items = stacks.get(i); if (items.isEmpty()) { this.ghostItems.setStackInSlot(i, ItemStack.EMPTY); continue; } ItemStack toSet = items.get(0); // if we have more than one item to choose from, we want to pick the one that we have most of in the system if (items.size() > 1) { int highestAmount = 0; for (ItemStack stack : items) { int amount = 0; // check existing items NetworkItem network = this.networkItems.get(new EquatableItemStack(stack, ItemEquality.NBT)); if (network != null) { amount = network.getLocations().stream() .mapToInt(l -> l.getItemAmount(this.world, stack, ItemEquality.NBT)) .sum(); } // check craftables if (amount <= 0 && highestAmount <= 0) { PipeTileEntity pipe = this.getConnectedPipe(); if (pipe != null) amount = PipeNetwork.get(this.world).getCraftableAmount(pipe.getPos(), null, stack, new Stack<>(), ItemEquality.NBT); } if (amount > highestAmount) { highestAmount = amount; toSet = stack; } } } this.ghostItems.setStackInSlot(i, toSet.copy()); } if (!this.world.isRemote) { ListMultimap<Integer, ItemStack> clients = ArrayListMultimap.create(); for (int i = 0; i < this.ghostItems.getSlots(); i++) clients.put(i, this.ghostItems.getStackInSlot(i)); PacketHandler.sendToAllLoaded(this.world, this.pos, new PacketGhostSlot(this.pos, clients)); } } public void requestCraftingItems(PlayerEntity player, int maxAmount) { PipeTileEntity pipe = this.getConnectedPipe(); if (pipe == null) return; PipeNetwork network = PipeNetwork.get(this.world); network.startProfile("terminal_request_crafting"); this.updateItems(); // get the amount of crafts that we can do int lowestAvailable = getAvailableCrafts(pipe, this.craftItems.getSlots(), i -> ItemHandlerHelper.copyStackWithSize(this.getRequestedCraftItem(i), 1), this::isGhostItem, s -> { NetworkItem item = this.networkItems.get(s); return item != null ? item.getLocations() : Collections.emptyList(); }, onItemUnavailable(player), new Stack<>(), ItemEquality.NBT); if (lowestAvailable > 0) { // if we're limiting the amount, pretend we only have that amount available if (maxAmount < lowestAvailable) lowestAvailable = maxAmount; for (int i = 0; i < this.craftItems.getSlots(); i++) { ItemStack requested = this.getRequestedCraftItem(i); if (requested.isEmpty()) continue; requested = requested.copy(); requested.setCount(lowestAvailable); this.requestItemImpl(requested, onItemUnavailable(player)); } player.sendMessage(new TranslationTextComponent("info." + PrettyPipes.ID + ".sending_ingredients", lowestAvailable).setStyle(Style.EMPTY.setFormatting(TextFormatting.GREEN)), UUID.randomUUID()); } network.endProfile(); } @Override public CompoundNBT write(CompoundNBT compound) { compound.put("craft_items", this.craftItems.serializeNBT()); return super.write(compound); } @Override public void read(BlockState state, CompoundNBT compound) { this.craftItems.deserializeNBT(compound.getCompound("craft_items")); super.read(state, compound); } @Override public ITextComponent getDisplayName() { return new TranslationTextComponent("container." + PrettyPipes.ID + ".crafting_terminal"); } @Nullable @Override public Container createMenu(int window, PlayerInventory inv, PlayerEntity player) { return new CraftingTerminalContainer(Registry.craftingTerminalContainer, window, player, this.pos); } @Override public ItemStack insertItem(BlockPos pipePos, Direction direction, ItemStack remain, boolean simulate) { BlockPos pos = pipePos.offset(direction); CraftingTerminalTileEntity tile = Utility.getTileEntity(CraftingTerminalTileEntity.class, this.world, pos); if (tile != null) { remain = remain.copy(); int lowestSlot = -1; do { for (int i = 0; i < tile.craftItems.getSlots(); i++) { ItemStack stack = tile.getRequestedCraftItem(i); int count = tile.isGhostItem(i) ? 0 : stack.getCount(); if (!ItemHandlerHelper.canItemStacksStack(stack, remain)) continue; // ensure that a single non-stackable item can still enter a ghost slot if (!stack.isStackable() && count >= 1) continue; if (lowestSlot < 0 || !tile.isGhostItem(lowestSlot) && count < tile.getRequestedCraftItem(lowestSlot).getCount()) lowestSlot = i; } if (lowestSlot >= 0) { ItemStack copy = remain.copy(); copy.setCount(1); // if there were remaining items inserting into the slot with lowest contents, we're overflowing if (tile.craftItems.insertItem(lowestSlot, copy, simulate).getCount() > 0) break; remain.shrink(1); if (remain.isEmpty()) return ItemStack.EMPTY; } } while (lowestSlot >= 0); return ItemHandlerHelper.insertItemStacked(tile.items, remain, simulate); } return remain; } public static int getAvailableCrafts(PipeTileEntity tile, int slots, Function<Integer, ItemStack> inputFunction, Predicate<Integer> isGhost, Function<EquatableItemStack, Collection<NetworkLocation>> locationsFunction, Consumer<ItemStack> unavailableConsumer, Stack<ItemStack> dependencyChain, ItemEquality... equalityTypes) { PipeNetwork network = PipeNetwork.get(tile.getWorld()); // the highest amount we can craft with the items we have int lowestAvailable = Integer.MAX_VALUE; // this is the amount of items required for each ingredient when crafting ONE Map<EquatableItemStack, MutableInt> requiredItems = new HashMap<>(); for (int i = 0; i < slots; i++) { ItemStack requested = inputFunction.apply(i); if (requested.isEmpty()) continue; MutableInt amount = requiredItems.computeIfAbsent(new EquatableItemStack(requested, equalityTypes), s -> new MutableInt()); amount.add(requested.getCount()); // if no items fit into the crafting input, we still want to pretend they do for requesting int fit = Math.max(requested.getMaxStackSize() - (isGhost.test(i) ? 0 : requested.getCount()), 1); if (lowestAvailable > fit) lowestAvailable = fit; } for (Map.Entry<EquatableItemStack, MutableInt> entry : requiredItems.entrySet()) { EquatableItemStack stack = entry.getKey(); // total amount of available items of this type int available = 0; for (NetworkLocation location : locationsFunction.apply(stack)) { int amount = location.getItemAmount(tile.getWorld(), stack.stack, equalityTypes); if (amount <= 0) continue; amount -= network.getLockedAmount(location.getPos(), stack.stack, null, equalityTypes); available += amount; } // divide the total by the amount required to get the amount that // we have available for each crafting slot that contains this item available /= entry.getValue().intValue(); // check how many craftable items we have and add those on if we need to if (available < lowestAvailable) { int craftable = network.getCraftableAmount(tile.getPos(), unavailableConsumer, stack.stack, dependencyChain, equalityTypes); if (craftable > 0) available += craftable / entry.getValue().intValue(); } // clamp to lowest available if (available < lowestAvailable) lowestAvailable = available; if (available <= 0 && unavailableConsumer != null) unavailableConsumer.accept(stack.stack); } return lowestAvailable; } }
47.736842
329
0.629209
43858132ab9b9f45795292c3d854d8e7eb4c5439
579
package org.dataportabilityproject.types.transfer.models.contacts; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import org.dataportabilityproject.types.transfer.models.DataModel; /** * A collection of contacts as serialized vCards. */ public class ContactsModelWrapper extends DataModel { private final String vCards; @JsonCreator public ContactsModelWrapper(@JsonProperty("vCards") String vCards) { this.vCards = vCards; } public String getVCards() { return vCards; } }
26.318182
72
0.75475
bf4c40c1c4a0316084ffdb9555c9d383d6c3a64a
330
package com.neteasemall.service; import com.neteasemall.common.ServerResponse; import com.neteasemall.pojo.User; public interface IUserService { ServerResponse<User> login(String username, String password); ServerResponse<String> checkValid(String str,String type); ServerResponse checkAdminRole(User user); }
19.411765
65
0.784848
fbdfd8688e40c8623877be9b180ee5c19d01a74d
2,576
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.jstarcraft.ai.jsat.classifiers.bayesian; import static org.junit.Assert.assertEquals; import java.util.Random; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import com.jstarcraft.ai.jsat.classifiers.ClassificationDataSet; import com.jstarcraft.ai.jsat.classifiers.Classifier; import com.jstarcraft.ai.jsat.classifiers.bayesian.NaiveBayes; import com.jstarcraft.ai.jsat.distributions.Normal; import com.jstarcraft.ai.jsat.utils.GridDataGenerator; /** * * @author Edward Raff */ public class NaiveBayesTest { static private ClassificationDataSet easyTrain; static private ClassificationDataSet easyTest; static private NaiveBayes nb; public NaiveBayesTest() { GridDataGenerator gdg = new GridDataGenerator(new Normal(0, 0.05), new Random(12), 2); easyTrain = new ClassificationDataSet(gdg.generateData(40).getList(), 0); easyTest = new ClassificationDataSet(gdg.generateData(40).getList(), 0); } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { nb = new NaiveBayes(); } /** * Test of train method, of class NaiveBayes. */ @Test public void testTrainC_ClassificationDataSet() { System.out.println("trainC"); nb.train(easyTrain); for (int i = 0; i < easyTest.size(); i++) assertEquals(easyTest.getDataPointCategory(i), nb.classify(easyTest.getDataPoint(i)).mostLikely()); } /** * Test of clone method, of class NaiveBayes. */ @Test public void testClone() { System.out.println("clone"); nb.train(easyTrain); Classifier clone = nb.clone(); for (int i = 0; i < easyTest.size(); i++) assertEquals(easyTest.getDataPointCategory(i), clone.classify(easyTest.getDataPoint(i)).mostLikely()); } /** * Test of train method, of class NaiveBayes. */ @Test public void testTrainC_ClassificationDataSet_ExecutorService() { System.out.println("trainC"); nb.train(easyTrain, true); for (int i = 0; i < easyTest.size(); i++) assertEquals(easyTest.getDataPointCategory(i), nb.classify(easyTest.getDataPoint(i)).mostLikely()); } }
30.666667
115
0.654891
a7c2d2b46ae9e12db9119cf34bfe28a016bfc8c1
195
package com.manorath.csye6225.exception; public class FileNotSupportedException extends RuntimeException { public FileNotSupportedException(String message) { super(message); } }
24.375
65
0.769231
8592138c18a97a8ae4a6e178d3171bbfbe773d9c
21,133
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: manage_service.proto package com.qingyuanos.core.googleprotobuf.openshiftapis; /** * Protobuf type {@code openshift.CreateOriginProjectRequest} */ public final class CreateOriginProjectRequest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:openshift.CreateOriginProjectRequest) CreateOriginProjectRequestOrBuilder { // Use CreateOriginProjectRequest.newBuilder() to construct. private CreateOriginProjectRequest(com.google.protobuf.GeneratedMessage.Builder<?> builder) { super(builder); } private CreateOriginProjectRequest() { name_ = ""; finalizers_ = com.google.protobuf.LazyStringArrayList.EMPTY; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private CreateOriginProjectRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); int mutable_bitField0_ = 0; try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!input.skipField(tag)) { done = true; } break; } case 10: { java.lang.String s = input.readStringRequireUtf8(); name_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); if (!((mutable_bitField0_ & 0x00000002) == 0x00000002)) { finalizers_ = new com.google.protobuf.LazyStringArrayList(); mutable_bitField0_ |= 0x00000002; } finalizers_.add(s); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000002) == 0x00000002)) { finalizers_ = finalizers_.getUnmodifiableView(); } makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.qingyuanos.core.googleprotobuf.openshiftapis.ProjectAndBuild.internal_static_openshift_CreateOriginProjectRequest_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.qingyuanos.core.googleprotobuf.openshiftapis.ProjectAndBuild.internal_static_openshift_CreateOriginProjectRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.qingyuanos.core.googleprotobuf.openshiftapis.CreateOriginProjectRequest.class, com.qingyuanos.core.googleprotobuf.openshiftapis.CreateOriginProjectRequest.Builder.class); } private int bitField0_; public static final int NAME_FIELD_NUMBER = 1; private volatile java.lang.Object name_; /** * <code>optional string name = 1;</code> */ public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } } /** * <code>optional string name = 1;</code> */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int FINALIZERS_FIELD_NUMBER = 2; private com.google.protobuf.LazyStringList finalizers_; /** * <code>repeated string finalizers = 2;</code> */ public com.google.protobuf.ProtocolStringList getFinalizersList() { return finalizers_; } /** * <code>repeated string finalizers = 2;</code> */ public int getFinalizersCount() { return finalizers_.size(); } /** * <code>repeated string finalizers = 2;</code> */ public java.lang.String getFinalizers(int index) { return finalizers_.get(index); } /** * <code>repeated string finalizers = 2;</code> */ public com.google.protobuf.ByteString getFinalizersBytes(int index) { return finalizers_.getByteString(index); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getNameBytes().isEmpty()) { com.google.protobuf.GeneratedMessage.writeString(output, 1, name_); } for (int i = 0; i < finalizers_.size(); i++) { com.google.protobuf.GeneratedMessage.writeString(output, 2, finalizers_.getRaw(i)); } } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getNameBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessage.computeStringSize(1, name_); } { int dataSize = 0; for (int i = 0; i < finalizers_.size(); i++) { dataSize += computeStringSizeNoTag(finalizers_.getRaw(i)); } size += dataSize; size += 1 * getFinalizersList().size(); } memoizedSize = size; return size; } private static final long serialVersionUID = 0L; public static com.qingyuanos.core.googleprotobuf.openshiftapis.CreateOriginProjectRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.qingyuanos.core.googleprotobuf.openshiftapis.CreateOriginProjectRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.qingyuanos.core.googleprotobuf.openshiftapis.CreateOriginProjectRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.qingyuanos.core.googleprotobuf.openshiftapis.CreateOriginProjectRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.qingyuanos.core.googleprotobuf.openshiftapis.CreateOriginProjectRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static com.qingyuanos.core.googleprotobuf.openshiftapis.CreateOriginProjectRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public static com.qingyuanos.core.googleprotobuf.openshiftapis.CreateOriginProjectRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input); } public static com.qingyuanos.core.googleprotobuf.openshiftapis.CreateOriginProjectRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.qingyuanos.core.googleprotobuf.openshiftapis.CreateOriginProjectRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input); } public static com.qingyuanos.core.googleprotobuf.openshiftapis.CreateOriginProjectRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessage .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.qingyuanos.core.googleprotobuf.openshiftapis.CreateOriginProjectRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code openshift.CreateOriginProjectRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:openshift.CreateOriginProjectRequest) com.qingyuanos.core.googleprotobuf.openshiftapis.CreateOriginProjectRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.qingyuanos.core.googleprotobuf.openshiftapis.ProjectAndBuild.internal_static_openshift_CreateOriginProjectRequest_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.qingyuanos.core.googleprotobuf.openshiftapis.ProjectAndBuild.internal_static_openshift_CreateOriginProjectRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.qingyuanos.core.googleprotobuf.openshiftapis.CreateOriginProjectRequest.class, com.qingyuanos.core.googleprotobuf.openshiftapis.CreateOriginProjectRequest.Builder.class); } // Construct using com.qingyuanos.core.googleprotobuf.openshiftapis.CreateOriginProjectRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); name_ = ""; finalizers_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000002); return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.qingyuanos.core.googleprotobuf.openshiftapis.ProjectAndBuild.internal_static_openshift_CreateOriginProjectRequest_descriptor; } public com.qingyuanos.core.googleprotobuf.openshiftapis.CreateOriginProjectRequest getDefaultInstanceForType() { return com.qingyuanos.core.googleprotobuf.openshiftapis.CreateOriginProjectRequest.getDefaultInstance(); } public com.qingyuanos.core.googleprotobuf.openshiftapis.CreateOriginProjectRequest build() { com.qingyuanos.core.googleprotobuf.openshiftapis.CreateOriginProjectRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public com.qingyuanos.core.googleprotobuf.openshiftapis.CreateOriginProjectRequest buildPartial() { com.qingyuanos.core.googleprotobuf.openshiftapis.CreateOriginProjectRequest result = new com.qingyuanos.core.googleprotobuf.openshiftapis.CreateOriginProjectRequest(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; result.name_ = name_; if (((bitField0_ & 0x00000002) == 0x00000002)) { finalizers_ = finalizers_.getUnmodifiableView(); bitField0_ = (bitField0_ & ~0x00000002); } result.finalizers_ = finalizers_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.qingyuanos.core.googleprotobuf.openshiftapis.CreateOriginProjectRequest) { return mergeFrom((com.qingyuanos.core.googleprotobuf.openshiftapis.CreateOriginProjectRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.qingyuanos.core.googleprotobuf.openshiftapis.CreateOriginProjectRequest other) { if (other == com.qingyuanos.core.googleprotobuf.openshiftapis.CreateOriginProjectRequest.getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; onChanged(); } if (!other.finalizers_.isEmpty()) { if (finalizers_.isEmpty()) { finalizers_ = other.finalizers_; bitField0_ = (bitField0_ & ~0x00000002); } else { ensureFinalizersIsMutable(); finalizers_.addAll(other.finalizers_); } onChanged(); } onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.qingyuanos.core.googleprotobuf.openshiftapis.CreateOriginProjectRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.qingyuanos.core.googleprotobuf.openshiftapis.CreateOriginProjectRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.lang.Object name_ = ""; /** * <code>optional string name = 1;</code> */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>optional string name = 1;</code> */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>optional string name = 1;</code> */ public Builder setName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; onChanged(); return this; } /** * <code>optional string name = 1;</code> */ public Builder clearName() { name_ = getDefaultInstance().getName(); onChanged(); return this; } /** * <code>optional string name = 1;</code> */ public Builder setNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; onChanged(); return this; } private com.google.protobuf.LazyStringList finalizers_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureFinalizersIsMutable() { if (!((bitField0_ & 0x00000002) == 0x00000002)) { finalizers_ = new com.google.protobuf.LazyStringArrayList(finalizers_); bitField0_ |= 0x00000002; } } /** * <code>repeated string finalizers = 2;</code> */ public com.google.protobuf.ProtocolStringList getFinalizersList() { return finalizers_.getUnmodifiableView(); } /** * <code>repeated string finalizers = 2;</code> */ public int getFinalizersCount() { return finalizers_.size(); } /** * <code>repeated string finalizers = 2;</code> */ public java.lang.String getFinalizers(int index) { return finalizers_.get(index); } /** * <code>repeated string finalizers = 2;</code> */ public com.google.protobuf.ByteString getFinalizersBytes(int index) { return finalizers_.getByteString(index); } /** * <code>repeated string finalizers = 2;</code> */ public Builder setFinalizers( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureFinalizersIsMutable(); finalizers_.set(index, value); onChanged(); return this; } /** * <code>repeated string finalizers = 2;</code> */ public Builder addFinalizers( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureFinalizersIsMutable(); finalizers_.add(value); onChanged(); return this; } /** * <code>repeated string finalizers = 2;</code> */ public Builder addAllFinalizers( java.lang.Iterable<java.lang.String> values) { ensureFinalizersIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, finalizers_); onChanged(); return this; } /** * <code>repeated string finalizers = 2;</code> */ public Builder clearFinalizers() { finalizers_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * <code>repeated string finalizers = 2;</code> */ public Builder addFinalizersBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureFinalizersIsMutable(); finalizers_.add(value); onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return this; } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return this; } // @@protoc_insertion_point(builder_scope:openshift.CreateOriginProjectRequest) } // @@protoc_insertion_point(class_scope:openshift.CreateOriginProjectRequest) private static final com.qingyuanos.core.googleprotobuf.openshiftapis.CreateOriginProjectRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.qingyuanos.core.googleprotobuf.openshiftapis.CreateOriginProjectRequest(); } public static com.qingyuanos.core.googleprotobuf.openshiftapis.CreateOriginProjectRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CreateOriginProjectRequest> PARSER = new com.google.protobuf.AbstractParser<CreateOriginProjectRequest>() { public CreateOriginProjectRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new CreateOriginProjectRequest(input, extensionRegistry); } }; public static com.google.protobuf.Parser<CreateOriginProjectRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CreateOriginProjectRequest> getParserForType() { return PARSER; } public com.qingyuanos.core.googleprotobuf.openshiftapis.CreateOriginProjectRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
34.815486
188
0.693087
15f4f05fbde02513ad532ec394265bb283df9923
340
package com.gpmall.shopping.form;/** * Created by mic on 2019/7/26. */ import lombok.Data; /** * 腾讯课堂搜索【咕泡学院】 * 官网:www.gupaoedu.com * 风骚的Mic 老师 * create-date: 2019/7/26-下午4:50 */ @Data public class CartForm { private Long userId; private Long productId; private String checked; private Integer productNum; }
12.592593
36
0.661765
d2fe73ffbc7af38346d6f742ccb110e20e1778f4
573
package com.helospark.lightdi.annotation; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Container for {@link PropertySource} annotations to make them repeatable. * @author helospark */ @Documented @Retention(RUNTIME) @Target(TYPE) @RepeatableAnnotationContainer public @interface PropertySources { /** * @return property sources */ PropertySource[] value(); }
22.92
76
0.769634
9fac951ccf59cfc4a2d9af09a411d4c2565c6e47
3,787
/* * Copyright 2018, OpenCensus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.opencensus.contrib.appengine.standard.util; import static com.google.common.base.Preconditions.checkNotNull; import com.google.apphosting.api.CloudTraceContext; import com.google.common.annotations.VisibleForTesting; import io.opencensus.trace.SpanContext; import io.opencensus.trace.SpanId; import io.opencensus.trace.TraceId; import io.opencensus.trace.TraceOptions; import io.opencensus.trace.Tracestate; import java.nio.ByteBuffer; /** * Utility class to convert between {@link io.opencensus.trace.SpanContext} and {@link * CloudTraceContext}. * * @since 0.14 */ public final class AppEngineCloudTraceContextUtils { private static final byte[] INVALID_TRACE_ID = TraceIdProto.newBuilder().setHi(0).setLo(0).build().toByteArray(); private static final long INVALID_SPAN_ID = 0L; private static final long INVALID_TRACE_MASK = 0L; private static final Tracestate TRACESTATE_DEFAULT = Tracestate.builder().build(); @VisibleForTesting static final CloudTraceContext INVALID_CLOUD_TRACE_CONTEXT = new CloudTraceContext(INVALID_TRACE_ID, INVALID_SPAN_ID, INVALID_TRACE_MASK); /** * Converts AppEngine {@code CloudTraceContext} to {@code SpanContext}. * * @param cloudTraceContext the AppEngine {@code CloudTraceContext}. * @return the converted {@code SpanContext}. * @since 0.14 */ public static SpanContext fromCloudTraceContext(CloudTraceContext cloudTraceContext) { checkNotNull(cloudTraceContext, "cloudTraceContext"); try { // Extract the trace ID from the binary protobuf CloudTraceContext#traceId. TraceIdProto traceIdProto = TraceIdProto.parseFrom(cloudTraceContext.getTraceId()); ByteBuffer traceIdBuf = ByteBuffer.allocate(TraceId.SIZE); traceIdBuf.putLong(traceIdProto.getHi()); traceIdBuf.putLong(traceIdProto.getLo()); ByteBuffer spanIdBuf = ByteBuffer.allocate(SpanId.SIZE); spanIdBuf.putLong(cloudTraceContext.getSpanId()); return SpanContext.create( TraceId.fromBytes(traceIdBuf.array()), SpanId.fromBytes(spanIdBuf.array()), TraceOptions.builder().setIsSampled(cloudTraceContext.isTraceEnabled()).build(), TRACESTATE_DEFAULT); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw new RuntimeException(e); } } /** * Converts {@code SpanContext} to AppEngine {@code CloudTraceContext}. * * @param spanContext the {@code SpanContext}. * @return the converted AppEngine {@code CloudTraceContext}. * @since 0.14 */ public static CloudTraceContext toCloudTraceContext(SpanContext spanContext) { checkNotNull(spanContext, "spanContext"); ByteBuffer traceIdBuf = ByteBuffer.wrap(spanContext.getTraceId().getBytes()); TraceIdProto traceIdProto = TraceIdProto.newBuilder().setHi(traceIdBuf.getLong()).setLo(traceIdBuf.getLong()).build(); ByteBuffer spanIdBuf = ByteBuffer.wrap(spanContext.getSpanId().getBytes()); return new CloudTraceContext( traceIdProto.toByteArray(), spanIdBuf.getLong(), spanContext.getTraceOptions().isSampled() ? 1L : 0L); } private AppEngineCloudTraceContextUtils() {} }
38.252525
98
0.744125
e01e8db8bda51cf983e8b667208857fdbe71cd8f
3,493
//////////////////////////////////////////////////////////////////////////\ // // Copyright (c) 2012-2019 60East Technologies Inc., All Rights Reserved. // // This computer software is owned by 60East Technologies Inc. and is // protected by U.S. copyright laws and other laws and by international // treaties. This computer software is furnished by 60East Technologies // Inc. pursuant to a written license agreement and may be used, copied, // transmitted, and stored only in accordance with the terms of such // license agreement and with the inclusion of the above copyright notice. // This computer software or any other copies thereof may not be provided // or otherwise made available to any other person. // // U.S. Government Restricted Rights. This computer software: (a) was // developed at private expense and is in all respects the proprietary // information of 60East Technologies Inc.; (b) was not developed with // government funds; (c) is a trade secret of 60East Technologies Inc. // for all purposes of the Freedom of Information Act; and (d) is a // commercial item and thus, pursuant to Section 12.212 of the Federal // Acquisition Regulations (FAR) and DFAR Supplement Section 227.7202, // Government's use, duplication or disclosure of the computer software // is subject to the restrictions set forth by 60East Technologies Inc.. // //////////////////////////////////////////////////////////////////////////// package com.crankuptheamps.authentication.kerberos; import java.util.Properties; import org.junit.Assume; import org.junit.Before; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.crankuptheamps.client.exception.AuthenticationException; /** * Unit test for AMPSKerberosAuthenticator. */ public class AMPSKerberosGSSAPIAuthenticatorTest extends AMPSKerberosAuthenticatorTestBase { private String _loginContextName; private static final Logger _logger = LoggerFactory.getLogger(AMPSKerberosGSSAPIAuthenticatorTest.class); public AMPSKerberosGSSAPIAuthenticatorTest() throws AuthenticationException { super(); } @Before public void setUp() throws AuthenticationException { super.setUp(); // Local authentication test exec via mvn // mvn -Djava.security.krb5.conf=/etc/krb5.conf // -Djava.security.auth.login.config=src/test/resources/jaas.conf // -Damps.auth.test.amps.host=ubuntu-desktop // -Damps.auth.test.amps.port=8554 // -Damps.auth.test.login.ctx.name=TestClientLocalKDC // test Properties props = System.getProperties(); if (props.getProperty("java.security.krb5.conf") == null) { throw new RuntimeException("java.security.krb5.conf must be set"); } if (props.getProperty("java.security.auth.login.config") == null) { throw new RuntimeException("java.security.auth.login.config must be set"); } _loginContextName = props.getProperty("amps.auth.test.login.ctx.name"); if (_loginContextName == null) { _loginContextName = "LoginContext"; _logger.info("No login context name set via amps.auth.test.login.ctx.name. Login context name set to \"" + _loginContextName + "\""); } String ampsUser = "60east"; _uri = "tcp://" + ampsUser + "@" + _ampsHost + ":" + _ampsPort + "/amps/json"; _authenticator = new AMPSKerberosGSSAPIAuthenticator(_spn, _loginContextName); } }
42.597561
116
0.682222
57a6de6c4dd8ecc4d89cc974aa8f46914c58194b
1,899
package com.ringcentral.platform.metrics.rate; import com.ringcentral.platform.metrics.*; import com.ringcentral.platform.metrics.dimensions.MetricDimensionValues; import com.ringcentral.platform.metrics.names.MetricName; import com.ringcentral.platform.metrics.rate.configs.*; import com.ringcentral.platform.metrics.utils.TimeMsProvider; import java.util.Set; import java.util.concurrent.ScheduledExecutorService; import static com.ringcentral.platform.metrics.counter.Counter.COUNT; import static com.ringcentral.platform.metrics.utils.Preconditions.checkArgument; public abstract class AbstractRate<MI> extends AbstractMeter< MI, RateInstanceConfig, RateSliceConfig, RateConfig> implements Rate { public static final Set<RateMeasurable> DEFAULT_RATE_MEASURABLES = Set.of( COUNT, MEAN_RATE, ONE_MINUTE_RATE, FIVE_MINUTES_RATE, FIFTEEN_MINUTES_RATE, RATE_UNIT); protected AbstractRate( MetricName name, RateConfig config, MeasurableValueProvidersProvider<MI, RateInstanceConfig, RateSliceConfig, RateConfig> measurableValueProvidersProvider, MeterImplMaker<MI, RateInstanceConfig, RateSliceConfig, RateConfig> meterImplMaker, MeterImplUpdater<MI> meterImplUpdater, InstanceMaker<MI> instanceMaker, TimeMsProvider timeMsProvider, ScheduledExecutorService executor, MetricRegistry registry) { super( name, config, measurableValueProvidersProvider, meterImplMaker, meterImplUpdater, instanceMaker, timeMsProvider, executor, registry); } @Override public void mark(long count, MetricDimensionValues dimensionValues) { checkArgument(count > 0L, "count <= 0"); super.update(count, dimensionValues); } }
32.741379
127
0.71564
85f457a7becce3ad2534bfb2dadf7f4bf3cc7c14
2,870
package org.cyclaps.cyclaps; import android.content.Intent; import android.support.annotation.NonNull; import android.support.design.internal.BottomNavigationMenu; import android.support.design.widget.BottomNavigationView; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.MenuItem; import android.view.Window; import android.webkit.WebView; import android.webkit.WebViewClient; public class raceScreen extends AppCompatActivity { private WebView wv; private BottomNavigationMenu bnm; private BottomNavigationView bottomNavigationView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_race_screen); //BottomNavigationView bottomNavigationView; bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation); //bottomNavigationView.setOnNavigationItemSelectedListener(myNavigationItemListener); bottomNavigationView.setSelectedItemId(R.id.navigation_race); bottomNavigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); getSupportActionBar().hide(); wv = (WebView) findViewById(R.id.mwebView); wv.getSettings().setJavaScriptEnabled(true); wv.setWebViewClient(new WebViewClient()); wv.loadUrl("http://mobilehci.s3-website.eu-west-2.amazonaws.com/race.html"); } private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.navigation_home: bottomNavigationView.getMenu().getItem(0).setChecked(true); startActivity(new Intent(raceScreen.this, homeScreen.class)); //mTextMessage.setText(R.string.title_home); return true; case R.id.navigation_race: //mTextMessage.setText("Race"); bottomNavigationView.getMenu().getItem(1).setChecked(true); startActivity(new Intent(raceScreen.this, raceScreen.class)); return true; case R.id.navigation_hunt: // mTextMessage.setText("Hunt"); return true; case R.id.navigation_leaderboard: // mTextMessage.setText("Leaderboard"); bottomNavigationView.getMenu().getItem(3).setChecked(true); startActivity(new Intent(raceScreen.this, leaderboardScreen.class)); return true; } return false; } }; }
36.794872
100
0.672822
c593ecc620f3bb2e9dbea0c97e0c62b6e326e963
769
package hrms.dataAccess.abstracts; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import hrms.core.dataAccess.BaseDao; import hrms.entities.concretes.IndividualTechnology; public interface IndividualTechnologyDao extends BaseDao<IndividualTechnology, Long>, JpaRepository<IndividualTechnology, Long> { @Query("From IndividualTechnology where individual.id=:id and active=:active") List<IndividualTechnology> getByIndividual(int id, boolean active); @Query("From IndividualTechnology where individual.id = :individualId and technology.id = :technologyId and active = true") IndividualTechnology doesExist(Integer individualId, short technologyId); }
42.722222
127
0.808843
b13b9bab42db539a6d69b713835f5132961a529c
1,485
package com.omar.abdotareq.meshkat.adapters; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentStatePagerAdapter; import com.omar.abdotareq.meshkat.activities.FragmentSearch; import java.util.ArrayList; import java.util.List; public class FragmentAdapter extends FragmentStatePagerAdapter { private List<androidx.fragment.app.Fragment> fragments = new ArrayList<>(); //Fragment List private List<String> NamePage = new ArrayList<>(); // Fragment Name List public FragmentAdapter(FragmentManager manager) { super(manager); } public void add(Fragment Frag, String Title) { fragments.add(Frag); NamePage.add(Title); } @Override public Fragment getItem(int position) { return fragments.get(position); } @Override public CharSequence getPageTitle(int position) { return NamePage.get(position); } @Override public int getCount() { return 2; } /** * A method called when searching , the searched word is passed to it and then the method * will call the search method in all fragments it holds */ public void changeAzkarAndAhadeth(String word) { //loop on all fragments inside it for (androidx.fragment.app.Fragment frag : fragments) { //call onSearchTextChange method ((FragmentSearch) frag).onSearchTextChange(word); } } }
27
95
0.688889
1060fa3fc4ce523e005471c74dc8f224d4e7a808
998
package computing.client; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.stream.Collectors; import org.springframework.http.client.ClientHttpResponse; import org.springframework.web.client.ResponseErrorHandler; import com.google.gson.Gson; import lombok.extern.slf4j.Slf4j; @Slf4j public class ErrorHandler implements ResponseErrorHandler { @Override public void handleError(ClientHttpResponse response) throws IOException { log.debug("======= Start Error report ========"); Gson g = new Gson(); String json = new BufferedReader(new InputStreamReader(response.getBody())).lines() .collect(Collectors.joining("\n")); ErrorResponse result = g.fromJson(json, ErrorResponse.class); log.debug(result.getDescription()); log.debug("======= End Error report ========"); } @Override public boolean hasError(ClientHttpResponse response) throws IOException { return !response.getStatusCode().is2xxSuccessful(); } }
29.352941
85
0.759519
60193b9229035416c0b88b006433af9a4d8e8383
2,068
package com.bah.ode.spark; import org.apache.spark.Accumulator; import org.apache.spark.api.java.JavaPairRDD; import org.apache.spark.api.java.function.Function; import org.apache.spark.broadcast.Broadcast; import org.apache.spark.sql.DataFrame; import org.apache.spark.sql.SQLContext; import com.bah.ode.wrapper.MQSerialazableProducerPool; public class VehicleSpeedAggregator extends BaseDistributor implements Function<JavaPairRDD<String, String>, Void> { private static final long serialVersionUID = 34991323740854373L; private String outputTopic; private Accumulator<Integer> distributorAccumulator; public VehicleSpeedAggregator( Accumulator<Integer> aggregatorAccumulator, Accumulator<Integer> distributorAccumulator, Broadcast<MQSerialazableProducerPool> producerPool, String outputTopic) { super(aggregatorAccumulator, producerPool); this.outputTopic = outputTopic; this.distributorAccumulator = distributorAccumulator; } @Override public Void call(JavaPairRDD<String, String> rdd) throws Exception { startTimer(); if (rdd.count() == 0){ return null; } SQLContext sqlContext = SqlContextSingleton.getInstance(rdd.context()); DataFrame ovdfDataFrame = sqlContext.jsonRDD(rdd.values()); // ovdfDataFrame.show(10); // Register as table ovdfDataFrame.registerTempTable("OVDF"); // Calculate stats for speed column on table using SQL try { DataFrame ovdfAggsDataFrame = sqlContext.sql("SELECT roadSeg, COUNT(speed), " + "MIN(speed), AVG(speed), MAX(speed) " + "FROM OVDF GROUP BY roadSeg"); // ovdfAggsDataFrame.show(10); ovdfAggsDataFrame.toJavaRDD().foreachPartition(new AggregateSpeedDistributor( distributorAccumulator, producerPool, outputTopic)); } catch (Exception e) { e.printStackTrace(); } stopTimer(); return null; } }
30.411765
86
0.679884
61942b2330f3019cac36757af542fe41e64429a7
5,725
package com.redhat.service.bridge.manager.dao; import java.util.List; import javax.enterprise.context.ApplicationScoped; import javax.persistence.TypedQuery; import javax.transaction.Transactional; import com.redhat.service.bridge.infra.models.ListResult; import com.redhat.service.bridge.infra.models.QueryInfo; import com.redhat.service.bridge.manager.models.Bridge; import com.redhat.service.bridge.manager.models.Processor; import io.quarkus.hibernate.orm.panache.PanacheQuery; import io.quarkus.hibernate.orm.panache.PanacheRepositoryBase; import io.quarkus.panache.common.Parameters; import static java.util.Collections.emptyList; @ApplicationScoped @Transactional public class ProcessorDAO implements PanacheRepositoryBase<Processor, String> { /* * NOTE: the Processor queries that use a left join on the filters **MUST** be wrapped by the method `removeDuplicates`! * see https://developer.jboss.org/docs/DOC-15782# * jive_content_id_Hibernate_does_not_return_distinct_results_for_a_query_with_outer_join_fetching_enabled_for_a_collection_even_if_I_use_the_distinct_keyword */ private static final String IDS_PARAM = "ids"; public Processor findByBridgeIdAndName(String bridgeId, String name) { Parameters p = Parameters.with(Processor.NAME_PARAM, name).and(Processor.BRIDGE_ID_PARAM, bridgeId); return singleResultFromList(find("#PROCESSOR.findByBridgeIdAndName", p)); } /* * For queries where we need to fetch join associations, this works around the fact that Hibernate has to * apply pagination in-memory _if_ we rely on Panaches .firstResult() or firstResultOptional() methods. This * manifests as "HHH000104: firstResult/maxResults specified with collection fetch; applying in memory!" in the log * * This performs the query as if we expect a list result, but then converts the list into a single result * response: either the entity if the list has a single result, or null if not. * * More than 1 entity in the list throws an IllegalStateException as it's not something that we expect to happen * */ private Processor singleResultFromList(PanacheQuery<Processor> find) { List<Processor> processors = find.list(); if (processors.size() > 1) { throw new IllegalStateException("Multiple Entities returned from a Query that should only return a single Entity"); } return processors.size() == 1 ? processors.get(0) : null; } public Processor findByIdBridgeIdAndCustomerId(String id, String bridgeId, String customerId) { Parameters p = Parameters.with(Processor.ID_PARAM, id) .and(Processor.BRIDGE_ID_PARAM, bridgeId) .and(Bridge.CUSTOMER_ID_PARAM, customerId); return singleResultFromList(find("#PROCESSOR.findByIdBridgeIdAndCustomerId", p)); } public List<Processor> findByShardIdWithReadyDependencies(String shardId) { Parameters p = Parameters .with("shardId", shardId); return find("#PROCESSOR.findByShardIdWithReadyDependencies", p).list(); } private Long countProcessorsOnBridge(Parameters params) { TypedQuery<Long> namedQuery = getEntityManager().createNamedQuery("PROCESSOR.countByBridgeIdAndCustomerId", Long.class); addParamsToNamedQuery(params, namedQuery); return namedQuery.getSingleResult(); } private void addParamsToNamedQuery(Parameters params, TypedQuery<?> namedQuery) { params.map().forEach((key, value) -> namedQuery.setParameter(key, value.toString())); } public ListResult<Processor> findByBridgeIdAndCustomerId(String bridgeId, String customerId, QueryInfo queryInfo) { /* * Unfortunately we can't rely on Panaches in-built Paging due the fetched join in our query * for Processor e.g. join fetch p.bridge. Instead, we simply build a list of ids to fetch and then * execute the join fetch as normal. So the workflow here is: * * - Count the number of Processors on a bridge. If > 0 * - Select the ids of the Processors that need to be retrieved based on the page/size requirements * - Select the Processors in the list of ids, performing the fetch join of the Bridge */ Parameters p = Parameters.with(Bridge.CUSTOMER_ID_PARAM, customerId).and(Processor.BRIDGE_ID_PARAM, bridgeId); Long processorCount = countProcessorsOnBridge(p); if (processorCount == 0L) { return new ListResult<>(emptyList(), queryInfo.getPageNumber(), processorCount); } int firstResult = getFirstResult(queryInfo.getPageNumber(), queryInfo.getPageSize()); TypedQuery<String> idsQuery = getEntityManager().createNamedQuery("PROCESSOR.idsByBridgeIdAndCustomerId", String.class); addParamsToNamedQuery(p, idsQuery); List<String> ids = idsQuery.setMaxResults(queryInfo.getPageSize()).setFirstResult(firstResult).getResultList(); List<Processor> processors = getEntityManager().createNamedQuery("PROCESSOR.findByIds", Processor.class).setParameter(IDS_PARAM, ids).getResultList(); return new ListResult<>(processors, queryInfo.getPageNumber(), processorCount); } public Long countByBridgeIdAndCustomerId(String bridgeId, String customerId) { Parameters p = Parameters.with(Bridge.CUSTOMER_ID_PARAM, customerId).and(Processor.BRIDGE_ID_PARAM, bridgeId); return countProcessorsOnBridge(p); } private int getFirstResult(int requestedPage, int requestedPageSize) { if (requestedPage <= 0) { return 0; } return requestedPage * requestedPageSize; } }
47.31405
162
0.727686
5d6f8d15f980adcd851990e327f2b66ca29b5f2a
709
package org.apache.maven.settings.building; import java.util.ArrayList; import java.util.List; import org.apache.maven.settings.Settings; class DefaultSettingsBuildingResult implements SettingsBuildingResult { private Settings effectiveSettings; private List<SettingsProblem> problems; public DefaultSettingsBuildingResult(Settings effectiveSettings, List<SettingsProblem> problems) { this.effectiveSettings = effectiveSettings; this.problems = (problems != null ? problems : new ArrayList()); } public Settings getEffectiveSettings() { return effectiveSettings; } public List<SettingsProblem> getProblems() { return problems; } }
12.660714
98
0.736248
5c3adbcc6a87da77ca1b8ec0aa3ff672f80ed12d
1,097
/** * © Copyright IBM Corporation 2016. * © Copyright HCL Technologies Ltd. 2017. * LICENSE: Apache License, Version 2.0 https://www.apache.org/licenses/LICENSE-2.0 */ package com.hcl.appscan.sdk.scanners.sast.targets; import java.io.File; import java.util.Map; import java.util.Set; import com.hcl.appscan.sdk.scan.ITarget; public interface ISASTTarget extends ITarget{ /** * Gets the target file. * @return The target file. */ File getTargetFile(); /** * Gets a map of properties associated with the target. * @return The Map of properties. */ Map<String, String> getProperties(); /** * Gets a list of exclusion patterns for this target. * @return A list of patterns to exclude. */ Set<String> getExclusionPatterns(); /** * Gets a list of inclusion patterns for this target. * @return A list of patterns to include. */ Set<String> getInclusionPatterns(); /** * Whether this target is only associated with build output files (e.g. .jar, .dll, etc.) * @return false if this target includes non-build outputs. */ boolean outputsOnly(); }
22.854167
90
0.694622
adcd425c0dba76bd97cf97ca25105ce87619388f
4,364
package com.emv.qrcode.decoder.mpm; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; import org.junit.Test; import com.emv.qrcode.core.exception.PresentedModeException; import com.emv.qrcode.core.model.mpm.TagLengthString; import com.emv.qrcode.model.mpm.MerchantAccountInformationReserved; import com.emv.qrcode.model.mpm.MerchantAccountInformationReservedAdditional; import com.emv.qrcode.model.mpm.MerchantAccountInformationTemplate; public class MerchantAccountInformationTemplateDecoderTest { @Test public void testSuccessDecodeReserved() throws PresentedModeException { final MerchantAccountInformationTemplate merchantAccountInformation = DecoderMpm.decode("02040004", MerchantAccountInformationTemplate.class); assertThat(merchantAccountInformation.getValue(), not(nullValue())); assertThat(merchantAccountInformation.getTag(), equalTo("02")); assertThat(merchantAccountInformation.getLength(), equalTo(4)); final MerchantAccountInformationReserved value = merchantAccountInformation.getTypeValue(MerchantAccountInformationReserved.class); assertThat(value, not(nullValue())); assertThat(value.getValue(), equalTo("0004")); } @Test public void testSuccessDecodeReservedAdditional() throws PresentedModeException { final MerchantAccountInformationTemplate merchantAccountInformation = DecoderMpm.decode("26160004hoge0104abcd", MerchantAccountInformationTemplate.class); assertThat(merchantAccountInformation.getValue(), not(nullValue())); assertThat(merchantAccountInformation.getTag(), equalTo("26")); assertThat(merchantAccountInformation.getLength(), equalTo(16)); final MerchantAccountInformationReservedAdditional value = merchantAccountInformation.getTypeValue(MerchantAccountInformationReservedAdditional.class); assertThat(value.getGloballyUniqueIdentifier(), not(nullValue())); assertThat(value.getPaymentNetworkSpecific().size(), equalTo(1)); assertThat(value.getGloballyUniqueIdentifier().getTag(), equalTo("00")); assertThat(value.getGloballyUniqueIdentifier().getLength(), equalTo(4)); assertThat(value.getGloballyUniqueIdentifier().getValue(), equalTo("hoge")); assertThat(value.getPaymentNetworkSpecific().get("01").getTag(), equalTo("01")); assertThat(value.getPaymentNetworkSpecific().get("01").getLength(), equalTo(4)); assertThat(value.getPaymentNetworkSpecific().get("01").getValue(), equalTo("abcd")); } @Test public void testSuccessDecodeEncode() throws PresentedModeException { final MerchantAccountInformationTemplate merchantAccountInformation1 = DecoderMpm.decode("02160004hoge0104abcd", MerchantAccountInformationTemplate.class); assertThat(merchantAccountInformation1.toString(), equalTo("02160004hoge0104abcd")); final MerchantAccountInformationTemplate merchantAccountInformation2 = DecoderMpm.decode("26160004hoge0104abcd", MerchantAccountInformationTemplate.class); assertThat(merchantAccountInformation2.toString(), equalTo("26160004hoge0104abcd")); } @Test public void testSuccessEncodeReserved() { final MerchantAccountInformationReserved value = new MerchantAccountInformationReserved("00004"); final MerchantAccountInformationTemplate merchantAccountInformation = new MerchantAccountInformationTemplate(); merchantAccountInformation.setValue(value); merchantAccountInformation.setTag("02"); assertThat(merchantAccountInformation.toString(), equalTo("020500004")); } @Test public void testSuccessEncodeReservedAdditional() { final TagLengthString paymentNetworkSpecific = new TagLengthString(); paymentNetworkSpecific.setTag("01"); paymentNetworkSpecific.setValue("abcd"); final MerchantAccountInformationReservedAdditional value = new MerchantAccountInformationReservedAdditional(); value.setGloballyUniqueIdentifier("hoge"); value.addPaymentNetworkSpecific(paymentNetworkSpecific); final MerchantAccountInformationTemplate merchantAccountInformation = new MerchantAccountInformationTemplate(); merchantAccountInformation.setValue(value); merchantAccountInformation.setTag("26"); assertThat(merchantAccountInformation.toString(), equalTo("26160004hoge0104abcd")); } }
44.989691
159
0.809578
5e2f726e22067bcb950dd52237afabaf1e1de08a
563
package ch.heigvd.amt.repositories; import ch.heigvd.amt.entities.ApiKeyEntity; import ch.heigvd.amt.entities.BadgeEntity; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Optional; import java.util.UUID; @Repository public interface BadgeRepository extends JpaRepository<BadgeEntity, Long> { Optional<List<BadgeEntity>> findByApiKeyEntityValue(String apiKeyId); Optional<BadgeEntity> findByApiKeyEntityValue_AndId(String apiKeyId, Long badgeId); }
33.117647
87
0.829485
2fb3db76c95dca9fc01776d25cd604c4c48f10b8
122
package steamAPI; import java.util.List; public class AppList { public int appId; public String name; }
13.555556
24
0.663934
0e48821a42487bb4be878d5f09ffc5c53a09fd60
1,934
/** * */ package com.flyover.boot.consul.config; import java.util.Arrays; import java.util.Map; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.context.EnvironmentAware; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; import org.springframework.core.type.AnnotationMetadata; /** * @author mramach * */ @Configuration public class ConsulPropertySourceConfiguration implements ImportBeanDefinitionRegistrar, EnvironmentAware { private ConfigurableEnvironment environment; @Override public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) { ConsulProperties configuration = override(metadata, new ConsulProperties()); ConsulAdapter consulAdapter = new ConsulAdapter(configuration); environment.getPropertySources().addFirst( new ConsulPropertySource(configuration, consulAdapter)); } private ConsulProperties override(AnnotationMetadata metadata, ConsulProperties configuration) { Map<String, Object> attributes = metadata .getAnnotationAttributes(EnableConsulPropertySource.class.getName()); configuration.setEndpoint(environment.getProperty("consul.endpoint", "http://localhost:8500/v1")); configuration.setPaths(Arrays.asList((String[])attributes.get("value"))); configuration.setFailFast(Boolean.valueOf(environment.getProperty("consul.failFast", "false"))); return configuration; } @Override public void setEnvironment(Environment environment) { this.environment = (ConfigurableEnvironment) environment; } }
33.929825
107
0.74302
7df420fe1a8245ba89a2a3a853155facf15784df
1,643
package ru.andreeva.library.web.views; import com.vaadin.flow.component.grid.HeaderRow; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; import ru.andreeva.library.service.dao.Book; import ru.andreeva.library.service.repositories.BooksRepository; import ru.andreeva.library.service.specifications.BookSpecificationFactoryImpl; @Route(value = "books", layout = MainLayout.class) @PageTitle("Фонд библиотеки") public class BooksView extends BaseView<Book, Integer, BooksRepository> { public BooksView(BookSpecificationFactoryImpl bookSpecificationFactory, BooksRepository booksRepository) { super(booksRepository, bookSpecificationFactory); } protected void createColumns() { HeaderRow filterRow = grid.appendHeaderRow(); filterService.addGridTextFilter(grid.addColumn(Book::getName).setHeader("Название").setKey("name"), filterRow); filterService.addGridTextFilter(grid.addColumn(Book::getAuthor).setHeader("Автор").setKey("author"), filterRow); filterService.addGridTextFilter(grid.addColumn(Book::getPublisher) .setHeader("Издатель") .setKey("publisher"), filterRow); filterService.addGridTextFilter(grid.addColumn(Book::getYear) .setHeader("Год издания") .setKey("year"), filterRow); filterService.addGridTextFilter(grid.addColumn(Book::getPageCount) .setHeader("Количество страниц") .setKey("pageCount"), filterRow); filterService.addGridTextFilter(grid.addColumn(Book::getPrice).setHeader("Цена").setKey("price"), filterRow); } }
48.323529
120
0.728545
fc47060e705afae191022b11887e93d79461c442
5,047
/* * 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.webbeans.logger; /* * These are for use of JDK util logging. */ import org.apache.webbeans.config.OWBLogConst; import org.apache.webbeans.util.WebBeansConstants; import javax.annotation.Priority; import java.text.MessageFormat; import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.ServiceLoader; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.StreamSupport; import static java.util.Comparator.comparing; import static java.util.Optional.ofNullable; /** * Wrapper class around the JUL logger class to include some checks before the * logs are actually written. * <p> * Actually, it is a thin layer on the JUL {@link Logger} implementation. * </p> * * @version $Rev$ $Date$ */ public final class WebBeansLoggerFacade { public static final String OPENWEBBEANS_LOGGING_FACTORY_PROP = "openwebbeans.logging.factory"; private static final WebBeansLoggerFactory FACTORY; static final ResourceBundle WB_BUNDLE = ResourceBundle.getBundle(WebBeansConstants.WEB_BEANS_MESSAGES); static { String factoryClassname = System.getProperty(OPENWEBBEANS_LOGGING_FACTORY_PROP); WebBeansLoggerFactory factory = null; Exception error = null; if (factoryClassname != null) { try { // don't use the org.apache.webbeans.util.WebBeansUtil.getCurrentClassLoader() // to avoid weird dependency and potential failing ClassLoader classloader = Thread.currentThread().getContextClassLoader(); if(classloader == null) { classloader = WebBeansLoggerFacade.class.getClassLoader(); } Class<?> factoryClazz = classloader.loadClass(factoryClassname); factory = (WebBeansLoggerFactory) factoryClazz.newInstance(); } catch (Exception e) { error = e; } } if (factory != null) { FACTORY = factory; } else { FACTORY = StreamSupport.stream(ServiceLoader.load(WebBeansLoggerFactory.class).spliterator(), false) .max(comparing(it -> ofNullable(it.getClass().getAnnotation(Priority.class)).map(Priority::value).orElse(0))) .orElseGet(JULLoggerFactory::new); } Logger logger = FACTORY.getLogger(WebBeansLoggerFacade.class); if (error != null && logger.isLoggable(Level.SEVERE)) { logger.log(Level.SEVERE, OWBLogConst.ERROR_0028, error); } } /** * Gets the new web beans logger instance. * * @param clazz own the return logger * @return new logger */ public static Logger getLogger(Class<?> clazz) { return FACTORY.getLogger(clazz); } /** * Gets the new web beans logger instance. * * @param clazz own the return logger * @param desiredLocale Locale used to select the Message resource bundle. * @return new logger */ public static Logger getLogger(Class<?> clazz, Locale desiredLocale) { return FACTORY.getLogger(clazz, desiredLocale); } public static String constructMessage(String messageKey, Object... args) { MessageFormat msgFrmt; String formattedString; msgFrmt = new MessageFormat(getTokenString(messageKey), Locale.getDefault()); formattedString = msgFrmt.format(args); return formattedString; } public static String getTokenString(String messageKey) { String strVal; if (WB_BUNDLE == null) { throw new IllegalStateException("ResourceBundle can not be null"); } try { strVal = WB_BUNDLE.getString(messageKey); } catch (MissingResourceException mre) { strVal = null; } if (strVal == null) { return messageKey; } return strVal; } // helper method public static Object[] args(Object... values) { return values; } }
30.77439
129
0.646721
1eb0b8d7c230c261eacea259360369a0305b9eea
414
package com.box.l10n.mojito.cli.command; import com.box.l10n.mojito.phabricator.DifferentialRevision; public class PhabricatorPreconditions { public static void checkNotNull(Object phabricatorDependency) { if (phabricatorDependency == null) { throw new CommandException("Phabricator must be configured with properties: l10n.phabricator.url and l10n.phabricator.token"); } } }
34.5
138
0.746377
c812d2dbcedf1182d8d9200520921f906ee2e563
3,578
package com.game.legendarygiggle; import com.game.legendarygiggle.adventure.Adventure; import com.game.legendarygiggle.adventure.map.UniverseMap; import com.game.legendarygiggle.adventure.player.Player; import com.game.legendarygiggle.menu.InGameMenu; import com.game.legendarygiggle.menu.MainMenu; import com.game.legendarygiggle.menu.MenuInterface; import com.game.legendarygiggle.utilities.Screen; import org.apache.commons.lang3.tuple.Pair; import java.util.Map; import java.util.Scanner; import java.util.function.BooleanSupplier; import java.util.HashMap; /** * GameApp to orchestrate legendary giggle adventure */ public class GameApp { public static Map<String, Pair<String, BooleanSupplier>> menuItems; static int [][] basicMap = { {1, 2, 0, 2, 3, 1}, {1, 2, 2, 2, 2, 1}, {2, 1, 3, 2, 3, 3}, {1, 2, 2, 2, 2, 1}, {1, 2, 1, 2, 3, 1}, {2, 1, 3, 2, 3, 3}, }; static String [][] planets = { {"Mercury", "Venus", "Earth", "Mercitron", "Uranitron", "Fearon"}, {"Gaspra", "Mars", "Eros", "Astrieon", "Mextron", "Texitron"}, {"Jupiter", "Pandia", "Valetudo", "Ramonton", "Hellton", "Kirton"}, {"Soccoalara", "Chilveuc", "Bonoria", "Nongora", "Kunerth", "Cacarro"}, {"Gnooria", "Bapupra", "Zolla", "Lichi", "Xubenope", "Katrides"}, {"Thiestea", "Aneron", "Ieclite", "Drabistea", "Giri 60BX", "Zealara"}, }; static UniverseMap map = new UniverseMap(basicMap, planets); private static Map<String, Pair<String, BooleanSupplier>> getMenuItems() { menuItems = new HashMap<>(); menuItems.put("1", Pair.of("1. Start a new adventure", () -> { startNewAdventure(); return false; })); menuItems.put("2", Pair.of("2. Resume adventure", () -> { System.out.println("\nLoading adventure..."); Screen.clearScreen(1); loadAdventure(); return false; })); menuItems.put("3", Pair.of("3. Exit", () -> { System.out.println("\nExiting game..."); return true; })); menuItems.put(Config.INVALID_OPTION, Pair.of("", () -> { System.out.println("\nInvalid option selected, select a valid option..\n"); return false; })); return menuItems; } private static void startNewAdventure() { Scanner input = new Scanner(System.in); System.out.println("\nStarting a new adventure..."); Screen.clearScreen(1); System.out.println("\nEnter your character's name:\n"); String characterName = input.nextLine(); Player player = new Player(characterName); System.out.println("\nLoading " + player.getName() + "'s Adventure...\n"); Screen.clearScreen(2); Adventure adventure = new Adventure(player, map); InGameMenu gameMenu = new InGameMenu(adventure); gameMenu.render(System.in); } public static void loadAdventure() { Adventure savedAdventure = Adventure.load(Config.SAVE_GAME_FILE); if (savedAdventure == null) { return; } InGameMenu gameMenu = new InGameMenu(savedAdventure); gameMenu.render(System.in); } public static void main(String[] args) { Map<String, Pair<String, BooleanSupplier>> menuItems = getMenuItems(); MenuInterface menuInterface = new MainMenu("The Legendary Giggle Adventure", menuItems); menuInterface.render(System.in); } }
38.473118
96
0.603689
be18aeaef2eaa843aa0095ed607dd514609b25c0
110
/** * Templates support for email message body. */ package eu.easyrpa.openframework.email.message.templates;
27.5
57
0.772727
1aa50ded7e41828eaaa8744778f651f1731ff92e
14,677
/** * 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.solr.update; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.TermDocs; import org.apache.lucene.index.Term; import org.apache.lucene.document.Document; import org.apache.lucene.search.Query; import java.util.HashSet; import java.util.concurrent.Future; import java.util.concurrent.ExecutionException; import java.io.IOException; import java.net.URL; import org.apache.solr.search.SolrIndexSearcher; import org.apache.solr.search.QueryParsing; import org.apache.solr.update.UpdateHandler; import org.apache.solr.common.SolrException; import org.apache.solr.common.util.NamedList; import org.apache.solr.common.util.SimpleOrderedMap; import org.apache.solr.core.SolrCore; import org.apache.solr.handler.NonUpdateHandler; /** * <code>DirectUpdateHandler</code> implements an UpdateHandler where documents are added * directly to the main lucene index as opposed to adding to a separate smaller index. * For this reason, not all combinations to/from pending and committed are supported. * * @version $Id: DirectUpdateHandler.java 1065312 2011-01-30 16:08:25Z rmuir $ * @since solr 0.9 * * @deprecated Use {@link DirectUpdateHandler2} instead. This is only kept around for back-compatibility (way back). */ @Deprecated public class DirectUpdateHandler extends NonUpdateHandler { public DirectUpdateHandler(SolrCore core) throws IOException { super(core); } // // // the set of ids in the "pending set" (those docs that have been added, but // // that are not yet visible. // final HashSet<String> pset; // IndexWriter writer; // SolrIndexSearcher searcher; // int numAdds=0; // number of docs added to the pending set // int numPending=0; // number of docs currently in this pending set // int numDeleted=0; // number of docs deleted or // // // public DirectUpdateHandler(SolrCore core) throws IOException { // super(core); // pset = new HashSet<String>(256); // } // // // protected void openWriter() throws IOException { // if (writer==null) { // writer = createMainIndexWriter("DirectUpdateHandler", false); // } // } // // protected void closeWriter() throws IOException { // try { // if (writer!=null) writer.close(); // } finally { // // TODO: if an exception causes the writelock to not be // // released, we could delete it here. // writer=null; // } // } // // protected void openSearcher() throws IOException { // if (searcher==null) { // searcher = core.newSearcherForUpdate("DirectUpdateHandler",UpdateHandler.UPDATEPARTION); // } // } // // protected void closeSearcher() throws IOException { // try { // if (searcher!=null) searcher.close(); // } finally { // // TODO: if an exception causes the writelock to not be // // released, we could delete it here. // searcher=null; // } // } // // protected void doAdd(Document doc) throws IOException { // closeSearcher(); openWriter(); // writer.addDocument(doc); // } // // protected boolean existsInIndex(String indexedId) throws IOException { // if (idField == null) throw new SolrException( SolrException.ErrorCode.BAD_REQUEST,"Operation requires schema to have a unique key field"); // // closeWriter(); // openSearcher(); // IndexReader ir = searcher.getReader(); // TermDocs tdocs = null; // boolean exists=false; // try { // tdocs = ir.termDocs(idTerm(indexedId)); // if (tdocs.next()) exists=true; // } finally { // try { if (tdocs != null) tdocs.close(); } catch (Exception e) {} // } // return exists; // } // // // protected int deleteInIndex(String indexedId) throws IOException { // if (idField == null) throw new SolrException( SolrException.ErrorCode.BAD_REQUEST,"Operation requires schema to have a unique key field"); // // closeWriter(); openSearcher(); // IndexReader ir = searcher.getReader(); // TermDocs tdocs = null; // int num=0; // try { // Term term = new Term(idField.getName(), indexedId); // num = ir.deleteDocuments(term); // if (core.log.isTraceEnabled()) { // core.log.trace( core.getLogId()+"deleted " + num + " docs matching id " + idFieldType.indexedToReadable(indexedId)); // } // } finally { // try { if (tdocs != null) tdocs.close(); } catch (Exception e) {} // } // return num; // } // // protected void overwrite(String indexedId, Document doc) throws IOException { // if (indexedId ==null) indexedId =getIndexedId(doc); // deleteInIndex(indexedId); // doAdd(doc); // } // // /************** Direct update handler - pseudo code *********** // def add(doc, id, allowDups, overwritePending, overwriteCommitted): // if not overwritePending and not overwriteCommitted: // #special case... no need to check pending set, and we don't keep // #any state around about this addition // if allowDups: // committed[id]=doc #100 // return // else: // #if no dups allowed, we must check the *current* index (pending and committed) // if not committed[id]: committed[id]=doc #000 // return // #001 (searchd addConditionally) // if not allowDups and not overwritePending and pending[id]: return // del committed[id] #delete from pending and committed 111 011 // committed[id]=doc // pending[id]=True // ****************************************************************/ // // // could return the number of docs deleted, but is that always possible to know??? // @Override // public void delete(DeleteUpdateCommand cmd) throws IOException { // if (!cmd.fromPending && !cmd.fromCommitted) // throw new SolrException( SolrException.ErrorCode.BAD_REQUEST,"meaningless command: " + cmd); // if (!cmd.fromPending || !cmd.fromCommitted) // throw new SolrException( SolrException.ErrorCode.BAD_REQUEST,"operation not supported" + cmd); // String indexedId = idFieldType.toInternal(cmd.id); // synchronized(this) { // deleteInIndex(indexedId); // pset.remove(indexedId); // } // } // // // TODO - return number of docs deleted? // // Depending on implementation, we may not be able to immediately determine num... // @Override // public void deleteByQuery(DeleteUpdateCommand cmd) throws IOException { // if (!cmd.fromPending && !cmd.fromCommitted) // throw new SolrException( SolrException.ErrorCode.BAD_REQUEST,"meaningless command: " + cmd); // if (!cmd.fromPending || !cmd.fromCommitted) // throw new SolrException( SolrException.ErrorCode.BAD_REQUEST,"operation not supported: " + cmd); // // Query q = QueryParsing.parseQuery(cmd.query, schema); // // int totDeleted = 0; // synchronized(this) { // closeWriter(); openSearcher(); // // // if we want to count the number of docs that were deleted, then // // we need a new instance of the DeleteHitCollector // final DeleteHitCollector deleter = new DeleteHitCollector(searcher); // searcher.search(q, null, deleter); // totDeleted = deleter.deleted; // } // // if (core.log.isDebugEnabled()) { // core.log.debug(core.getLogId()+"docs deleted:" + totDeleted); // } // // } // // /**************** old hit collector... new one is in base class // // final DeleteHitCollector deleter = new DeleteHitCollector(); // class DeleteHitCollector extends HitCollector { // public int deleted=0; // public void collect(int doc, float score) { // try { // searcher.getReader().delete(doc); // deleted++; // } catch (IOException e) { // try { closeSearcher(); } catch (Exception ee) { SolrException.log(SolrCore.log,ee); } // SolrException.log(SolrCore.log,e); // throw new SolrException( SolrException.StatusCode.SERVER_ERROR,"Error deleting doc# "+doc,e); // } // } // } // ***************************/ // // @Override // public int mergeIndexes(MergeIndexesCommand cmd) throws IOException { // throw new SolrException( // SolrException.ErrorCode.BAD_REQUEST, // "DirectUpdateHandler doesn't support mergeIndexes. Use DirectUpdateHandler2 instead."); // } // // @Override // public void commit(CommitUpdateCommand cmd) throws IOException { // Future[] waitSearcher = null; // if (cmd.waitSearcher) { // waitSearcher = new Future[1]; // } // // synchronized (this) { // pset.clear(); // closeSearcher(); // flush any deletes // if (cmd.optimize || cmd.expungeDeletes) { // openWriter(); // writer needs to be open to optimize // if(cmd.optimize) writer.optimize(cmd.maxOptimizeSegments); // if(cmd.expungeDeletes) writer.expungeDeletes(cmd.expungeDeletes); // } // closeWriter(); // // callPostCommitCallbacks(); // if (cmd.optimize) { // callPostOptimizeCallbacks(); // } // // core.getSearcher(UpdateHandler.UPDATEPARTION,true,true); // } // // if (waitSearcher!=null && waitSearcher[0] != null) { // try { // waitSearcher[0].get(); // } catch (InterruptedException e) { // SolrException.log(log,e); // } catch (ExecutionException e) { // SolrException.log(log,e); // } // } // // return; // } // // /** // * @since Solr 1.4 // */ // @Override // public void rollback(RollbackUpdateCommand cmd) throws IOException { // throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, // "DirectUpdateHandler doesn't support rollback. Use DirectUpdateHandler2 instead."); // } // // // /////////////////////////////////////////////////////////////////// // /////////////////// helper method for each add type /////////////// // /////////////////////////////////////////////////////////////////// // // protected int addNoOverwriteNoDups(AddUpdateCommand cmd) throws IOException { // if (cmd.indexedId ==null) { // cmd.indexedId =getIndexedId(cmd.doc); // } // synchronized (this) { // if (existsInIndex(cmd.indexedId)) return 0; // doAdd(cmd.doc); // } // return 1; // } // // protected int addConditionally(AddUpdateCommand cmd) throws IOException { // if (cmd.indexedId ==null) { // cmd.indexedId =getIndexedId(cmd.doc); // } // synchronized(this) { // if (pset.contains(cmd.indexedId)) return 0; // // since case 001 is currently the only case to use pset, only add // // to it in that instance. // pset.add(cmd.indexedId); // overwrite(cmd.indexedId,cmd.doc); // return 1; // } // } // // // // overwrite both pending and committed // protected synchronized int overwriteBoth(AddUpdateCommand cmd) throws IOException { // overwrite(cmd.indexedId, cmd.doc); // return 1; // } // // // // add without checking // protected synchronized int allowDups(AddUpdateCommand cmd) throws IOException { // doAdd(cmd.doc); // return 1; // } // // // @Override // public int addDoc(AddUpdateCommand cmd) throws IOException { // // // if there is no ID field, use allowDups // if( idField == null ) { // cmd.allowDups = true; // cmd.overwriteCommitted = false; // cmd.overwritePending = false; // } // // if (!cmd.allowDups && !cmd.overwritePending && !cmd.overwriteCommitted) { // return addNoOverwriteNoDups(cmd); // } else if (!cmd.allowDups && !cmd.overwritePending && cmd.overwriteCommitted) { // return addConditionally(cmd); // } else if (!cmd.allowDups && cmd.overwritePending && !cmd.overwriteCommitted) { // // return overwriteBoth(cmd); // throw new SolrException( SolrException.ErrorCode.BAD_REQUEST,"unsupported param combo:" + cmd); // } else if (!cmd.allowDups && cmd.overwritePending && cmd.overwriteCommitted) { // return overwriteBoth(cmd); // } else if (cmd.allowDups && !cmd.overwritePending && !cmd.overwriteCommitted) { // return allowDups(cmd); // } else if (cmd.allowDups && !cmd.overwritePending && cmd.overwriteCommitted) { // // return overwriteBoth(cmd); // throw new SolrException( SolrException.ErrorCode.BAD_REQUEST,"unsupported param combo:" + cmd); // } else if (cmd.allowDups && cmd.overwritePending && !cmd.overwriteCommitted) { // // return overwriteBoth(cmd); // throw new SolrException( SolrException.ErrorCode.BAD_REQUEST,"unsupported param combo:" + cmd); // } else if (cmd.allowDups && cmd.overwritePending && cmd.overwriteCommitted) { // return overwriteBoth(cmd); // } // throw new SolrException( SolrException.ErrorCode.BAD_REQUEST,"unsupported param combo:" + cmd); // } // // @Override // public void close() throws IOException { // synchronized(this) { // closeSearcher(); // closeWriter(); // } // } // // // // ///////////////////////////////////////////////////////////////////// // // SolrInfoMBean stuff: Statistics and Module Info // ///////////////////////////////////////////////////////////////////// // // public String getName() { // return DirectUpdateHandler.class.getName(); // } // // public String getVersion() { // return SolrCore.version; // } // // public String getDescription() { // return "Update handler that directly changes the on-disk main lucene index"; // } // // public Category getCategory() { // return Category.CORE; // } // // public String getSourceId() { // return "$Id: DirectUpdateHandler.java 1065312 2011-01-30 16:08:25Z rmuir $"; // } // // public String getSource() { // return "$URL: https://svn.apache.org/repos/asf/lucene/dev/branches/lucene_solr_3_5/solr/core/src/java/org/apache/solr/update/DirectUpdateHandler.java $"; // } // // public URL[] getDocs() { // return null; // } // // public NamedList getStatistics() { // NamedList lst = new SimpleOrderedMap(); // return lst; // } // }
35.11244
159
0.638823
d40111c751eba7433fbda0d20f03ccfbbf75ea87
523
package sqlru.jobparser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Writer of new offers to the single log file. */ public class LogWriter { /** * The job offers logger. */ private final Logger logger = LoggerFactory.getLogger("ExternalAppLogger"); /** * Writes specified offers to log. * * @param offers - offers. */ public void write(Offers offers) { for (Offer offer : offers) { logger.info(offer.toString()); } } }
19.37037
79
0.604207
8d0f4576e65a07d4a36a57351ebfaa7a97c1204c
7,237
/* * Copyright 2015-2016 Hewlett-Packard Development Company, L.P. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. */ package com.hp.autonomy.hod.client.api.authentication; import com.hp.autonomy.hod.client.config.HodServiceConfig; import com.hp.autonomy.hod.client.util.Request; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.message.BasicNameValuePair; import org.joda.time.DateTime; import org.junit.Before; import org.junit.Test; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.hamcrest.core.Is.is; public class AuthenticationServiceImplTest { private static final String ENDPOINT = "https://api.testdomain.com"; private static final String COMBINED_PATH = "/2/authenticate/combined"; private static final List<String> ALLOWED_ORIGINS = Arrays.asList("https://example.idolondemand.com", "http://example2.idolondemna.com"); private static final AuthenticationToken<EntityType.Unbound, TokenType.HmacSha1> TOKEN = new AuthenticationToken<>( EntityType.Unbound.INSTANCE, TokenType.HmacSha1.INSTANCE, new DateTime(123), "my-token-id", "my-token-secret", new DateTime(456) ); private static final String DOMAIN = "MY-APPLICATION-DOMAIN"; private static final String APPLICATION = "MY-APPLICATION-NAME"; private static final String USER_STORE_DOMAIN = "MY-STORE-DOMAIN"; private static final String USER_STORE_NAME = "MY-STORE-NAME"; private AuthenticationService service; @Before public void initialise() { final HodServiceConfig<?, ?> config = new HodServiceConfig.Builder<>(ENDPOINT).build(); service = new AuthenticationServiceImpl(config); } @Test public void generatesGetCombinedSignedRequest() throws URISyntaxException { final SignedRequest request = service.combinedGetRequest(ALLOWED_ORIGINS, TOKEN); assertThat(request.getVerb(), is(Request.Verb.GET)); final List<NameValuePair> expectedParameters = Arrays.<NameValuePair>asList( new BasicNameValuePair("allowed_origins", ALLOWED_ORIGINS.get(0)), new BasicNameValuePair("allowed_origins", ALLOWED_ORIGINS.get(1)) ); checkCombinedUrl(request, expectedParameters); assertThat(request.getBody(), is(nullValue())); assertThat(request.getToken(), is("UNB:HMAC_SHA1:my-token-id::iIccQELdwLXw9zypF86bwXKbaNQ")); } @Test public void generatesPatchCombinedSignedRequest() throws URISyntaxException { final SignedRequest request = service.combinedPatchRequest(ALLOWED_ORIGINS, TOKEN); assertThat(request.getVerb(), is(Request.Verb.PATCH)); final List<NameValuePair> expectedParameters = Arrays.<NameValuePair>asList( new BasicNameValuePair("allowed_origins", ALLOWED_ORIGINS.get(0)), new BasicNameValuePair("allowed_origins", ALLOWED_ORIGINS.get(1)) ); checkCombinedUrl(request, expectedParameters); assertThat(request.getBody(), is(nullValue())); assertThat(request.getToken(), is("UNB:HMAC_SHA1:my-token-id::p8OjRSGH3MSCTuoYQ_FVYg7TE2g")); } @Test public void generatesPatchCombinedSignedRequestWithRedirectUrl() throws URISyntaxException { final SignedRequest request = service.combinedPatchRequest(ALLOWED_ORIGINS, "http://my-domain/my-page", TOKEN); assertThat(request.getVerb(), is(Request.Verb.PATCH)); final List<NameValuePair> expectedParameters = Arrays.<NameValuePair>asList( new BasicNameValuePair("allowed_origins", ALLOWED_ORIGINS.get(0)), new BasicNameValuePair("allowed_origins", ALLOWED_ORIGINS.get(1)), new BasicNameValuePair("redirect_url", "http://my-domain/my-page") ); checkCombinedUrl(request, expectedParameters); assertThat(request.getBody(), is(nullValue())); assertThat(request.getToken(), is("UNB:HMAC_SHA1:my-token-id::1AOt8y6LgWVSwyQmeCpp2Qfwll0")); } @Test public void generatesCombinedSignedRequest() throws URISyntaxException { final SignedRequest request = service.combinedRequest(ALLOWED_ORIGINS, TOKEN, DOMAIN, APPLICATION, USER_STORE_DOMAIN, USER_STORE_NAME, TokenType.Simple.INSTANCE); assertThat(request.getVerb(), is(Request.Verb.POST)); final List<NameValuePair> expectedParameters = Arrays.<NameValuePair>asList( new BasicNameValuePair("allowed_origins", ALLOWED_ORIGINS.get(0)), new BasicNameValuePair("allowed_origins", ALLOWED_ORIGINS.get(1)) ); checkCombinedUrl(request, expectedParameters); final List<NameValuePair> pairs = URLEncodedUtils.parse(request.getBody(), StandardCharsets.UTF_8); checkParameterPair(pairs, "domain", DOMAIN); checkParameterPair(pairs, "application", APPLICATION); checkParameterPair(pairs, "userstore_domain", USER_STORE_DOMAIN); checkParameterPair(pairs, "userstore_name", USER_STORE_NAME); checkParameterPair(pairs, "token_type", TokenType.Simple.INSTANCE.getParameter()); assertThat(request.getToken(), is("UNB:HMAC_SHA1:my-token-id:wJkMexQxgEhW13IAeN6i6A:R9XBlyBildIbslAWyxDwQ5O-8WQ")); } @Test public void generatesANonce() { final SignedRequest request = service.combinedRequest(ALLOWED_ORIGINS, TOKEN, DOMAIN, APPLICATION, USER_STORE_DOMAIN, USER_STORE_NAME, TokenType.Simple.INSTANCE, true); final List<NameValuePair> bodyPairs = URLEncodedUtils.parse(request.getBody(), StandardCharsets.UTF_8); final NameValuePair noncePair = getParameterPair(bodyPairs, "nonce"); assertThat(noncePair, notNullValue()); final String nonce = noncePair.getValue(); assertThat(nonce, notNullValue()); } private void checkCombinedUrl(final SignedRequest request, final List<NameValuePair> expectedParameters) throws URISyntaxException { final URI uri = new URI(request.getUrl()); assertThat(uri.getScheme() + "://" + uri.getHost(), is(ENDPOINT)); assertThat(uri.getPath(), is(COMBINED_PATH)); final List<NameValuePair> pairs = URLEncodedUtils.parse(uri, "UTF-8"); assertThat(pairs, containsInAnyOrder(expectedParameters.toArray())); } private void checkParameterPair(final List<NameValuePair> pairs, final String name, final String value) { final NameValuePair expectedPair = getParameterPair(pairs, name); assertThat(expectedPair, is(notNullValue())); if (expectedPair != null) { assertThat(expectedPair.getValue(), is(value)); } } private NameValuePair getParameterPair(final List<NameValuePair> pairs, final String name) { for (final NameValuePair pair : pairs) { if (pair.getName().equals(name)) { return pair; } } return null; } }
42.822485
176
0.712588
48bcd3fd97bca87437d26c2d165ab418ebe60171
472
package cn.test11.cc; import java.util.Scanner; public class J1166 { public static void main(String[] args) { Scanner cn = new Scanner(System.in); int[] n = new int[10001]; int i =0; while(cn.hasNext()){ n[i] =cn.nextInt(); i++; } if(isSorted(n,i)) System.out.println("YES"); else System.out.println("NO"); } private static boolean isSorted(int[] n,int i) { for(int j =0 ;j<i-1;j++){ if(n[j]>n[j+1]) return false; } return true; } }
18.153846
49
0.605932
3e8f97ab330bae1029efebf941bbf55ef572b8f6
4,708
/****************************************************************** * File: TestDatasetMonitor.java * Created by: Dave Reynolds * Created on: 27 Apr 2014 * * (c) Copyright 2014, Epimorphics Limited * *****************************************************************/ package com.epimorphics.appbase.monitor; import static org.junit.Assert.*; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Files; import java.util.ArrayList; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.epimorphics.appbase.core.App; import com.epimorphics.appbase.data.SparqlSource; import com.epimorphics.appbase.data.TestUnionSource; import com.epimorphics.appbase.data.impl.UnionDatasetSparqlSource; import com.epimorphics.appbase.monitor.DatasetMonitor.MonitoredGraph; import com.epimorphics.util.FileUtil; import com.epimorphics.util.TestUtil; import org.apache.jena.query.ResultSet; import org.apache.jena.util.FileUtils; public class TestDatasetMonitor { protected App app; protected DatasetMonitor monitor; protected CachingDatasetMonitor cmonitor; protected SparqlSource source; protected File testDir; private static final int MONITOR_CHECK_DELAY = 15; private static final int NTRIES = 100; @Before public void setup() throws IOException { testDir = Files.createTempDirectory("testmonitor").toFile(); app = new App("TestMonitor"); source = new UnionDatasetSparqlSource(); monitor = new DatasetMonitor(); monitor.setDirectory(testDir.getPath()); monitor.setFileSampleLength(1000); monitor.setSparqlSource(source); app.addComponent("monitor", monitor); cmonitor = new CachingDatasetMonitor(); cmonitor.setDirectory(testDir.getPath()); cmonitor.setFileSampleLength(1000); cmonitor.setSparqlSource(source); app.addComponent("cmonitor", cmonitor); app.startup(); } @After public void cleanUp() { FileUtil.deleteDirectory(testDir); } @Test public void testMonitor() throws IOException, InterruptedException { monitor.setScanInterval(5); cmonitor.setScanInterval(5); assertTrue( monitor.getEntries().isEmpty() ); addFile("graph1", "g1.ttl"); waitFor(monitor, "file:g1.ttl", true); TestUtil.testArray(TestUnionSource.checkGraphs(source), new String[]{"graph1"}); addFile("graph2", "subdir/g2.ttl"); waitFor(monitor, "file:subdir/g2.ttl", true); TestUtil.testArray(TestUnionSource.checkGraphs(source), new String[]{"graph1", "graph2"}); TestUtil.testArray(checkGraphNames(source), new String[]{"file:g1.ttl", "file:subdir/g2.ttl"}); waitFor(cmonitor, "file:subdir/g2.ttl", true); assertEquals(2, cmonitor.getCachedUnion().size()); removeFile("g1.ttl"); waitFor(monitor, "file:g1.ttl", false); TestUtil.testArray(TestUnionSource.checkGraphs(source), new String[]{"graph2"}); TestUtil.testArray(checkGraphNames(source), new String[]{"file:subdir/g2.ttl"}); waitFor(cmonitor, "file:g1.ttl", false); assertEquals(1, cmonitor.getCachedUnion().size()); } protected void waitFor(DatasetMonitor dsmon, String graphname, boolean present) throws InterruptedException { for (int t = 0; t < NTRIES; t++) { Thread.sleep(MONITOR_CHECK_DELAY); MonitoredGraph m = dsmon.get(graphname); if ( (present && m != null) || (!present && m == null) ) { return; } } assertTrue("Failed to detected " + (present ? "addition" : "removal") + " of " + graphname, false); } protected void addFile(String marker, String filename) throws IOException { File file = new File(testDir, filename); FileUtil.ensureDir( file.getParent() ); FileOutputStream out = new FileOutputStream(file); TestUnionSource.createGraph(marker).write(out, FileUtils.langTurtle); out.close(); } protected void removeFile(String filename) throws IOException { File file = new File(testDir, filename); file.delete(); } public static List<String> checkGraphNames(SparqlSource source) { ResultSet rs = source.select("SELECT ?g WHERE {GRAPH ?g {}}"); List<String> results = new ArrayList<>(); while (rs.hasNext()) { results.add( rs.next().getResource("g").getURI() ); } return results; } }
35.398496
113
0.635302
634481b4917bb26029198188939957c67634d0c3
1,457
package org.demo.learn.util.leetcode.sort; import java.util.Arrays; /** * @author luwt * @date 2021/5/6. * 快速排序 */ public class QuickSort { public static void main(String[] args) { int[] array = {1, 3, 2, 5, 6, 4}; sort(array, 0, array.length - 1); System.out.println(Arrays.toString(array)); } // 快排 public static void sort(int[] array, int start, int end) { if (start >= end) { return; } int left = start, right = end; boolean direction = true; int key = array[start]; L: while (left < right) { if (direction) { for (int i = right; i > left; i --) { if (array[i] < key) { array[left ++] = array[i]; right = i; direction = false; continue L; } } right = left; } else { for (int i = left; i < right; i ++) { if (array[i] > key) { array[right --] = array[i]; left = i; direction = true; continue L; } } left = right; } } array[left] = key; sort(array, start, left - 1); sort(array, left + 1, end); } }
26.490909
62
0.382292
23e6379808a25fca8b1c2e1b58d7e5b4f4ac945d
8,096
package master.logica.servicios; import accesoDatos.AccesoDatos; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import master.logica.entidades.Modulo; import master.logica.entidades.Rol; public class ServiciosRoles { public static Rol obtenerRolDadoCodigo(int codigo) throws Exception { Rol rol = null; AccesoDatos accesoDatos; String sql; PreparedStatement prstm; ResultSet resultSet; try { accesoDatos = new AccesoDatos(); sql = "select * from master.f_select_rol_dado_codigo(?)"; prstm = accesoDatos.creaPreparedSmt(sql); prstm.setInt(1, codigo); resultSet = accesoDatos.ejecutaPrepared(prstm); while (resultSet.next()) { rol = new Rol(); rol.setIdModulo(new Modulo()); rol.getIdModulo().setIdModulo(resultSet.getInt("int_id_modulo")); rol.setIdRol(resultSet.getInt("int_id_rol")); rol.setNombre(resultSet.getString("chv_nombre")); rol.setDescripcion(resultSet.getString("chv_descripcion")); } accesoDatos.desconectar(); } catch (Exception e) { throw e; } return rol; } public static ArrayList<Rol> obtenerRolesDadoEstado(String estado) throws Exception { ArrayList<Rol> lst = new ArrayList<Rol>(); Rol rol; AccesoDatos accesoDatos; String sql; PreparedStatement prstm; ResultSet resultSet; try { accesoDatos = new AccesoDatos(); sql = "select * from master.f_seleccionar_roles_dado_estado(?)"; prstm = accesoDatos.creaPreparedSmt(sql); prstm.setString(1, estado); resultSet = accesoDatos.ejecutaPrepared(prstm); while (resultSet.next()) { rol = new Rol(); rol.setIdModulo(new Modulo()); rol.setIdModulo(ServiciosModulo.obtenerModuloDadoCodigo(resultSet.getInt("int_id_modulo"))); rol.setIdRol(resultSet.getInt("int_id_rol")); rol.setDescripcion(resultSet.getString("chv_descripcion")); rol.setNombre(resultSet.getString("chv_nombre")); rol.setEstadoLogico(resultSet.getString("ch_estado_logico")); rol.setFechaRegistro(resultSet.getDate("ts_fecha_registro")); rol.setFechaActualizacion(resultSet.getDate("ts_fecha_actualizacion")); rol.setFechaBaja(resultSet.getDate("ts_fecha_baja")); rol.setIcono(resultSet.getString("chv_icono")); lst.add(rol); } } catch (Exception e) { throw e; } return lst; } public static Rol obtenerRolDadoCodigoMenuCero(int codigo) throws Exception { Rol rol = null; AccesoDatos accesoDatos; String sql; PreparedStatement prstm; ResultSet resultSet; try { accesoDatos = new AccesoDatos(); sql = "select * from master.f_selecionar_rol__dado_menu_modulo(?)"; prstm = accesoDatos.creaPreparedSmt(sql); prstm.setInt(1, codigo); resultSet = accesoDatos.ejecutaPrepared(prstm); while (resultSet.next()) { rol = new Rol(); rol.setIdModulo(new Modulo()); rol.setIdModulo(ServiciosModulo.obtenerModuloDadoCodigo(resultSet.getInt("int_id_modulo"))); rol.setIdRol(resultSet.getInt("int_id_rol")); rol.setDescripcion(resultSet.getString("chv_descripcion")); rol.setNombre(resultSet.getString("chv_nombre")); rol.setEstadoLogico(resultSet.getString("ch_estado_logico")); rol.setFechaRegistro(resultSet.getDate("ts_fecha_registro")); rol.setFechaActualizacion(resultSet.getDate("ts_fecha_actualizacion")); rol.setFechaBaja(resultSet.getDate("ts_fecha_baja")); rol.setIcono(resultSet.getString("chv_icono")); } accesoDatos.desconectar(); } catch (Exception e) { throw e; } return rol; } public static String registrarRol(Rol rol) throws Exception { String respuesta; AccesoDatos accesoDatos; String sql; PreparedStatement prstm; ResultSet resultSet; try { accesoDatos = new AccesoDatos(); sql = "select * from master.f_insertar_rol(?,?,?,?)"; prstm = accesoDatos.creaPreparedSmt(sql); prstm.setString(1, rol.getDescripcion()); prstm.setString(2, rol.getNombre()); prstm.setInt(3, rol.getIdModulo().getIdModulo()); prstm.setInt(4,rol.getSessionUsuario().getIdPersona()); resultSet = accesoDatos.ejecutaPrepared(prstm); if (resultSet.next()) { respuesta = resultSet.getString(1); return respuesta; } else { return null; } } catch (Exception e) { throw e; } } public static String actualizarRol(Rol rol) throws Exception { String respuesta; AccesoDatos accesoDatos; String sql; PreparedStatement prstm; ResultSet resultSet; try { accesoDatos = new AccesoDatos(); sql = "select * from master.f_actualizar_rol(?,?,?,?,?)"; prstm = accesoDatos.creaPreparedSmt(sql); prstm.setString(1, rol.getDescripcion()); prstm.setString(2, rol.getNombre()); prstm.setInt(3, rol.getIdModulo().getIdModulo()); prstm.setInt(4, rol.getIdRol()); prstm.setInt(5, rol.getSessionUsuario().getIdPersona()); resultSet = accesoDatos.ejecutaPrepared(prstm); if (resultSet.next()) { respuesta = resultSet.getString(1); return respuesta; } else { return null; } } catch (Exception e) { throw e; } } public static String elimianrRol(Rol rol) throws Exception { String respuesta; AccesoDatos accesoDatos; String sql; PreparedStatement prstm; ResultSet resultSet; try { accesoDatos = new AccesoDatos(); sql = "select * from master.f_eliminar_rol(?,?)"; prstm = accesoDatos.creaPreparedSmt(sql); prstm.setInt(1, rol.getIdRol()); prstm.setInt(2, rol.getSessionUsuario().getIdPersona()); resultSet = accesoDatos.ejecutaPrepared(prstm); if (resultSet.next()) { respuesta = resultSet.getString(1); return respuesta; } else { return null; } } catch (Exception e) { throw e; } } // actualizar imagen rol public static String actualizarIcono(Rol rol) throws Exception { String respuesta; AccesoDatos accesoDatos; String sql; PreparedStatement prstm; ResultSet resultSet; try { accesoDatos = new AccesoDatos(); sql = "select * from master.f_actualizar_imagen_rol(?,?)"; prstm = accesoDatos.creaPreparedSmt(sql); prstm.setInt(1, rol.getIdRol()); prstm.setString(2, rol.getIcono()); resultSet = accesoDatos.ejecutaPrepared(prstm); if (resultSet.next()) { respuesta = resultSet.getString(1); return respuesta; } else { return null; } } catch (Exception e) { throw e; } } }
38.736842
109
0.554348
ad4b275f499998413395526033bedb64e544e259
1,381
package org.apache.spark.sql.catalyst.analysis; /** * An inline table that has not been resolved yet. Once resolved, it is turned by the analyzer into * a {@link org.apache.spark.sql.catalyst.plans.logical.LocalRelation}. * <p> * param: names list of column names * param: rows expressions for the data */ public class UnresolvedInlineTable extends org.apache.spark.sql.catalyst.plans.logical.LeafNode implements scala.Product, scala.Serializable { static public abstract R apply (T1 v1, T2 v2) ; static public java.lang.String toString () { throw new RuntimeException(); } public scala.collection.Seq<java.lang.String> names () { throw new RuntimeException(); } public scala.collection.Seq<scala.collection.Seq<org.apache.spark.sql.catalyst.expressions.Expression>> rows () { throw new RuntimeException(); } // not preceding public UnresolvedInlineTable (scala.collection.Seq<java.lang.String> names, scala.collection.Seq<scala.collection.Seq<org.apache.spark.sql.catalyst.expressions.Expression>> rows) { throw new RuntimeException(); } // not preceding public boolean expressionsResolved () { throw new RuntimeException(); } // not preceding public boolean resolved () { throw new RuntimeException(); } public scala.collection.Seq<org.apache.spark.sql.catalyst.expressions.Attribute> output () { throw new RuntimeException(); } }
62.772727
217
0.751629
7b34c8b53844a7266e0130820b0adfe168ee58c6
584
package com.github.vincemann.ezcompare; import lombok.AllArgsConstructor; import org.checkerframework.checker.units.qual.C; @AllArgsConstructor public abstract class AbstractConfigModifier<M extends AbstractConfigModifier, C extends RapidEqualsBuilder.CompareConfig> { private C config; public M reflectUpToClass(Class<?> value) { config.reflectUpToClass = value; return (M) this; } public M fullDiff(boolean value) { config.minimalDiff = value; return (M) this; } protected C getConfig() { return config; } }
23.36
124
0.702055
2fd4ab65fe4f5678405e7c318d5de51ee11b83ae
33,068
/* * Copyright (c) 2010-2018. Axon Framework * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.axonframework.extensions.springcloud.commandhandling; import com.google.common.collect.ImmutableList; import org.axonframework.commandhandling.CommandMessage; import org.axonframework.commandhandling.GenericCommandMessage; import org.axonframework.commandhandling.distributed.*; import org.axonframework.commandhandling.distributed.commandfilter.AcceptAll; import org.axonframework.commandhandling.distributed.commandfilter.CommandNameFilter; import org.axonframework.serialization.xml.XStreamSerializer; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.cloud.client.discovery.event.HeartbeatEvent; import org.springframework.cloud.client.discovery.event.InstanceRegisteredEvent; import org.springframework.cloud.client.serviceregistry.Registration; import org.springframework.web.util.UriBuilder; import org.springframework.web.util.UriComponentsBuilder; import java.lang.reflect.Field; import java.net.URI; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.IntStream; import static java.util.Collections.singletonList; import static java.util.stream.Collectors.toList; import static org.axonframework.common.ReflectionUtils.getFieldValue; import static org.axonframework.common.ReflectionUtils.setFieldValue; import static org.junit.Assert.*; import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) public class SpringCloudCommandRouterTest { private static final String LOAD_FACTOR_KEY = "loadFactor"; private static final String SERIALIZED_COMMAND_FILTER_KEY = "serializedCommandFilter"; private static final String SERIALIZED_COMMAND_FILTER_CLASS_NAME_KEY = "serializedCommandFilterClassName"; private static final String CONTEXT_ROOT_KEY = "contextRoot"; private static final int LOAD_FACTOR = 1; private static final CommandMessage<Object> TEST_COMMAND = GenericCommandMessage.asCommandMessage("testCommand"); private static final String ROUTING_KEY = "routingKey"; private static final String SERVICE_INSTANCE_ID = "SERVICE_ID"; private static final URI SERVICE_INSTANCE_URI = URI.create("endpoint"); private static final CommandMessageFilter COMMAND_NAME_FILTER = AcceptAll.INSTANCE; private static final boolean LOCAL_MEMBER = true; private static final boolean REMOTE_MEMBER = false; private static final boolean REGISTERED = true; private static final boolean NOT_REGISTERED = false; private SpringCloudCommandRouter testSubject; @Mock private DiscoveryClient discoveryClient; @Mock private Registration localServiceInstance; @Mock private RoutingStrategy routingStrategy; private Field atomicConsistentHashField; private Field blackListedServiceInstancesField; private String serializedCommandFilterData; private String serializedCommandFilterClassName; private HashMap<String, String> serviceInstanceMetadata; @Mock private ConsistentHashChangeListener consistentHashChangeListener; @Before public void setUp() throws Exception { serializedCommandFilterData = XStreamSerializer.builder().build() .serialize(COMMAND_NAME_FILTER, String.class).getData(); serializedCommandFilterClassName = COMMAND_NAME_FILTER.getClass().getName(); String atomicConsistentHashFieldName = "atomicConsistentHash"; atomicConsistentHashField = SpringCloudCommandRouter.class.getDeclaredField(atomicConsistentHashFieldName); String blackListedServiceInstancesFieldName = "blackListedServiceInstances"; blackListedServiceInstancesField = SpringCloudCommandRouter.class.getDeclaredField( blackListedServiceInstancesFieldName); serviceInstanceMetadata = new HashMap<>(); when(localServiceInstance.getServiceId()).thenReturn(SERVICE_INSTANCE_ID); when(localServiceInstance.getUri()).thenReturn(SERVICE_INSTANCE_URI); when(localServiceInstance.getMetadata()).thenReturn(serviceInstanceMetadata); when(discoveryClient.getServices()).thenReturn(singletonList(SERVICE_INSTANCE_ID)); when(discoveryClient.getInstances(SERVICE_INSTANCE_ID)) .thenReturn(singletonList(localServiceInstance)); when(routingStrategy.getRoutingKey(any())).thenReturn(ROUTING_KEY); testSubject = SpringCloudCommandRouter.builder() .discoveryClient(discoveryClient) .localServiceInstance(localServiceInstance) .routingStrategy(routingStrategy) .serviceInstanceFilter(serviceInstance -> true) .consistentHashChangeListener(consistentHashChangeListener) .build(); } @Test public void testFindDestinationReturnsEmptyOptionalMemberForCommandMessage() { Optional<Member> result = testSubject.findDestination(TEST_COMMAND); assertFalse(result.isPresent()); verify(routingStrategy).getRoutingKey(TEST_COMMAND); } // reproduces issue #1 (https://github.com/AxonFramework/extension-springcloud/issues/1) @Test public void testPreRegistrationLocalMemberIgnoredWhenNotPresent() { testSubject.resetLocalMembership(null); } @Test public void testFindDestinationReturnsMemberForCommandMessage() { SimpleMember<URI> testMember = new SimpleMember<>( SERVICE_INSTANCE_ID + "[" + SERVICE_INSTANCE_URI + "]", SERVICE_INSTANCE_URI, false, null ); AtomicReference<ConsistentHash> testAtomicConsistentHash = new AtomicReference<>(new ConsistentHash().with(testMember, LOAD_FACTOR, commandMessage -> true)); setFieldValue(atomicConsistentHashField, testSubject, testAtomicConsistentHash); Optional<Member> resultOptional = testSubject.findDestination(TEST_COMMAND); assertTrue(resultOptional.isPresent()); Member resultMember = resultOptional.orElseThrow(IllegalStateException::new); assertMember(REMOTE_MEMBER, resultMember, NOT_REGISTERED); verify(routingStrategy).getRoutingKey(TEST_COMMAND); } @Test public void testUpdateMembershipUpdatesLocalServiceInstance() { CommandMessageFilter commandNameFilter = new CommandNameFilter(String.class.getName()); String commandFilterData = XStreamSerializer.builder().build() .serialize(commandNameFilter, String.class).getData(); testSubject.updateMembership(LOAD_FACTOR, commandNameFilter); assertEquals(Integer.toString(LOAD_FACTOR), serviceInstanceMetadata.get(LOAD_FACTOR_KEY)); assertEquals(commandFilterData, serviceInstanceMetadata.get(SERIALIZED_COMMAND_FILTER_KEY)); assertEquals(CommandNameFilter.class.getName(), serviceInstanceMetadata.get(SERIALIZED_COMMAND_FILTER_CLASS_NAME_KEY)); verify(consistentHashChangeListener).onConsistentHashChanged(argThat(item -> item.getMembers() .stream() .map(Member::name) .anyMatch(memberName -> memberName .contains( SERVICE_INSTANCE_ID)))); } @Test public void testUpdateMemberShipUpdatesConsistentHash() { testSubject.updateMembership(LOAD_FACTOR, COMMAND_NAME_FILTER); AtomicReference<ConsistentHash> resultAtomicConsistentHash = getFieldValue(atomicConsistentHashField, testSubject); Set<Member> resultMemberSet = resultAtomicConsistentHash.get().getMembers(); assertFalse(resultMemberSet.isEmpty()); assertMember(LOCAL_MEMBER, resultMemberSet.iterator().next(), NOT_REGISTERED); } @Test public void testResetLocalMemberUpdatesConsistentHashByReplacingLocalMember() { serviceInstanceMetadata.put(LOAD_FACTOR_KEY, Integer.toString(LOAD_FACTOR)); serviceInstanceMetadata.put(SERIALIZED_COMMAND_FILTER_KEY, serializedCommandFilterData); serviceInstanceMetadata.put(SERIALIZED_COMMAND_FILTER_CLASS_NAME_KEY, serializedCommandFilterClassName); testSubject.updateMembership(LOAD_FACTOR, COMMAND_NAME_FILTER); AtomicReference<ConsistentHash> resultAtomicConsistentHash = getFieldValue(atomicConsistentHashField, testSubject); Set<Member> resultMemberSet = resultAtomicConsistentHash.get().getMembers(); assertFalse(resultMemberSet.isEmpty()); assertMember(LOCAL_MEMBER, resultMemberSet.iterator().next(), NOT_REGISTERED); testSubject.resetLocalMembership(mock(InstanceRegisteredEvent.class)); resultAtomicConsistentHash = getFieldValue(atomicConsistentHashField, testSubject); resultMemberSet = resultAtomicConsistentHash.get().getMembers(); assertFalse(resultMemberSet.isEmpty()); assertMember(LOCAL_MEMBER, resultMemberSet.iterator().next(), REGISTERED); verify(discoveryClient).getServices(); verify(discoveryClient).getInstances(SERVICE_INSTANCE_ID); } @Test public void testUpdateMembershipsOnHeartbeatEventUpdatesConsistentHash() { // Start up command router testSubject.updateMembership(LOAD_FACTOR, COMMAND_NAME_FILTER); // Set command router has passed the start up phase testSubject.resetLocalMembership(mock(InstanceRegisteredEvent.class)); serviceInstanceMetadata.put(LOAD_FACTOR_KEY, Integer.toString(LOAD_FACTOR)); serviceInstanceMetadata.put(SERIALIZED_COMMAND_FILTER_KEY, serializedCommandFilterData); serviceInstanceMetadata.put(SERIALIZED_COMMAND_FILTER_CLASS_NAME_KEY, serializedCommandFilterClassName); testSubject.updateMemberships(mock(HeartbeatEvent.class)); AtomicReference<ConsistentHash> resultAtomicConsistentHash = getFieldValue(atomicConsistentHashField, testSubject); Set<Member> resultMemberSet = resultAtomicConsistentHash.get().getMembers(); assertFalse(resultMemberSet.isEmpty()); assertMember(LOCAL_MEMBER, resultMemberSet.iterator().next(), REGISTERED); verify(discoveryClient, times(2)).getServices(); verify(discoveryClient, times(2)).getInstances(SERVICE_INSTANCE_ID); } @Test public void testUpdateMembershipsAfterHeartbeatEventDoesNotOverwriteMembers() { serviceInstanceMetadata.put(LOAD_FACTOR_KEY, Integer.toString(LOAD_FACTOR)); serviceInstanceMetadata.put(SERIALIZED_COMMAND_FILTER_KEY, serializedCommandFilterData); serviceInstanceMetadata.put(SERIALIZED_COMMAND_FILTER_CLASS_NAME_KEY, serializedCommandFilterClassName); String remoteServiceId = SERVICE_INSTANCE_ID + "-1"; ServiceInstance remoteServiceInstance = mock(ServiceInstance.class); when(remoteServiceInstance.getMetadata()).thenReturn(serviceInstanceMetadata); when(remoteServiceInstance.getUri()).thenReturn(URI.create("remote")); when(remoteServiceInstance.getServiceId()).thenReturn(remoteServiceId); when(discoveryClient.getInstances(remoteServiceId)).thenReturn(ImmutableList.of(remoteServiceInstance)); when(discoveryClient.getServices()).thenReturn(ImmutableList.of(SERVICE_INSTANCE_ID, remoteServiceId)); testSubject.updateMemberships(mock(HeartbeatEvent.class)); AtomicReference<ConsistentHash> resultAtomicConsistentHash = getFieldValue(atomicConsistentHashField, testSubject); Set<Member> resultMemberSet = resultAtomicConsistentHash.get().getMembers(); assertEquals(2, resultMemberSet.size()); testSubject.updateMembership(LOAD_FACTOR, COMMAND_NAME_FILTER); AtomicReference<ConsistentHash> resultAtomicConsistentHashAfterLocalUpdate = getFieldValue(atomicConsistentHashField, testSubject); Set<Member> resultMemberSetAfterLocalUpdate = resultAtomicConsistentHashAfterLocalUpdate.get().getMembers(); assertEquals(2, resultMemberSetAfterLocalUpdate.size()); } @Test public void testUpdateMembershipsWithVanishedMemberOnHeartbeatEventRemovesMember() { // Start up command router testSubject.updateMembership(LOAD_FACTOR, COMMAND_NAME_FILTER); // Set router has passed the start up phase testSubject.resetLocalMembership(mock(InstanceRegisteredEvent.class)); // Update router memberships with local and remote service instance serviceInstanceMetadata.put(LOAD_FACTOR_KEY, Integer.toString(LOAD_FACTOR)); serviceInstanceMetadata.put(SERIALIZED_COMMAND_FILTER_KEY, serializedCommandFilterData); serviceInstanceMetadata.put(SERIALIZED_COMMAND_FILTER_CLASS_NAME_KEY, serializedCommandFilterClassName); String remoteServiceId = SERVICE_INSTANCE_ID + "-1"; ServiceInstance remoteServiceInstance = mock(ServiceInstance.class); when(remoteServiceInstance.getMetadata()).thenReturn(serviceInstanceMetadata); when(remoteServiceInstance.getUri()).thenReturn(URI.create("remote")); when(remoteServiceInstance.getServiceId()).thenReturn(remoteServiceId); when(discoveryClient.getInstances(remoteServiceId)).thenReturn(ImmutableList.of(remoteServiceInstance)); when(discoveryClient.getServices()).thenReturn(ImmutableList.of(SERVICE_INSTANCE_ID, remoteServiceId)); testSubject.updateMemberships(mock(HeartbeatEvent.class)); AtomicReference<ConsistentHash> resultAtomicConsistentHash = getFieldValue(atomicConsistentHashField, testSubject); Set<Member> resultMemberSet = resultAtomicConsistentHash.get().getMembers(); assertEquals(2, resultMemberSet.size()); // Evict remote service instance from discovery client and update router memberships when(discoveryClient.getServices()).thenReturn(ImmutableList.of(SERVICE_INSTANCE_ID)); testSubject.updateMemberships(mock(HeartbeatEvent.class)); AtomicReference<ConsistentHash> resultAtomicConsistentHashAfterVanish = getFieldValue(atomicConsistentHashField, testSubject); Set<Member> resultMemberSetAfterVanish = resultAtomicConsistentHashAfterVanish.get().getMembers(); assertEquals(1, resultMemberSetAfterVanish.size()); assertMember(LOCAL_MEMBER, resultMemberSetAfterVanish.iterator().next(), REGISTERED); } @Test public void testUpdateMembershipsOnHeartbeatEventFiltersInstancesWithoutCommandRouterSpecificMetadata() { int expectedMemberSetSize = 1; String expectedServiceInstanceId = "nonCommandRouterServiceInstance"; serviceInstanceMetadata.put(LOAD_FACTOR_KEY, Integer.toString(LOAD_FACTOR)); serviceInstanceMetadata.put(SERIALIZED_COMMAND_FILTER_KEY, serializedCommandFilterData); serviceInstanceMetadata.put(SERIALIZED_COMMAND_FILTER_CLASS_NAME_KEY, serializedCommandFilterClassName); ServiceInstance nonCommandRouterServiceInstance = mock(ServiceInstance.class); when(nonCommandRouterServiceInstance.getServiceId()).thenReturn(expectedServiceInstanceId); when(discoveryClient.getServices()) .thenReturn(ImmutableList.of(SERVICE_INSTANCE_ID, expectedServiceInstanceId)); when(discoveryClient.getInstances(SERVICE_INSTANCE_ID)) .thenReturn(ImmutableList.of(localServiceInstance, nonCommandRouterServiceInstance)); testSubject.updateMemberships(mock(HeartbeatEvent.class)); AtomicReference<ConsistentHash> resultAtomicConsistentHash = getFieldValue(atomicConsistentHashField, testSubject); Set<Member> resultMemberSet = resultAtomicConsistentHash.get().getMembers(); assertEquals(expectedMemberSetSize, resultMemberSet.size()); verify(discoveryClient).getServices(); verify(discoveryClient).getInstances(SERVICE_INSTANCE_ID); verify(discoveryClient).getInstances(expectedServiceInstanceId); } @Test public void testUpdateMembershipsOnHeartbeatEventBlackListsNonAxonInstances() throws Exception { SpringCloudCommandRouter testSubject = SpringCloudCommandRouter.builder() .discoveryClient(discoveryClient) .localServiceInstance(localServiceInstance) .routingStrategy(routingStrategy) .serviceInstanceFilter(serviceInstance -> true) .build(); String blackListedInstancesFieldName = "blackListedServiceInstances"; Field blackListedInstancesField = SpringCloudCommandRouter.class.getDeclaredField(blackListedInstancesFieldName); int expectedMemberSetSize = 1; String nonAxonServiceInstanceId = "nonAxonInstance"; serviceInstanceMetadata.put(LOAD_FACTOR_KEY, Integer.toString(LOAD_FACTOR)); serviceInstanceMetadata.put(SERIALIZED_COMMAND_FILTER_KEY, serializedCommandFilterData); serviceInstanceMetadata.put(SERIALIZED_COMMAND_FILTER_CLASS_NAME_KEY, serializedCommandFilterClassName); ServiceInstance nonAxonInstance = mock(ServiceInstance.class); when(nonAxonInstance.getServiceId()).thenReturn(nonAxonServiceInstanceId); when(discoveryClient.getServices()).thenReturn(ImmutableList.of(SERVICE_INSTANCE_ID, nonAxonServiceInstanceId)); when(discoveryClient.getInstances(nonAxonServiceInstanceId)).thenReturn(ImmutableList.of(nonAxonInstance)); testSubject.updateMemberships(mock(HeartbeatEvent.class)); AtomicReference<ConsistentHash> resultAtomicConsistentHash = getFieldValue(atomicConsistentHashField, testSubject); Set<Member> resultMemberSet = resultAtomicConsistentHash.get().getMembers(); assertEquals(expectedMemberSetSize, resultMemberSet.size()); Set<ServiceInstance> resultBlackList = getFieldValue(blackListedInstancesField, testSubject); assertTrue(resultBlackList.contains(nonAxonInstance)); verify(discoveryClient).getServices(); verify(discoveryClient).getInstances(SERVICE_INSTANCE_ID); verify(discoveryClient).getInstances(nonAxonServiceInstanceId); } @Test public void testUpdateMembershipsOnHeartbeatEventDoesNotRequestInfoFromBlackListedServiceInstance() { SpringCloudCommandRouter testSubject = SpringCloudCommandRouter.builder() .discoveryClient(discoveryClient) .localServiceInstance(localServiceInstance) .routingStrategy(routingStrategy) .serviceInstanceFilter(serviceInstance -> true) .build(); serviceInstanceMetadata.put(LOAD_FACTOR_KEY, Integer.toString(LOAD_FACTOR)); serviceInstanceMetadata.put(SERIALIZED_COMMAND_FILTER_KEY, serializedCommandFilterData); serviceInstanceMetadata.put(SERIALIZED_COMMAND_FILTER_CLASS_NAME_KEY, serializedCommandFilterClassName); String nonAxonServiceInstanceId = "nonAxonInstance"; ServiceInstance nonAxonInstance = mock(ServiceInstance.class); when(nonAxonInstance.getServiceId()).thenReturn(nonAxonServiceInstanceId); when(nonAxonInstance.getHost()).thenReturn("nonAxonHost"); when(nonAxonInstance.getPort()).thenReturn(0); when(nonAxonInstance.getMetadata()).thenReturn(Collections.emptyMap()); when(discoveryClient.getServices()).thenReturn(ImmutableList.of(SERVICE_INSTANCE_ID, nonAxonServiceInstanceId)); when(discoveryClient.getInstances(nonAxonServiceInstanceId)).thenReturn(ImmutableList.of(nonAxonInstance)); // First update - black lists 'nonAxonServiceInstance' as it does not contain any message routing information testSubject.updateMemberships(mock(HeartbeatEvent.class)); // Second update testSubject.updateMemberships(mock(HeartbeatEvent.class)); verify(discoveryClient, times(2)).getServices(); verify(discoveryClient, times(2)).getInstances(nonAxonServiceInstanceId); verify(discoveryClient, times(2)).getInstances(SERVICE_INSTANCE_ID); } @Test public void testUpdateMembershipsOnHeartbeatEventTwoInstancesOnSameServiceIdUpdatesConsistentHash() { int expectedMemberSetSize = 2; serviceInstanceMetadata.put(LOAD_FACTOR_KEY, Integer.toString(LOAD_FACTOR)); serviceInstanceMetadata.put(SERIALIZED_COMMAND_FILTER_KEY, serializedCommandFilterData); serviceInstanceMetadata.put(SERIALIZED_COMMAND_FILTER_CLASS_NAME_KEY, serializedCommandFilterClassName); ServiceInstance remoteInstance = mock(ServiceInstance.class); when(remoteInstance.getServiceId()).thenReturn(SERVICE_INSTANCE_ID); when(remoteInstance.getUri()).thenReturn(URI.create("remote")); when(remoteInstance.getMetadata()).thenReturn(serviceInstanceMetadata); when(discoveryClient.getServices()).thenReturn(ImmutableList.of(SERVICE_INSTANCE_ID)); when(discoveryClient.getInstances(SERVICE_INSTANCE_ID)) .thenReturn(ImmutableList.of(localServiceInstance, remoteInstance)); testSubject.updateMemberships(mock(HeartbeatEvent.class)); AtomicReference<ConsistentHash> resultAtomicConsistentHash = getFieldValue(atomicConsistentHashField, testSubject); Set<Member> resultMemberSet = resultAtomicConsistentHash.get().getMembers(); assertEquals(expectedMemberSetSize, resultMemberSet.size()); } @SuppressWarnings("unchecked") @Test public void testBlackListCleaning() { serviceInstanceMetadata.put(LOAD_FACTOR_KEY, Integer.toString(LOAD_FACTOR)); serviceInstanceMetadata.put(SERIALIZED_COMMAND_FILTER_KEY, serializedCommandFilterData); serviceInstanceMetadata.put(SERIALIZED_COMMAND_FILTER_CLASS_NAME_KEY, serializedCommandFilterClassName); String serviceInstanceToBeBlackListedId = "toBeBlackListed"; ServiceInstance serviceInstanceToBeBlackListed = mock(ServiceInstance.class); when(serviceInstanceToBeBlackListed.getServiceId()).thenReturn(serviceInstanceToBeBlackListedId); when(serviceInstanceToBeBlackListed.getHost()).thenReturn("host"); when(serviceInstanceToBeBlackListed.getPort()).thenReturn(0); when(serviceInstanceToBeBlackListed.getMetadata()).thenReturn( Collections.emptyMap(), serviceInstanceMetadata ); when(discoveryClient.getServices()).thenReturn( ImmutableList.of(SERVICE_INSTANCE_ID, serviceInstanceToBeBlackListedId), ImmutableList.of(SERVICE_INSTANCE_ID), ImmutableList.of(SERVICE_INSTANCE_ID, serviceInstanceToBeBlackListedId) ); when(discoveryClient.getInstances(serviceInstanceToBeBlackListedId)).thenReturn(ImmutableList .of(serviceInstanceToBeBlackListed)); testSubject.updateMemberships(mock(HeartbeatEvent.class)); Set<ServiceInstance> blackListed = getFieldValue(blackListedServiceInstancesField, testSubject); assertEquals(1, blackListed.size()); assertEquals(serviceInstanceToBeBlackListedId, blackListed.iterator().next().getServiceId()); testSubject.updateMemberships(mock(HeartbeatEvent.class)); blackListed = getFieldValue(blackListedServiceInstancesField, testSubject); assertTrue(blackListed.isEmpty()); testSubject.updateMemberships(mock(HeartbeatEvent.class)); blackListed = getFieldValue(blackListedServiceInstancesField, testSubject); assertTrue(blackListed.isEmpty()); } private void assertMember(boolean localMember, Member resultMember, Boolean registered) { String expectedMemberName = SpringCloudCommandRouterTest.SERVICE_INSTANCE_ID; URI expectedEndpoint = SpringCloudCommandRouterTest.SERVICE_INSTANCE_URI; assertEquals(resultMember.getClass(), ConsistentHash.ConsistentHashMember.class); ConsistentHash.ConsistentHashMember result = (ConsistentHash.ConsistentHashMember) resultMember; if (localMember && !registered) { assertTrue(result.name().contains(expectedMemberName)); } else { assertEquals(expectedMemberName + "[" + expectedEndpoint + "]", result.name()); } assertEquals(LOAD_FACTOR, result.segmentCount()); Optional<URI> connectionEndpointOptional = result.getConnectionEndpoint(URI.class); if (localMember && !registered) { assertFalse(connectionEndpointOptional.isPresent()); } else { assertTrue(connectionEndpointOptional.isPresent()); URI resultEndpoint = connectionEndpointOptional.orElseThrow(IllegalStateException::new); assertEquals(resultEndpoint, expectedEndpoint); } } @Test public void testConsistentHashCreatedOnDistinctHostsShouldBeEqual() { serviceInstanceMetadata.put(LOAD_FACTOR_KEY, Integer.toString(100)); serviceInstanceMetadata.put(SERIALIZED_COMMAND_FILTER_KEY, serializedCommandFilterData); serviceInstanceMetadata.put(SERIALIZED_COMMAND_FILTER_CLASS_NAME_KEY, serializedCommandFilterClassName); when(discoveryClient.getServices()).thenReturn(singletonList(SERVICE_INSTANCE_ID)); int numberOfInstances = 6; List<ServiceInstance> serviceInstances = mockServiceInstances(numberOfInstances); when(discoveryClient.getInstances(SERVICE_INSTANCE_ID)).thenReturn(serviceInstances); List<SpringCloudCommandRouter> routers = createRoutersFor(serviceInstances); initAll(routers); List<ConsistentHash> hashes = getHashesFor(routers); assertEquals(hashes.size(), numberOfInstances); hashes.forEach(hash -> assertEquals(hash, hashes.get(0))); } private List<ConsistentHash> getHashesFor(List<SpringCloudCommandRouter> routers) { return routers.stream() .map(this::getHash) .map(AtomicReference::get) .collect(toList()); } private void initAll(List<SpringCloudCommandRouter> routers) { routers.forEach(r -> { r.updateMemberships(mock(HeartbeatEvent.class)); r.resetLocalMembership(mock(InstanceRegisteredEvent.class)); }); } private List<SpringCloudCommandRouter> createRoutersFor(List<ServiceInstance> serviceInstances) { return serviceInstances.stream() .map(ServiceInstance::getHost) .map(this::createRouterFor) .collect(toList()); } private AtomicReference<ConsistentHash> getHash(SpringCloudCommandRouter r) { return getFieldValue(atomicConsistentHashField, r); } private SpringCloudCommandRouter createRouterFor(String host) { Registration localServiceInstance = mock(Registration.class); when(localServiceInstance.getUri()).thenReturn(URI.create("http://" + host)); return SpringCloudCommandRouter.builder() .discoveryClient(discoveryClient) .localServiceInstance(localServiceInstance) .routingStrategy(routingStrategy) .serviceInstanceFilter(serviceInstance -> true) .consistentHashChangeListener(consistentHashChangeListener) .build(); } private List<ServiceInstance> mockServiceInstances(int number) { return IntStream.rangeClosed(1, number) .mapToObj(i -> { ServiceInstance instance = mock(ServiceInstance.class); when(instance.getHost()).thenReturn("host" + i); when(instance.getServiceId()).thenReturn(SERVICE_INSTANCE_ID); when(instance.getUri()).thenReturn(URI.create("http://host" + i)); when(instance.getMetadata()).thenReturn(serviceInstanceMetadata); return instance; }) .collect(toList()); } @Test public void testBuildMemberWithContextRootPropertynameCreatesAnUriWithContextRoot() { testSubject = SpringCloudCommandRouter.builder() .discoveryClient(discoveryClient) .localServiceInstance(localServiceInstance) .routingStrategy(routingStrategy) .serviceInstanceFilter(serviceInstance -> true) .consistentHashChangeListener(ConsistentHashChangeListener.noOp()) .contextRootMetadataPropertyname(CONTEXT_ROOT_KEY) .build(); serviceInstanceMetadata.put(CONTEXT_ROOT_KEY, "/contextRootPath"); ServiceInstance remoteInstance = mock(ServiceInstance.class); when(remoteInstance.getServiceId()).thenReturn(SERVICE_INSTANCE_ID); when(remoteInstance.getUri()).thenReturn(URI.create("remote")); when(remoteInstance.getMetadata()).thenReturn(serviceInstanceMetadata); Member memberWithContextRootUri = testSubject.buildMember(remoteInstance); Optional<URI> connectionEndpoint = memberWithContextRootUri.getConnectionEndpoint(URI.class); assertTrue(connectionEndpoint.isPresent()); assertEquals(connectionEndpoint.get().toString(), "remote/contextRootPath"); } @Test public void testLocalBuildMemberWithContextRootPropertynameCreatesAnUriWithContextRoot() { testSubject = SpringCloudCommandRouter.builder() .discoveryClient(discoveryClient) .localServiceInstance(localServiceInstance) .routingStrategy(routingStrategy) .serviceInstanceFilter(serviceInstance -> true) .consistentHashChangeListener(ConsistentHashChangeListener.noOp()) .contextRootMetadataPropertyname(CONTEXT_ROOT_KEY) .build(); testSubject.resetLocalMembership(null); serviceInstanceMetadata.put(CONTEXT_ROOT_KEY, "/contextRootPath"); ServiceInstance localInstance = mock(ServiceInstance.class); when(localInstance.getServiceId()).thenReturn(SERVICE_INSTANCE_ID); when(localInstance.getUri()).thenReturn(URI.create("remote")); when(localInstance.getMetadata()).thenReturn(serviceInstanceMetadata); // the localServiceInstance has the same uri when(localServiceInstance.getUri()).thenReturn( UriComponentsBuilder.fromUriString("remote/contextRootPath") .build().toUri()); Member memberWithContextRootUri = testSubject.buildMember(localInstance); Optional<URI> connectionEndpoint = memberWithContextRootUri.getConnectionEndpoint(URI.class); assertTrue(connectionEndpoint.isPresent()); // the endpoint for the local service should get the contextroot, too: assertEquals(connectionEndpoint.get().toString(), "remote/contextRootPath"); } }
52.656051
133
0.709296
bfd97fd4b51ee299eb283dc77d9ce6413129ae96
511
package DTO; /** * * @author Lucas Pereira */ public class FuncionarioLoginDTO { private int Id; private String nome, senha; public int getId() { return Id; } public void setId(int Id) { this.Id = Id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getSenha() { return senha; } public void setSenha(String senha) { this.senha = senha; } }
17.62069
40
0.555773
cbbda508e83fd41f727ad5f87fe6d6e86f7871b8
1,932
package com.our.news.admin.service.Impl; import com.our.news.admin.dao.CommentDao; import com.our.news.admin.dao.NewInfoDao; import com.our.news.admin.service.CommentService; import com.our.news.admin.service.NewInfoService; import com.ournews.commons.dto.BaseResult; import com.ournews.commons.dto.PageInfo; import com.ournews.domain.entity.Comment; import com.ournews.domain.entity.NewsInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @author ljs * @time 2018-10-31 */ @Service public class CommentServiceImpl implements CommentService { @Autowired private CommentDao commentDao; @Autowired private NewInfoDao newInfoDao; /** * 评论分页(只根据新闻id查询的数据分页) * @author ljs */ @Override public PageInfo<Comment> page(int start, int length, int draw, Comment comment) { PageInfo<Comment> pageInfo = new PageInfo<>(); pageInfo.setDraw(draw); pageInfo.setData(commentDao.getCommentListByNewInfoId(start,length,comment.getNewInfo_id())); Long count = commentDao.getCommentCountByNewInfoId(comment.getNewInfo_id()); pageInfo.setRecordsTotal(count.intValue()); pageInfo.setRecordsFiltered(count.intValue()); return pageInfo; } /** * 删除单个评论 * @author ljs */ @Override public BaseResult deleteComment(String id) { BaseResult baseResult = null; try{ Long newId = Long.parseLong(commentDao.getComment(Long.parseLong(id))); commentDao.deleteCommentById(Long.parseLong(id)); Long count = commentDao.getCommentCountByNewInfoId(newId); newInfoDao.updateNewInfoCommentCount(""+newId,count.intValue()); baseResult = BaseResult.success("删除成功"); } catch(Exception e){ baseResult = BaseResult.fail("删除失败"); } return baseResult; } }
31.672131
101
0.693582
b5d7613cc0c599748f08e50acd647669c21e4325
398
package com.web.blog.dao; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface StudentgroupDao { public int creategroup(@Param("group_id") String group_id,@Param("student_id") String student_id,@Param("direction")String direction); public List findgroup(@Param("direction")String direction); }
30.615385
138
0.788945
fb5c9560dfa2b662241715bd84c9c7fba026e08d
2,283
package de.exceptionflug.protocolize.items; import net.md_5.bungee.api.ProxyServer; import static de.exceptionflug.protocolize.api.util.ProtocolVersions.MINECRAFT_1_13; public enum ItemType { NO_DATA(new ItemIDMapping(0, 0, -1)); private final ItemIDMapping[] mappings; private final int maxStackSize; ItemType(final ItemIDMapping... mappings) { this(64, mappings); } ItemType(final int maxStackSize, final ItemIDMapping... mappings) { this.maxStackSize = maxStackSize; this.mappings = mappings; } public static ItemType getType(final int id, final int protocolVersion, final ItemStack stack) { return getType(id, (short) 0, protocolVersion, stack); } public static ItemType getType( final int id, short durability, final int protocolVersion, final ItemStack stack) { if (protocolVersion >= MINECRAFT_1_13) durability = 0; for (final ItemType type : values()) { final ItemIDMapping mapping = type.getApplicableMapping(protocolVersion); if (mapping != null) { if (mapping instanceof AbstractCustomItemIDMapping) { if (((AbstractCustomItemIDMapping) mapping).isApplicable( stack, protocolVersion, id, durability)) { return type; } } else { if (mapping.getId() == id && mapping.getData() == durability) { return type; } } } } if (durability != 0) { return getType(id, protocolVersion, stack); } ProxyServer .getInstance() .getLogger() .warning("[Protocolize] Don't know what item " + id + ":" + durability + " is at version " + protocolVersion); return null; } public int getMaxStackSize() { return maxStackSize; } public ItemIDMapping getApplicableMapping(final int protocolVersion) { for (final ItemIDMapping mapping : mappings) { if (mapping.getProtocolVersionRangeStart() <= protocolVersion && mapping.getProtocolVersionRangeEnd() >= protocolVersion) return mapping; } return null; } }
28.185185
98
0.601402
c82021f05987724fe304a41c9cbda99e90e35447
41,275
package uk.gov.hmcts.ethos.replacement.docmosis.reports.casescompleted; import org.junit.Test; import uk.gov.hmcts.ecm.common.model.ccd.CaseData; import uk.gov.hmcts.ecm.common.model.ccd.SubmitEvent; import uk.gov.hmcts.ecm.common.model.ccd.items.DateListedTypeItem; import uk.gov.hmcts.ecm.common.model.ccd.items.HearingTypeItem; import uk.gov.hmcts.ecm.common.model.ccd.items.JurCodesTypeItem; import uk.gov.hmcts.ecm.common.model.ccd.types.DateListedType; import uk.gov.hmcts.ecm.common.model.ccd.types.HearingType; import uk.gov.hmcts.ecm.common.model.ccd.types.JurCodesType; import uk.gov.hmcts.ecm.common.model.listing.ListingData; import uk.gov.hmcts.ecm.common.model.listing.ListingDetails; import uk.gov.hmcts.ecm.common.model.listing.types.AdhocReportType; import java.util.*; import static org.junit.Assert.*; import static uk.gov.hmcts.ecm.common.model.helper.Constants.CLOSED_STATE; import static uk.gov.hmcts.ecm.common.model.helper.Constants.CONCILIATION_TRACK_FAST_TRACK; import static uk.gov.hmcts.ecm.common.model.helper.Constants.CONCILIATION_TRACK_NO_CONCILIATION; import static uk.gov.hmcts.ecm.common.model.helper.Constants.CONCILIATION_TRACK_OPEN_TRACK; import static uk.gov.hmcts.ecm.common.model.helper.Constants.CONCILIATION_TRACK_STANDARD_TRACK; import static uk.gov.hmcts.ecm.common.model.helper.Constants.HEARING_STATUS_HEARD; import static uk.gov.hmcts.ecm.common.model.helper.Constants.HEARING_STATUS_WITHDRAWN; import static uk.gov.hmcts.ecm.common.model.helper.Constants.HEARING_TYPE_JUDICIAL_REMEDY; import static uk.gov.hmcts.ecm.common.model.helper.Constants.HEARING_TYPE_PERLIMINARY_HEARING; import static uk.gov.hmcts.ecm.common.model.helper.Constants.JURISDICTION_OUTCOME_DISMISSED_AT_HEARING; import static uk.gov.hmcts.ecm.common.model.helper.Constants.NEWCASTLE_LISTING_CASE_TYPE_ID; import static uk.gov.hmcts.ecm.common.model.helper.Constants.NO; import static uk.gov.hmcts.ecm.common.model.helper.Constants.POSITION_TYPE_CASE_INPUT_IN_ERROR; import static uk.gov.hmcts.ecm.common.model.helper.Constants.POSITION_TYPE_CASE_TRANSFERRED_OTHER_COUNTRY; import static uk.gov.hmcts.ecm.common.model.helper.Constants.POSITION_TYPE_CASE_TRANSFERRED_SAME_COUNTRY; import static uk.gov.hmcts.ecm.common.model.helper.Constants.SINGLE_HEARING_DATE_TYPE; import static uk.gov.hmcts.ecm.common.model.helper.Constants.SUBMITTED_STATE; import static uk.gov.hmcts.ecm.common.model.helper.Constants.YES; import static uk.gov.hmcts.ethos.replacement.docmosis.reports.casescompleted.CasesCompletedReport.COMPLETED_PER_SESSION_FORMAT; public class CaseCompletedReportTest { @Test public void testReportHeaderTotalsAreZeroIfNoCasesExist() { // given no cases exist // when we generate report data // then totals are all zero ListingDetails listingDetails = new ListingDetails(); listingDetails.setCaseTypeId(NEWCASTLE_LISTING_CASE_TYPE_ID); ListingData caseData = new ListingData(); listingDetails.setCaseData(caseData); List<SubmitEvent> submitEvents = new ArrayList<>(); CasesCompletedReport casesCompletedReport = new CasesCompletedReport(); ListingData listingData = casesCompletedReport.generateReportData(listingDetails, submitEvents); verifyReportHeaderIsZero(listingData); } @Test public void testIgnoreCaseIfNotClosed() { // given case is not closed // when we generate report data // then no data returned ListingDetails listingDetails = new ListingDetails(); listingDetails.setCaseTypeId(NEWCASTLE_LISTING_CASE_TYPE_ID); ListingData caseData = new ListingData(); listingDetails.setCaseData(caseData); List<SubmitEvent> submitEvents = new ArrayList<>(); submitEvents.add(createSubmitEvent(SUBMITTED_STATE)); CasesCompletedReport casesCompletedReport = new CasesCompletedReport(); ListingData listingData = casesCompletedReport.generateReportData(listingDetails, submitEvents); verifyReportHeaderIsZero(listingData); } @Test public void testIgnoreCaseIfPositionTypeInvalid() { // given case is closed // given position type is invalid // when we generate report data // then no data returned ListingDetails listingDetails = new ListingDetails(); listingDetails.setCaseTypeId(NEWCASTLE_LISTING_CASE_TYPE_ID); ListingData listingData = new ListingData(); listingDetails.setCaseData(listingData); List<SubmitEvent> submitEvents = new ArrayList<>(); submitEvents.add(createSubmitEvent(CLOSED_STATE)); List<String> invalidPositionTypes = Arrays.asList(POSITION_TYPE_CASE_INPUT_IN_ERROR, POSITION_TYPE_CASE_TRANSFERRED_SAME_COUNTRY, POSITION_TYPE_CASE_TRANSFERRED_OTHER_COUNTRY); CaseData caseData = submitEvents.get(0).getCaseData(); for (String positionType : invalidPositionTypes) { caseData.setPositionType(positionType); CasesCompletedReport casesCompletedReport = new CasesCompletedReport(); ListingData reportListingData = casesCompletedReport.generateReportData(listingDetails, submitEvents); verifyReportHeaderIsZero(reportListingData); } } @Test public void testIgnoreCaseIfJurisdictionOutcomeInvalid() { // given case is closed // given position type is valid // given jurisdiction outcome is invalid // when we generate report data // then no data returned ListingDetails listingDetails = new ListingDetails(); listingDetails.setCaseTypeId(NEWCASTLE_LISTING_CASE_TYPE_ID); ListingData listingData = new ListingData(); listingDetails.setCaseData(listingData); List<SubmitEvent> submitEvents = new ArrayList<>(); submitEvents.add(createSubmitEvent(CLOSED_STATE)); List<String> invalidOutcomes = Arrays.asList("This is not a valid outcome", null); CaseData caseData = submitEvents.get(0).getCaseData(); caseData.setJurCodesCollection(new ArrayList<>()); for (String outcome : invalidOutcomes) { caseData.getJurCodesCollection().add(createJurisdiction(outcome)); CasesCompletedReport casesCompletedReport = new CasesCompletedReport(); ListingData reportListingData = casesCompletedReport.generateReportData(listingDetails, submitEvents); verifyReportHeaderIsZero(reportListingData); caseData.getJurCodesCollection().clear(); } } @Test public void testIgnoreCaseIfItContainsNoHearings() { // given case is closed // given case position type is valid // given case jurisdiction outcome is valid // given case has no hearings // when we generate report data // then no data returned ListingDetails listingDetails = new ListingDetails(); listingDetails.setCaseTypeId(NEWCASTLE_LISTING_CASE_TYPE_ID); ListingData caseData = new ListingData(); listingDetails.setCaseData(caseData); List<SubmitEvent> submitEvents = new ArrayList<>(); submitEvents.add(createSubmitEvent(CLOSED_STATE, JURISDICTION_OUTCOME_DISMISSED_AT_HEARING, Collections.emptyList())); CasesCompletedReport casesCompletedReport = new CasesCompletedReport(); ListingData listingData = casesCompletedReport.generateReportData(listingDetails, submitEvents); verifyReportHeaderIsZero(listingData); } @Test public void testIgnoreCaseIfHearingTypeInvalid() { // given case is closed // given case position type is valid // given case jurisdiction outcome is valid // given case has a hearing with a type that is invalid // when we generate report data // then no data returned ListingDetails listingDetails = new ListingDetails(); listingDetails.setCaseTypeId(NEWCASTLE_LISTING_CASE_TYPE_ID); ListingData listingData = new ListingData(); listingDetails.setCaseData(listingData); List<SubmitEvent> submitEvents = new ArrayList<>(); DateListedTypeItem dateListedTypeItem = createHearingDateListed("1970-01-01T00:00:00", HEARING_STATUS_HEARD, YES); List<HearingTypeItem> hearings = createHearingCollection(createHearing(HEARING_TYPE_JUDICIAL_REMEDY, dateListedTypeItem)); submitEvents.add(createSubmitEvent(CLOSED_STATE, JURISDICTION_OUTCOME_DISMISSED_AT_HEARING, hearings)); CasesCompletedReport casesCompletedReport = new CasesCompletedReport(); ListingData reportListingData = casesCompletedReport.generateReportData(listingDetails, submitEvents); verifyReportHeaderIsZero(reportListingData); } @Test public void testIgnoreCaseIfHearingListingDateNotInSearchRange() { // given case is closed // given case position type is valid // given case jurisdiction outcome is valid // given case has a hearing that was disposed // given case has a hearing listing date that is different to report search date // when we generate report data // then no data returned String searchDate = "1970-01-01"; String listingDate = "1970-01-02T00:00:00"; ListingDetails listingDetails = new ListingDetails(); listingDetails.setCaseTypeId(NEWCASTLE_LISTING_CASE_TYPE_ID); ListingData listingData = new ListingData(); listingData.setListingDate(searchDate); listingData.setHearingDateType(SINGLE_HEARING_DATE_TYPE); listingDetails.setCaseData(listingData); List<SubmitEvent> submitEvents = new ArrayList<>(); DateListedTypeItem dateListedTypeItem = createHearingDateListed(listingDate, HEARING_STATUS_HEARD, YES); List<HearingTypeItem> hearings = createHearingCollection(createHearing(HEARING_TYPE_PERLIMINARY_HEARING, dateListedTypeItem)); submitEvents.add(createSubmitEvent(CLOSED_STATE, JURISDICTION_OUTCOME_DISMISSED_AT_HEARING, hearings)); CasesCompletedReport casesCompletedReport = new CasesCompletedReport(); ListingData reportListingData = casesCompletedReport.generateReportData(listingDetails, submitEvents); verifyReportHeaderIsZero(reportListingData); } @Test public void testIgnoreCaseIfHearingNotDisposed() { // given case is closed // given case position type is valid // given case jurisdiction outcome is valid // given case has a hearing with a valid type // given case has a hearing that was not disposed // when we generate report data // then no data returned String searchDate = "1970-01-01"; String listingDate = "1970-01-01T00:00:00"; ListingDetails listingDetails = new ListingDetails(); listingDetails.setCaseTypeId(NEWCASTLE_LISTING_CASE_TYPE_ID); ListingData listingData = new ListingData(); listingData.setListingDate(searchDate); listingData.setHearingDateType(SINGLE_HEARING_DATE_TYPE); listingDetails.setCaseData(listingData); List<SubmitEvent> submitEvents = new ArrayList<>(); DateListedTypeItem dateListedTypeItem = createHearingDateListed(listingDate, HEARING_STATUS_HEARD, NO); List<HearingTypeItem> hearings = createHearingCollection(createHearing(HEARING_TYPE_PERLIMINARY_HEARING, dateListedTypeItem)); submitEvents.add(createSubmitEvent(CLOSED_STATE, JURISDICTION_OUTCOME_DISMISSED_AT_HEARING, hearings)); CasesCompletedReport casesCompletedReport = new CasesCompletedReport(); ListingData reportListingData = casesCompletedReport.generateReportData(listingDetails, submitEvents); verifyReportHeaderIsZero(reportListingData); } @Test public void testValidNullConciliationTrackCaseIsAddedToReport() { // given case is closed // given case position type is valid // given case jurisdiction outcome is valid // given case has a hearing with a valid type // given case has a hearing that was disposed // given case has a hearing listed date that is within report search range // given case has a null conciliation track i.e. it is not set // when we generate report data // then we have some data String searchDate = "1970-01-01"; String listingDate = "1970-01-01T00:00:00"; ListingDetails listingDetails = new ListingDetails(); listingDetails.setCaseTypeId(NEWCASTLE_LISTING_CASE_TYPE_ID); ListingData listingData = new ListingData(); listingData.setListingDate(searchDate); listingData.setHearingDateType(SINGLE_HEARING_DATE_TYPE); listingDetails.setCaseData(listingData); List<SubmitEvent> submitEvents = new ArrayList<>(); DateListedTypeItem dateListedTypeItem = createHearingDateListed(listingDate, HEARING_STATUS_HEARD, YES); List<HearingTypeItem> hearings = createHearingCollection(createHearing(HEARING_TYPE_PERLIMINARY_HEARING, dateListedTypeItem)); submitEvents.add(createSubmitEvent(CLOSED_STATE, JURISDICTION_OUTCOME_DISMISSED_AT_HEARING, hearings, null)); CasesCompletedReport casesCompletedReport = new CasesCompletedReport(); ListingData reportListingData = casesCompletedReport.generateReportData(listingDetails, submitEvents); ReportHeaderValues reportHeaderValues = new ReportHeaderValues( 1, 1, 1.0, "Newcastle", 1, 1, 1.0, 0, 0, 0, 0, 0, 0, 0, 0, 0); verifyReportHeader(reportListingData, reportHeaderValues); verifyReportDetails(reportListingData, 1); } @Test public void testValidNoneConciliationTrackCaseIsAddedToReport() { // given case is closed // given case position type is valid // given case jurisdiction outcome is valid // given case has a hearing with a valid type // given case has a hearing that was disposed // given case has a hearing listed date that is within report search range // given case is for none conciliation track // when we generate report data // then we have some data String searchDate = "1970-01-01"; String listingDate = "1970-01-01T00:00:00"; ListingDetails listingDetails = new ListingDetails(); listingDetails.setCaseTypeId(NEWCASTLE_LISTING_CASE_TYPE_ID); ListingData listingData = new ListingData(); listingData.setListingDate(searchDate); listingData.setHearingDateType(SINGLE_HEARING_DATE_TYPE); listingDetails.setCaseData(listingData); List<SubmitEvent> submitEvents = new ArrayList<>(); DateListedTypeItem dateListedTypeItem = createHearingDateListed(listingDate, HEARING_STATUS_HEARD, YES); List<HearingTypeItem> hearings = createHearingCollection(createHearing(HEARING_TYPE_PERLIMINARY_HEARING, dateListedTypeItem)); submitEvents.add(createSubmitEvent(CLOSED_STATE, JURISDICTION_OUTCOME_DISMISSED_AT_HEARING, hearings, CONCILIATION_TRACK_NO_CONCILIATION)); CasesCompletedReport casesCompletedReport = new CasesCompletedReport(); ListingData reportListingData = casesCompletedReport.generateReportData(listingDetails, submitEvents); ReportHeaderValues reportHeaderValues = new ReportHeaderValues( 1, 1, 1.0, "Newcastle", 1, 1, 1.0, 0, 0, 0, 0, 0, 0, 0, 0, 0); verifyReportHeader(reportListingData, reportHeaderValues); verifyReportDetails(reportListingData, 1); } @Test public void testValidFastConciliationTrackCaseIsAddedToReport() { // given case is closed // given case position type is valid // given case jurisdiction outcome is valid // given case has a hearing with a valid type // given case has a hearing that was disposed // given case has a hearing listed date that is within report search range // given case is for fast conciliation track // when we generate report data // then we have some data String searchDate = "1970-01-01"; String listingDate = "1970-01-01T00:00:00"; ListingDetails listingDetails = new ListingDetails(); listingDetails.setCaseTypeId(NEWCASTLE_LISTING_CASE_TYPE_ID); ListingData listingData = new ListingData(); listingData.setListingDate(searchDate); listingData.setHearingDateType(SINGLE_HEARING_DATE_TYPE); listingDetails.setCaseData(listingData); List<SubmitEvent> submitEvents = new ArrayList<>(); DateListedTypeItem dateListedTypeItem = createHearingDateListed(listingDate, HEARING_STATUS_HEARD, YES); List<HearingTypeItem> hearings = createHearingCollection(createHearing(HEARING_TYPE_PERLIMINARY_HEARING, dateListedTypeItem)); submitEvents.add(createSubmitEvent(CLOSED_STATE, JURISDICTION_OUTCOME_DISMISSED_AT_HEARING, hearings, CONCILIATION_TRACK_FAST_TRACK)); CasesCompletedReport casesCompletedReport = new CasesCompletedReport(); ListingData reportListingData = casesCompletedReport.generateReportData(listingDetails, submitEvents); ReportHeaderValues reportHeaderValues = new ReportHeaderValues( 1, 1, 1.0, "Newcastle", 0, 0, 0, 1, 1, 1.0, 0, 0, 0, 0, 0, 0); verifyReportHeader(reportListingData, reportHeaderValues); verifyReportDetails(reportListingData, 1); } @Test public void testValidStdConciliationTrackCaseIsAddedToReport() { // given case is closed // given case position type is valid // given case jurisdiction outcome is valid // given case has a hearing with a valid type // given case has a hearing that was disposed // given case has a hearing listed date that is within report search range // given case is for standard conciliation track // when we generate report data // then we have some data String searchDate = "1970-01-01"; String listingDate = "1970-01-01T00:00:00"; ListingDetails listingDetails = new ListingDetails(); listingDetails.setCaseTypeId(NEWCASTLE_LISTING_CASE_TYPE_ID); ListingData listingData = new ListingData(); listingData.setListingDate(searchDate); listingData.setHearingDateType(SINGLE_HEARING_DATE_TYPE); listingDetails.setCaseData(listingData); List<SubmitEvent> submitEvents = new ArrayList<>(); DateListedTypeItem dateListedTypeItem = createHearingDateListed(listingDate, HEARING_STATUS_HEARD, YES); List<HearingTypeItem> hearings = createHearingCollection(createHearing(HEARING_TYPE_PERLIMINARY_HEARING, dateListedTypeItem)); submitEvents.add(createSubmitEvent(CLOSED_STATE, JURISDICTION_OUTCOME_DISMISSED_AT_HEARING, hearings, CONCILIATION_TRACK_STANDARD_TRACK)); CasesCompletedReport casesCompletedReport = new CasesCompletedReport(); ListingData reportListingData = casesCompletedReport.generateReportData(listingDetails, submitEvents); ReportHeaderValues reportHeaderValues = new ReportHeaderValues( 1, 1, 1.0, "Newcastle", 0, 0, 0, 0, 0, 0, 1, 1, 1.0, 0, 0, 0); verifyReportHeader(reportListingData, reportHeaderValues); verifyReportDetails(reportListingData, 1); } @Test public void testValidOpenConciliationTrackCaseIsAddedToReport() { // given case is closed // given case position type is valid // given case jurisdiction outcome is valid // given case has a hearing with a valid type // given case has a hearing that was disposed // given case has a hearing listed date that is within report search range // given case is for open conciliation track // when we generate report data // then we have some data String searchDate = "1970-01-01"; String listingDate = "1970-01-01T00:00:00"; ListingDetails listingDetails = new ListingDetails(); listingDetails.setCaseTypeId(NEWCASTLE_LISTING_CASE_TYPE_ID); ListingData listingData = new ListingData(); listingData.setListingDate(searchDate); listingData.setHearingDateType(SINGLE_HEARING_DATE_TYPE); listingDetails.setCaseData(listingData); List<SubmitEvent> submitEvents = new ArrayList<>(); DateListedTypeItem dateListedTypeItem = createHearingDateListed(listingDate, HEARING_STATUS_HEARD, YES); List<HearingTypeItem> hearings = createHearingCollection(createHearing(HEARING_TYPE_PERLIMINARY_HEARING, dateListedTypeItem)); submitEvents.add(createSubmitEvent(CLOSED_STATE, JURISDICTION_OUTCOME_DISMISSED_AT_HEARING, hearings, CONCILIATION_TRACK_OPEN_TRACK)); CasesCompletedReport casesCompletedReport = new CasesCompletedReport(); ListingData reportListingData = casesCompletedReport.generateReportData(listingDetails, submitEvents); ReportHeaderValues reportHeaderValues = new ReportHeaderValues( 1, 1, 1.0, "Newcastle", 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1.0); verifyReportHeader(reportListingData, reportHeaderValues); verifyReportDetails(reportListingData, 1); } @Test public void testMultipleCasesAreSummedUpInTotals() { // given we have multiple cases that are valid // when we generate report data // then we have data for all cases String searchDate = "1970-01-01"; String listingDate = "1970-01-01T00:00:00"; ListingDetails listingDetails = new ListingDetails(); listingDetails.setCaseTypeId(NEWCASTLE_LISTING_CASE_TYPE_ID); ListingData listingData = new ListingData(); listingData.setListingDate(searchDate); listingData.setHearingDateType(SINGLE_HEARING_DATE_TYPE); listingDetails.setCaseData(listingData); List<SubmitEvent> submitEvents = new ArrayList<>(); DateListedTypeItem dateListedTypeItem = createHearingDateListed(listingDate, HEARING_STATUS_HEARD, YES); List<HearingTypeItem> hearings = createHearingCollection(createHearing(HEARING_TYPE_PERLIMINARY_HEARING, dateListedTypeItem)); submitEvents.add(createSubmitEvent(CLOSED_STATE, JURISDICTION_OUTCOME_DISMISSED_AT_HEARING, hearings, CONCILIATION_TRACK_NO_CONCILIATION)); submitEvents.add(createSubmitEvent(CLOSED_STATE, JURISDICTION_OUTCOME_DISMISSED_AT_HEARING, hearings, CONCILIATION_TRACK_FAST_TRACK)); submitEvents.add(createSubmitEvent(CLOSED_STATE, JURISDICTION_OUTCOME_DISMISSED_AT_HEARING, hearings, CONCILIATION_TRACK_STANDARD_TRACK)); submitEvents.add(createSubmitEvent(CLOSED_STATE, JURISDICTION_OUTCOME_DISMISSED_AT_HEARING, hearings, CONCILIATION_TRACK_OPEN_TRACK)); CasesCompletedReport casesCompletedReport = new CasesCompletedReport(); ListingData reportListingData = casesCompletedReport.generateReportData(listingDetails, submitEvents); ReportHeaderValues reportHeaderValues = new ReportHeaderValues( 4, 4, 1.0, "Newcastle", 1, 1, 1.0, 1, 1, 1.0, 1, 1, 1.0, 1, 1, 1.0); verifyReportHeader(reportListingData, reportHeaderValues); verifyReportDetails(reportListingData, 4); } @Test public void testMultipleCasesOnlyValidAreSummedUpInTotals() { // given we have two cases that are valid // given we have two cases that are not valid // when we generate report data // then we have data for only valid cases String searchDate = "1970-01-01"; String listingDate = "1970-01-01T00:00:00"; ListingDetails listingDetails = new ListingDetails(); listingDetails.setCaseTypeId(NEWCASTLE_LISTING_CASE_TYPE_ID); ListingData listingData = new ListingData(); listingData.setListingDate(searchDate); listingData.setHearingDateType(SINGLE_HEARING_DATE_TYPE); listingDetails.setCaseData(listingData); List<SubmitEvent> submitEvents = new ArrayList<>(); DateListedTypeItem dateListedTypeItem = createHearingDateListed(listingDate, HEARING_STATUS_HEARD, YES); List<HearingTypeItem> hearings = createHearingCollection(createHearing(HEARING_TYPE_PERLIMINARY_HEARING, dateListedTypeItem)); submitEvents.add(createSubmitEvent(CLOSED_STATE, JURISDICTION_OUTCOME_DISMISSED_AT_HEARING, hearings, CONCILIATION_TRACK_NO_CONCILIATION)); submitEvents.add(createSubmitEvent(SUBMITTED_STATE, JURISDICTION_OUTCOME_DISMISSED_AT_HEARING, hearings, CONCILIATION_TRACK_FAST_TRACK)); submitEvents.add(createSubmitEvent(CLOSED_STATE, JURISDICTION_OUTCOME_DISMISSED_AT_HEARING, hearings, CONCILIATION_TRACK_STANDARD_TRACK)); submitEvents.add(createSubmitEvent(SUBMITTED_STATE, JURISDICTION_OUTCOME_DISMISSED_AT_HEARING, hearings, CONCILIATION_TRACK_OPEN_TRACK)); CasesCompletedReport casesCompletedReport = new CasesCompletedReport(); ListingData reportListingData = casesCompletedReport.generateReportData(listingDetails, submitEvents); ReportHeaderValues reportHeaderValues = new ReportHeaderValues( 2, 2, 1.0, "Newcastle", 1, 1, 1.0, 0, 0, 0, 1, 1, 1.0, 0, 0, 0); verifyReportHeader(reportListingData, reportHeaderValues); verifyReportDetails(reportListingData, 2); } @Test public void testSessionDaysSingleCase() { // given the case is valid // given the case has a single hearing over multiple days // when we generate report data // then we have some data String searchDate = "1970-01-04"; ListingDetails listingDetails = new ListingDetails(); listingDetails.setCaseTypeId(NEWCASTLE_LISTING_CASE_TYPE_ID); ListingData listingData = new ListingData(); listingData.setListingDate(searchDate); listingData.setHearingDateType(SINGLE_HEARING_DATE_TYPE); listingDetails.setCaseData(listingData); List<SubmitEvent> submitEvents = new ArrayList<>(); DateListedTypeItem[] dateListedTypeItem = new DateListedTypeItem[] { createHearingDateListed("1970-01-01T00:00:00", HEARING_STATUS_HEARD, NO), createHearingDateListed("1970-01-02T00:00:00", HEARING_STATUS_WITHDRAWN, NO), // should be ignored createHearingDateListed("1970-01-03T00:00:00", HEARING_STATUS_HEARD, NO), createHearingDateListed("1970-01-04T00:00:00", HEARING_STATUS_HEARD, YES), createHearingDateListed("1970-01-05T00:00:00", HEARING_STATUS_WITHDRAWN, YES) }; List<HearingTypeItem> hearings = createHearingCollection(createHearing(HEARING_TYPE_PERLIMINARY_HEARING, dateListedTypeItem)); submitEvents.add(createSubmitEvent(CLOSED_STATE, JURISDICTION_OUTCOME_DISMISSED_AT_HEARING, hearings, CONCILIATION_TRACK_NO_CONCILIATION)); CasesCompletedReport casesCompletedReport = new CasesCompletedReport(); ListingData reportListingData = casesCompletedReport.generateReportData(listingDetails, submitEvents); ReportHeaderValues reportHeaderValues = new ReportHeaderValues( 1, 3, 0.33, "Newcastle", 1, 3, 0.33, 0, 0, 0, 0, 0, 0, 0, 0, 0); verifyReportHeader(reportListingData, reportHeaderValues); verifyReportDetails(reportListingData, 1); } @Test public void testSessionDaysMultipleCases() { // given there are multiple valid cases // when we generate report data // then we have some data String searchDate = "1970-01-04"; ListingDetails listingDetails = new ListingDetails(); listingDetails.setCaseTypeId(NEWCASTLE_LISTING_CASE_TYPE_ID); ListingData listingData = new ListingData(); listingData.setListingDate(searchDate); listingData.setHearingDateType(SINGLE_HEARING_DATE_TYPE); listingDetails.setCaseData(listingData); List<SubmitEvent> submitEvents = new ArrayList<>(); // Case 1: 4 session days no conciliation DateListedTypeItem[] dateListedTypeItem = new DateListedTypeItem[] { createHearingDateListed("1970-01-01T00:00:00", HEARING_STATUS_HEARD, NO), createHearingDateListed("1970-01-02T00:00:00", HEARING_STATUS_HEARD, NO), createHearingDateListed("1970-01-03T00:00:00", HEARING_STATUS_HEARD, NO), createHearingDateListed("1970-01-04T00:00:00", HEARING_STATUS_HEARD, YES), createHearingDateListed("1970-01-05T00:00:00", HEARING_STATUS_WITHDRAWN, YES) }; List<HearingTypeItem> hearings = createHearingCollection(createHearing(HEARING_TYPE_PERLIMINARY_HEARING, dateListedTypeItem)); submitEvents.add(createSubmitEvent(CLOSED_STATE, JURISDICTION_OUTCOME_DISMISSED_AT_HEARING, hearings, CONCILIATION_TRACK_NO_CONCILIATION)); // Case 2: 2 session days fast track dateListedTypeItem = new DateListedTypeItem[] { createHearingDateListed("1970-01-03T00:00:00", HEARING_STATUS_HEARD, NO), createHearingDateListed("1970-01-04T00:00:00", HEARING_STATUS_HEARD, YES) }; hearings = createHearingCollection(createHearing(HEARING_TYPE_PERLIMINARY_HEARING, dateListedTypeItem)); submitEvents.add(createSubmitEvent(CLOSED_STATE, JURISDICTION_OUTCOME_DISMISSED_AT_HEARING, hearings, CONCILIATION_TRACK_FAST_TRACK)); // Case 3: 1 session day standard conciliation dateListedTypeItem = new DateListedTypeItem[] { createHearingDateListed("1970-01-04T00:00:00", HEARING_STATUS_HEARD, YES) }; hearings = createHearingCollection(createHearing(HEARING_TYPE_PERLIMINARY_HEARING, dateListedTypeItem)); submitEvents.add(createSubmitEvent(CLOSED_STATE, JURISDICTION_OUTCOME_DISMISSED_AT_HEARING, hearings, CONCILIATION_TRACK_STANDARD_TRACK)); // Case 4: 2 session day open conciliation dateListedTypeItem = new DateListedTypeItem[] { createHearingDateListed("1970-01-03T00:00:00", HEARING_STATUS_HEARD, YES), createHearingDateListed("1970-01-04T00:00:00", HEARING_STATUS_HEARD, YES) }; hearings = createHearingCollection(createHearing(HEARING_TYPE_PERLIMINARY_HEARING, dateListedTypeItem)); submitEvents.add(createSubmitEvent(CLOSED_STATE, JURISDICTION_OUTCOME_DISMISSED_AT_HEARING, hearings, CONCILIATION_TRACK_OPEN_TRACK)); CasesCompletedReport casesCompletedReport = new CasesCompletedReport(); ListingData reportListingData = casesCompletedReport.generateReportData(listingDetails, submitEvents); ReportHeaderValues reportHeaderValues = new ReportHeaderValues( 4, 9, 0.44, "Newcastle", 1, 4, 0.25, 1, 2, 0.5, 1, 1, 1.0, 1, 2, 0.5); verifyReportHeader(reportListingData, reportHeaderValues); verifyReportDetails(reportListingData, 4); } @Test public void testSessionDaysMultipleTracks() { // given there are multiple valid cases for different conciliation tracks // when we generate report data // then we have some data String searchDate = "1970-01-04"; ListingDetails listingDetails = new ListingDetails(); listingDetails.setCaseTypeId(NEWCASTLE_LISTING_CASE_TYPE_ID); ListingData listingData = new ListingData(); listingData.setListingDate(searchDate); listingData.setHearingDateType(SINGLE_HEARING_DATE_TYPE); listingDetails.setCaseData(listingData); List<SubmitEvent> submitEvents = new ArrayList<>(); // Case 1: 4 session days DateListedTypeItem[] dateListedTypeItem = new DateListedTypeItem[] { createHearingDateListed("1970-01-01T00:00:00", HEARING_STATUS_HEARD, NO), createHearingDateListed("1970-01-02T00:00:00", HEARING_STATUS_HEARD, NO), createHearingDateListed("1970-01-03T00:00:00", HEARING_STATUS_HEARD, NO), createHearingDateListed("1970-01-04T00:00:00", HEARING_STATUS_HEARD, YES), createHearingDateListed("1970-01-05T00:00:00", HEARING_STATUS_WITHDRAWN, YES) }; List<HearingTypeItem> hearings = createHearingCollection(createHearing(HEARING_TYPE_PERLIMINARY_HEARING, dateListedTypeItem)); submitEvents.add(createSubmitEvent(CLOSED_STATE, JURISDICTION_OUTCOME_DISMISSED_AT_HEARING, hearings, CONCILIATION_TRACK_NO_CONCILIATION)); // Case 2: 2 session days dateListedTypeItem = new DateListedTypeItem[] { createHearingDateListed("1970-01-03T00:00:00", HEARING_STATUS_HEARD, NO), createHearingDateListed("1970-01-04T00:00:00", HEARING_STATUS_HEARD, YES) }; hearings = createHearingCollection(createHearing(HEARING_TYPE_PERLIMINARY_HEARING, dateListedTypeItem)); submitEvents.add(createSubmitEvent(CLOSED_STATE, JURISDICTION_OUTCOME_DISMISSED_AT_HEARING, hearings, CONCILIATION_TRACK_NO_CONCILIATION)); // Case 3: 1 session days dateListedTypeItem = new DateListedTypeItem[] { createHearingDateListed("1970-01-04T00:00:00", HEARING_STATUS_HEARD, YES) }; hearings = createHearingCollection(createHearing(HEARING_TYPE_PERLIMINARY_HEARING, dateListedTypeItem)); submitEvents.add(createSubmitEvent(CLOSED_STATE, JURISDICTION_OUTCOME_DISMISSED_AT_HEARING, hearings, CONCILIATION_TRACK_NO_CONCILIATION)); CasesCompletedReport casesCompletedReport = new CasesCompletedReport(); ListingData reportListingData = casesCompletedReport.generateReportData(listingDetails, submitEvents); ReportHeaderValues reportHeaderValues = new ReportHeaderValues( 3, 7, 0.43, "Newcastle", 3, 7, 0.43, 0, 0, 0, 0, 0, 0, 0, 0, 0); verifyReportHeader(reportListingData, reportHeaderValues); verifyReportDetails(reportListingData, 3); } private SubmitEvent createSubmitEvent(String state) { return createSubmitEvent(state, null, null); } private SubmitEvent createSubmitEvent(String state, String jurisdictionOutcome, List<HearingTypeItem> hearingCollection) { return createSubmitEvent(state, jurisdictionOutcome, hearingCollection, CONCILIATION_TRACK_NO_CONCILIATION); } private SubmitEvent createSubmitEvent(String state, String jurisdictionOutcome, List<HearingTypeItem> hearingCollection, String conciliationTrack) { SubmitEvent submitEvent = new SubmitEvent(); submitEvent.setState(state); CaseData caseData = new CaseData(); caseData.setConciliationTrack(conciliationTrack); if (jurisdictionOutcome != null) { caseData.setJurCodesCollection(new ArrayList<>()); caseData.getJurCodesCollection().add(createJurisdiction(jurisdictionOutcome)); } caseData.setHearingCollection(hearingCollection); submitEvent.setCaseData(caseData); return submitEvent; } private JurCodesTypeItem createJurisdiction(String outcome) { JurCodesTypeItem jurCodesTypeItem = new JurCodesTypeItem(); JurCodesType jurCodesType = new JurCodesType(); jurCodesType.setJudgmentOutcome(outcome); jurCodesTypeItem.setValue(jurCodesType); return jurCodesTypeItem; } private DateListedTypeItem createHearingDateListed(String listedDate, String status, String disposed) { DateListedTypeItem dateListedTypeItem = new DateListedTypeItem(); DateListedType dateListedType = new DateListedType(); dateListedType.setListedDate(listedDate); dateListedType.setHearingStatus(status); dateListedType.setHearingCaseDisposed(disposed); dateListedTypeItem.setValue(dateListedType); return dateListedTypeItem; } private HearingTypeItem createHearing(String type, DateListedTypeItem... dateListedTypeItems) { HearingTypeItem hearingTypeItem = new HearingTypeItem(); HearingType hearingType = new HearingType(); hearingType.setHearingType(type); List<DateListedTypeItem> hearingDateCollection = new ArrayList<>(); Collections.addAll(hearingDateCollection, dateListedTypeItems); hearingType.setHearingDateCollection(hearingDateCollection); hearingTypeItem.setValue(hearingType); return hearingTypeItem; } private List<HearingTypeItem> createHearingCollection(HearingTypeItem... hearings) { List<HearingTypeItem> hearingTypeItems = new ArrayList<>(); Collections.addAll(hearingTypeItems, hearings); return hearingTypeItems; } private void verifyReportHeaderIsZero(ListingData listingData) { ReportHeaderValues reportHeaderValues = new ReportHeaderValues( 0,0,0,"Newcastle", 0,0,0, 0,0,0, 0,0,0, 0,0,0); verifyReportHeader(listingData, reportHeaderValues); verifyReportDetails(listingData, 0); } private void verifyReportHeader(ListingData listingData, ReportHeaderValues reportHeaderValues) { AdhocReportType adhocReportType = listingData.getLocalReportsDetailHdr(); // Report header assertEquals(String.valueOf(reportHeaderValues.casesCompletedHearingTotal), adhocReportType.getCasesCompletedHearingTotal()); assertEquals(String.valueOf(reportHeaderValues.sessionDaysTotal), adhocReportType.getSessionDaysTotal()); assertEquals(String.format(Locale.ROOT, COMPLETED_PER_SESSION_FORMAT, reportHeaderValues.completedPerSessionTotal), adhocReportType.getCompletedPerSessionTotal()); assertEquals(reportHeaderValues.reportOffice, adhocReportType.getReportOffice()); // Conciliation - No Conciliation assertEquals(String.valueOf(reportHeaderValues.conNoneCasesCompletedHearing), adhocReportType.getConNoneCasesCompletedHearing()); assertEquals(String.valueOf(reportHeaderValues.conNoneSessionDays), adhocReportType.getConNoneSessionDays()); assertEquals(String.format(Locale.ROOT, COMPLETED_PER_SESSION_FORMAT, reportHeaderValues.conNoneCompletedPerSession), adhocReportType.getConNoneCompletedPerSession()); // Conciliation - Fast Track assertEquals(String.valueOf(reportHeaderValues.conFastCasesCompletedHearing), adhocReportType.getConFastCasesCompletedHearing()); assertEquals(String.valueOf(reportHeaderValues.conFastSessionDays), adhocReportType.getConFastSessionDays()); assertEquals(String.format(Locale.ROOT, COMPLETED_PER_SESSION_FORMAT, reportHeaderValues.conFastCompletedPerSession), adhocReportType.getConFastCompletedPerSession()); // Conciliation - Standard Track assertEquals(String.valueOf(reportHeaderValues.conStdCasesCompletedHearing), adhocReportType.getConStdCasesCompletedHearing()); assertEquals(String.valueOf(reportHeaderValues.conStdSessionDays), adhocReportType.getConStdSessionDays()); assertEquals(String.format(Locale.ROOT, COMPLETED_PER_SESSION_FORMAT, reportHeaderValues.conStdCompletedPerSession), adhocReportType.getConStdCompletedPerSession()); // Conciliation - Open Track assertEquals(String.valueOf(reportHeaderValues.conOpenCasesCompletedHearing), adhocReportType.getConOpenCasesCompletedHearing()); assertEquals(String.valueOf(reportHeaderValues.conOpenSessionDays), adhocReportType.getConOpenSessionDays()); assertEquals(String.format(Locale.ROOT, COMPLETED_PER_SESSION_FORMAT, reportHeaderValues.conOpenCompletedPerSession), adhocReportType.getConOpenCompletedPerSession()); } private void verifyReportDetails(ListingData listingData, int size) { assertEquals(size, listingData.getLocalReportsDetail().size()); } }
49.195471
127
0.711569
5b7aad3978774f7795234f87c40abda82b15f5bb
5,204
package MapperToSql; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import java.io.File; import java.util.Iterator; import java.util.List; public class MapperParse { public static String parse(File f) throws Exception { // 解析mapper.xml文件 // 创建SAXReader的对象reader SAXReader reader = new SAXReader(); String sql = ""; try { // 通过reader对象的read方法加载mapper.xml文件,获取docuemnt对象。 Document document = reader.read(f); // 通过document对象获取根节点bookstore Element mapper = document.getRootElement(); // 通过element对象的elementIterator方法获取迭代器 Iterator it = mapper.elementIterator(); // 遍历迭代器,获取根节点中的信息(书籍) String table = ""; String columns = ""; while (it.hasNext()) { Element resultMap = (Element) it.next(); // table = searchTable(resultMap); if (columns.trim().length() == 0) { columns = searchColumns(resultMap); } if (table.trim().length() == 0) { table = searchTable(resultMap); } if (table.trim().length() != 0 && columns.trim().length() != 0) { break; } } if (table.trim().length() != 0 && columns.trim().length() != 0) { sql = "CREATE TABLE `" + table.trim() + "` ( `id` char(36) NOT NULL COMMENT '主键ID'," + columns + "PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;\r\n"; } else { sql = "表文件 -----" + f.getName() + "----------有问题,请自行查看"; } System.out.println(sql); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } return sql; } public static String searchTable(Element e) { String table = ""; if (e.getName().equals("delete")) { List<Attribute> resultMapAttrs = e.attributes(); for (Attribute attr : resultMapAttrs) { if (attr.getName().equals("id") && attr.getValue().equals("deleteByPrimaryKey")) { String delSql = e.getText(); table = delSql.substring(delSql.indexOf("from") + 4, delSql.indexOf("where")).replaceAll("\n\t\t", ""); } } } return table; } public static String searchColumns(Element el) { String sql = ""; if (el.getName().equals("resultMap")) { List<Attribute> resultMapAttrs = el.attributes(); for (Attribute attr : resultMapAttrs) { if (attr.getName().equals("id") && attr.getValue().equals("BaseResultMap")) { Iterator itt = el.elementIterator(); while (itt.hasNext()) { Element result = (Element) itt.next(); if (!result.getName().equals("id")) { List<Attribute> resultAttrs = result.attributes(); for (Attribute resultAttr : resultAttrs) { if (resultAttr.getName().equals("column")) { sql = sql + "`" + resultAttr.getValue() + "` "; } if (resultAttr.getName().equals("jdbcType")) { if (resultAttr.getValue().equals("VARCHAR")) { sql = sql + " varchar(50) DEFAULT NULL, "; } if (resultAttr.getValue().equals("TIMESTAMP")) { sql = sql + " datetime DEFAULT NULL, "; } if (resultAttr.getValue().equals("CHAR")) { sql = sql + " char(36) DEFAULT NULL, "; } if (resultAttr.getValue().equals("DATE")) { sql = sql + " date DEFAULT NULL, "; } if (resultAttr.getValue().equals("DECIMAL")) { sql = sql + " decimal(18,4) DEFAULT NULL, "; } if (resultAttr.getValue().equals("TINYINT")) { sql = sql + " tinyint(4) DEFAULT NULL, "; } if (resultAttr.getValue().equals("INTEGER")) { sql = sql + " int(11) DEFAULT NULL, "; } } } } } } } } return sql; } }
41.301587
118
0.417948
de8acfbafd816e3da27347ec71616313ce7db7bb
1,122
/** * Copyright (C) 2010-16 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.rvesse.airline.restrictions.ranges; import com.github.rvesse.airline.annotations.Command; import com.github.rvesse.airline.annotations.Option; import com.github.rvesse.airline.annotations.restrictions.ranges.DoubleRange; @Command(name = "OptionDoubleRange") public class OptionDoubleRangeInclusive extends OptionRangeBase { @Option(name = "-d", title = "Double") @DoubleRange(min = 0.0d, minInclusive = true, max = 1.0d, maxInclusive = true) public double d; }
38.689655
82
0.749554
86f99836284b330b675991352efd9bc3942498a4
5,668
/* * 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 net.comze.framework.orm.util; import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.net.URL; import java.sql.Array; import java.sql.Blob; import java.sql.Clob; import java.sql.Date; import java.sql.NClob; import java.sql.Ref; import java.sql.RowId; import java.sql.SQLXML; import java.sql.Time; import java.sql.Timestamp; import net.comze.framework.orm.bind.BigDecimalWrapper; import net.comze.framework.orm.bind.BlobWrapper; import net.comze.framework.orm.bind.BooleanWrapper; import net.comze.framework.orm.bind.ByteWrapper; import net.comze.framework.orm.bind.BytesWrapper; import net.comze.framework.orm.bind.ClobWrapper; import net.comze.framework.orm.bind.ColumnWrapper; import net.comze.framework.orm.bind.DateWrapper; import net.comze.framework.orm.bind.DoubleWrapper; import net.comze.framework.orm.bind.EnumWrapper; import net.comze.framework.orm.bind.FloatWrapper; import net.comze.framework.orm.bind.IntegerWrapper; import net.comze.framework.orm.bind.LongWrapper; import net.comze.framework.orm.bind.NClobWrapper; import net.comze.framework.orm.bind.ObjectWrapper; import net.comze.framework.orm.bind.RefWrapper; import net.comze.framework.orm.bind.RowIdWrapper; import net.comze.framework.orm.bind.SQLArrayWrapper; import net.comze.framework.orm.bind.SQLDateWrapper; import net.comze.framework.orm.bind.SQLXMLWrapper; import net.comze.framework.orm.bind.ShortWrapper; import net.comze.framework.orm.bind.StringWrapper; import net.comze.framework.orm.bind.TimeWrapper; import net.comze.framework.orm.bind.TimestampWrapper; import net.comze.framework.orm.bind.URLWrapper; /** * @author <a href="mailto:gkzhong@gmail.com">GK.ZHONG</a> * @since 3.1.0 * @version ColumnWrapperFactory.java 3.2.7 Jun 14, 2014 11:30:47 AM */ public abstract class ColumnWrapperFactory { @SuppressWarnings("unchecked") public static <T> ColumnWrapper<T> wrapper(Class<T> requiredType) { if (requiredType.equals(Array.class)) { return (ColumnWrapper<T>) new SQLArrayWrapper(); } if (requiredType.equals(InputStream.class)) { return (ColumnWrapper<T>) new ObjectWrapper(); // :~ } if (requiredType.equals(BigDecimal.class)) { return (ColumnWrapper<T>) new BigDecimalWrapper(); } if (requiredType.equals(Blob.class)) { return (ColumnWrapper<T>) new BlobWrapper(); } if (requiredType.equals(Boolean.class) || requiredType.equals(Boolean.TYPE)) { return (ColumnWrapper<T>) new BooleanWrapper(); } if (requiredType.equals(byte[].class)) { return (ColumnWrapper<T>) new BytesWrapper(); } if (requiredType.equals(Byte.class) || requiredType.equals(Byte.TYPE)) { return (ColumnWrapper<T>) new ByteWrapper(); } if (requiredType.equals(Reader.class)) { return (ColumnWrapper<T>) new ObjectWrapper(); // :~ } if (requiredType.equals(Clob.class)) { return (ColumnWrapper<T>) new ClobWrapper(); } if (requiredType.equals(Date.class)) { return (ColumnWrapper<T>) new SQLDateWrapper(); } if (requiredType.equals(Double.class) || requiredType.equals(Double.TYPE)) { return (ColumnWrapper<T>) new DoubleWrapper(); } if (requiredType.equals(Float.class) || requiredType.equals(Float.TYPE)) { return (ColumnWrapper<T>) new FloatWrapper(); } if (requiredType.equals(Integer.class) || requiredType.equals(Integer.TYPE)) { return (ColumnWrapper<T>) new IntegerWrapper(); } if (requiredType.equals(Long.class) || requiredType.equals(Long.TYPE)) { return (ColumnWrapper<T>) new LongWrapper(); } if (requiredType.equals(NClob.class)) { return (ColumnWrapper<T>) new NClobWrapper(); } if (requiredType.equals(Number.class)) { return (ColumnWrapper<T>) new DoubleWrapper(); } if (requiredType.equals(Object.class)) { return (ColumnWrapper<T>) new ObjectWrapper(); } if (requiredType.equals(Ref.class)) { return (ColumnWrapper<T>) new RefWrapper(); } if (requiredType.equals(RowId.class)) { return (ColumnWrapper<T>) new RowIdWrapper(); } if (requiredType.equals(Short.class) || requiredType.equals(Short.TYPE)) { return (ColumnWrapper<T>) new ShortWrapper(); } if (requiredType.equals(SQLXML.class)) { return (ColumnWrapper<T>) new SQLXMLWrapper(); } if (requiredType.equals(String.class)) { return (ColumnWrapper<T>) new StringWrapper(); } if (requiredType.equals(Timestamp.class)) { return (ColumnWrapper<T>) new TimestampWrapper(); } if (requiredType.equals(Time.class)) { return (ColumnWrapper<T>) new TimeWrapper(); } if (requiredType.equals(URL.class)) { return (ColumnWrapper<T>) new URLWrapper(); } if (java.util.Date.class.isAssignableFrom(requiredType)) { return (ColumnWrapper<T>) new DateWrapper(); } if (requiredType.isEnum()) { return (ColumnWrapper<T>) new EnumWrapper<T>(requiredType); } return (ColumnWrapper<T>) new ObjectWrapper(); } }
36.805195
80
0.742061
549789e28c633e7463e60b3b71e0818c2776f7fc
7,283
package codepath.nytarticlesapp.activities; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.support.v4.content.LocalBroadcastManager; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.OrientationHelper; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import org.parceler.Parcels; import javax.inject.Inject; import butterknife.BindView; import butterknife.ButterKnife; import codepath.nytarticlesapp.R; import codepath.nytarticlesapp.adapters.NewsRecyclerViewAdapter; import codepath.nytarticlesapp.dialogs.SearchDialog; import codepath.nytarticlesapp.interfaces.DaggerInjector; import codepath.nytarticlesapp.interfaces.NewsCallback; import codepath.nytarticlesapp.models.NewsResponse; import codepath.nytarticlesapp.network.NYTApiClient; import codepath.nytarticlesapp.network.SearchRequest; import codepath.nytarticlesapp.utils.Constants; import codepath.nytarticlesapp.utils.EndlessRecyclerViewScrollListener; import codepath.nytarticlesapp.utils.NewsSearchListener; import codepath.nytarticlesapp.utils.SearchBroadCastReceiver; import codepath.nytarticlesapp.views.StatusView; public class MainActivity extends AppCompatActivity { @BindView(R.id.statusView) StatusView statusView; @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.newsRecyclerView) RecyclerView newsRecyclerView; StaggeredGridLayoutManager recyclerViewLayoutManager; @Inject NYTApiClient nyApiClient; private NewsRecyclerViewAdapter newsAdapter; private SearchDialog searchDialog; private SearchBroadCastReceiver mMessageReceiver; private SearchRequest lastSearchRequest; private EndlessRecyclerViewScrollListener loadMoreScrollListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); DaggerInjector.builder().build().inject(this); ButterKnife.bind(this); initGui(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main_activity, menu); MenuItem searchItem = menu.findItem(R.id.action_search); SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem); NewsSearchListener searchListener = new NewsSearchListener(this, searchView); searchView.setOnQueryTextListener(searchListener); searchListener.onQueryTextSubmit(null); return true; } @Override protected void onPause() { LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver); super.onPause(); } @Override protected void onResume() { LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter(Constants.SEARCH_REQUEST_CREATED)); super.onResume(); } private void initGui() { setSupportActionBar(toolbar); if (null != getSupportActionBar()) { getSupportActionBar().setTitle(R.string.app_title); } toolbar.setTitleTextColor(ContextCompat.getColor(this, R.color.white)); recyclerViewLayoutManager = new StaggeredGridLayoutManager(2, OrientationHelper.VERTICAL); newsRecyclerView.setLayoutManager(recyclerViewLayoutManager); newsAdapter = new NewsRecyclerViewAdapter(MainActivity.this, null); newsRecyclerView.setAdapter(newsAdapter); loadMoreScrollListener = new EndlessRecyclerViewScrollListener(recyclerViewLayoutManager) { @Override public void onLoadMore(int page, int totalItemsCount, RecyclerView view) { loadMoreNews(page); } }; newsRecyclerView.addOnScrollListener(loadMoreScrollListener); NewsCallback newsCallback = new NewsCallback() { @Override public void before(SearchRequest searchRequest) { if (searchRequest.getPage() == 1) { newsAdapter.clearData(); newsAdapter.notifyDataSetChanged(); loadMoreScrollListener.resetState(); newsRecyclerView.setVisibility(View.GONE); statusView.showLoading(); } } @Override public void onSuccess(NewsResponse response, SearchRequest searchRequest) { lastSearchRequest = searchRequest; updateResults(response, searchRequest); } @Override public void onError(Exception e, String message, SearchRequest searchRequest) { lastSearchRequest = searchRequest; updateResults(null, searchRequest); } }; mMessageReceiver = new SearchBroadCastReceiver(this, nyApiClient, newsCallback); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_advanced_search: showAdvancedDialog(); break; } return true; } private void showAdvancedDialog() { if (null == searchDialog) { searchDialog = new SearchDialog(); } searchDialog.show(getSupportFragmentManager(), "search"); } private void updateResults(NewsResponse response, SearchRequest searchRequest) { boolean secondaryPage = searchRequest.getPage() != 1; if (null != response && null != response.getResponse() && null != response.getResponse().getNews() && response.getResponse().getNews().isEmpty()) { if (secondaryPage) { return; } newsRecyclerView.setVisibility(View.GONE); statusView.showMessage(getResources().getString(R.string.empty_results)); return; } else if (null == response || null == response.getResponse()) { if (secondaryPage) { return; } newsRecyclerView.setVisibility(View.GONE); statusView.showMessage(getResources().getString(R.string.unexpected_error)); return; } statusView.hide(); newsRecyclerView.setVisibility(View.VISIBLE); if (newsAdapter.getItemCount() == 0) { newsAdapter.setNewsList(response.getResponse().getNews()); } else { newsAdapter.addPage(response.getResponse().getNews()); } newsAdapter.notifyDataSetChanged(); } private void loadMoreNews(int nextPage) { lastSearchRequest.setPage(nextPage + 1); Intent searchIntent = new Intent(Constants.SEARCH_REQUEST_CREATED); searchIntent.putExtra("data", Parcels.wrap(lastSearchRequest)); LocalBroadcastManager.getInstance(this).sendBroadcast(searchIntent); } }
35.70098
155
0.696142