hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
923175917ba40e20d81612107b6de8fcd3d61ff1 | 447 | java | Java | src/test/java/leetcode/oo/design/TrieTestCase.java | strogiyotec/leetcode-oo | dee7a2241338ed328a0736f9d0b08fb85ae2a435 | [
"MIT"
] | 4 | 2021-02-14T03:25:43.000Z | 2021-05-03T16:51:47.000Z | src/test/java/leetcode/oo/design/TrieTestCase.java | mdfraz13/leetcode-oo | 33931610fed983254460cb18aeea0e295f347cb7 | [
"MIT"
] | 1 | 2020-10-13T18:00:37.000Z | 2020-10-13T18:00:37.000Z | src/test/java/leetcode/oo/design/TrieTestCase.java | mdfraz13/leetcode-oo | 33931610fed983254460cb18aeea0e295f347cb7 | [
"MIT"
] | 1 | 2021-02-15T14:26:56.000Z | 2021-02-15T14:26:56.000Z | 23.526316 | 50 | 0.621924 | 995,851 | package leetcode.oo.design;
import org.junit.Assert;
import org.junit.Test;
public final class TrieTestCase {
@Test
public void test() {
final Trie trie = new Trie();
trie.insert("apple");
Assert.assertTrue(trie.search("apple"));
Assert.assertFalse(trie.search("app"));
Assert.assertTrue(trie.startsWith("app"));
trie.insert("app");
Assert.assertTrue(trie.search("app"));
}
}
|
92317591809af60bbfcd92245d03c134ddf8e15f | 3,462 | java | Java | computer-core/src/main/java/com/baidu/hugegraph/computer/core/compute/input/ReusablePointer.java | jadepeng/hugegraph-computer | 8308ffdd4872ed16d321336e55cb1305c323c7c2 | [
"Apache-2.0"
] | 16 | 2021-07-15T14:01:23.000Z | 2022-02-17T17:40:50.000Z | computer-core/src/main/java/com/baidu/hugegraph/computer/core/compute/input/ReusablePointer.java | jadepeng/hugegraph-computer | 8308ffdd4872ed16d321336e55cb1305c323c7c2 | [
"Apache-2.0"
] | 80 | 2021-07-15T03:17:39.000Z | 2022-03-11T21:11:01.000Z | computer-core/src/main/java/com/baidu/hugegraph/computer/core/compute/input/ReusablePointer.java | jadepeng/hugegraph-computer | 8308ffdd4872ed16d321336e55cb1305c323c7c2 | [
"Apache-2.0"
] | 8 | 2021-08-19T06:44:51.000Z | 2022-01-19T06:25:43.000Z | 32.35514 | 80 | 0.669266 | 995,852 | /*
* Copyright 2017 HugeGraph Authors
*
* 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 com.baidu.hugegraph.computer.core.compute.input;
import java.io.IOException;
import com.baidu.hugegraph.computer.core.common.Constants;
import com.baidu.hugegraph.computer.core.common.exception.ComputerException;
import com.baidu.hugegraph.computer.core.io.IOFactory;
import com.baidu.hugegraph.computer.core.io.RandomAccessInput;
import com.baidu.hugegraph.computer.core.io.RandomAccessOutput;
import com.baidu.hugegraph.computer.core.io.Readable;
import com.baidu.hugegraph.computer.core.store.hgkvfile.entry.Pointer;
import com.baidu.hugegraph.computer.core.util.BytesUtil;
public class ReusablePointer implements Pointer, Readable {
private int length;
private byte[] bytes;
private RandomAccessInput input;
public ReusablePointer() {
this.bytes = Constants.EMPTY_BYTES;
this.length = 0;
this.input = IOFactory.createBytesInput(this.bytes);
}
public ReusablePointer(byte[] bytes, int length) {
this.bytes = bytes;
this.length = length;
this.input = IOFactory.createBytesInput(this.bytes);
}
@Override
public void read(RandomAccessInput in) throws IOException {
this.length = in.readFixedInt();
if (this.bytes.length < this.length) {
this.bytes = new byte[this.length];
this.input = IOFactory.createBytesInput(this.bytes);
}
in.readFully(this.bytes, 0, this.length);
}
@Override
public RandomAccessInput input() {
try {
this.input.seek(0L);
} catch (IOException e) {
throw new ComputerException(
"ResuablePointer can't seek to position 0", e);
}
return this.input;
}
/**
* Only [0 .. length) of the returned byte array is valid. The extra data
* [length .. bytes.length) is meaningless, may be left by previous pointer.
*/
@Override
public byte[] bytes() {
return this.bytes;
}
@Override
public void write(RandomAccessOutput output) throws IOException {
output.writeFixedInt(this.length);
output.write(this.bytes(), 0, this.length);
}
@Override
public long offset() {
return 0L;
}
@Override
public long length() {
return this.length;
}
@Override
public int compareTo(Pointer other) {
try {
return BytesUtil.compare(this.bytes(), this.length,
other.bytes(), (int) other.length());
} catch (IOException e) {
throw new ComputerException(e.getMessage(), e);
}
}
}
|
9231763b2f87d590c1fda583b96b5b109853946a | 3,930 | java | Java | carnvial-purchase/common-module/src/main/java/com/splendid/common/bean/order/OrderState.java | mliyz/springcloud | 4ce873cf87378aa4587645aacdc8d9df8dc2c5e0 | [
"MIT"
] | 6 | 2018-07-25T08:05:20.000Z | 2018-10-09T01:33:33.000Z | carnvial-purchase/common-module/src/main/java/com/splendid/common/bean/order/OrderState.java | mliyz/springcloud | 4ce873cf87378aa4587645aacdc8d9df8dc2c5e0 | [
"MIT"
] | null | null | null | carnvial-purchase/common-module/src/main/java/com/splendid/common/bean/order/OrderState.java | mliyz/springcloud | 4ce873cf87378aa4587645aacdc8d9df8dc2c5e0 | [
"MIT"
] | null | null | null | 17.863636 | 66 | 0.505598 | 995,853 | package com.splendid.common.bean.order;
import java.io.Serializable;
import java.util.Date;
public class OrderState implements Serializable {
/**
*
*/
private String tid;
/**
* 流水号
*/
private String serialNo;
/**
* 订单状态
*/
private String status;
/**
* 创建时间
*/
private Date createDate;
/**
*
*/
private String updateBy;
/**
* 更新时间
*/
private Date updateDate;
/**
* 原因
*/
private String remark;
/**
* 版本
*/
private Integer version;
/**
* 状态
*/
private Integer state;
/**
* tb_ord_state
*/
private static final long serialVersionUID = 1L;
/**
*
* @return tid
*/
public String getTid() {
return tid;
}
/**
*
* @param tid
*/
public void setTid(String tid) {
this.tid = tid == null ? null : tid.trim();
}
/**
* 流水号
* @return serial_no 流水号
*/
public String getSerialNo() {
return serialNo;
}
/**
* 流水号
* @param serialNo 流水号
*/
public void setSerialNo(String serialNo) {
this.serialNo = serialNo == null ? null : serialNo.trim();
}
/**
* 订单状态
* @return status 订单状态
*/
public String getStatus() {
return status;
}
/**
* 订单状态
* @param status 订单状态
*/
public void setStatus(String status) {
this.status = status == null ? null : status.trim();
}
/**
* 创建时间
* @return create_date 创建时间
*/
public Date getCreateDate() {
return createDate;
}
/**
* 创建时间
* @param createDate 创建时间
*/
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
/**
*
* @return update_by
*/
public String getUpdateBy() {
return updateBy;
}
/**
*
* @param updateBy
*/
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy == null ? null : updateBy.trim();
}
/**
* 更新时间
* @return update_date 更新时间
*/
public Date getUpdateDate() {
return updateDate;
}
/**
* 更新时间
* @param updateDate 更新时间
*/
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
/**
* 原因
* @return remark 原因
*/
public String getRemark() {
return remark;
}
/**
* 原因
* @param remark 原因
*/
public void setRemark(String remark) {
this.remark = remark == null ? null : remark.trim();
}
/**
* 版本
* @return version 版本
*/
public Integer getVersion() {
return version;
}
/**
* 版本
* @param version 版本
*/
public void setVersion(Integer version) {
this.version = version;
}
/**
* 状态
* @return state 状态
*/
public Integer getState() {
return state;
}
/**
* 状态
* @param state 状态
*/
public void setState(Integer state) {
this.state = state;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", tid=").append(tid);
sb.append(", serialNo=").append(serialNo);
sb.append(", status=").append(status);
sb.append(", createDate=").append(createDate);
sb.append(", updateBy=").append(updateBy);
sb.append(", updateDate=").append(updateDate);
sb.append(", remark=").append(remark);
sb.append(", version=").append(version);
sb.append(", state=").append(state);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} |
923176beb99110b954422a531c71a4a8fa49b116 | 1,258 | java | Java | Anki Source Analyzer/src/main/java/ph/rye/anki/util/Ano2.java | roycetech/Anki-Tools | d9cc5ddd45e1af20a4497d204394255c0f47002d | [
"Apache-2.0"
] | null | null | null | Anki Source Analyzer/src/main/java/ph/rye/anki/util/Ano2.java | roycetech/Anki-Tools | d9cc5ddd45e1af20a4497d204394255c0f47002d | [
"Apache-2.0"
] | null | null | null | Anki Source Analyzer/src/main/java/ph/rye/anki/util/Ano2.java | roycetech/Anki-Tools | d9cc5ddd45e1af20a4497d204394255c0f47002d | [
"Apache-2.0"
] | null | null | null | 22.872727 | 76 | 0.647854 | 995,854 | /**
* Copyright 2016 Royce Remulla
*
* 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 ph.rye.anki.util;
import ph.rye.common.lang.Ano;
/**
* Another nice Object too.
*
* Can be used to avoid re-assignment in the client code.
*
* @author royce
*/
public class Ano2<T, U> extends Ano<T> {
private transient U value2;
public Ano2() {
this(null, null);
}
public Ano2(final T defaultValue1, final U defaultValue2) {
super(defaultValue1);
value2 = defaultValue2;
}
public U get2() {
return value2;
}
@Override
public String toString() {
return super.toString() + ", " + value2 == null ? "null"
: value2.toString();
}
}
|
923177d5a206ec203d0f285f0d2a98e7d3cad0bd | 7,638 | java | Java | modules/shoes-web/src/main/java/com/shoes/scarecrow/web/controller/GoodsController.java | youwenqian/scarecrow | 5dfdcbc7c43e1e0bc094885c30f3bcfe7246e08a | [
"Unlicense"
] | 2 | 2018-02-26T08:52:49.000Z | 2018-03-05T06:26:06.000Z | modules/shoes-web/src/main/java/com/shoes/scarecrow/web/controller/GoodsController.java | youwenqian/scarecrow | 5dfdcbc7c43e1e0bc094885c30f3bcfe7246e08a | [
"Unlicense"
] | null | null | null | modules/shoes-web/src/main/java/com/shoes/scarecrow/web/controller/GoodsController.java | youwenqian/scarecrow | 5dfdcbc7c43e1e0bc094885c30f3bcfe7246e08a | [
"Unlicense"
] | 1 | 2018-02-26T08:52:53.000Z | 2018-02-26T08:52:53.000Z | 41.064516 | 137 | 0.614428 | 995,855 | package com.shoes.scarecrow.web.controller;
import com.shoes.scarecrow.persistence.domain.Goods;
import com.shoes.scarecrow.persistence.domain.GoodsCondition;
import com.shoes.scarecrow.persistence.service.GoodsService;
import org.apache.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;
/**
* Create with IntelliJ IDEA
* Create by zz
* Date 18-4-24
* Time 下午9:32
*/
@Controller
@RequestMapping("/goods")
public class GoodsController {
private static Logger log = Logger.getLogger(BrandController.class);
@Autowired
private GoodsService goodsService;
@RequestMapping("/allDetail")
@ResponseBody
public Map<String, Object> getBrandDetailByPage(int page, int limit, HttpSession session, HttpServletResponse response) {
log.info(session.getAttribute("userName") + "进入到分页获取商品信息的方法,limit=" + limit + ",page=" + page);
Map<String,Object> map = new HashMap<>();
GoodsCondition goodsCondition = new GoodsCondition();
Integer userId = Integer.valueOf(String.valueOf(session.getAttribute("userId")));
goodsCondition.setUserId(userId);
goodsCondition.setStatus(1);
goodsCondition.setPage(null);
goodsCondition.setStartRow(null);
goodsCondition.setPageSize(null);
int total = goodsService.queryCountByCondition(goodsCondition);
goodsCondition.setPage(page);
goodsCondition.setPageSize(limit);
int start = (page-1)*limit;
goodsCondition.setStartRow(start);
List<Goods> list = goodsService.queryByCondition(goodsCondition);
ObjectMapper mapper = new ObjectMapper();
/* List<Map<String,Object>> list = new ArrayList<>();
for(int i=0;i<50;i++){
Map<String,Object> map1 = new HashMap<String,Object>();
map1.put("id",i);
map1.put("userId",i);
map1.put("price",987.98d);
map1.put("keyword","关键字");
map1.put("goodsType","商品分类");
map1.put("goodsName","商品"+i);
map1.put("goodsBrand","品牌"+i);
map1.put("goodsSize",i+"码");
map1.put("goodsColor","颜色");
map1.put("sex","男鞋");map1.put("goodsColor","颜色");
map1.put("createTime",new Date());
map1.put("createUser","创建人");
map1.put("updateTime",new Date());
map1.put("updateUser","更新人");
map1.put("remark","颜色很好看");
list.add(map1);
}
int end = page*limit<=list.size()?page*limit:list.size();
List<Map<String,Object>> list2 = list.subList(start,end);*/
map.put("code","0");
map.put("msg","");
map.put("count",50);
map.put("count",total);
map.put("data",list);
try {
log.info(session.getAttribute("userName")+"退出分页获取商品信息的方法,result="+mapper.writeValueAsString(map));
} catch (IOException e) {
e.printStackTrace();
}
/* ObjectMapper objectMapper = new ObjectMapper();
try{
String retStr = objectMapper.writeValueAsString(map);
response.setCharacterEncoding("utf-8");
PrintWriter printWriter = response.getWriter();
printWriter.print(retStr);
}catch (IOException e){
log.error("请求goods/allDetail.do。"+e.getMessage());
}*/
return map;
}
@RequestMapping("/deleteType/{id}")
@ResponseBody
public Map deleteGoodsById(@PathVariable("id") Integer goodId, HttpServletResponse response, HttpSession session){
log.info(session.getAttribute("userName") + "进入到删除商品信息的方法,删除商品id="+goodId);
Map<String,Object> map = new HashMap<>();
map.put("success",true);
return map;
}
@RequestMapping("/updateGoods")
@ResponseBody
public Map putGoods(Goods goods, String goodsSize, HttpSession session){
Map<String,Object> map = new HashMap<>();
ObjectMapper objMapper = new ObjectMapper();
try {
log.info(session.getAttribute("userName")+"进入修改商品信息方法,修改的商品信息="+objMapper.writeValueAsString(goods)+" goodsSize="+goodsSize);
} catch (IOException e) {
e.printStackTrace();
}
map.put("success",true);
try {
log.info(session.getAttribute("userName")+"离开修改商品信息方法,修改的商品信息="+objMapper.writeValueAsString(goods)+" goodsSize="+goodsSize);
} catch (IOException e) {
e.printStackTrace();
}
return map ;
}
@RequestMapping("/addGoods")
@ResponseBody
public Map postGoods(Goods goods, String goodsSize, HttpSession session){
Map<String,Object> map = new HashMap<>();
Integer goodSize = Integer.valueOf(goodsSize);
ObjectMapper objMapper = new ObjectMapper();
try {
log.info(session.getAttribute("userName")+"进入添加商品信息方法,修改的商品信息="+objMapper.writeValueAsString(goods)+" goodsSize="+goodSize);
} catch (IOException e) {
e.printStackTrace();
}
goodsService.saveGoods(goods,goodSize);
map.put("success",true);
try {
log.info(session.getAttribute("userName")+"离开添加商品信息方法,修改的商品信息="+objMapper.writeValueAsString(goods)+" goodsSize="+goodsSize);
} catch (IOException e) {
e.printStackTrace();
}
return map ;
}
@RequestMapping("/getGoods")
@ResponseBody
public Map getGoods(int page, int limit, Goods goods, String goodsSize, HttpSession session){
Map<String,Object> map = new HashMap<>();
ObjectMapper objMapper = new ObjectMapper();
try {
log.info(session.getAttribute("userName")+"进入查找商品信息方法,查找的商品信息="+objMapper.writeValueAsString(goods)+" goodsSize="+goodsSize);
} catch (IOException e) {
e.printStackTrace();
}
ObjectMapper mapper = new ObjectMapper();
List<Map<String,Object>> list = new ArrayList<>();
for(int i=0;i<50;i++){
Map<String,Object> map1 = new HashMap<String,Object>();
map1.put("id",i);
map1.put("userId",i);
map1.put("price",987.98d);
map1.put("keyword","关键字");
map1.put("goodsType","商品分类");
map1.put("goodsName","商品"+i);
map1.put("goodsBrand","品牌"+i);
map1.put("goodsSize",i+"码");
map1.put("goodsColor","颜色");
map1.put("sex","男鞋");map1.put("goodsColor","颜色");
map1.put("createTime",new Date());
map1.put("createUser","创建人");
map1.put("updateTime",new Date());
map1.put("updateUser","更新人");
map1.put("remark","颜色很好看");
list.add(map1);
}
map.put("code","0");
map.put("msg","");
map.put("count",50);
int start = (page-1)*limit;
int end = page*limit<=list.size()?page*limit:list.size();
List<Map<String,Object>> list2 = list.subList(start,end);
map.put("data",list2);
try {
log.info(session.getAttribute("userName")+"离开查找商品信息方法,修改的商品信息="+objMapper.writeValueAsString(goods));
} catch (IOException e) {
e.printStackTrace();
}
return map ;
}
}
|
9231782311a60fce399db06306bbb1c984353e18 | 2,520 | java | Java | java/com/android/dialer/logging/LoggingBindingsStub.java | unknownyard/packages_apps_Dialer | 889165652e2bf4688593d590bc36741740be8890 | [
"Apache-2.0"
] | 34 | 2017-01-17T07:05:15.000Z | 2022-03-04T02:45:13.000Z | java/com/android/dialer/logging/LoggingBindingsStub.java | unknownyard/packages_apps_Dialer | 889165652e2bf4688593d590bc36741740be8890 | [
"Apache-2.0"
] | 10 | 2017-01-14T02:21:01.000Z | 2020-01-19T17:08:11.000Z | java/com/android/dialer/logging/LoggingBindingsStub.java | unknownyard/packages_apps_Dialer | 889165652e2bf4688593d590bc36741740be8890 | [
"Apache-2.0"
] | 285 | 2016-12-28T19:54:49.000Z | 2022-03-26T09:24:56.000Z | 32.307692 | 100 | 0.777778 | 995,856 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.android.dialer.logging;
import android.app.Activity;
import android.widget.QuickContactBadge;
import java.util.Collection;
/** Default implementation for logging bindings. */
public class LoggingBindingsStub implements LoggingBindings {
@Override
public void logImpression(DialerImpression.Type dialerImpression) {}
@Override
public void logImpression(int dialerImpression) {}
@Override
public void logCallImpression(
DialerImpression.Type dialerImpression, String callId, long callStartTimeMillis) {}
@Override
public void logInteraction(InteractionEvent.Type interaction) {}
@Override
public void logScreenView(ScreenEvent.Type screenEvent, Activity activity) {}
@Override
public void logSpeedDialContactComposition(
int counter,
int starredContactsCount,
int pinnedContactsCount,
int multipleNumbersContactsCount,
int contactsWithPhotoCount,
int contactsWithNameCount,
int lightbringerReachableContactsCount) {}
@Override
public void sendHitEventAnalytics(String category, String action, String label, long value) {}
@Override
public void logQuickContactOnTouch(
QuickContactBadge quickContact,
InteractionEvent.Type interactionEvent,
boolean shouldPerformClick) {}
@Override
public void logPeopleApiLookupReportWithError(
long latency, int httpResponseCode, PeopleApiLookupError.Type errorType) {}
@Override
public void logSuccessfulPeopleApiLookupReport(long latency, int httpResponseCode) {}
@Override
public void logAutoBlockedCall(String phoneNumber) {}
@Override
public void logAnnotatedCallLogMetrics(int invalidNumbersInCallLog) {}
@Override
public void logAnnotatedCallLogMetrics(int numberRowsThatDidPop, int numberRowsThatDidNotPop) {}
@Override
public void logContactsProviderMetrics(Collection<ContactsProviderMatchInfo> matchInfos) {}
}
|
923178a0292ea7b3dd0b128d79a92e9560326921 | 7,058 | java | Java | src/entity/building/room.java | DiDongDongDi/dormitory | 49feee448928bfb0d5e73bffa334e6fe97101246 | [
"MIT"
] | 3 | 2019-07-09T00:02:33.000Z | 2019-07-09T07:48:43.000Z | src/entity/building/room.java | DiDongDongDi/dormitory | 49feee448928bfb0d5e73bffa334e6fe97101246 | [
"MIT"
] | null | null | null | src/entity/building/room.java | DiDongDongDi/dormitory | 49feee448928bfb0d5e73bffa334e6fe97101246 | [
"MIT"
] | 1 | 2019-07-12T02:25:40.000Z | 2019-07-12T02:25:40.000Z | 28.691057 | 124 | 0.507934 | 995,857 | package entity.building;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
import DataBase.*;
public class room {
private int blockId;
private int floorId;
private int roomId;
private int contain;
private boolean []bedId;
private double elecBillBala;
private double healScore;
public void change(){
Scanner scanner=new Scanner(System.in);
while(true){
System.out.println("请输入您要更新的信息:\n1. 电费余量\n2. 卫生分数");
int choose=scanner.nextInt();
if(choose==1){
while(true){
System.out.println("请输入新的电费余量:");
double ch=scanner.nextDouble();
setElecBillBala(ch);
break;
}
break;
}
if(choose==2){
while(true){
System.out.println("请输入新的卫生分数:");
double ch=scanner.nextDouble();
if(ch<0){
System.out.println("您的输入有误, 请重新输入!");
}
else{
setHealScore(ch);
break;
}
}
break;
}
}
}
public void setElecBillBala(double elecBillBala) {
this.elecBillBala = elecBillBala;
}
public double getElecBillBala() {
return elecBillBala;
}
public void setHealScore(double healScore) {
this.healScore = healScore;
}
public double getHealScore() {
return healScore;
}
public room()
{contain=4;}
public int getBlockId() {
return blockId;
}
public void setBlockId(int blockId) {
this.blockId = blockId;
}
public room(int fI,int rI)
{
floorId=fI;
roomId=rI;
bedId=new boolean[4];
for(int i=0;i<4;i++)
{
bedId[i]=false;//初始化,四个床都没有人住进来哪个床哪个true
}
contain=4;//一个宿舍最多住四个人,住进去一个--,出来一个++
}
public room(int bI, int fI, int rI)
{
blockId=bI;
bedId=new boolean[4];
for(int i=0;i<4;i++)
{
bedId[i]=false;//初始化,四个床都没有人住进来哪个床哪个true
}
contain=4;//一个宿舍最多住四个人,住进去一个--,出来一个++
this.floorId=fI;
this.roomId=rI;
}
public boolean[] getBedId() {
return bedId;
}
public int getRoomId() {
return roomId;
}
public void setRoomId(int roomId) {
this.roomId = roomId;
}
public int getFloorId() {
return floorId;
}
public void setFloorId(int floorId) {
this.floorId = floorId;
}
public int getContain() {
return contain;
}
public void setContain(int contain) {
this.contain = contain;
}
public void gotoBed(int bedid)//调用这个函数来入住具体床位
{
if(bedId[bedid]==true)
{
System.out.println("该床位已占用!");
return;
}
else
bedId[bedid]=true;
System.out.println("入住成功!");
}
private static boolean If_roomExists(int blockId,int floorId,int roomId){ //给定房间信息判断是否存在于数据库,静态,仅供操作数据库的方法内部使用
try{
PreparedStatement pstmt = null;
String sql="select * from rooms where buildId=? and floorId=? and roomId=?";//查找的sql
pstmt=DataBase.getConnection().prepareStatement(sql);
pstmt.setInt(1,blockId);
pstmt.setInt(2,floorId);
pstmt.setInt(3,roomId);
ResultSet rs=pstmt.executeQuery();
return rs.next();//是否找到room ?(boolean)
}catch (SQLException e) {
System.out.println("查找房间是否存在异常!");//此处最后可以注释掉
//e.printStackTrace(); //此处最后可以注释掉
return false;
}
}
public int display(int blockId,int floorId,int roomId){//给定房间查找并打印--hwt
//查找失败返回1
//未找到返回3
//直接从数据库查找显示即可
if(!If_roomExists(blockId,floorId,roomId)){//房间不存在
return 3;
}
try{
PreparedStatement pstmt = null;
String sql="select * from rooms where buildId=? and floorId=? and roomId=?";//查找的sql
pstmt=DataBase.getConnection().prepareStatement(sql);
pstmt.setInt(1,blockId);
pstmt.setInt(2,floorId);
pstmt.setInt(3,roomId);
ResultSet rs=pstmt.executeQuery();
System.out.println("宿舍楼号\t\t楼层号\t\t房间号\t\t电费余额\t\t卫生评分");
while(rs.next()){//打印房间信息
System.out.println(
rs.getInt(1)+"\t\t"+
rs.getInt(2)+"\t\t"+
rs.getInt(3)+"\t\t"+
rs.getDouble(4)+"\t\t"+
rs.getDouble(5));
}
return 0;//正常打印了学生信息
}catch (SQLException e) {//过程中出现异常
System.out.println("尝试显示学生信息...\n查找学生异常!");//此处最后可以注释掉
//e.printStackTrace(); //此处最后可以注释掉
return 1;
}
}
public int load(){//已有主码的房间,从数据库获得其他信息
if(!If_roomExists(getBlockId(),getFloorId(),getRoomId())){//号码不存在!
return 2;
}
else{
try{
PreparedStatement pstmt = null;
String sql="select * from rooms where buildId=? and floorId=? and roomId=?";//查找的sql
pstmt=DataBase.getConnection().prepareStatement(sql);
pstmt.setInt(1,blockId);
pstmt.setInt(2,floorId);
pstmt.setInt(3,roomId);
ResultSet rs=pstmt.executeQuery();
rs.next();
setElecBillBala(rs.getDouble(4));
setHealScore(rs.getDouble(5));//
return 0;//load successfully
}catch (SQLException e) {//load room过程中出现异常
System.out.println("加载房间信息异常!");//此处最后可以注释掉
e.printStackTrace(); //此处最后可以注释掉
return 1;
}
}
}
public int update(){
if(!If_roomExists(getBlockId(),getFloorId(),getRoomId())){//号码不存在!
return 2;
}
else{
try{
PreparedStatement pstmt = null;
String sql="update rooms set elecBillBala=?,healScore=? where buildId=? and floorId=? and roomId=?";//查找的sql
pstmt=DataBase.getConnection().prepareStatement(sql);
pstmt.setDouble(1,getElecBillBala());
pstmt.setDouble(2,getHealScore());
pstmt.setInt(3,blockId);
pstmt.setInt(4,floorId);
pstmt.setInt(5,roomId);
pstmt.executeUpdate();
return 0;//update successfully
}catch (SQLException e) {//load room过程中出现异常
System.out.println("更新房间信息异常!");//此处最后可以注释掉
e.printStackTrace(); //此处最后可以注释掉
return 1;
}
}
}
}
|
923178e5547a71047980c1ab02472c077a50c12b | 484 | java | Java | src/org/appwork/utils/ColorUtils.java | friedlwo/AppWoksUtils | 35a2b21892432ecaa563f042305dfaeca732a856 | [
"Artistic-2.0"
] | 2 | 2015-08-30T13:01:19.000Z | 2020-06-07T19:54:25.000Z | src/org/appwork/utils/ColorUtils.java | friedlwo/AppWoksUtils | 35a2b21892432ecaa563f042305dfaeca732a856 | [
"Artistic-2.0"
] | null | null | null | src/org/appwork/utils/ColorUtils.java | friedlwo/AppWoksUtils | 35a2b21892432ecaa563f042305dfaeca732a856 | [
"Artistic-2.0"
] | null | null | null | 23.047619 | 100 | 0.578512 | 995,858 | package org.appwork.utils;
import java.awt.Color;
public class ColorUtils {
/**
* Returns a color instance which has the given alpha value
*
* @param background
* @param alpha
* 0-255
* @return
*/
public static Color getAlphaInstance(final Color background, final int alpha) {
final Color ret = new Color(background.getRGB() & 0x00FFFFFF | (alpha & 0xFF) << 24, true);
return ret;
}
}
|
9231794fce0029a8f4054b58c3b67d6b2897305c | 1,114 | java | Java | src/main/java/br/com/zupacademy/bruno/proposta/controller/exceptions/ControllerExceptionHandler.java | brunolitzenberger/orange-talents-03-template-proposta | ecb5827b30898d1822d54fcb6ffd6567473ec2b4 | [
"Apache-2.0"
] | null | null | null | src/main/java/br/com/zupacademy/bruno/proposta/controller/exceptions/ControllerExceptionHandler.java | brunolitzenberger/orange-talents-03-template-proposta | ecb5827b30898d1822d54fcb6ffd6567473ec2b4 | [
"Apache-2.0"
] | null | null | null | src/main/java/br/com/zupacademy/bruno/proposta/controller/exceptions/ControllerExceptionHandler.java | brunolitzenberger/orange-talents-03-template-proposta | ecb5827b30898d1822d54fcb6ffd6567473ec2b4 | [
"Apache-2.0"
] | null | null | null | 34.8125 | 175 | 0.824955 | 995,859 | package br.com.zupacademy.bruno.proposta.controller.exceptions;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import feign.FeignException;
@RestControllerAdvice
public class ControllerExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<StandardError> validation(MethodArgumentNotValidException e, HttpServletRequest request){
ValidationError err = new ValidationError(System.currentTimeMillis(), HttpStatus.UNPROCESSABLE_ENTITY.value(), "Erro de validação", e.getMessage(), request.getRequestURI());
for (FieldError x : e.getBindingResult().getFieldErrors()) {
err.addError(x.getField(), x.getDefaultMessage());
}
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(err);
}
}
|
92317994a45892ff26c008794261395773b0e34c | 2,091 | java | Java | src/main/java/com/magc/sensecane/controller/LoginControllerImpl.java | g-gar/SensecaneDesktop-JavaFX | 08b37b6e9a9796532968336aa197c0efc65a9ac4 | [
"MIT"
] | null | null | null | src/main/java/com/magc/sensecane/controller/LoginControllerImpl.java | g-gar/SensecaneDesktop-JavaFX | 08b37b6e9a9796532968336aa197c0efc65a9ac4 | [
"MIT"
] | null | null | null | src/main/java/com/magc/sensecane/controller/LoginControllerImpl.java | g-gar/SensecaneDesktop-JavaFX | 08b37b6e9a9796532968336aa197c0efc65a9ac4 | [
"MIT"
] | null | null | null | 27.513158 | 155 | 0.654711 | 995,860 | package com.magc.sensecane.controller;
import java.net.URL;
import java.util.function.Consumer;
import com.magc.sensecane.Application;
import com.magc.sensecane.Configuration;
import com.magc.sensecane.framework.javafx.controller.AbstractController;
import com.magc.sensecane.model.domain.User;
import com.magc.sensecane.service.AuthService;
import com.magc.sensecane.util.ChangeView;
import javafx.fxml.FXML;
import javafx.scene.control.TextField;
public class LoginControllerImpl extends AbstractController implements LoginController {
@FXML
private TextField username;
@FXML
private TextField password;
public LoginControllerImpl(URL fxml) {
super(fxml);
}
@Override
public void start() {
username.setText("patient1");
password.setText("patient1");
}
@Override
public void destroy() {
password.setText("");
}
@Override @FXML
public void login() {
Consumer<User> onComplete = user -> {
System.out.println(user);
Application.getInstance().execute(() -> {
if (user != null) {
Application.getInstance().get(Configuration.class).put("user", user);
ChangeView.execute(MainController.class);
}
});
};
Runnable onError = () -> {
Application.getInstance().execute(() -> {
password.setText("");
});
};
AuthService.authenticate(username.getText(), password.getText(), onComplete, onError);
// Application.getInstance().get(Configuration.class).put("user", new User(1, "admin", "2342352341532", "admin", "admin", "doctor", "324123513451324n"));
// String[] types = new String[] {"patient", "carer", "doctor"};
// for (int i = 0; i < 200000000; i++) {
// int rand = new Random().nextInt(types.length - 1 + 1);
// String type = types[rand];
// String dni = NifUtil.generaNif();
//
// while (dni == null) { dni = NifUtil.generaNif();}
//
// User usr = new User(null, type+i, dni, type, ""+i, type);
// UserService.createUser(usr, type+i, u -> {}, () -> {});
// }
}
@Override
public void exit() {
System.exit(0);
}
}
|
92317a814389897588d1a9cff79297f76bf1a151 | 1,109 | java | Java | test-framework/junit5/src/main/java/io/quarkus/test/junit/NativeImageTest.java | n1hility/quarkus-ci | f66babef34f647aa899a393af6dfd5c90b1dd44e | [
"Apache-2.0"
] | 1 | 2020-10-28T14:38:36.000Z | 2020-10-28T14:38:36.000Z | test-framework/junit5/src/main/java/io/quarkus/test/junit/NativeImageTest.java | n1hility/quarkus-ci | f66babef34f647aa899a393af6dfd5c90b1dd44e | [
"Apache-2.0"
] | 182 | 2019-12-16T10:38:33.000Z | 2021-08-02T16:57:21.000Z | test-framework/junit5/src/main/java/io/quarkus/test/junit/NativeImageTest.java | n1hility/quarkus-ci | f66babef34f647aa899a393af6dfd5c90b1dd44e | [
"Apache-2.0"
] | 2 | 2020-02-06T13:30:00.000Z | 2020-11-04T03:17:21.000Z | 36.966667 | 108 | 0.785392 | 995,861 | package io.quarkus.test.junit;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.junit.jupiter.api.extension.ExtendWith;
/**
* Annotation that indicates that this test should be run using a native image,
* rather than in the JVM.
*
* The standard usage pattern is expected to be a base test class that runs the
* tests using the JVM version of Quarkus, with a subclass that extends the base
* test and is annotated with this annotation to perform the same checks against
* the native image.
*
* Note that it is not possible to mix JVM and native image tests in the same test
* run, it is expected that the JVM tests will be standard unit tests that are
* executed by surefire, while the native image tests will be integration tests
* executed by failsafe.
*
*/
@Target(ElementType.TYPE)
@ExtendWith({ DisabledOnNativeImageCondition.class, QuarkusTestExtension.class, NativeTestExtension.class })
@Retention(RetentionPolicy.RUNTIME)
public @interface NativeImageTest {
}
|
92317be730cd0fc10854edc42501706becf572b4 | 3,288 | java | Java | solace-jms-sample-app-jndi/src/main/java/jndidemo/JndiConsumerConfiguration.java | SolaceDev/solace-jms-spring-boot | afb90c408cdff643a6998f4a0c2f1c845664aed1 | [
"Apache-2.0"
] | 7 | 2020-02-06T22:19:26.000Z | 2022-03-15T06:01:06.000Z | solace-jms-sample-app-jndi/src/main/java/jndidemo/JndiConsumerConfiguration.java | SolaceDev/solace-jms-spring-boot | afb90c408cdff643a6998f4a0c2f1c845664aed1 | [
"Apache-2.0"
] | 13 | 2020-02-09T07:47:13.000Z | 2022-03-11T17:54:50.000Z | solace-spring-boot-samples/solace-jms-sample-app-jndi/src/main/java/jndidemo/JndiConsumerConfiguration.java | Nephery/solace-spring-boot | 68af7fb5ea1bade0b7385886dd187231eea6f97e | [
"Apache-2.0"
] | 7 | 2020-02-03T20:19:20.000Z | 2021-10-07T04:55:57.000Z | 36.533333 | 99 | 0.757908 | 995,862 | package jndidemo;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import javax.jms.ConnectionFactory;
import javax.naming.NamingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.support.destination.JndiDestinationResolver;
import org.springframework.jndi.JndiObjectFactoryBean;
import org.springframework.jndi.JndiTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ErrorHandler;
@EnableJms
@Configuration
public class JndiConsumerConfiguration {
@Value("${solace.jms.demoConnectionFactoryJndiName}")
private String connectionFactoryJndiName;
@Autowired
private JndiTemplate jndiTemplate;
private static final Logger logger = LoggerFactory.getLogger(JndiConsumerConfiguration.class);
private JndiObjectFactoryBean consumerConnectionFactory() {
JndiObjectFactoryBean factoryBean = new JndiObjectFactoryBean();
factoryBean.setJndiTemplate(jndiTemplate);
factoryBean.setJndiName(connectionFactoryJndiName);
// following ensures all the properties are injected before returning
try {
factoryBean.afterPropertiesSet();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (NamingException e) {
e.printStackTrace();
}
return factoryBean;
}
// Configure the destination resolver for the consumer:
// Here we are using JndiDestinationResolver for JNDI destinations
// Other options include using DynamicDestinationResolver for non-JNDI destinations
private JndiDestinationResolver consumerJndiDestinationResolver() {
JndiDestinationResolver jdr = new JndiDestinationResolver();
jdr.setCache(true);
jdr.setJndiTemplate(jndiTemplate);
return jdr;
}
// Example configuration of the JmsListenerContainerFactory
@Bean
public DefaultJmsListenerContainerFactory cFactory(DemoErrorHandler errorHandler) {
DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
factory.setConnectionFactory((ConnectionFactory) consumerConnectionFactory().getObject());
factory.setDestinationResolver(consumerJndiDestinationResolver());
factory.setErrorHandler(errorHandler);
factory.setConcurrency("3-10");
return factory;
}
@Service
public class DemoErrorHandler implements ErrorHandler{
public void handleError(Throwable t) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(os);
t.printStackTrace(ps);
try {
String output = os.toString("UTF8");
logger.error("============= Error processing message: " + t.getMessage()+"\n"+output);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
}
|
92317cacb8c058c98b97cc1b3d5b93b97c8b1ea9 | 2,259 | java | Java | src/test/java/vua/pavic/ZhoonstagramApi/services/CommentIntegrationTest.java | Pig3on/ZhoonstagramApi | 6f40a8087dffc2dea75527f39ca98314a6b2a547 | [
"MIT"
] | null | null | null | src/test/java/vua/pavic/ZhoonstagramApi/services/CommentIntegrationTest.java | Pig3on/ZhoonstagramApi | 6f40a8087dffc2dea75527f39ca98314a6b2a547 | [
"MIT"
] | null | null | null | src/test/java/vua/pavic/ZhoonstagramApi/services/CommentIntegrationTest.java | Pig3on/ZhoonstagramApi | 6f40a8087dffc2dea75527f39ca98314a6b2a547 | [
"MIT"
] | null | null | null | 30.12 | 74 | 0.739265 | 995,863 | package vua.pavic.ZhoonstagramApi.services;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.junit4.SpringRunner;
import vua.pavic.ZhoonstagramApi.db.CommentRepository;
import vua.pavic.ZhoonstagramApi.db.PostRepository;
import vua.pavic.ZhoonstagramApi.model.Comment;
import vua.pavic.ZhoonstagramApi.model.Post;
import vua.pavic.ZhoonstagramApi.services.CommentService;
import vua.pavic.ZhoonstagramApi.services.CommentServiceImpl;
import vua.pavic.ZhoonstagramApi.services.PostService;
import vua.pavic.ZhoonstagramApi.services.PostServiceImpl;
import java.util.ArrayList;
import java.util.List;
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
@RunWith(SpringRunner.class)
@DataJpaTest
public class CommentIntegrationTest {
@TestConfiguration
static class CommentServiceImplTestContextConfiguration {
@Bean
public CommentService employeeService() {
return new CommentServiceImpl();
}
}
@Autowired
private CommentService commentService;
@MockBean
private CommentRepository commentRepository;
@MockBean
private PostRepository postRepository;
@Before
public void setUp() {
Post post = new Post(1);
List<Comment> comments = new ArrayList<>();
Comment c = new Comment();
c.setPost(post);
c.setPost(post);
c.setPost(post);
comments.add(c);
comments.add(c);
Mockito.when(postRepository.getOne(post.getId()))
.thenReturn(post);
Mockito.when(commentRepository.findAllByPost(post))
.thenReturn(comments);
}
@Test
public void whenValidId_thenPostShouldBeFound() {
long id = 1;
List<Comment> found = commentService.getCommentsByPostId(id);
assertThat(found.size()).isEqualTo(2);
}
}
|
92317ce7ddcc557c1156e5cbd9a068af1a271a82 | 4,610 | java | Java | cibet-core/src/main/java/com/logitags/cibet/sensor/pojo/CustomAspect.java | Jurrie/cibet | 7867e43d77876a170539a5a1e42cf5f4927e9a91 | [
"Apache-2.0"
] | 7 | 2017-07-05T05:58:24.000Z | 2021-12-20T10:08:37.000Z | cibet-core/src/main/java/com/logitags/cibet/sensor/pojo/CustomAspect.java | Jurrie/cibet | 7867e43d77876a170539a5a1e42cf5f4927e9a91 | [
"Apache-2.0"
] | 11 | 2020-03-04T21:46:49.000Z | 2021-12-17T12:29:21.000Z | cibet-core/src/main/java/com/logitags/cibet/sensor/pojo/CustomAspect.java | Jurrie/cibet | 7867e43d77876a170539a5a1e42cf5f4927e9a91 | [
"Apache-2.0"
] | 2 | 2019-02-01T07:50:03.000Z | 2021-03-18T12:09:43.000Z | 39.067797 | 121 | 0.619523 | 995,864 | /*
*******************************************************************************
* L O G I T A G S
* Software and Programming
* Dr. Wolfgang Winter
* Germany
*
* All rights reserved
*
* Copyright 2012 Dr. Wolfgang Winter
*
* 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.logitags.cibet.sensor.pojo;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import com.logitags.cibet.sensor.common.Invoker;
import com.logitags.cibet.sensor.ejb.EJBInvoker;
@Aspect
public abstract class CustomAspect extends AbstractAspect {
private Log log = LogFactory.getLog(CustomAspect.class);
private static Boolean springAvailable;
@Pointcut
abstract void cibetIntercept();
@Around(value = "cibetIntercept()", argNames = "thisJoinPoint")
public Object doIntercept(ProceedingJoinPoint thisJoinPoint) throws Throwable {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Class<? extends Invoker> factoryClass = PojoInvoker.class;
Object invokedObject = thisJoinPoint.getTarget();
if (invokedObject != null) {
// check if EJB
final String stateless = "javax.ejb.Stateless";
final String stateful = "javax.ejb.Stateful";
try {
@SuppressWarnings("unchecked")
Class<? extends Annotation> statelessClass = (Class<? extends Annotation>) classLoader.loadClass(stateless);
@SuppressWarnings("unchecked")
Class<? extends Annotation> statefulClass = (Class<? extends Annotation>) classLoader.loadClass(stateful);
if (invokedObject.getClass().getAnnotation(statelessClass) != null
|| invokedObject.getClass().getAnnotation(statefulClass) != null) {
factoryClass = EJBInvoker.class;
}
} catch (ClassNotFoundException e) {
log.info("Failed to instantiate " + stateless);
}
// check if Spring bean
if (factoryClass == PojoInvoker.class && isSpringAvailable()) {
try {
final String springInvokerClassname = "com.logitags.cibet.sensor.pojo.SpringBeanInvoker";
@SuppressWarnings("unchecked")
Class<? extends Invoker> springInvokerClass = (Class<? extends Invoker>) classLoader
.loadClass(springInvokerClassname);
Method createMethod = springInvokerClass.getMethod("createInstance", (Class<?>[]) null);
Object springInvoker = createMethod.invoke(null, (Object[]) null);
if (springInvoker != null) {
Method findBean = springInvokerClass.getMethod("findBean", Class.class);
Object bean = findBean.invoke(springInvoker, invokedObject.getClass());
if (bean != null) {
factoryClass = springInvokerClass;
}
}
} catch (ClassNotFoundException e) {
log.info(e.getMessage());
}
}
log.debug("CustomAspect uses " + factoryClass + " for class " + invokedObject.getClass().getName());
}
return doIntercept(thisJoinPoint, factoryClass, null);
}
private boolean isSpringAvailable() {
if (springAvailable == null) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
try {
classLoader.loadClass("org.springframework.context.ApplicationContextAware");
springAvailable = true;
} catch (Throwable e) {
springAvailable = false;
}
}
return springAvailable;
}
}
|
92317e09676729191d86424feafe71cadd0fe34e | 1,108 | java | Java | java/debugger/impl/src/com/intellij/debugger/ui/HotSwapUI.java | nvartolomei/intellij-community | 1aac326dadacf65d45decc25cef21f94f7b80d69 | [
"Apache-2.0"
] | 2 | 2019-04-28T07:48:50.000Z | 2020-12-11T14:18:08.000Z | java/debugger/impl/src/com/intellij/debugger/ui/HotSwapUI.java | nvartolomei/intellij-community | 1aac326dadacf65d45decc25cef21f94f7b80d69 | [
"Apache-2.0"
] | 2 | 2022-02-19T09:45:05.000Z | 2022-02-27T20:32:55.000Z | java/debugger/impl/src/com/intellij/debugger/ui/HotSwapUI.java | nvartolomei/intellij-community | 1aac326dadacf65d45decc25cef21f94f7b80d69 | [
"Apache-2.0"
] | 2 | 2020-03-15T08:57:37.000Z | 2020-04-07T04:48:14.000Z | 41.037037 | 140 | 0.788809 | 995,865 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.debugger.ui;
import com.intellij.openapi.project.Project;
import com.intellij.debugger.impl.DebuggerSession;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public abstract class HotSwapUI {
public static HotSwapUI getInstance(Project project) {
return project.getService(HotSwapUI.class);
}
public abstract void reloadChangedClasses(@NotNull DebuggerSession session, boolean compileBeforeHotswap);
public abstract void reloadChangedClasses(@NotNull DebuggerSession session, boolean compileBeforeHotswap,
@Nullable HotSwapStatusListener callback);
public abstract void compileAndReload(@NotNull DebuggerSession session, VirtualFile @NotNull ... files);
public abstract void addListener(HotSwapVetoableListener listener);
public abstract void removeListener(HotSwapVetoableListener listener);
}
|
92317e0ed0c6fdae1a139f5a008d9583667ddc9b | 5,602 | java | Java | src/test/java/com/codeborne/selenide/impl/WebDriverThreadLocalContainerTest.java | wallaceok/selenide | 6cc7f977f98d3fdf606b6143929435b03a7703ba | [
"MIT"
] | 2 | 2018-11-25T14:50:44.000Z | 2021-12-09T07:27:50.000Z | src/test/java/com/codeborne/selenide/impl/WebDriverThreadLocalContainerTest.java | wallaceok/selenide | 6cc7f977f98d3fdf606b6143929435b03a7703ba | [
"MIT"
] | null | null | null | src/test/java/com/codeborne/selenide/impl/WebDriverThreadLocalContainerTest.java | wallaceok/selenide | 6cc7f977f98d3fdf606b6143929435b03a7703ba | [
"MIT"
] | null | null | null | 34.795031 | 133 | 0.773117 | 995,866 | package com.codeborne.selenide.impl;
import com.codeborne.selenide.Configuration;
import com.codeborne.selenide.WebDriverRunner;
import com.codeborne.selenide.webdriver.WebDriverFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.openqa.selenium.NoSuchSessionException;
import org.openqa.selenium.NoSuchWindowException;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.UnreachableBrowserException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.logging.Handler;
import java.util.logging.Logger;
import java.util.logging.StreamHandler;
import static com.codeborne.selenide.Configuration.FileDownloadMode.HTTPGET;
import static com.codeborne.selenide.Configuration.FileDownloadMode.PROXY;
import static com.codeborne.selenide.Selenide.close;
import static java.lang.Thread.currentThread;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.*;
public class WebDriverThreadLocalContainerTest {
private final WebDriverThreadLocalContainer container = spy(new WebDriverThreadLocalContainer());
private static final Logger log =
Logger.getLogger(WebDriverThreadLocalContainer.class.getName()); // matches the logger in the affected class
private static OutputStream logCapturingStream;
private static StreamHandler customLogHandler;
private static String getTestCapturedLog() {
customLogHandler.flush();
return logCapturingStream.toString();
}
@Before
public void setUp() {
container.factory = mock(WebDriverFactory.class);
doReturn(mock(WebDriver.class)).when(container.factory).createWebDriver(any());
doReturn(mock(WebDriver.class)).when(container.factory).createWebDriver(null);
WebDriverRunner.setProxy(null);
logCapturingStream = new ByteArrayOutputStream();
Handler[] handlers = log.getParent().getHandlers();
customLogHandler = new StreamHandler(logCapturingStream, handlers[0].getFormatter());
log.addHandler(customLogHandler);
}
@After
public void tearDown() {
WebDriverRunner.setProxy(null);
close();
}
@Test
public void createWebDriverWithoutProxy() {
Configuration.fileDownload = HTTPGET;
container.createDriver();
verify(container.factory).createWebDriver(null);
}
@Test
public void createWebDriverWithSelenideProxyServer() {
Configuration.fileDownload = PROXY;
container.createDriver();
ArgumentCaptor<Proxy> captor = ArgumentCaptor.forClass(Proxy.class);
verify(container.factory).createWebDriver(captor.capture());
assertThat(captor.getValue().getHttpProxy(), is(notNullValue()));
assertThat(captor.getValue().getSslProxy(), is(notNullValue()));
}
@Test
public void checksIfBrowserIsStillAlive() {
Configuration.reopenBrowserOnFail = true;
WebDriver webdriver = mock(WebDriver.class);
container.THREAD_WEB_DRIVER.put(currentThread().getId(), webdriver);
assertSame(webdriver, container.getAndCheckWebDriver());
verify(container).isBrowserStillOpen(any());
}
@Test
public void doesNotReopenBrowserIfItFailed() {
Configuration.reopenBrowserOnFail = false;
WebDriver webdriver = mock(WebDriver.class);
container.THREAD_WEB_DRIVER.put(currentThread().getId(), webdriver);
assertSame(webdriver, container.getAndCheckWebDriver());
verify(container, never()).isBrowserStillOpen(any());
}
@Test
public void checksIfBrowserIsStillAlive_byCallingGetTitle() {
WebDriver webdriver = mock(WebDriver.class);
doReturn("blah").when(webdriver).getTitle();
assertThat(container.isBrowserStillOpen(webdriver), is(true));
}
@Test
public void isBrowserStillOpen_UnreachableBrowserException() {
WebDriver webdriver = mock(WebDriver.class);
doThrow(UnreachableBrowserException.class).when(webdriver).getTitle();
assertThat(container.isBrowserStillOpen(webdriver), is(false));
}
@Test
public void isBrowserStillOpen_NoSuchWindowException() {
WebDriver webdriver = mock(WebDriver.class);
doThrow(NoSuchWindowException.class).when(webdriver).getTitle();
assertThat(container.isBrowserStillOpen(webdriver), is(false));
}
@Test
public void isBrowserStillOpen_NoSuchSessionException() {
WebDriver webdriver = mock(WebDriver.class);
doThrow(NoSuchSessionException.class).when(webdriver).getTitle();
assertThat(container.isBrowserStillOpen(webdriver), is(false));
}
@Test
public void closeWebDriverLoggingWhenProxyIsAdded() throws IOException {
Configuration.holdBrowserOpen = false;
Configuration.fileDownload = PROXY;
Proxy mockedProxy = Mockito.mock(Proxy.class);
when(mockedProxy.getHttpProxy()).thenReturn("selenide:0");
container.setProxy(mockedProxy);
container.createDriver();
ChromeDriver mockedWebDriver = Mockito.mock(ChromeDriver.class);
container.setWebDriver(mockedWebDriver);
container.closeWebDriver();
String capturedLog = getTestCapturedLog();
String currentThreadId = String.valueOf(currentThread().getId());
assertThat(capturedLog, containsString(String.format("Close webdriver: %s -> %s", currentThreadId, mockedWebDriver.toString())));
assertThat(capturedLog, containsString(String.format("Close proxy server: %s ->", currentThreadId)));
}
}
|
92317e222216f980f278b38872b4327fc557c8ad | 5,554 | java | Java | jsettlers.main.swing/src/main/java/jsettlers/main/swing/lookandfeel/ui/ButtonUiStone.java | Da-Krause/settlers-remake | 1e19b8007193d96e9307b4af26ce6c770d61d1db | [
"MIT"
] | 392 | 2015-04-05T18:07:04.000Z | 2022-03-26T21:36:46.000Z | jsettlers.main.swing/src/main/java/jsettlers/main/swing/lookandfeel/ui/ButtonUiStone.java | Marvi-Marv/settlers-remake | 0c4734186c7e08a3c9b0d0860e1c32e8a2cd9efa | [
"MIT"
] | 648 | 2015-04-06T12:12:07.000Z | 2022-02-05T17:45:20.000Z | jsettlers.main.swing/src/main/java/jsettlers/main/swing/lookandfeel/ui/ButtonUiStone.java | Marvi-Marv/settlers-remake | 0c4734186c7e08a3c9b0d0860e1c32e8a2cd9efa | [
"MIT"
] | 157 | 2015-04-05T19:54:09.000Z | 2022-02-12T20:00:51.000Z | 31.737143 | 150 | 0.71462 | 995,867 | /*******************************************************************************
* Copyright (c) 2016 - 2018
*
* 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 jsettlers.main.swing.lookandfeel.ui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.swing.AbstractButton;
import javax.swing.ButtonModel;
import javax.swing.JComponent;
import javax.swing.JToggleButton;
import javax.swing.plaf.basic.BasicButtonUI;
import jsettlers.main.swing.lookandfeel.DrawHelper;
import jsettlers.main.swing.lookandfeel.ui.img.UiImageLoader;
/**
* Button UI Implementation
*
* @author Andreas Butti
*/
public class ButtonUiStone extends BasicButtonUI {
/**
* Background Image
*/
private final BufferedImage backgroundImage = UiImageLoader.get("ui_button/ui_button-bg.png");
/**
* Background Image pressed
*/
private final BufferedImage backgroundImagePressed = UiImageLoader.get("ui_button_down/ui_button-bg.png");
/**
* Border images if the Button is not pressed
*/
private final BufferedImage[] BORDER_NORMAL = { UiImageLoader.get("ui_button/ui_button-corner-upper-left.png"),
UiImageLoader.get("ui_button/ui_button-border-top.png"),
UiImageLoader.get("ui_button/ui_button-corner-upper-right.png"),
UiImageLoader.get("ui_button/ui_button-border-right.png"),
UiImageLoader.get("ui_button/ui_button-corner-bottom-right.png"),
UiImageLoader.get("ui_button/ui_button-border-bottom.png"),
UiImageLoader.get("ui_button/ui_button-corner-bottom_left.png"),
UiImageLoader.get("ui_button/ui_button-border-left.png")
};
/**
* Border images if the Button is pressed
*/
private final BufferedImage[] BORDER_DOWN = { UiImageLoader.get("ui_button_down/ui_button-corner-upper-left.png"),
UiImageLoader.get("ui_button_down/ui_button-border-top.png"),
UiImageLoader.get("ui_button_down/ui_button-corner-upper-right.png"),
UiImageLoader.get("ui_button_down/ui_button-border-right.png"),
UiImageLoader.get("ui_button_down/ui_button-corner-bottom-right.png"),
UiImageLoader.get("ui_button_down/ui_button-border-bottom.png"),
UiImageLoader.get("ui_button_down/ui_button-corner-bottom_left.png"),
UiImageLoader.get("ui_button_down/ui_button-border-left.png")
};
/**
* Scale factor of the border
*/
private final float scale;
/**
* Text padding
*/
private int textPaddingTopBottom;
/**
* Text padding
*/
private int textPaddingLeftRight;
/**
* Constructor
*
* @param scale
* Scale factor of the border
* @param textPaddingTopBottom
* Text padding
* @param textPaddingLeftRight
* Text padding
*/
public ButtonUiStone(float scale, int textPaddingTopBottom, int textPaddingLeftRight) {
this.scale = scale;
this.textPaddingTopBottom = textPaddingTopBottom;
this.textPaddingLeftRight = textPaddingLeftRight;
}
@Override
public void installDefaults(AbstractButton button) {
button.setFont(UIDefaults.FONT);
button.setForeground(UIDefaults.LABEL_TEXT_COLOR);
}
@Override
public void uninstallDefaults(AbstractButton b) {
}
@Override
public void paint(Graphics g1, JComponent c) {
Graphics2D g = DrawHelper.enableAntialiasing(g1);
AbstractButton b = (AbstractButton) c;
ButtonModel model = b.getModel();
boolean down;
if (c instanceof JToggleButton) {
down = ((JToggleButton) c).isSelected();
} else {
down = model.isArmed() && model.isPressed();
}
BufferedImage bg;
BufferedImage[] border;
float scale = this.scale;
if (down) {
border = BORDER_DOWN;
scale /= 2;
bg = backgroundImagePressed;
} else {
bg = backgroundImage;
border = BORDER_NORMAL;
}
// Draw background
g.drawImage(bg, 0, 0, c);
BorderHelper.drawBorder(g1, c, border, scale);
FontMetrics fm = g.getFontMetrics();
int y = (b.getHeight() - fm.getAscent() - fm.getDescent()) / 2 + fm.getAscent();
int x = textPaddingLeftRight;
if (down) {
x += 1;
y += 1;
}
g.setFont(c.getFont());
// draw shadow
g.setColor(Color.BLACK);
g.drawString(b.getText(), x + 1, y + 1);
g.setColor(c.getForeground());
g.drawString(b.getText(), x, y);
}
@Override
public Dimension getPreferredSize(JComponent c) {
Dimension size = super.getPreferredSize(c);
size.width += textPaddingLeftRight * 2;
size.height += textPaddingTopBottom * 2;
return size;
}
} |
92317f5696e53207400cbc6abafe19f0dc58cd07 | 31,317 | java | Java | mr/src/main/java/org/elasticsearch/hadoop/rest/RestService.java | vroyer/elasticsearch-hadoop | 8059356b8384b0a637342dc04fc8a42561b06d8e | [
"Apache-2.0"
] | 1 | 2016-09-06T08:11:48.000Z | 2016-09-06T08:11:48.000Z | mr/src/main/java/org/elasticsearch/hadoop/rest/RestService.java | vroyer/elasticsearch-hadoop | 8059356b8384b0a637342dc04fc8a42561b06d8e | [
"Apache-2.0"
] | null | null | null | mr/src/main/java/org/elasticsearch/hadoop/rest/RestService.java | vroyer/elasticsearch-hadoop | 8059356b8384b0a637342dc04fc8a42561b06d8e | [
"Apache-2.0"
] | null | null | null | 44.866762 | 180 | 0.611042 | 995,868 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.hadoop.rest;
import org.apache.commons.logging.Log;
import org.elasticsearch.hadoop.EsHadoopIllegalArgumentException;
import org.elasticsearch.hadoop.cfg.ConfigurationOptions;
import org.elasticsearch.hadoop.cfg.FieldPresenceValidation;
import org.elasticsearch.hadoop.cfg.Settings;
import org.elasticsearch.hadoop.rest.query.BoolQueryBuilder;
import org.elasticsearch.hadoop.rest.query.ConstantScoreQueryBuilder;
import org.elasticsearch.hadoop.rest.query.QueryBuilder;
import org.elasticsearch.hadoop.rest.query.QueryUtils;
import org.elasticsearch.hadoop.rest.query.RawQueryBuilder;
import org.elasticsearch.hadoop.rest.request.GetAliasesRequestBuilder;
import org.elasticsearch.hadoop.serialization.ScrollReader;
import org.elasticsearch.hadoop.serialization.ScrollReader.ScrollReaderConfig;
import org.elasticsearch.hadoop.serialization.builder.ValueReader;
import org.elasticsearch.hadoop.serialization.dto.IndicesAliases;
import org.elasticsearch.hadoop.serialization.dto.NodeInfo;
import org.elasticsearch.hadoop.serialization.dto.ShardInfo;
import org.elasticsearch.hadoop.serialization.dto.mapping.Field;
import org.elasticsearch.hadoop.serialization.dto.mapping.MappingUtils;
import org.elasticsearch.hadoop.serialization.field.IndexExtractor;
import org.elasticsearch.hadoop.util.Assert;
import org.elasticsearch.hadoop.util.EsMajorVersion;
import org.elasticsearch.hadoop.util.IOUtils;
import org.elasticsearch.hadoop.util.ObjectUtils;
import org.elasticsearch.hadoop.util.SettingsUtils;
import org.elasticsearch.hadoop.util.StringUtils;
import org.elasticsearch.hadoop.util.Version;
import java.io.Closeable;
import java.io.IOException;
import java.io.Serializable;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
public abstract class RestService implements Serializable {
public static class PartitionReader implements Closeable {
public final ScrollReader scrollReader;
public final RestRepository client;
public final SearchRequestBuilder queryBuilder;
private ScrollQuery scrollQuery;
private boolean closed = false;
PartitionReader(ScrollReader scrollReader, RestRepository client, SearchRequestBuilder queryBuilder) {
this.scrollReader = scrollReader;
this.client = client;
this.queryBuilder = queryBuilder;
}
@Override
public void close() {
if (!closed) {
closed = true;
if (scrollQuery != null) {
scrollQuery.close();
}
client.close();
}
}
public ScrollQuery scrollQuery() {
if (scrollQuery == null) {
scrollQuery = queryBuilder.build(client, scrollReader);
}
return scrollQuery;
}
}
public static class PartitionWriter implements Closeable {
public final RestRepository repository;
public final int number;
public final int total;
public final Settings settings;
private boolean closed = false;
PartitionWriter(Settings settings, int splitIndex, int splitsSize, RestRepository repository) {
this.settings = settings;
this.repository = repository;
this.number = splitIndex;
this.total = splitsSize;
}
@Override
public void close() {
if (!closed) {
closed = true;
repository.close();
}
}
}
public static class MultiReaderIterator implements Closeable, Iterator {
private final List<PartitionDefinition> definitions;
private final Iterator<PartitionDefinition> definitionIterator;
private PartitionReader currentReader;
private ScrollQuery currentScroll;
private boolean finished = false;
private final Settings settings;
private final Log log;
MultiReaderIterator(List<PartitionDefinition> defs, Settings settings, Log log) {
this.definitions = defs;
definitionIterator = defs.iterator();
this.settings = settings;
this.log = log;
}
@Override
public void close() {
if (finished) {
return;
}
ScrollQuery sq = getCurrent();
if (sq != null) {
sq.close();
}
if (currentReader != null) {
currentReader.close();
}
finished = true;
}
@Override
public boolean hasNext() {
ScrollQuery sq = getCurrent();
return (sq != null ? sq.hasNext() : false);
}
private ScrollQuery getCurrent() {
if (finished) {
return null;
}
for (boolean hasValue = false; !hasValue; ) {
if (currentReader == null) {
if (definitionIterator.hasNext()) {
currentReader = RestService.createReader(settings, definitionIterator.next(), log);
} else {
finished = true;
return null;
}
}
if (currentScroll == null) {
currentScroll = currentReader.scrollQuery();
}
hasValue = currentScroll.hasNext();
if (!hasValue) {
currentScroll.close();
currentScroll = null;
currentReader.close();
currentReader = null;
}
}
return currentScroll;
}
@Override
public Object[] next() {
ScrollQuery sq = getCurrent();
return sq.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
@SuppressWarnings("unchecked")
public static List<PartitionDefinition> findPartitions(Settings settings, Log log) {
Version.logVersion();
InitializationUtils.validateSettings(settings);
InitializationUtils.validateSettingsForReading(settings);
EsMajorVersion version = InitializationUtils.discoverEsVersion(settings, log);
List<NodeInfo> nodes = InitializationUtils.discoverNodesIfNeeded(settings, log);
InitializationUtils.filterNonClientNodesIfNeeded(settings, log);
InitializationUtils.filterNonDataNodesIfNeeded(settings, log);
InitializationUtils.filterNonIngestNodesIfNeeded(settings, log);
RestRepository client = new RestRepository(settings);
try {
boolean indexExists = client.indexExists(true);
List<List<Map<String, Object>>> shards = null;
if (!indexExists) {
if (settings.getIndexReadMissingAsEmpty()) {
log.info(String.format("Index [%s] missing - treating it as empty", settings.getResourceRead()));
shards = Collections.emptyList();
} else {
throw new EsHadoopIllegalArgumentException(
String.format("Index [%s] missing and settings [%s] is set to false", settings.getResourceRead(), ConfigurationOptions.ES_INDEX_READ_MISSING_AS_EMPTY));
}
} else {
shards = client.getReadTargetShards();
if (log.isTraceEnabled()) {
log.trace("Creating splits for shards " + shards);
}
}
log.info(String.format("Reading from [%s]", settings.getResourceRead()));
Field mapping = null;
if (!shards.isEmpty()) {
mapping = client.getMapping();
if (log.isDebugEnabled()) {
log.debug(String.format("Discovered mapping {%s} for [%s]", mapping, settings.getResourceRead()));
}
// validate if possible
FieldPresenceValidation validation = settings.getReadFieldExistanceValidation();
if (validation.isRequired()) {
// MappingUtils.validateMapping(settings.getScrollFields(), mapping, validation, log);
MappingUtils.validateMapping(SettingsUtils.determineSourceFields(settings), mapping, validation, log);
}
}
final Map<String, NodeInfo> nodesMap = new HashMap<String, NodeInfo>();
if (nodes != null) {
for (NodeInfo node : nodes) {
nodesMap.put(node.getId(), node);
}
}
final List<PartitionDefinition> partitions;
if (version.onOrAfter(EsMajorVersion.V_5_X)) {
partitions = findSlicePartitions(client.getRestClient(), settings, mapping, nodesMap, shards, log);
} else {
partitions = findShardPartitions(settings, mapping, nodesMap, shards, log);
}
Collections.shuffle(partitions);
return partitions;
} finally {
client.close();
}
}
/**
* Create one {@link PartitionDefinition} per shard for each requested index.
*/
static List<PartitionDefinition> findShardPartitions(Settings settings, Field mapping, Map<String, NodeInfo> nodes,
List<List<Map<String, Object>>> shards, Log log) {
List<PartitionDefinition> partitions = new ArrayList<PartitionDefinition>(shards.size());
for (List<Map<String, Object>> group : shards) {
String index = null;
int shardId = -1;
List<String> locationList = new ArrayList<String> ();
String tokenRanges = null;
for (Map<String, Object> replica : group) {
ShardInfo shard = new ShardInfo(replica);
index = shard.getIndex();
shardId = shard.getName();
if (nodes.containsKey(shard.getNode())) {
locationList.add(nodes.get(shard.getNode()).getPublishAddress());
}
tokenRanges= shard.getTokenRanges();
}
if (index == null) {
// Could not find shards for this partition. Continue anyway?
if (settings.getIndexReadAllowRedStatus()) {
log.warn("Shard information is missing from an index and will not be reached during job execution. " +
"Assuming shard is unavailable and cluster is red! Continuing with read operation by " +
"skipping this shard! This may result in incomplete data retrieval!");
} else {
throw new IllegalStateException("Could not locate shard information for one of the read indices. " +
"Check your cluster status to see if it is unstable!");
}
} else {
PartitionDefinition partition = new PartitionDefinition(settings, mapping, index, shardId,
locationList.toArray(new String[0]), tokenRanges);
partitions.add(partition);
}
}
return partitions;
}
/**
* Partitions the query based on the max number of documents allowed per partition {@link Settings#getMaxDocsPerPartition()}.
*/
static List<PartitionDefinition> findSlicePartitions(RestClient client, Settings settings, Field mapping,
Map<String, NodeInfo> nodes, List<List<Map<String, Object>>> shards, Log log) {
QueryBuilder query = QueryUtils.parseQueryAndFilters(settings);
int maxDocsPerPartition = settings.getMaxDocsPerPartition();
String types = new Resource(settings, true).type();
List<PartitionDefinition> partitions = new ArrayList<PartitionDefinition>(shards.size());
for (List<Map<String, Object>> group : shards) {
String index = null;
int shardId = -1;
List<String> locationList = new ArrayList<String> ();
String tokenRanges = null;
for (Map<String, Object> replica : group) {
ShardInfo shard = new ShardInfo(replica);
index = shard.getIndex();
shardId = shard.getName();
if (nodes.containsKey(shard.getNode())) {
locationList.add(nodes.get(shard.getNode()).getPublishAddress());
}
tokenRanges = shard.getTokenRanges();
}
String[] locations = locationList.toArray(new String[0]);
if (index == null) {
// Could not find shards for this partition. Continue anyway?
if (settings.getIndexReadAllowRedStatus()) {
log.warn("Shard information is missing from an index and will not be reached during job execution. " +
"Assuming shard is unavailable and cluster is red! Continuing with read operation by " +
"skipping this shard! This may result in incomplete data retrieval!");
} else {
throw new IllegalStateException("Could not locate shard information for one of the read indices. " +
"Check your cluster status to see if it is unstable!");
}
} else {
StringBuilder indexAndType = new StringBuilder(index);
if (StringUtils.hasLength(types)) {
indexAndType.append("/");
indexAndType.append(types);
}
// TODO applyAliasMetaData should be called in order to ensure that the count are exact (alias filters and routing may change the number of documents)
long numDocs = client.count(indexAndType.toString(), Integer.toString(shardId), query);
int numPartitions = (int) Math.max(1, numDocs / maxDocsPerPartition);
for (int i = 0; i < numPartitions; i++) {
PartitionDefinition.Slice slice = new PartitionDefinition.Slice(i, numPartitions);
partitions.add(new PartitionDefinition(settings, mapping, index, shardId, slice, locations, tokenRanges));
}
}
}
return partitions;
}
/**
* Returns the first address in {@code locations} that is equals to a public IP of the system
* @param locations The list of address (hostname:port or ip:port) to check
* @return The first address in {@code locations} that is equals to a public IP of the system or null if none
*/
static String checkLocality(String[] locations, Log log) {
try {
InetAddress[] candidates = NetworkUtils.getGlobalInterfaces();
for (String address : locations) {
StringUtils.IpAndPort ipAndPort = StringUtils.parseIpAddress(address);
InetAddress addr = InetAddress.getByName(ipAndPort.ip);
for (InetAddress candidate : candidates) {
if (addr.equals(candidate)) {
return address;
}
}
}
} catch (SocketException e) {
if (log.isDebugEnabled()) {
log.debug("Unable to retrieve the global interfaces of the system", e);
}
} catch (UnknownHostException e) {
if (log.isDebugEnabled()) {
log.debug("Unable to retrieve IP address", e);
}
}
return null;
}
/**
* Creates a PartitionReader from a {@code PartitionDefinition}
* @param settings The settings for the reader
* @param partition The {@link PartitionDefinition} used to create the reader
* @param log The logger
* @return The {@link PartitionReader} that is able to read the documents associated with the {@code partition}
*/
public static PartitionReader createReader(Settings settings, PartitionDefinition partition, Log log) {
if (!SettingsUtils.hasPinnedNode(settings) && partition.getLocations().length > 0) {
String pinAddress = checkLocality(partition.getLocations(), log);
if (pinAddress != null) {
if (log.isDebugEnabled()) {
log.debug(String.format("Partition reader instance [%s] assigned to [%s]:[%s]", partition, pinAddress));
}
SettingsUtils.pinNode(settings, pinAddress);
}
}
EsMajorVersion version = InitializationUtils.discoverEsVersion(settings, log);
ValueReader reader = ObjectUtils.instantiate(settings.getSerializerValueReaderClassName(), settings);
// initialize REST client
//RestRepository repository = new RestRepository(settings);
// force connection to the node having the partition.
Settings nodeSettings = settings.copy().setNodes(partition.getLocations()[0]);
SettingsUtils.setDiscoveredNodes(nodeSettings, null);
RestRepository repository = new RestRepository(nodeSettings);
Field fieldMapping = null;
if (StringUtils.hasText(partition.getSerializedMapping())) {
fieldMapping = IOUtils.deserializeFromBase64(partition.getSerializedMapping());
}
else {
log.warn(String.format("No mapping found for [%s] - either no index exists or the partition configuration has been corrupted", partition));
}
ScrollReader scrollReader = new ScrollReader(new ScrollReaderConfig(reader, fieldMapping, settings));
if (settings.getNodesClientOnly()) {
String clientNode = repository.getRestClient().getCurrentNode();
if (log.isDebugEnabled()) {
log.debug(String.format("Client-node routing detected; partition reader instance [%s] assigned to [%s]",
partition, clientNode));
}
SettingsUtils.pinNode(settings, clientNode);
}
// take into account client node routing
boolean includeVersion = settings.getReadMetadata() && settings.getReadMetadataVersion();
Resource read = new Resource(settings, true);
SearchRequestBuilder requestBuilder =
new SearchRequestBuilder(version, includeVersion)
.types(read.type())
.indices(partition.getIndex())
.query(QueryUtils.parseQuery(settings))
.scroll(settings.getScrollKeepAlive())
.size(settings.getScrollSize())
.limit(settings.getScrollLimit())
.fields(SettingsUtils.determineSourceFields(settings))
.filters(QueryUtils.parseFilters(settings))
//.shard(Integer.toString(partition.getShardId()))
.shard("0")
.local(true)
.excludeSource(settings.getExcludeSource());
if (partition.getSlice() != null && partition.getSlice().max > 1) {
requestBuilder.slice(partition.getSlice().id, partition.getSlice().max);
}
String[] indices = read.index().split(",");
if (QueryUtils.isExplicitlyRequested(partition.getIndex(), indices) == false) {
IndicesAliases indicesAliases =
new GetAliasesRequestBuilder(repository.getRestClient())
.indices(partition.getIndex())
.execute().getIndices();
Map<String, IndicesAliases.Alias> aliases = indicesAliases.getAliases(partition.getIndex());
if (aliases != null && aliases.size() > 0) {
requestBuilder = applyAliasMetadata(version, aliases, requestBuilder, partition.getIndex(), indices);
}
}
return new PartitionReader(scrollReader, repository, requestBuilder);
}
/**
* Check if the index name is part of the requested indices or the result of an alias.
* If the index is the result of an alias, the filters and routing values of the alias are added in the
* provided {@link SearchRequestBuilder}.
*/
static SearchRequestBuilder applyAliasMetadata(EsMajorVersion version,
Map<String, IndicesAliases.Alias> aliases,
SearchRequestBuilder searchRequestBuilder,
String index, String... indicesOrAliases) {
if (QueryUtils.isExplicitlyRequested(index, indicesOrAliases)) {
return searchRequestBuilder;
}
Set<String> routing = new HashSet<String>();
List<QueryBuilder> aliasFilters = new ArrayList<QueryBuilder>();
for (IndicesAliases.Alias alias : aliases.values()) {
if (QueryUtils.isExplicitlyRequested(alias.getName(), indicesOrAliases)) {
// The alias is explicitly requested
if (StringUtils.hasLength(alias.getSearchRouting())) {
for (String value : alias.getSearchRouting().split(",")) {
routing.add(value.trim());
}
}
if (alias.getFilter() != null) {
try {
aliasFilters.add(new RawQueryBuilder(alias.getFilter(), false));
} catch (IOException e) {
throw new EsHadoopIllegalArgumentException("Failed to parse alias filter: [" + alias.getFilter() + "]");
}
}
}
}
if (aliasFilters.size() > 0) {
QueryBuilder aliasQuery;
if (aliasFilters.size() == 1) {
aliasQuery = aliasFilters.get(0);
} else {
aliasQuery = new BoolQueryBuilder();
for (QueryBuilder filter : aliasFilters) {
((BoolQueryBuilder) aliasQuery).should(filter);
}
}
if (searchRequestBuilder.query() == null) {
searchRequestBuilder.query(aliasQuery);
} else {
BoolQueryBuilder mainQuery = new BoolQueryBuilder();
mainQuery.must(searchRequestBuilder.query());
if (version.after(EsMajorVersion.V_1_X)) {
mainQuery.filter(aliasQuery);
} else {
mainQuery.must(new ConstantScoreQueryBuilder().filter(aliasQuery).boost(0.0f));
}
searchRequestBuilder.query(mainQuery);
}
}
if (routing.size() > 0) {
searchRequestBuilder.routing(StringUtils.concatenate(routing, ","));
}
return searchRequestBuilder;
}
// expects currentTask to start from 0
public static List<PartitionDefinition> assignPartitions(List<PartitionDefinition> partitions, int currentTask, int totalTasks) {
int esPartitions = partitions.size();
if (totalTasks >= esPartitions) {
return (currentTask >= esPartitions ? Collections.<PartitionDefinition>emptyList() : Collections.singletonList(partitions.get(currentTask)));
} else {
int partitionsPerTask = esPartitions / totalTasks;
int remainder = esPartitions % totalTasks;
int partitionsPerCurrentTask = partitionsPerTask;
// spread the reminder against the tasks
if (currentTask < remainder) {
partitionsPerCurrentTask++;
}
// find the offset inside the collection
int offset = partitionsPerTask * currentTask;
if (currentTask != 0) {
offset += (remainder > currentTask ? 1 : remainder);
}
// common case
if (partitionsPerCurrentTask == 1) {
return Collections.singletonList(partitions.get(offset));
}
List<PartitionDefinition> pa = new ArrayList<PartitionDefinition>(partitionsPerCurrentTask);
for (int index = offset; index < offset + partitionsPerCurrentTask; index++) {
pa.add(partitions.get(index));
}
return pa;
}
}
public static MultiReaderIterator multiReader(Settings settings, List<PartitionDefinition> definitions, Log log) {
return new MultiReaderIterator(definitions, settings, log);
}
public static PartitionWriter createWriter(Settings settings, int currentSplit, int totalSplits, Log log) {
Version.logVersion();
InitializationUtils.validateSettings(settings);
InitializationUtils.discoverEsVersion(settings, log);
InitializationUtils.discoverNodesIfNeeded(settings, log);
InitializationUtils.filterNonClientNodesIfNeeded(settings, log);
InitializationUtils.filterNonDataNodesIfNeeded(settings, log);
InitializationUtils.filterNonIngestNodesIfNeeded(settings, log);
List<String> nodes = SettingsUtils.discoveredOrDeclaredNodes(settings);
// check invalid splits (applicable when running in non-MR environments) - in this case fall back to Random..
int selectedNode = (currentSplit < 0) ? new Random().nextInt(nodes.size()) : currentSplit % nodes.size();
// select the appropriate nodes first, to spread the load before-hand
SettingsUtils.pinNode(settings, nodes.get(selectedNode));
Resource resource = new Resource(settings, false);
log.info(String.format("Writing to [%s]", resource));
// single index vs multi indices
IndexExtractor iformat = ObjectUtils.instantiate(settings.getMappingIndexExtractorClassName(), settings);
iformat.compile(resource.toString());
RestRepository repository = (iformat.hasPattern() ? initMultiIndices(settings, currentSplit, resource, log) : initSingleIndex(settings, currentSplit, resource, log));
return new PartitionWriter(settings, currentSplit, totalSplits, repository);
}
private static RestRepository initSingleIndex(Settings settings, int currentInstance, Resource resource, Log log) {
if (log.isDebugEnabled()) {
log.debug(String.format("Resource [%s] resolves as a single index", resource));
}
RestRepository repository = new RestRepository(settings);
// create the index if needed
if (repository.touch()) {
if (repository.waitForYellow()) {
log.warn(String.format("Timed out waiting for index [%s] to reach yellow health", resource));
}
}
if (settings.getNodesWANOnly()) {
return randomNodeWrite(settings, currentInstance, resource, log);
}
// if client-nodes are used, simply use the underlying nodes
if (settings.getNodesClientOnly()) {
String clientNode = repository.getRestClient().getCurrentNode();
if (log.isDebugEnabled()) {
log.debug(String.format("Client-node routing detected; partition writer instance [%s] assigned to [%s]",
currentInstance, clientNode));
}
return repository;
}
// no routing necessary; select the relevant target shard/node
Map<ShardInfo, NodeInfo> targetShards = Collections.emptyMap();
targetShards = repository.getWriteTargetPrimaryShards(settings.getNodesClientOnly());
repository.close();
Assert.isTrue(!targetShards.isEmpty(),
String.format("Cannot determine write shards for [%s]; likely its format is incorrect (maybe it contains illegal characters?)", resource));
List<ShardInfo> orderedShards = new ArrayList<ShardInfo>(targetShards.keySet());
// make sure the order is strict
Collections.sort(orderedShards);
if (log.isTraceEnabled()) {
log.trace(String.format("Partition writer instance [%s] discovered [%s] primary shards %s", currentInstance, orderedShards.size(), orderedShards));
}
// if there's no task info, just pick a random bucket
if (currentInstance <= 0) {
currentInstance = new Random().nextInt(targetShards.size()) + 1;
}
int bucket = currentInstance % targetShards.size();
ShardInfo chosenShard = orderedShards.get(bucket);
NodeInfo targetNode = targetShards.get(chosenShard);
// pin settings
SettingsUtils.pinNode(settings, targetNode.getPublishAddress());
String node = SettingsUtils.getPinnedNode(settings);
repository = new RestRepository(settings);
if (log.isDebugEnabled()) {
log.debug(String.format("Partition writer instance [%s] assigned to primary shard [%s] at address [%s]",
currentInstance, chosenShard.getName(), node));
}
return repository;
}
private static RestRepository initMultiIndices(Settings settings, int currentInstance, Resource resource, Log log) {
if (log.isDebugEnabled()) {
log.debug(String.format("Resource [%s] resolves as an index pattern", resource));
}
return randomNodeWrite(settings, currentInstance, resource, log);
}
private static RestRepository randomNodeWrite(Settings settings, int currentInstance, Resource resource, Log log) {
// multi-index write - since we don't know before hand what index will be used, pick a random node from the given list
List<String> nodes = SettingsUtils.discoveredOrDeclaredNodes(settings);
String node = nodes.get(new Random().nextInt(nodes.size()));
// override the global settings to communicate directly with the target node
SettingsUtils.pinNode(settings, node);
if (log.isDebugEnabled()) {
log.debug(String.format("Partition writer instance [%s] assigned to [%s]", currentInstance, node));
}
return new RestRepository(settings);
}
}
|
92317fabb354cf7b005645fd1a5bf28dbcc6a47a | 56,313 | java | Java | controllersvc/src/main/java/com/emc/storageos/volumecontroller/impl/block/VnxMaskingOrchestrator.java | CoprHD/sds-controller | a575ec96928b1e9258313efe92c930bfe9d6753a | [
"Apache-2.0"
] | 91 | 2015-06-06T01:40:34.000Z | 2020-11-24T07:26:40.000Z | controllersvc/src/main/java/com/emc/storageos/volumecontroller/impl/block/VnxMaskingOrchestrator.java | CoprHD/sds-controller | a575ec96928b1e9258313efe92c930bfe9d6753a | [
"Apache-2.0"
] | 3 | 2015-07-14T18:47:53.000Z | 2015-07-14T18:50:16.000Z | controllersvc/src/main/java/com/emc/storageos/volumecontroller/impl/block/VnxMaskingOrchestrator.java | CoprHD/sds-controller | a575ec96928b1e9258313efe92c930bfe9d6753a | [
"Apache-2.0"
] | 71 | 2015-06-05T21:35:31.000Z | 2021-11-07T16:32:46.000Z | 56.70997 | 148 | 0.589171 | 995,869 | /*
* Copyright 2015 EMC Corporation
* All Rights Reserved
*/
package com.emc.storageos.volumecontroller.impl.block;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import com.emc.storageos.customconfigcontroller.CustomConfigConstants;
import com.emc.storageos.db.client.URIUtil;
import com.emc.storageos.db.client.model.BlockObject;
import com.emc.storageos.db.client.model.BlockSnapshot;
import com.emc.storageos.db.client.model.ExportGroup;
import com.emc.storageos.db.client.model.ExportMask;
import com.emc.storageos.db.client.model.ExportPathParams;
import com.emc.storageos.db.client.model.Initiator;
import com.emc.storageos.db.client.model.StorageSystem;
import com.emc.storageos.db.client.model.StringMap;
import com.emc.storageos.db.client.model.VirtualPool;
import com.emc.storageos.db.client.model.Volume;
import com.emc.storageos.db.client.util.CommonTransformerFunctions;
import com.emc.storageos.db.client.util.NullColumnValueGetter;
import com.emc.storageos.db.client.util.StringSetUtil;
import com.emc.storageos.exceptions.DeviceControllerException;
import com.emc.storageos.svcs.errorhandling.model.ServiceError;
import com.emc.storageos.util.ExportUtils;
import com.emc.storageos.volumecontroller.BlockStorageDevice;
import com.emc.storageos.volumecontroller.impl.ControllerServiceImpl;
import com.emc.storageos.volumecontroller.impl.block.taskcompleter.ExportDeregisterInitiatorCompleter;
import com.emc.storageos.volumecontroller.impl.block.taskcompleter.ExportMaskAddInitiatorCompleter;
import com.emc.storageos.volumecontroller.impl.block.taskcompleter.ExportOrchestrationTask;
import com.emc.storageos.volumecontroller.impl.block.taskcompleter.ExportTaskCompleter;
import com.emc.storageos.volumecontroller.impl.block.taskcompleter.SnapshotWorkflowEntryPoints;
import com.emc.storageos.volumecontroller.impl.block.taskcompleter.VolumeUpdateCompleter;
import com.emc.storageos.volumecontroller.impl.utils.ExportMaskUtils;
import com.emc.storageos.volumecontroller.placement.BlockStorageScheduler;
import com.emc.storageos.workflow.Workflow;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Collections2;
import com.google.common.collect.ListMultimap;
/**
* This class will contain VNX specific masking orchestration implementations.
* The goal of this implementation would be to flexibly support export
* operations. Essentially, the export operations need to be amenable to the
* existence of exports created outside of the system. It should take to make
* sure that it does what it can to allow the operation to succeed in light of
* such cases.
*
* TODO: You'll notice several areas of code are very similar.
* Recommend refactor to consolidate methods:
* - Create, AddVolumes, AddInitiators should have its main BL in one place
* - Delete, RemoveVolumes, RemoveInitiators should have its main BL in one place
*
*/
public class VnxMaskingOrchestrator extends AbstractBasicMaskingOrchestrator {
private static final Logger _log = LoggerFactory.getLogger(VnxMaskingOrchestrator.class);
private static final AtomicReference<BlockStorageDevice> VNX_BLOCK_DEVICE = new AtomicReference<BlockStorageDevice>();
public static final String VNX_SMIS_DEVICE = "vnxSmisDevice";
public static final String DEFAULT_LABEL = "Default";
@Override
public BlockStorageDevice getDevice() {
BlockStorageDevice device = VNX_BLOCK_DEVICE.get();
synchronized (VNX_BLOCK_DEVICE) {
if (device == null) {
device = (BlockStorageDevice) ControllerServiceImpl.getBean(VNX_SMIS_DEVICE);
VNX_BLOCK_DEVICE.compareAndSet(null, device);
}
}
return device;
}
/*
* (non-Javadoc)
*
* @see
* com.emc.storageos.volumecontroller.impl.block.AbstractDefaultMaskingOrchestrator#
* generateExportMaskAddInitiatorsWorkflow(com.emc.
* storageos.workflow.Workflow, java.lang.String, com.emc.storageos.db.client.model.StorageSystem,
* com.emc.storageos.db.client.model.ExportGroup, com.emc.storageos.db.client.model.ExportMask, java.util.List,
* java.util.Set,
* java.lang.String)
*/
@Override
public String generateExportMaskAddInitiatorsWorkflow(Workflow workflow,
String previousStep,
StorageSystem storage,
ExportGroup exportGroup,
ExportMask exportMask,
List<URI> initiatorURIs,
Set<URI> newVolumeURIs,
String token)
throws Exception {
URI exportGroupURI = exportGroup.getId();
URI exportMaskURI = exportMask.getId();
URI storageURI = storage.getId();
List<URI> newTargetURIs = new ArrayList<>();
List<Initiator> initiators = null;
if (initiatorURIs != null && !initiatorURIs.isEmpty()) {
initiators = _dbClient.queryObject(Initiator.class, initiatorURIs);
}
// Allocate any new ports that are required for the initiators
// and update the zoning map in the exportMask.
Collection<URI> volumeURIs = (exportMask.getVolumes() == null) ? newVolumeURIs
: (Collection<URI>) (Collections2.transform(exportMask.getVolumes().keySet(),
CommonTransformerFunctions.FCTN_STRING_TO_URI));
ExportPathParams pathParams = _blockScheduler.calculateExportPathParamForVolumes(
volumeURIs, exportGroup.getNumPaths(), storage.getId(), exportGroup.getId());
if (exportGroup.getType() != null) {
pathParams.setExportGroupType(exportGroup.getType());
}
Map<URI, List<URI>> assignments = _blockScheduler.assignStoragePorts(storage, exportGroup, initiators,
exportMask.getZoningMap(), pathParams, volumeURIs, _networkDeviceController, exportGroup.getVirtualArray(), token);
newTargetURIs = BlockStorageScheduler.getTargetURIsFromAssignments(assignments);
exportMask.addZoningMap(BlockStorageScheduler.getZoneMapFromAssignments(assignments));
_dbClient.updateObject(exportMask);
String maskingStep = workflow.createStepId();
ExportTaskCompleter exportTaskCompleter = new ExportMaskAddInitiatorCompleter(
exportGroupURI, exportMask.getId(), initiatorURIs, newTargetURIs,
maskingStep);
Workflow.Method maskingExecuteMethod = new Workflow.Method(
"doExportGroupAddInitiators", storageURI, exportGroupURI,
exportMaskURI, new ArrayList<URI>(volumeURIs), initiatorURIs, newTargetURIs, exportTaskCompleter);
Workflow.Method rollbackMethod = new Workflow.Method(
"rollbackExportGroupAddInitiators", storageURI, exportGroupURI,
exportMaskURI, new ArrayList<URI>(volumeURIs), initiatorURIs, maskingStep);
maskingStep = workflow.createStep(EXPORT_GROUP_MASKING_TASK,
String.format("Adding initiators to mask %s (%s)",
exportMask.getMaskName(), exportMask.getId().toString()),
previousStep, storageURI, storage.getSystemType(),
MaskingWorkflowEntryPoints.class, maskingExecuteMethod,
rollbackMethod, maskingStep);
return maskingStep;
}
/**
* Create storage level masking components to support the requested
* ExportGroup object. This operation will be flexible enough to take into
* account initiators that are in some already existent in some
* StorageGroup. In such a case, the underlying masking component will be
* "adopted" by the ExportGroup. Further operations against the "adopted"
* mask will only allow for addition and removal of those initiators/volumes
* that were added by a Bourne request. Existing initiators/volumes will be
* maintained.
*
*
* @param storageURI
* - URI referencing underlying storage array
* @param exportGroupURI
* - URI referencing Bourne-level masking, ExportGroup
* @param initiatorURIs
* - List of Initiator URIs
* @param volumeMap
* - Map of Volume URIs to requested Integer URI
* @param token
* - Identifier for operation
* @throws Exception
*/
@Override
public void exportGroupCreate(URI storageURI, URI exportGroupURI, List<URI> initiatorURIs,
Map<URI, Integer> volumeMap, String token) throws Exception {
ExportOrchestrationTask taskCompleter = null;
try {
BlockStorageDevice device = getDevice();
ExportGroup exportGroup = _dbClient.queryObject(ExportGroup.class, exportGroupURI);
StorageSystem storage = _dbClient.queryObject(StorageSystem.class, storageURI);
taskCompleter = new ExportOrchestrationTask(exportGroupURI, token);
logExportGroup(exportGroup, storageURI);
if (initiatorURIs != null && !initiatorURIs.isEmpty()) {
_log.info("export_create: initiator list non-empty");
// Set up workflow steps.
Workflow workflow = _workflowService.getNewWorkflow(
MaskingWorkflowEntryPoints.getInstance(), "exportGroupCreate", true, token);
boolean createdSteps = determineExportGroupCreateSteps(workflow, null,
device, storage, exportGroup, initiatorURIs, volumeMap, false, token);
String zoningStep = generateDeviceSpecificZoningCreateWorkflow(workflow,
EXPORT_GROUP_MASKING_TASK, exportGroup, null, volumeMap);
if (createdSteps && null != zoningStep) {
// Execute the plan and allow the WorkflowExecutor to fire the
// taskCompleter.
String successMessage = String.format(
"ExportGroup successfully applied for StorageArray %s", storage.getLabel());
workflow.executePlan(taskCompleter, successMessage);
} else {
_log.info("export_create: no steps created.");
taskCompleter.ready(_dbClient);
}
} else {
_log.info("export_create: initiator list");
taskCompleter.ready(_dbClient);
}
} catch (DeviceControllerException dex) {
if (taskCompleter != null) {
taskCompleter.error(_dbClient, DeviceControllerException.errors
.vmaxExportGroupCreateError(dex.getMessage()));
}
} catch (Exception ex) {
_log.error("ExportGroup Orchestration failed.", ex);
// TODO add service code here
if (taskCompleter != null) {
ServiceError serviceError = DeviceControllerException.errors.jobFailedMsg(ex.getMessage(), ex);
taskCompleter.error(_dbClient, serviceError);
}
}
}
@Override
public void exportGroupAddVolumes(URI storageURI, URI exportGroupURI,
Map<URI, Integer> volumeMap, String token) throws Exception {
ExportOrchestrationTask taskCompleter = null;
try {
BlockStorageDevice device = getDevice();
taskCompleter = new ExportOrchestrationTask(exportGroupURI, token);
StorageSystem storage = _dbClient.queryObject(StorageSystem.class, storageURI);
ExportGroup exportGroup = _dbClient.queryObject(ExportGroup.class, exportGroupURI);
logExportGroup(exportGroup, storageURI);
boolean anyVolumesAdded = false;
boolean createdNewMask = false;
if (exportGroup != null && exportGroup.getExportMasks() != null) {
// Set up workflow steps.
Workflow workflow = _workflowService.getNewWorkflow(
MaskingWorkflowEntryPoints.getInstance(), "exportGroupAddVolumes", true,
token);
List<ExportMask> exportMasksToZoneAddVolumes = new ArrayList<ExportMask>();
List<URI> volumesToZoneAddVolumes = new ArrayList<URI>();
// Add the volume to all the ExportMasks that are contained in the
// ExportGroup. The volumes should be added only if they don't
// already exist for the ExportMask.
Collection<URI> initiatorURIs = Collections2.transform(exportGroup.getInitiators(),
CommonTransformerFunctions.FCTN_STRING_TO_URI);
List<URI> hostURIs = new ArrayList<URI>();
Map<String, URI> portNameToInitiatorURI = new HashMap<String, URI>();
List<String> portNames = new ArrayList<String>();
processInitiators(exportGroup, initiatorURIs, portNames, portNameToInitiatorURI, hostURIs);
// We always want to have the full list of initiators for the hosts involved in
// this export. This will allow the export operation to always find any
// existing exports for a given host.
queryHostInitiatorsAndAddToList(portNames, portNameToInitiatorURI,
initiatorURIs, hostURIs);
Map<String, Set<URI>> foundMatches = device.findExportMasks(storage, portNames, false);
findAndUpdateFreeHLUsForClusterExport(storage, exportGroup, new ArrayList<URI>(initiatorURIs), volumeMap);
Set<String> checkMasks = mergeWithExportGroupMaskURIs(exportGroup, foundMatches.values());
for (String maskURIStr : checkMasks) {
ExportMask exportMask = _dbClient.queryObject(ExportMask.class,
URI.create(maskURIStr));
_log.info(String.format("Checking mask %s", exportMask.getMaskName()));
// Check for NO_VIPR. If found, avoid this mask.
if (exportMask.getMaskName() != null && exportMask.getMaskName().toUpperCase().contains(ExportUtils.NO_VIPR)) {
_log.info(String.format(
"ExportMask %s disqualified because the name contains %s (in upper or lower case) to exclude it",
exportMask.getMaskName(), ExportUtils.NO_VIPR));
continue;
}
if (!exportMask.getInactive()
&& exportMask.getStorageDevice().equals(storageURI)) {
exportMask = device.refreshExportMask(storage, exportMask);
// BlockStorageDevice level, so that it has up-to-date
// info from the array
Map<URI, Integer> volumesToAdd = new HashMap<URI, Integer>();
for (URI boURI : volumeMap.keySet()) {
BlockObject bo = Volume.fetchExportMaskBlockObject(_dbClient, boURI);
if (bo != null && !exportMask.hasExistingVolume(bo.getWWN()) &&
!exportMask.hasUserAddedVolume(bo.getWWN())) {
URI thisVol = bo.getId();
Integer hlu = volumeMap.get(boURI);
volumesToAdd.put(thisVol, hlu);
}
// Check if the volume is present in existing volumes. If yes, move it to user created
// volumes
if (bo != null && exportMask.hasExistingVolume(bo.getWWN())) {
exportMask.removeFromExistingVolumes(bo);
exportMask.addToUserCreatedVolumes(bo);
_dbClient.updateObject(exportMask);
}
// Check if the requested HLU for the volume is
// already taken by a pre-existing volume.
Integer requestedHLU = volumeMap.get(boURI);
StringMap existingVolumesInMask = exportMask.getExistingVolumes();
if (existingVolumesInMask != null && requestedHLU.intValue() != ExportGroup.LUN_UNASSIGNED &&
!ExportGroup.LUN_UNASSIGNED_DECIMAL_STR.equals(requestedHLU.toString()) &&
existingVolumesInMask.containsValue(requestedHLU.toString())) {
ExportOrchestrationTask completer = new ExportOrchestrationTask(
exportGroup.getId(), token);
ServiceError serviceError = DeviceControllerException.errors
.exportHasExistingVolumeWithRequestedHLU(boURI.toString(), requestedHLU.toString());
completer.error(_dbClient, serviceError);
return;
}
}
_log.info(String.format("Mask %s, adding volumes %s",
exportMask.getMaskName(),
Joiner.on(',').join(volumesToAdd.entrySet())));
if (volumesToAdd.size() > 0) {
List<URI> volumeURIs = new ArrayList<URI>();
volumeURIs.addAll(volumesToAdd.keySet());
exportMasksToZoneAddVolumes.add(exportMask);
volumesToZoneAddVolumes.addAll(volumeURIs);
// This is the list of export masks where volumes will be added
// some may be user-created and being 'accepted' into ViPR for
// the first time. Need to update zoning map
updateZoningMap(exportGroup, exportMask, true);
generateExportMaskAddVolumesWorkflow(workflow, EXPORT_GROUP_ZONING_TASK, storage,
exportGroup, exportMask, volumesToAdd, null);
anyVolumesAdded = true;
// Need to check if the mask is not already associated with
// ExportGroup. This is case when we are adding volume to
// the export and there is an existing export on the array.
// We have to reuse that existing export, but we need also
// associated it with the ExportGroup.
if (!exportGroup.hasMask(exportMask.getId())) {
exportGroup.addExportMask(exportMask.getId());
_dbClient.updateAndReindexObject(exportGroup);
}
}
}
}
if (!anyVolumesAdded) {
String attachGroupSnapshot;
// This is the case where we were requested to add volumes to the
// export for this storage array, but none were scheduled to be
// added. This could be either because there are existing masks,
// but the volumes are already in the export mask or there are no
// masks for the storage array. We are checking if there are any
// masks and if there are initiators for the export.
if (!ExportMaskUtils.hasExportMaskForStorage(_dbClient,
exportGroup, storageURI) && exportGroup.hasInitiators()) {
_log.info("No existing masks to which the requested volumes can be added. Creating a new mask");
List<URI> initiators = StringSetUtil.stringSetToUriList(exportGroup.getInitiators());
attachGroupSnapshot = checkForSnapshotsToCopyToTarget(workflow, storage,
null, volumeMap, null);
Map<URI, List<URI>> hostInitiatorMap = new HashMap<URI, List<URI>>();
for (URI newExportMaskInitiator : initiators) {
Initiator initiator = _dbClient.queryObject(Initiator.class, newExportMaskInitiator);
// Not all initiators have hosts, be sure to handle either case.
URI hostURI = initiator.getHost();
if (hostURI == null) {
hostURI = NullColumnValueGetter.getNullURI();
}
List<URI> initiatorSet = hostInitiatorMap.get(hostURI);
if (initiatorSet == null) {
initiatorSet = new ArrayList<URI>();
hostInitiatorMap.put(hostURI, initiatorSet);
}
initiatorSet.add(initiator.getId());
_log.info(String.format("host = %s, "
+ "initiators to add: %d, ",
hostURI,
hostInitiatorMap.get(hostURI).size()));
}
if (!hostInitiatorMap.isEmpty()) {
for (URI hostID : hostInitiatorMap.keySet()) {
_log.info(String.format("new export masks %s",
Joiner.on(",").join(hostInitiatorMap.get(hostID))));
String zoningStep = workflow.createStepId();
GenExportMaskCreateWorkflowResult result = generateExportMaskCreateWorkflow(workflow, zoningStep,
storage, exportGroup,
hostInitiatorMap.get(hostID), volumeMap, token);
List<URI> masks = new ArrayList<URI>();
masks.add(result.getMaskURI());
generateZoningCreateWorkflow(workflow,
attachGroupSnapshot, exportGroup, masks, volumeMap, zoningStep);
}
createdNewMask = true;
}
}
}
if (!exportMasksToZoneAddVolumes.isEmpty()) {
generateZoningAddVolumesWorkflow(workflow, null,
exportGroup, exportMasksToZoneAddVolumes, volumesToZoneAddVolumes);
}
String successMessage = String.format(
"Successfully added volumes to export on StorageArray %s",
storage.getLabel());
workflow.executePlan(taskCompleter, successMessage);
} else {
if (exportGroup.hasInitiators()) {
_log.info("There are no masks for this export. Need to create anew.");
List<URI> initiatorURIs = new ArrayList<URI>();
for (String initiatorURIStr : exportGroup.getInitiators()) {
initiatorURIs.add(URI.create(initiatorURIStr));
}
// Invoke the export group create operation,
// which should in turn create a workflow operations to
// create the export for the newly added volume(s).
exportGroupCreate(storageURI, exportGroupURI, initiatorURIs, volumeMap, token);
anyVolumesAdded = true;
} else {
_log.warn("There are no initiator for export group: " + exportGroup.getLabel());
}
}
if (!anyVolumesAdded && !createdNewMask) {
taskCompleter.ready(_dbClient);
_log.info("No volumes pushed to array because either they already exist " +
"or there were no initiators added to the export yet.");
}
} catch (Exception ex) {
_log.error("ExportGroup Orchestration failed.", ex);
// TODO add service code here
if (taskCompleter != null) {
ServiceError serviceError = DeviceControllerException.errors.jobFailedMsg(ex.getMessage(), ex);
taskCompleter.error(_dbClient, serviceError);
}
}
}
@Override
protected boolean useComputedMaskName() {
return true;
}
@Override
protected String getMaskingCustomConfigTypeName(String exportType) {
return CustomConfigConstants.VNX_HOST_STORAGE_GROUP_MASK_NAME;
}
@Override
public void findAndUpdateFreeHLUsForClusterExport(StorageSystem storage, ExportGroup exportGroup, List<URI> initiatorURIs,
Map<URI, Integer> volumeMap) {
findUpdateFreeHLUsForClusterExport(storage, exportGroup, initiatorURIs, volumeMap);
}
/**
* Routine contains logic to create an export mask on the array
*
* @param workflow
* - Workflow object to create steps against
* @param previousStep
* - [optional] Identifier of workflow step to wait for
* @param device
* - BlockStorageDevice implementation
* @param storage
* - StorageSystem object representing the underlying array
* @param exportGroup
* - ExportGroup object representing Bourne-level masking
* @param initiatorURIs
* - List of Initiator URIs
* @param volumeMap
* - Map of Volume URIs to requested Integer HLUs
* @param zoningStepNeeded
* - No specific logic required for VNX as zoning is taken care of already.
* @param token
* - Identifier for the operation
* @throws Exception
*/
@Override
public boolean determineExportGroupCreateSteps(Workflow workflow, String waitFor,
BlockStorageDevice device, StorageSystem storage, ExportGroup exportGroup,
List<URI> initiatorURIs, Map<URI, Integer> volumeMap, boolean zoningStepNeeded, String token) throws Exception {
// If we didn't create any workflows by the end of this method, we can return an appropriate exception (instead
// of the Task just hanging)
String previousStep = waitFor;
boolean flowCreated = false;
Map<String, URI> portNameToInitiatorURI = new HashMap<String, URI>();
List<URI> volumeURIs = new ArrayList<URI>();
volumeURIs.addAll(volumeMap.keySet());
Map<URI, URI> hostToExistingExportMaskMap = new HashMap<URI, URI>();
List<URI> hostURIs = new ArrayList<URI>();
List<String> portNames = new ArrayList<String>();
// Populate the port WWN/IQNs (portNames) and the
// mapping of the WWN/IQNs to Initiator URIs
processInitiators(exportGroup, initiatorURIs, portNames, portNameToInitiatorURI, hostURIs);
// We always want to have the full list of initiators for the hosts involved in
// this export. This will allow the export operation to always find any
// existing exports for a given host.
queryHostInitiatorsAndAddToList(portNames, portNameToInitiatorURI,
initiatorURIs, hostURIs);
// Find the export masks that are associated with any or all the ports in
// portNames. We will have to do processing differently based on whether
// or there is an existing ExportMasks.
Map<String, Set<URI>> matchingExportMaskURIs = device.findExportMasks(storage, portNames, false);
/**
* COP-28674: During Vblock boot volume export, if existing masking views are found then check for existing volumes
* If found throw exception. This condition is valid only for boot volume vblock export.
*/
if (exportGroup.forHost() && ExportMaskUtils.isVblockHost(initiatorURIs, _dbClient) && ExportMaskUtils.isBootVolume(_dbClient, volumeMap)) {
_log.info("VBlock boot volume Export: Validating the storage system {} to find existing storage groups",
storage.getNativeGuid());
if (CollectionUtils.isEmpty(matchingExportMaskURIs)) {
_log.info("No existing masking views found, passed validation..");
} else {
List<String> maskNames = new ArrayList<String>();
for (Entry<String, Set<URI>> maskEntry : matchingExportMaskURIs.entrySet()) {
List<ExportMask> masks = _dbClient.queryObject(ExportMask.class, maskEntry.getValue());
if (!CollectionUtils.isEmpty(masks)) {
for (ExportMask mask : masks) {
maskNames.add(mask.getMaskName());
}
}
}
InitiatorHelper initiatorHelper = new InitiatorHelper(initiatorURIs).process(exportGroup);
Map<String, List<URI>> initiatorToComputeResourceMap = initiatorHelper.getResourceToInitiators();
Set<String> computeResourceSet = initiatorToComputeResourceMap.keySet();
ExportOrchestrationTask completer = new ExportOrchestrationTask(exportGroup.getId(), token);
ServiceError serviceError = DeviceControllerException.errors.existingMaskFoundDuringBootVolumeExport(
Joiner.on(",").join(maskNames), computeResourceSet.iterator().next());
completer.error(_dbClient, serviceError);
return false;
}
} else {
_log.info("VBlock Boot volume Export Validation : Skipping");
}
findAndUpdateFreeHLUsForClusterExport(storage, exportGroup, initiatorURIs, volumeMap);
if (matchingExportMaskURIs.isEmpty()) {
previousStep = checkForSnapshotsToCopyToTarget(workflow, storage, previousStep,
volumeMap, null);
_log.info(String.format("No existing mask found w/ initiators { %s }", Joiner.on(",")
.join(portNames)));
createNewExportMaskWorkflowForInitiators(initiatorURIs, exportGroup, workflow, volumeMap, storage, token,
previousStep);
flowCreated = true;
} else {
_log.info(String.format("Mask(s) found w/ initiators {%s}. "
+ "MatchingExportMaskURIs {%s}, portNameToInitiators {%s}", Joiner.on(",")
.join(portNames),
Joiner.on(",").join(matchingExportMaskURIs.keySet()), Joiner
.on(",").join(portNameToInitiatorURI.entrySet())));
// There are some initiators that already exist. We need to create a
// workflow that create new masking containers or updates masking
// containers as necessary.
// These data structures will be used to track new initiators - ones
// that don't already exist on the array
List<URI> initiatorURIsCopy = new ArrayList<URI>();
initiatorURIsCopy.addAll(initiatorURIs);
// This loop will determine a list of volumes to update per export mask
Map<URI, Map<URI, Integer>> existingMasksToUpdateWithNewVolumes = new HashMap<URI, Map<URI, Integer>>();
Map<URI, Set<Initiator>> existingMasksToUpdateWithNewInitiators = new HashMap<URI, Set<Initiator>>();
for (Map.Entry<String, Set<URI>> entry : matchingExportMaskURIs.entrySet()) {
URI initiatorURI = portNameToInitiatorURI.get(entry.getKey());
Initiator initiator = _dbClient.queryObject(Initiator.class, initiatorURI);
// Keep track of those initiators that have been found to exist already
// in some export mask on the array
initiatorURIsCopy.remove(initiatorURI);
// Get a list of the ExportMasks that were matched to the initiator
List<URI> exportMaskURIs = new ArrayList<URI>();
exportMaskURIs.addAll(entry.getValue());
List<ExportMask> masks = _dbClient.queryObject(ExportMask.class, exportMaskURIs);
_log.info(String.format("initiator %s masks {%s}", initiator.getInitiatorPort(),
Joiner.on(',').join(exportMaskURIs)));
for (ExportMask mask : masks) {
_log.info(String.format("mask %s has initiator %s", mask.getMaskName(),
initiator.getInitiatorPort()));
getDevice().refreshExportMask(storage, mask);
// Check for NO_VIPR. If found, avoid this mask.
if (mask.getMaskName() != null && mask.getMaskName().toUpperCase().contains(ExportUtils.NO_VIPR)) {
_log.info(String.format(
"ExportMask %s disqualified because the name contains %s (in upper or lower case) to exclude it",
mask.getMaskName(), ExportUtils.NO_VIPR));
continue;
}
if (mask.getCreatedBySystem()) {
_log.info(String.format("initiator %s is in persisted mask %s",
initiator.getInitiatorPort(),
mask.getMaskName()));
// We're still OK if the mask contains ONLY initiators that can be found
// in our export group, because we would simply add to them.
if (mask.getInitiators() != null) {
for (String existingMaskInitiatorStr : mask.getInitiators()) {
// Now look at it from a different angle. Which one of our export group initiators
// are NOT in the current mask? And if so, if it belongs to the same host as an existing
// one,
// we should add it to this mask.
Iterator<URI> initiatorIter = initiatorURIsCopy.iterator();
while (initiatorIter.hasNext()) {
Initiator initiatorCopy = _dbClient.queryObject(Initiator.class, initiatorIter.next());
if (initiatorCopy != null && initiatorCopy.getId() != null
&& !mask.hasInitiator(initiatorCopy.getId().toString())) {
Initiator existingMaskInitiator = _dbClient.queryObject(Initiator.class,
URI.create(existingMaskInitiatorStr));
if (existingMaskInitiator != null && initiatorCopy.getHost() != null &&
initiatorCopy.getHost().equals(existingMaskInitiator.getHost())) {
// Add to the list of initiators we need to add to this mask
Set<Initiator> existingMaskInitiators = existingMasksToUpdateWithNewInitiators
.get(mask.getId());
if (existingMaskInitiators == null) {
existingMaskInitiators = new HashSet<Initiator>();
existingMasksToUpdateWithNewInitiators.put(mask.getId(), existingMaskInitiators);
}
existingMaskInitiators.add(initiatorCopy);
initiatorIter.remove(); // remove this from the list of initiators we'll
// make a new mask from
}
}
}
}
}
} else {
// Insert this initiator into the mask's list of initiators managed by the system.
// This will get persisted below.
mask.addInitiator(initiator);
if (!NullColumnValueGetter.isNullURI(initiator.getHost())) {
hostToExistingExportMaskMap.put(initiator.getHost(),
mask.getId());
}
}
// We need to see if the volume also exists the mask,
// if it doesn't then we'll add it to the list of volumes to add.
for (URI boURI : volumeURIs) {
BlockObject bo = Volume.fetchExportMaskBlockObject(_dbClient, boURI);
if (bo != null && !mask.hasExistingVolume(bo)) {
_log.info(String.format("volume %s is not in mask %s", bo.getWWN(),
mask.getMaskName()));
// The volume doesn't exist, so we have to add it to
// the masking container.
Map<URI, Integer> newVolumes = existingMasksToUpdateWithNewVolumes
.get(mask.getId());
if (newVolumes == null) {
newVolumes = new HashMap<URI, Integer>();
existingMasksToUpdateWithNewVolumes.put(mask.getId(), newVolumes);
}
// Check if the requested HLU for the volume is
// already taken by a pre-existing volume.
Integer requestedHLU = volumeMap.get(boURI);
StringMap existingVolumesInMask = mask.getExistingVolumes();
if (existingVolumesInMask != null && requestedHLU.intValue() != ExportGroup.LUN_UNASSIGNED &&
!ExportGroup.LUN_UNASSIGNED_DECIMAL_STR.equals(requestedHLU.toString()) &&
existingVolumesInMask.containsValue(requestedHLU.toString())) {
ExportOrchestrationTask completer = new ExportOrchestrationTask(
exportGroup.getId(), token);
ServiceError serviceError = DeviceControllerException.errors
.exportHasExistingVolumeWithRequestedHLU(boURI.toString(), requestedHLU.toString());
completer.error(_dbClient, serviceError);
return false;
}
newVolumes.put(bo.getId(), requestedHLU);
mask.addToUserCreatedVolumes(bo);
} else if (bo != null && mask.hasExistingVolume(bo)) {
_log.info(String.format(
"volume %s is already in mask %s. Removing it from mask's existing volumes and adding to user created volumes",
bo.getWWN(), mask.getMaskName()));
String hlu = mask.getExistingVolumes().get(BlockObject.normalizeWWN(bo.getWWN()));
mask.removeFromExistingVolumes(bo);
mask.addVolume(bo.getId(), Integer.parseInt(hlu));
mask.addToUserCreatedVolumes(bo);
}
}
// Update the list of volumes and initiators for the mask
Map<URI, Integer> volumeMapForExistingMask = existingMasksToUpdateWithNewVolumes
.get(mask.getId());
if (volumeMapForExistingMask != null && !volumeMapForExistingMask.isEmpty()) {
mask.addVolumes(volumeMapForExistingMask);
}
Set<Initiator> initiatorSetForExistingMask = existingMasksToUpdateWithNewInitiators
.get(mask.getId());
if (initiatorSetForExistingMask != null && initiatorSetForExistingMask.isEmpty()) {
mask.addInitiators(initiatorSetForExistingMask);
}
updateZoningMap(exportGroup, mask);
_dbClient.updateAndReindexObject(mask);
// TODO: All export group modifications should be moved to completers
exportGroup.addExportMask(mask.getId());
_dbClient.updateAndReindexObject(exportGroup);
}
}
// The initiatorURIsCopy was used in the foreach initiator loop to see
// which initiators already exist in a mask. If it is non-empty,
// then it means there are initiators that are new,
// so let's add them to the main tracker
Map<URI, List<URI>> hostInitiatorMap = new HashMap<URI, List<URI>>();
if (!initiatorURIsCopy.isEmpty()) {
for (URI newExportMaskInitiator : initiatorURIsCopy) {
Initiator initiator = _dbClient.queryObject(Initiator.class, newExportMaskInitiator);
List<URI> initiatorSet = hostInitiatorMap.get(initiator.getHost());
if (initiatorSet == null) {
initiatorSet = new ArrayList<URI>();
hostInitiatorMap.put(initiator.getHost(), initiatorSet);
}
initiatorSet.add(initiator.getId());
_log.info(String.format("host = %s, "
+ "initiators to add: %d, "
+ "existingMasksToUpdateWithNewVolumes.size = %d",
initiator.getHost(),
hostInitiatorMap.get(initiator.getHost()).size(),
existingMasksToUpdateWithNewVolumes.size()));
}
}
_log.info(String.format("existingMasksToUpdateWithNewVolumes.size = %d",
existingMasksToUpdateWithNewVolumes.size()));
previousStep = checkForSnapshotsToCopyToTarget(workflow, storage, previousStep,
volumeMap, existingMasksToUpdateWithNewVolumes.values());
// At this point we have the necessary data structures populated to
// determine the workflow steps. We are going to create new masks
// and/or add volumes to existing masks.
if (!hostInitiatorMap.isEmpty()) {
for (URI hostID : hostInitiatorMap.keySet()) {
// Check if there is an existing mask (created outside of ViPR) for
// the host. If there is we will need to add these intiators
// associated with that host to the list
if (hostToExistingExportMaskMap.containsKey(hostID)) {
URI existingExportMaskURI = hostToExistingExportMaskMap.get(hostID);
Set<Initiator> toAddInits = new HashSet<Initiator>();
List<URI> hostInitaitorList = hostInitiatorMap.get(hostID);
for (URI initURI : hostInitaitorList) {
Initiator initiator = _dbClient.queryObject(Initiator.class, initURI);
if (!initiator.getInactive()) {
toAddInits.add(initiator);
}
}
_log.info(String.format("Need to add new initiators to existing mask %s, %s",
existingExportMaskURI.toString(),
Joiner.on(',').join(hostInitaitorList)));
existingMasksToUpdateWithNewInitiators.put(existingExportMaskURI, toAddInits);
continue;
}
// We have some brand new initiators, let's add them to new masks
_log.info(String.format("new export masks %s",
Joiner.on(",").join(hostInitiatorMap.get(hostID))));
GenExportMaskCreateWorkflowResult result = generateExportMaskCreateWorkflow(workflow, previousStep, storage,
exportGroup,
hostInitiatorMap.get(hostID), volumeMap, token);
previousStep = result.getStepId();
flowCreated = true;
}
}
for (Map.Entry<URI, Map<URI, Integer>> entry : existingMasksToUpdateWithNewVolumes
.entrySet()) {
ExportMask mask = _dbClient.queryObject(ExportMask.class, entry.getKey());
Map<URI, Integer> volumesToAdd = entry.getValue();
_log.info(String.format("adding these volumes %s to mask %s",
Joiner.on(",").join(volumesToAdd.keySet()), mask.getMaskName()));
previousStep = generateExportMaskAddVolumesWorkflow(workflow, previousStep, storage, exportGroup, mask,
volumesToAdd, null);
flowCreated = true;
}
for (Entry<URI, Set<Initiator>> entry : existingMasksToUpdateWithNewInitiators.entrySet()) {
ExportMask mask = _dbClient.queryObject(ExportMask.class, entry.getKey());
Set<Initiator> initiatorsToAdd = entry.getValue();
List<URI> initiatorsURIs = new ArrayList<URI>();
for (Initiator initiator : initiatorsToAdd) {
initiatorsURIs.add(initiator.getId());
}
_log.info(String.format("adding these initiators %s to mask %s",
Joiner.on(",").join(initiatorsURIs), mask.getMaskName()));
// To make the right pathing assignments, send down the volumes we are going to add to this mask, if
// available.
previousStep = generateExportMaskAddInitiatorsWorkflow(workflow, previousStep, storage, exportGroup, mask,
initiatorsURIs,
existingMasksToUpdateWithNewVolumes.get(entry.getKey()) != null
? existingMasksToUpdateWithNewVolumes.get(entry.getKey()).keySet() : null,
token);
flowCreated = true;
}
}
return flowCreated;
}
/**
* Method creates a workflow step for copying snapshots to the target devices,
* so that they can be exported.
*
* @param workflow
* - Workflow object to create steps against
* @param previousStep
* - [optional] Identifier of workflow step to wait for
* @param storageSystem
* - StorageSystem object representing the underlying array
* @param volumeMap
* - Map of Volume URIs to requested Integer HLUs
* @param volumesToAdd
* - Map of Volumes that need to be added to the export
*
* @return String workflow step ID. If no workflow is added,
* the passed in previousStep id is returned.
*
*/
@Override
public String checkForSnapshotsToCopyToTarget(Workflow workflow, StorageSystem storageSystem,
String previousStep,
Map<URI, Integer> volumeMap,
Collection<Map<URI, Integer>> volumesToAdd) {
String step = previousStep;
ListMultimap<String, URI> snaps = getBlockSnapshotsRequiringCopyToTarget(volumeMap, volumesToAdd);
if (snaps != null && !snaps.isEmpty()) {
for (Map.Entry<String, Collection<URI>> entries : snaps.asMap().entrySet()) {
List<URI> snapshots = new ArrayList<URI>();
snapshots.addAll(entries.getValue());
_log.info(String.format("Need to run copy-to-target snapshots in snap set %s:%n%s",
entries.getKey(), Joiner.on(',').join(snapshots)));
step = SnapshotWorkflowEntryPoints.generateCopySnapshotsToTargetWorkflow(workflow, step,
storageSystem, snapshots);
}
} else {
_log.info("There are no block snapshots that require copy-to-target.");
}
return step;
}
@Override
public GenExportMaskCreateWorkflowResult generateDeviceSpecificExportMaskCreateWorkFlow(Workflow workflow,
String zoningGroupId, StorageSystem storage, ExportGroup exportGroup,
List<URI> hostInitiators, Map<URI, Integer> volumeMap, String token) throws Exception {
return generateExportMaskCreateWorkflow(workflow, null, storage, exportGroup, hostInitiators, volumeMap, token);
}
@Override
public String generateDeviceSpecificAddInitiatorWorkFlow(Workflow workflow,
String previousStep, StorageSystem storage, ExportGroup exportGroup,
ExportMask mask, List<URI> volumeURIs,
List<URI> initiatorsURIs, Map<URI, List<URI>> maskToInitiatorsMap, String token) throws Exception {
String maskingStep = generateExportMaskAddInitiatorsWorkflow(workflow, previousStep,
storage, exportGroup, mask, initiatorsURIs, null, token);
return generateZoningAddInitiatorsWorkflow(workflow, maskingStep, exportGroup,
maskToInitiatorsMap);
}
/**
* Method will return a ListMultimap of String snapsetLabel to snapshots that need
* to have copyToTarget setup for them.
*
* @param volumeMap
* - Map of Volume URIs to requested Integer HLUs
* @param volumesToAdd
* - Map of Volumes that need to be added to the export
*
* @return
*/
private ListMultimap<String, URI> getBlockSnapshotsRequiringCopyToTarget(Map<URI, Integer> volumeMap,
Collection<Map<URI, Integer>> volumesToAdd) {
ListMultimap<String, URI> snapLabelToSnapURIs = ArrayListMultimap.create();
List<URI> list = new ArrayList<URI>();
if (volumeMap != null) {
list.addAll(volumeMap.keySet());
}
if (volumesToAdd != null) {
for (Map<URI, Integer> map : volumesToAdd) {
list.addAll(map.keySet());
}
}
for (URI uri : list) {
if (!URIUtil.isType(uri, BlockSnapshot.class)) {
continue;
}
BlockSnapshot snapshot = _dbClient.queryObject(BlockSnapshot.class, uri);
if (snapshot != null && snapshot.getNeedsCopyToTarget()) {
String label = (Strings.isNullOrEmpty(snapshot.getSnapsetLabel())) ? DEFAULT_LABEL : snapshot.getSnapsetLabel();
snapLabelToSnapURIs.put(label, uri);
}
}
return snapLabelToSnapURIs;
}
@Override
public void increaseMaxPaths(Workflow workflow, StorageSystem storageSystem, ExportGroup exportGroup,
ExportMask exportMask, List<URI> newInitiators, String token) throws Exception {
// Increases the MaxPaths for a given ExportMask if it has Initiators
// that are not currently zoned to ports. The method
// generateExportMaskAddInitiatorsWorkflow will
// allocate additional ports for the newInitiators to be processed.
// These will be zoned and then subsequently added to the MaskingView /
// ExportMask.
Map<URI, List<URI>> zoneMasksToInitiatorsURIs = new HashMap<URI, List<URI>>();
zoneMasksToInitiatorsURIs.put(exportMask.getId(), newInitiators);
String deregisterInitiatorStep = workflow.createStepId();
ExportTaskCompleter completer = new ExportDeregisterInitiatorCompleter(exportGroup.getId(),
exportMask.getId(), newInitiators, deregisterInitiatorStep);
// These new initiators will be first removed from the storagesystem for
// the following reason:
// There seems to be a bug in provider or some other place for VNX only where
// in a case when initiators are already registered and associated with the
// storage groups, when these initiators are zoned and registered again
// they don't get associated with the storage groups and hence these
// new initiators don't have connectivity to the volumes. Thus it is done
// this way to ensure newly zoned initiators have connectivity to volumes.
String removeInitiatorStep = generateExportMaskRemoveInitiatorsWorkflow(workflow, null,
storageSystem, exportGroup, exportMask, null, newInitiators, true, completer);
String zoningStep = generateZoningAddInitiatorsWorkflow(workflow, removeInitiatorStep,
exportGroup, zoneMasksToInitiatorsURIs);
generateExportMaskAddInitiatorsWorkflow(workflow, zoningStep, storageSystem, exportGroup, exportMask,
newInitiators, null, token);
}
/**
* Overridden implementation of createNewExportMaskWorkflowForInitiators for VNX. The difference
* with this implementation and the superclass' is that here the creates will be run sequentially.
*/
@Override
protected List<String> createNewExportMaskWorkflowForInitiators(List<URI> initiatorURIs,
ExportGroup exportGroup, Workflow workflow, Map<URI, Integer> volumeMap,
StorageSystem storage, String token, String previousStep) throws Exception {
List<String> newSteps = new ArrayList<>();
if (!initiatorURIs.isEmpty()) {
Map<String, List<URI>> computeResourceToInitiators = mapInitiatorsToComputeResource(
exportGroup, initiatorURIs);
for (Map.Entry<String, List<URI>> resourceEntry : computeResourceToInitiators
.entrySet()) {
String computeKey = resourceEntry.getKey();
List<URI> computeInitiatorURIs = resourceEntry.getValue();
_log.info(String.format("New export masks for %s", computeKey));
GenExportMaskCreateWorkflowResult result = generateDeviceSpecificExportMaskCreateWorkFlow(workflow, previousStep, storage,
exportGroup,
computeInitiatorURIs, volumeMap, token);
// Run the creates sequentially. There could be some issues with database consistency if
// masking operations are run in parallel as calls get interleaved against the provider.
previousStep = result.getStepId();
}
}
newSteps.add(previousStep);
return newSteps;
}
@Override
public void exportGroupChangePolicyAndLimits(URI storageURI, URI exportMaskURI,
URI exportGroupURI, List<URI> volumeURIs, URI newVpoolURI,
boolean rollback, String token) throws Exception {
// EXportGroup and ExportMask URIs will be null for VNX.
VolumeUpdateCompleter taskCompleter = new VolumeUpdateCompleter(
volumeURIs, token);
StorageSystem storage = _dbClient.queryObject(StorageSystem.class, storageURI);
VirtualPool newVpool = _dbClient.queryObject(VirtualPool.class, newVpoolURI);
BlockStorageDevice device = getDevice();
device.updatePolicyAndLimits(storage, null, volumeURIs, newVpool,
rollback, taskCompleter);
}
}
|
92318082e30ddf4e0dd07ed5ae5c9ce2e334c271 | 11,999 | java | Java | fineract-provider/src/main/java/org/apache/fineract/accounting/budget/domain/Budget.java | Fordclifford/mifos-checkout | 186d03b8581ef1a84ba3a4eeb1bee295ac232450 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | fineract-provider/src/main/java/org/apache/fineract/accounting/budget/domain/Budget.java | Fordclifford/mifos-checkout | 186d03b8581ef1a84ba3a4eeb1bee295ac232450 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | fineract-provider/src/main/java/org/apache/fineract/accounting/budget/domain/Budget.java | Fordclifford/mifos-checkout | 186d03b8581ef1a84ba3a4eeb1bee295ac232450 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | 33.238227 | 197 | 0.723977 | 995,870 | /**
* 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.fineract.accounting.budget.domain;
import java.math.BigDecimal;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.UniqueConstraint;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.fineract.accounting.budget.api.BudgetJsonInputParams;
import org.apache.fineract.accounting.glaccount.api.GLAccountJsonInputParams;
import org.apache.fineract.accounting.glaccount.domain.GLAccount;
import org.apache.fineract.infrastructure.codes.domain.CodeValue;
import org.apache.fineract.infrastructure.core.api.JsonCommand;
import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom;
import org.apache.fineract.organisation.office.domain.Office;
import software.amazon.ion.Decimal;
@Entity
@Table(name = "gl_acc_budget")
public class Budget extends AbstractPersistableCustom<Long> {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "liability_account_id")
private GLAccount liabilityAccountId;
@ManyToOne
@JoinColumn(name = "office_id", nullable = false)
private Office office;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "expense_account_id")
private GLAccount expenseAccountId;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "cash_account_id")
private GLAccount cashAccountId;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "asset_account_id")
private GLAccount assetAccountId;
@Column(name = "amount", nullable = false)
private BigDecimal amount;
@Column(name = "name", nullable = false)
private String name;
@Column(name = "description", nullable = false)
private String description;
@Column(name = "disabled", nullable = false)
private Boolean disabled;
@Column(name = "from_date")
@Temporal(TemporalType.DATE)
private Date fromDate;
@Column(name = "to_date")
@Temporal(TemporalType.DATE)
private Date toDate;
@Column(name = "create_date")
@Temporal(TemporalType.DATE)
private Date createDate;
@Column(name = "year")
@Temporal(TemporalType.DATE)
private Long year;
protected Budget() {
//
}
public Budget(Office office,GLAccount liabilityAccountId, GLAccount expenseAccountId, GLAccount assetAccountId, BigDecimal amount,
String name, String description, Boolean disabled, Date fromDate, Date toDate, Date createDate, Long year,GLAccount cashAccountId) {
this.office = office;
this.liabilityAccountId = liabilityAccountId;
this.cashAccountId = cashAccountId;
this.expenseAccountId = expenseAccountId;
this.assetAccountId = assetAccountId;
this.amount = amount;
this.name = name;
this.description = description;
this.disabled = disabled;
this.fromDate = fromDate;
this.toDate = toDate;
this.createDate = createDate;
this.year = year;
}
public static Budget fromJson(Office office,final GLAccount liabilityAccountId,final GLAccount expenseAccountId,final GLAccount assetAccountId, JsonCommand command,final GLAccount cashAccountId) {
final BigDecimal amount = command.bigDecimalValueOfParameterNamed(BudgetJsonInputParams.AMOUNT.getValue());
final Boolean disabled = command.booleanObjectValueOfParameterNamed(BudgetJsonInputParams.DISABLED.getValue());
final String description = command.stringValueOfParameterNamed(BudgetJsonInputParams.DESCRIPTION.getValue());
final Long year = command.longValueOfParameterNamed(BudgetJsonInputParams.YEAR.getValue());
final String name = command.stringValueOfParameterNamed(BudgetJsonInputParams.NAME.getValue());
final Date fromDate = command.DateValueOfParameterNamed(BudgetJsonInputParams.FROM_DATE.getValue());
final Date toDate = command.DateValueOfParameterNamed(BudgetJsonInputParams.TO_DATE.getValue());
final Date createdate = command.DateValueOfParameterNamed(BudgetJsonInputParams.CREATE_DATE.getValue());
return new Budget(office,liabilityAccountId,expenseAccountId,assetAccountId,amount,name,description,disabled, fromDate, toDate,createdate,year,cashAccountId);
}
public Map<String, Object> update(final JsonCommand command) {
final Map<String, Object> actualChanges = new LinkedHashMap<>(15);
handlePropertyUpdate(command, actualChanges, BudgetJsonInputParams.ASSET_ACCOUNT_ID.getValue(), 0L);
handlePropertyUpdate(command, actualChanges, BudgetJsonInputParams.OFFICE.getValue(), 0L);
handlePropertyUpdate(command, actualChanges, BudgetJsonInputParams.CASH_ACCOUNT_ID.getValue(), 0L);
handlePropertyUpdate(command, actualChanges, BudgetJsonInputParams.LIABILITY_ACCOUNT_ID.getValue(), 0L);
handlePropertyUpdate(command, actualChanges, BudgetJsonInputParams.EXPENSE_ACCOUNT_ID.getValue(), 0L);
handlePropertyUpdate(command, actualChanges, BudgetJsonInputParams.NAME.getValue(), this.name);
handlePropertyUpdate(command, actualChanges, BudgetJsonInputParams.DESCRIPTION.getValue(), this.description);
handlePropertyUpdate(command, actualChanges, BudgetJsonInputParams.FROM_DATE.getValue(), this.fromDate);
handlePropertyUpdate(command, actualChanges, BudgetJsonInputParams.TO_DATE.getValue(), this.toDate);
handlePropertyUpdate(command, actualChanges, BudgetJsonInputParams.CREATE_DATE.getValue(), this.createDate);
handlePropertyUpdate(command, actualChanges, BudgetJsonInputParams.YEAR.getValue(), 0L);
handlePropertyUpdate(command, actualChanges, BudgetJsonInputParams.AMOUNT.getValue(), this.amount);
handlePropertyUpdate(command, actualChanges, BudgetJsonInputParams.DISABLED.getValue(), this.disabled);
return actualChanges;
}
private void handlePropertyUpdate(final JsonCommand command, final Map<String, Object> actualChanges, final String paramName,
final BigDecimal propertyToBeUpdated) {
if (command.isChangeInBigDecimalParameterNamed(paramName, propertyToBeUpdated)) {
final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(paramName);
actualChanges.put(paramName, newValue);
// now update actual property
if (paramName.equals(BudgetJsonInputParams.AMOUNT.getValue())) {
this.amount = newValue;
}
}
}
private void handlePropertyUpdate(final JsonCommand command, final Map<String, Object> actualChanges, final String paramName,
final Date propertyToBeUpdated) {
if (command.isChangeInDateParameterNamed(paramName, propertyToBeUpdated)) {
final Date newValue = command.DateValueOfParameterNamed(paramName);
actualChanges.put(paramName, newValue);
// now update actual property
if (paramName.equals(BudgetJsonInputParams.FROM_DATE.getValue())) {
this.fromDate = newValue;
}
if (paramName.equals(BudgetJsonInputParams.TO_DATE.getValue())) {
this.toDate = newValue;
}
}
}
private void handlePropertyUpdate(final JsonCommand command, final Map<String, Object> actualChanges, final String paramName,
final Long propertyToBeUpdated) {
if (command.isChangeInLongParameterNamed(paramName, propertyToBeUpdated)) {
final Long newValue = command.longValueOfParameterNamed(paramName);
actualChanges.put(paramName, newValue);
// now update actual property
if (paramName.equals(BudgetJsonInputParams.ASSET_ACCOUNT_ID.getValue())) {
// do nothing as this is a nested property
}
}
}
private void handlePropertyUpdate(final JsonCommand command, final Map<String, Object> actualChanges, final String paramName,
final Boolean propertyToBeUpdated) {
if (command.isChangeInBooleanParameterNamed(paramName, propertyToBeUpdated)) {
final Boolean newValue = command.booleanObjectValueOfParameterNamed(paramName);
actualChanges.put(paramName, newValue);
// now update actual property
if (paramName.equals(BudgetJsonInputParams.DISABLED.getValue())) {
// do nothing as this is a nested property
}
}
}
private void handlePropertyUpdate(final JsonCommand command, final Map<String, Object> actualChanges, final String paramName,
final String propertyToBeUpdated) {
if (command.isChangeInStringParameterNamed(paramName, propertyToBeUpdated)) {
final String newValue = command.stringValueOfParameterNamed(paramName);
actualChanges.put(paramName, newValue);
// now update actual property
if (paramName.equals(BudgetJsonInputParams.DESCRIPTION.getValue())) {
this.description=newValue;
// do nothing as this is a nested property
}else if (paramName.equals(BudgetJsonInputParams.NAME.getValue())) {
this.name=newValue;
// do nothing as this is a nested property
}
}
}
public void updateAssetAccount(final GLAccount assetAccount) {
this.assetAccountId = assetAccount;
}
public void updateExpenseAccount(final GLAccount expenseAccountId) {
this.expenseAccountId = expenseAccountId;
}
public void updateLiabilityAccount(final GLAccount liabilityAccountId) {
this.liabilityAccountId = liabilityAccountId;
}
public GLAccount getLiabilityAccountId() {
return liabilityAccountId;
}
public void setLiabilityAccountId(GLAccount liabilityAccountId) {
this.liabilityAccountId = liabilityAccountId;
}
public GLAccount getExpenseAccountId() {
return expenseAccountId;
}
public void setExpenseAccountId(GLAccount expenseAccountId) {
this.expenseAccountId = expenseAccountId;
}
public GLAccount getAssetAccountId() {
return assetAccountId;
}
public void setAssetAccountId(GLAccount assetAccountId) {
this.assetAccountId = assetAccountId;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Boolean getDisabled() {
return disabled;
}
public void setDisabled(Boolean disabled) {
this.disabled = disabled;
}
} |
9231812dcfd3378f3903580907d15bba6c06b875 | 474 | java | Java | org/apache/batik/svggen/SVGFilterDescriptor.java | JaneMandy/CS | 4a95148cbeb3804b9c50da003d1a7cb12254cb58 | [
"Apache-2.0"
] | 1 | 2022-02-24T01:32:41.000Z | 2022-02-24T01:32:41.000Z | org/apache/batik/svggen/SVGFilterDescriptor.java | JaneMandy/CS | 4a95148cbeb3804b9c50da003d1a7cb12254cb58 | [
"Apache-2.0"
] | null | null | null | org/apache/batik/svggen/SVGFilterDescriptor.java | JaneMandy/CS | 4a95148cbeb3804b9c50da003d1a7cb12254cb58 | [
"Apache-2.0"
] | null | null | null | 18.230769 | 58 | 0.670886 | 995,871 | package org.apache.batik.svggen;
import org.w3c.dom.Element;
public class SVGFilterDescriptor {
private Element def;
private String filterValue;
public SVGFilterDescriptor(String var1) {
this.filterValue = var1;
}
public SVGFilterDescriptor(String var1, Element var2) {
this(var1);
this.def = var2;
}
public String getFilterValue() {
return this.filterValue;
}
public Element getDef() {
return this.def;
}
}
|
923181ef3b274a2cb1ef962cb7615f5af37506e2 | 71,300 | java | Java | lucene/spatial3d/src/test/org/apache/lucene/spatial3d/TestGeo3DPoint.java | keren123/lucence | 1dcb64b492b33f2adc3735458eefbc80e8feb1ef | [
"BSD-2-Clause",
"Apache-2.0"
] | 903 | 2015-01-02T22:13:47.000Z | 2022-03-31T13:40:42.000Z | lucene/spatial3d/src/test/org/apache/lucene/spatial3d/TestGeo3DPoint.java | keren123/lucence | 1dcb64b492b33f2adc3735458eefbc80e8feb1ef | [
"BSD-2-Clause",
"Apache-2.0"
] | 429 | 2021-03-10T14:47:58.000Z | 2022-03-31T21:26:52.000Z | lucene/spatial3d/src/test/org/apache/lucene/spatial3d/TestGeo3DPoint.java | keren123/lucence | 1dcb64b492b33f2adc3735458eefbc80e8feb1ef | [
"BSD-2-Clause",
"Apache-2.0"
] | 480 | 2015-01-05T03:07:05.000Z | 2022-03-31T10:35:08.000Z | 35.955623 | 134 | 0.561893 | 995,872 | /*
* 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.lucene.spatial3d;
import com.carrotsearch.randomizedtesting.generators.RandomNumbers;
import com.carrotsearch.randomizedtesting.generators.RandomPicks;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import org.apache.lucene.codecs.Codec;
import org.apache.lucene.codecs.FilterCodec;
import org.apache.lucene.codecs.PointsFormat;
import org.apache.lucene.codecs.PointsReader;
import org.apache.lucene.codecs.PointsWriter;
import org.apache.lucene.codecs.lucene90.Lucene90PointsReader;
import org.apache.lucene.codecs.lucene90.Lucene90PointsWriter;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.geo.Polygon;
import org.apache.lucene.geo.Rectangle;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.LeafReader;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.MultiDocValues;
import org.apache.lucene.index.NumericDocValues;
import org.apache.lucene.index.PointValues.IntersectVisitor;
import org.apache.lucene.index.PointValues.Relation;
import org.apache.lucene.index.ReaderUtil;
import org.apache.lucene.index.SegmentReadState;
import org.apache.lucene.index.SegmentWriteState;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreMode;
import org.apache.lucene.search.SimpleCollector;
import org.apache.lucene.spatial3d.geom.GeoArea;
import org.apache.lucene.spatial3d.geom.GeoAreaFactory;
import org.apache.lucene.spatial3d.geom.GeoBBoxFactory;
import org.apache.lucene.spatial3d.geom.GeoCircleFactory;
import org.apache.lucene.spatial3d.geom.GeoPathFactory;
import org.apache.lucene.spatial3d.geom.GeoPoint;
import org.apache.lucene.spatial3d.geom.GeoPolygon;
import org.apache.lucene.spatial3d.geom.GeoPolygonFactory;
import org.apache.lucene.spatial3d.geom.GeoShape;
import org.apache.lucene.spatial3d.geom.Plane;
import org.apache.lucene.spatial3d.geom.PlanetModel;
import org.apache.lucene.spatial3d.geom.SidedPlane;
import org.apache.lucene.spatial3d.geom.XYZBounds;
import org.apache.lucene.spatial3d.geom.XYZSolid;
import org.apache.lucene.spatial3d.geom.XYZSolidFactory;
import org.apache.lucene.store.Directory;
import org.apache.lucene.tests.geo.GeoTestUtil;
import org.apache.lucene.tests.index.RandomIndexWriter;
import org.apache.lucene.tests.util.LuceneTestCase;
import org.apache.lucene.tests.util.TestUtil;
import org.apache.lucene.util.DocIdSetBuilder;
import org.apache.lucene.util.FixedBitSet;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.NumericUtils;
public class TestGeo3DPoint extends LuceneTestCase {
protected PlanetModel randomPlanetModel() {
return RandomPicks.randomFrom(
random(),
new PlanetModel[] {PlanetModel.WGS84, PlanetModel.CLARKE_1866, PlanetModel.SPHERE});
}
private static Codec getCodec() {
if (Codec.getDefault().getName().equals("Lucene84")) {
int maxPointsInLeafNode = TestUtil.nextInt(random(), 16, 2048);
double maxMBSortInHeap = 3.0 + (3 * random().nextDouble());
if (VERBOSE) {
System.out.println(
"TEST: using Lucene60PointsFormat with maxPointsInLeafNode="
+ maxPointsInLeafNode
+ " and maxMBSortInHeap="
+ maxMBSortInHeap);
}
return new FilterCodec("Lucene84", Codec.getDefault()) {
@Override
public PointsFormat pointsFormat() {
return new PointsFormat() {
@Override
public PointsWriter fieldsWriter(SegmentWriteState writeState) throws IOException {
return new Lucene90PointsWriter(writeState, maxPointsInLeafNode, maxMBSortInHeap);
}
@Override
public PointsReader fieldsReader(SegmentReadState readState) throws IOException {
return new Lucene90PointsReader(readState);
}
};
}
};
} else {
return Codec.getDefault();
}
}
public void testBasic() throws Exception {
Directory dir = getDirectory();
IndexWriterConfig iwc = newIndexWriterConfig();
iwc.setCodec(getCodec());
IndexWriter w = new IndexWriter(dir, iwc);
Document doc = new Document();
PlanetModel planetModel = randomPlanetModel();
doc.add(new Geo3DPoint("field", planetModel, 50.7345267, -97.5303555));
w.addDocument(doc);
IndexReader r = DirectoryReader.open(w);
// We can't wrap with "exotic" readers because the query must see the BKD3DDVFormat:
IndexSearcher s = newSearcher(r, false);
assertEquals(
1,
s.search(
Geo3DPoint.newShapeQuery(
"field",
GeoCircleFactory.makeGeoCircle(
planetModel, toRadians(50), toRadians(-97), Math.PI / 180.)),
1)
.totalHits
.value);
w.close();
r.close();
dir.close();
}
private static double toRadians(double degrees) {
return degrees * Geo3DUtil.RADIANS_PER_DEGREE;
}
private static class Cell {
static int nextCellID;
final Cell parent;
final int cellID;
final int xMinEnc, xMaxEnc;
final int yMinEnc, yMaxEnc;
final int zMinEnc, zMaxEnc;
final int splitCount;
final PlanetModel planetModel;
public Cell(
Cell parent,
int xMinEnc,
int xMaxEnc,
int yMinEnc,
int yMaxEnc,
int zMinEnc,
int zMaxEnc,
final PlanetModel planetModel,
int splitCount) {
this.parent = parent;
this.xMinEnc = xMinEnc;
this.xMaxEnc = xMaxEnc;
this.yMinEnc = yMinEnc;
this.yMaxEnc = yMaxEnc;
this.zMinEnc = zMinEnc;
this.zMaxEnc = zMaxEnc;
this.cellID = nextCellID++;
this.splitCount = splitCount;
this.planetModel = planetModel;
}
/** Returns true if the quantized point lies within this cell, inclusive on all bounds. */
public boolean contains(GeoPoint point) {
int docX = planetModel.encodeValue(point.x);
int docY = planetModel.encodeValue(point.y);
int docZ = planetModel.encodeValue(point.z);
return docX >= xMinEnc
&& docX <= xMaxEnc
&& docY >= yMinEnc
&& docY <= yMaxEnc
&& docZ >= zMinEnc
&& docZ <= zMaxEnc;
}
@Override
public String toString() {
return "cell="
+ cellID
+ (parent == null ? "" : " parentCellID=" + parent.cellID)
+ " x: "
+ xMinEnc
+ " TO "
+ xMaxEnc
+ ", y: "
+ yMinEnc
+ " TO "
+ yMaxEnc
+ ", z: "
+ zMinEnc
+ " TO "
+ zMaxEnc
+ ", splits: "
+ splitCount;
}
}
private static double quantize(double xyzValue, final PlanetModel planetModel) {
return planetModel.decodeValue(planetModel.encodeValue(xyzValue));
}
private static GeoPoint quantize(GeoPoint point, final PlanetModel planetModel) {
return new GeoPoint(
quantize(point.x, planetModel),
quantize(point.y, planetModel),
quantize(point.z, planetModel));
}
/** Tests consistency of GeoArea.getRelationship vs GeoShape.isWithin */
public void testGeo3DRelations() throws Exception {
int numDocs = atLeast(200);
if (VERBOSE) {
System.out.println("TEST: " + numDocs + " docs");
}
GeoPoint[] docs = new GeoPoint[numDocs];
GeoPoint[] unquantizedDocs = new GeoPoint[numDocs];
PlanetModel planetModel = PlanetModel.CLARKE_1866;
for (int docID = 0; docID < numDocs; docID++) {
unquantizedDocs[docID] =
new GeoPoint(
planetModel,
toRadians(GeoTestUtil.nextLatitude()),
toRadians(GeoTestUtil.nextLongitude()));
docs[docID] = quantize(unquantizedDocs[docID], planetModel);
if (VERBOSE) {
System.out.println(
" doc=" + docID + ": " + docs[docID] + "; unquantized: " + unquantizedDocs[docID]);
}
}
int iters = atLeast(10);
int recurseDepth = RandomNumbers.randomIntBetween(random(), 5, 15);
for (int iter = 0; iter < iters; iter++) {
GeoShape shape = randomShape(planetModel);
StringWriter sw = new StringWriter();
PrintWriter log = new PrintWriter(sw, true);
if (VERBOSE) {
log.println("TEST: iter=" + iter + " shape=" + shape);
}
XYZBounds bounds = new XYZBounds();
shape.getBounds(bounds);
// Start with the root cell that fully contains the shape:
Cell root =
new Cell(
null,
encodeValueLenient(bounds.getMinimumX(), planetModel),
encodeValueLenient(bounds.getMaximumX(), planetModel),
encodeValueLenient(bounds.getMinimumY(), planetModel),
encodeValueLenient(bounds.getMaximumY(), planetModel),
encodeValueLenient(bounds.getMinimumZ(), planetModel),
encodeValueLenient(bounds.getMaximumZ(), planetModel),
planetModel,
0);
if (VERBOSE) {
log.println(" root cell: " + root);
}
// make sure the root cell (XYZBounds) does in fact contain all points that the shape contains
{
boolean fail = false;
for (int docID = 0; docID < numDocs; docID++) {
if (root.contains(docs[docID]) == false) {
boolean expected = shape.isWithin(unquantizedDocs[docID]);
if (expected) {
log.println(
" doc="
+ docID
+ " is contained by shape but is outside the returned XYZBounds");
log.println(" unquantized=" + unquantizedDocs[docID]);
log.println(" quantized=" + docs[docID]);
fail = true;
}
}
}
if (fail) {
log.println(" shape=" + shape);
log.println(" bounds=" + bounds);
System.out.print(sw.toString());
fail("invalid bounds for shape=" + shape);
}
}
List<Cell> queue = new ArrayList<>();
queue.add(root);
Set<Integer> hits = new HashSet<>();
while (queue.size() > 0) {
Cell cell = queue.get(queue.size() - 1);
queue.remove(queue.size() - 1);
if (VERBOSE) {
log.println(" cycle: " + cell + " queue.size()=" + queue.size());
}
if (random().nextInt(10) == 7 || cell.splitCount > recurseDepth) {
if (VERBOSE) {
log.println(" leaf");
}
// Leaf cell: brute force check all docs that fall within this cell:
for (int docID = 0; docID < numDocs; docID++) {
GeoPoint point = docs[docID];
GeoPoint mappedPoint = unquantizedDocs[docID];
boolean pointWithinShape = shape.isWithin(point);
boolean mappedPointWithinShape = shape.isWithin(mappedPoint);
if (cell.contains(point)) {
if (mappedPointWithinShape) {
if (VERBOSE) {
log.println(
" check doc="
+ docID
+ ": match! Actual quantized point within: "
+ pointWithinShape);
}
hits.add(docID);
} else {
if (VERBOSE) {
log.println(
" check doc="
+ docID
+ ": no match. Quantized point within: "
+ pointWithinShape);
}
}
}
}
} else {
GeoArea xyzSolid =
GeoAreaFactory.makeGeoArea(
planetModel,
Geo3DUtil.decodeValueFloor(cell.xMinEnc, planetModel),
Geo3DUtil.decodeValueCeil(cell.xMaxEnc, planetModel),
Geo3DUtil.decodeValueFloor(cell.yMinEnc, planetModel),
Geo3DUtil.decodeValueCeil(cell.yMaxEnc, planetModel),
Geo3DUtil.decodeValueFloor(cell.zMinEnc, planetModel),
Geo3DUtil.decodeValueCeil(cell.zMaxEnc, planetModel));
if (VERBOSE) {
log.println(
" minx="
+ Geo3DUtil.decodeValueFloor(cell.xMinEnc, planetModel)
+ " maxx="
+ Geo3DUtil.decodeValueCeil(cell.xMaxEnc, planetModel)
+ " miny="
+ Geo3DUtil.decodeValueFloor(cell.yMinEnc, planetModel)
+ " maxy="
+ Geo3DUtil.decodeValueCeil(cell.yMaxEnc, planetModel)
+ " minz="
+ Geo3DUtil.decodeValueFloor(cell.zMinEnc, planetModel)
+ " maxz="
+ Geo3DUtil.decodeValueCeil(cell.zMaxEnc, planetModel));
}
switch (xyzSolid.getRelationship(shape)) {
case GeoArea.CONTAINS:
// Shape fully contains the cell: blindly add all docs in this cell:
if (VERBOSE) {
log.println(" GeoArea.CONTAINS: now addAll");
}
for (int docID = 0; docID < numDocs; docID++) {
if (cell.contains(docs[docID])) {
if (VERBOSE) {
log.println(" addAll doc=" + docID);
}
hits.add(docID);
}
}
continue;
case GeoArea.OVERLAPS:
if (VERBOSE) {
log.println(" GeoArea.OVERLAPS: keep splitting");
}
// They do overlap but neither contains the other:
// log.println(" crosses1");
break;
case GeoArea.WITHIN:
if (VERBOSE) {
log.println(" GeoArea.WITHIN: keep splitting");
}
// Cell fully contains the shape:
// log.println(" crosses2");
break;
case GeoArea.DISJOINT:
// They do not overlap at all: don't recurse on this cell
// log.println(" outside");
if (VERBOSE) {
log.println(" GeoArea.DISJOINT: drop this cell");
for (int docID = 0; docID < numDocs; docID++) {
if (cell.contains(docs[docID])) {
log.println(" skip doc=" + docID);
}
}
}
continue;
default:
assert false;
}
// Randomly split:
switch (random().nextInt(3)) {
case 0:
// Split on X:
{
int splitValue =
RandomNumbers.randomIntBetween(random(), cell.xMinEnc, cell.xMaxEnc);
if (VERBOSE) {
log.println(" now split on x=" + splitValue);
}
Cell cell1 =
new Cell(
cell,
cell.xMinEnc,
splitValue,
cell.yMinEnc,
cell.yMaxEnc,
cell.zMinEnc,
cell.zMaxEnc,
planetModel,
cell.splitCount + 1);
Cell cell2 =
new Cell(
cell,
splitValue,
cell.xMaxEnc,
cell.yMinEnc,
cell.yMaxEnc,
cell.zMinEnc,
cell.zMaxEnc,
planetModel,
cell.splitCount + 1);
if (VERBOSE) {
log.println(" split cell1: " + cell1);
log.println(" split cell2: " + cell2);
}
queue.add(cell1);
queue.add(cell2);
}
break;
case 1:
// Split on Y:
{
int splitValue =
RandomNumbers.randomIntBetween(random(), cell.yMinEnc, cell.yMaxEnc);
if (VERBOSE) {
log.println(" now split on y=" + splitValue);
}
Cell cell1 =
new Cell(
cell,
cell.xMinEnc,
cell.xMaxEnc,
cell.yMinEnc,
splitValue,
cell.zMinEnc,
cell.zMaxEnc,
planetModel,
cell.splitCount + 1);
Cell cell2 =
new Cell(
cell,
cell.xMinEnc,
cell.xMaxEnc,
splitValue,
cell.yMaxEnc,
cell.zMinEnc,
cell.zMaxEnc,
planetModel,
cell.splitCount + 1);
if (VERBOSE) {
log.println(" split cell1: " + cell1);
log.println(" split cell2: " + cell2);
}
queue.add(cell1);
queue.add(cell2);
}
break;
case 2:
// Split on Z:
{
int splitValue =
RandomNumbers.randomIntBetween(random(), cell.zMinEnc, cell.zMaxEnc);
if (VERBOSE) {
log.println(" now split on z=" + splitValue);
}
Cell cell1 =
new Cell(
cell,
cell.xMinEnc,
cell.xMaxEnc,
cell.yMinEnc,
cell.yMaxEnc,
cell.zMinEnc,
splitValue,
planetModel,
cell.splitCount + 1);
Cell cell2 =
new Cell(
cell,
cell.xMinEnc,
cell.xMaxEnc,
cell.yMinEnc,
cell.yMaxEnc,
splitValue,
cell.zMaxEnc,
planetModel,
cell.splitCount + 1);
if (VERBOSE) {
log.println(" split cell1: " + cell1);
log.println(" split cell2: " + cell2);
}
queue.add(cell1);
queue.add(cell2);
}
break;
}
}
}
if (VERBOSE) {
log.println(" " + hits.size() + " hits");
}
// Done matching, now verify:
boolean fail = false;
for (int docID = 0; docID < numDocs; docID++) {
GeoPoint point = docs[docID];
GeoPoint mappedPoint = unquantizedDocs[docID];
boolean expected = shape.isWithin(mappedPoint);
boolean actual = hits.contains(docID);
if (actual != expected) {
if (actual) {
log.println("doc=" + docID + " should not have matched but did");
} else {
log.println("doc=" + docID + " should match but did not");
}
log.println(" point=" + point);
log.println(" mappedPoint=" + mappedPoint);
fail = true;
}
}
if (fail) {
System.out.print(sw.toString());
fail("invalid hits for shape=" + shape);
}
}
}
public void testRandomTiny() throws Exception {
// Make sure single-leaf-node case is OK:
doTestRandom(10);
}
public void testRandomMedium() throws Exception {
doTestRandom(1000);
}
@Nightly
public void testRandomBig() throws Exception {
doTestRandom(50000);
}
private void doTestRandom(int count) throws Exception {
int numPoints = atLeast(count);
if (VERBOSE) {
System.err.println("TEST: numPoints=" + numPoints);
}
double[] lats = new double[numPoints];
double[] lons = new double[numPoints];
boolean haveRealDoc = false;
for (int docID = 0; docID < numPoints; docID++) {
int x = random().nextInt(20);
if (x == 17) {
// Some docs don't have a point:
lats[docID] = Double.NaN;
if (VERBOSE) {
System.err.println(" doc=" + docID + " is missing");
}
continue;
}
if (docID > 0 && x < 3 && haveRealDoc) {
int oldDocID;
while (true) {
oldDocID = random().nextInt(docID);
if (Double.isNaN(lats[oldDocID]) == false) {
break;
}
}
if (x == 0) {
// Identical lat to old point
lats[docID] = lats[oldDocID];
lons[docID] = GeoTestUtil.nextLongitude();
if (VERBOSE) {
System.err.println(
" doc="
+ docID
+ " lat="
+ lats[docID]
+ " lon="
+ lons[docID]
+ " (same lat as doc="
+ oldDocID
+ ")");
}
} else if (x == 1) {
// Identical lon to old point
lats[docID] = GeoTestUtil.nextLatitude();
lons[docID] = lons[oldDocID];
if (VERBOSE) {
System.err.println(
" doc="
+ docID
+ " lat="
+ lats[docID]
+ " lon="
+ lons[docID]
+ " (same lon as doc="
+ oldDocID
+ ")");
}
} else {
assert x == 2;
// Fully identical point:
lats[docID] = lats[oldDocID];
lons[docID] = lons[oldDocID];
if (VERBOSE) {
System.err.println(
" doc="
+ docID
+ " lat="
+ lats[docID]
+ " lon="
+ lons[docID]
+ " (same lat/lon as doc="
+ oldDocID
+ ")");
}
}
} else {
lats[docID] = GeoTestUtil.nextLatitude();
lons[docID] = GeoTestUtil.nextLongitude();
haveRealDoc = true;
if (VERBOSE) {
System.err.println(" doc=" + docID + " lat=" + lats[docID] + " lon=" + lons[docID]);
}
}
}
verify(lats, lons, randomPlanetModel());
}
public void testPolygonOrdering() {
final double[] lats =
new double[] {
51.204382859999996,
50.89947531437482,
50.8093624806861,
50.8093624806861,
50.89947531437482,
51.204382859999996,
51.51015366140113,
51.59953838204167,
51.59953838204167,
51.51015366140113,
51.204382859999996
};
final double[] lons =
new double[] {
0.8747711978759765,
0.6509219832137298,
0.35960265165247807,
0.10290284834752167,
-0.18841648321373008,
-0.41226569787597667,
-0.18960465285650027,
0.10285893781346236,
0.35964656218653757,
0.6521101528565002,
0.8747711978759765
};
final Query q =
Geo3DPoint.newPolygonQuery("point", randomPlanetModel(), new Polygon(lats, lons));
// System.out.println(q);
assertTrue(!q.toString().contains("GeoConcavePolygon"));
}
private static Query random3DQuery(final String field, final PlanetModel planetModel) {
while (true) {
final int shapeType = random().nextInt(5);
switch (shapeType) {
case 4:
{
// Large polygons
final boolean isClockwise = random().nextDouble() < 0.5;
try {
final Query q =
Geo3DPoint.newLargePolygonQuery(
field,
planetModel,
makePoly(
planetModel,
new GeoPoint(
planetModel,
toRadians(GeoTestUtil.nextLatitude()),
toRadians(GeoTestUtil.nextLongitude())),
isClockwise,
true));
// System.err.println("Generated: "+q);
// assertTrue(false);
return q;
} catch (
@SuppressWarnings("unused")
IllegalArgumentException e) {
continue;
}
}
case 0:
{
// Polygons
final boolean isClockwise = random().nextDouble() < 0.5;
try {
final Query q =
Geo3DPoint.newPolygonQuery(
field,
planetModel,
makePoly(
planetModel,
new GeoPoint(
planetModel,
toRadians(GeoTestUtil.nextLatitude()),
toRadians(GeoTestUtil.nextLongitude())),
isClockwise,
true));
// System.err.println("Generated: "+q);
// assertTrue(false);
return q;
} catch (
@SuppressWarnings("unused")
IllegalArgumentException e) {
continue;
}
}
case 1:
{
// Circles
final double widthMeters =
random().nextDouble() * Math.PI * planetModel.getMeanRadius();
try {
return Geo3DPoint.newDistanceQuery(
field,
planetModel,
GeoTestUtil.nextLatitude(),
GeoTestUtil.nextLongitude(),
widthMeters);
} catch (
@SuppressWarnings("unused")
IllegalArgumentException e) {
continue;
}
}
case 2:
{
// Rectangles
final Rectangle r = GeoTestUtil.nextBox();
try {
return Geo3DPoint.newBoxQuery(
field, planetModel, r.minLat, r.maxLat, r.minLon, r.maxLon);
} catch (
@SuppressWarnings("unused")
IllegalArgumentException e) {
continue;
}
}
case 3:
{
// Paths
// TBD: Need to rework generation to be realistic
final int pointCount = random().nextInt(5) + 1;
final double width =
random().nextDouble() * Math.PI * 0.5 * planetModel.getMeanRadius();
final double[] latitudes = new double[pointCount];
final double[] longitudes = new double[pointCount];
for (int i = 0; i < pointCount; i++) {
latitudes[i] = GeoTestUtil.nextLatitude();
longitudes[i] = GeoTestUtil.nextLongitude();
}
try {
return Geo3DPoint.newPathQuery(field, latitudes, longitudes, width, planetModel);
} catch (
@SuppressWarnings("unused")
IllegalArgumentException e) {
// This is what happens when we create a shape that is invalid. Although it is
// conceivable that there are cases where
// the exception is thrown incorrectly, we aren't going to be able to do that in this
// random test.
continue;
}
}
default:
throw new IllegalStateException("Unexpected shape type");
}
}
}
// Poached from Geo3dRptTest.randomShape:
private static GeoShape randomShape(final PlanetModel planetModel) {
while (true) {
final int shapeType = random().nextInt(4);
switch (shapeType) {
case 0:
{
// Polygons
final int vertexCount = random().nextInt(3) + 3;
final List<GeoPoint> geoPoints = new ArrayList<>();
while (geoPoints.size() < vertexCount) {
final GeoPoint gPt =
new GeoPoint(
planetModel,
toRadians(GeoTestUtil.nextLatitude()),
toRadians(GeoTestUtil.nextLongitude()));
geoPoints.add(gPt);
}
try {
final GeoShape rval = GeoPolygonFactory.makeGeoPolygon(planetModel, geoPoints);
if (rval == null) {
// Degenerate polygon
continue;
}
return rval;
} catch (
@SuppressWarnings("unused")
IllegalArgumentException e) {
// This is what happens when we create a shape that is invalid. Although it is
// conceivable that there are cases where
// the exception is thrown incorrectly, we aren't going to be able to do that in this
// random test.
continue;
}
}
case 1:
{
// Circles
double lat = toRadians(GeoTestUtil.nextLatitude());
double lon = toRadians(GeoTestUtil.nextLongitude());
double angle = random().nextDouble() * Math.PI / 2.0;
try {
return GeoCircleFactory.makeGeoCircle(planetModel, lat, lon, angle);
} catch (
@SuppressWarnings("unused")
IllegalArgumentException iae) {
// angle is too small; try again:
continue;
}
}
case 2:
{
// Rectangles
double lat0 = toRadians(GeoTestUtil.nextLatitude());
double lat1 = toRadians(GeoTestUtil.nextLatitude());
if (lat1 < lat0) {
double x = lat0;
lat0 = lat1;
lat1 = x;
}
double lon0 = toRadians(GeoTestUtil.nextLongitude());
double lon1 = toRadians(GeoTestUtil.nextLongitude());
if (lon1 < lon0) {
double x = lon0;
lon0 = lon1;
lon1 = x;
}
return GeoBBoxFactory.makeGeoBBox(planetModel, lat1, lat0, lon0, lon1);
}
case 3:
{
// Paths
final int pointCount = random().nextInt(5) + 1;
final double width = toRadians(random().nextInt(89) + 1);
final GeoPoint[] points = new GeoPoint[pointCount];
for (int i = 0; i < pointCount; i++) {
points[i] =
new GeoPoint(
planetModel,
toRadians(GeoTestUtil.nextLatitude()),
toRadians(GeoTestUtil.nextLongitude()));
}
try {
return GeoPathFactory.makeGeoPath(planetModel, width, points);
} catch (
@SuppressWarnings("unused")
IllegalArgumentException e) {
// This is what happens when we create a shape that is invalid. Although it is
// conceivable that there are cases where
// the exception is thrown incorrectly, we aren't going to be able to do that in this
// random test.
continue;
}
}
default:
throw new IllegalStateException("Unexpected shape type");
}
}
}
private static void verify(double[] lats, double[] lons, final PlanetModel planetModel)
throws Exception {
IndexWriterConfig iwc = newIndexWriterConfig();
GeoPoint[] points = new GeoPoint[lats.length];
GeoPoint[] unquantizedPoints = new GeoPoint[lats.length];
// Pre-quantize all lat/lons:
for (int i = 0; i < lats.length; i++) {
if (Double.isNaN(lats[i]) == false) {
// System.out.println("lats[" + i + "] = " + lats[i]);
unquantizedPoints[i] = new GeoPoint(planetModel, toRadians(lats[i]), toRadians(lons[i]));
points[i] = quantize(unquantizedPoints[i], planetModel);
}
}
// Else we can get O(N^2) merging:
int mbd = iwc.getMaxBufferedDocs();
if (mbd != -1 && mbd < points.length / 100) {
iwc.setMaxBufferedDocs(points.length / 100);
}
iwc.setCodec(getCodec());
Directory dir;
if (points.length > 100000) {
dir = newFSDirectory(createTempDir("TestBKDTree"));
} else {
dir = getDirectory();
}
Set<Integer> deleted = new HashSet<>();
// RandomIndexWriter is too slow here:
IndexWriter w = new IndexWriter(dir, iwc);
for (int id = 0; id < points.length; id++) {
Document doc = new Document();
doc.add(newStringField("id", "" + id, Field.Store.NO));
doc.add(new NumericDocValuesField("id", id));
GeoPoint point = points[id];
if (point != null) {
doc.add(new Geo3DPoint("point", planetModel, point.x, point.y, point.z));
}
w.addDocument(doc);
if (id > 0 && random().nextInt(100) == 42) {
int idToDelete = random().nextInt(id);
w.deleteDocuments(new Term("id", "" + idToDelete));
deleted.add(idToDelete);
if (VERBOSE) {
System.err.println(" delete id=" + idToDelete);
}
}
}
if (random().nextBoolean()) {
w.forceMerge(1);
}
final IndexReader r = DirectoryReader.open(w);
if (VERBOSE) {
System.out.println("TEST: using reader " + r);
}
w.close();
// We can't wrap with "exotic" readers because the geo3d query must see the Geo3DDVFormat:
IndexSearcher s = newSearcher(r, false);
final int iters = atLeast(100);
for (int iter = 0; iter < iters; iter++) {
/*
GeoShape shape = randomShape();
if (VERBOSE) {
System.err.println("\nTEST: iter=" + iter + " shape="+shape);
}
*/
Query query =
random3DQuery("point", planetModel); // Geo3DPoint.newShapeQuery("point", shape);
if (VERBOSE) {
System.err.println(" using query: " + query);
}
final FixedBitSet hits = new FixedBitSet(r.maxDoc());
s.search(
query,
new SimpleCollector() {
private int docBase;
@Override
public ScoreMode scoreMode() {
return ScoreMode.COMPLETE_NO_SCORES;
}
@Override
protected void doSetNextReader(LeafReaderContext context) throws IOException {
docBase = context.docBase;
}
@Override
public void collect(int doc) {
hits.set(docBase + doc);
}
});
if (VERBOSE) {
System.err.println(" hitCount: " + hits.cardinality());
}
NumericDocValues docIDToID = MultiDocValues.getNumericValues(r, "id");
for (int docID = 0; docID < r.maxDoc(); docID++) {
assertEquals(docID, docIDToID.nextDoc());
int id = (int) docIDToID.longValue();
GeoPoint point = points[id];
GeoPoint unquantizedPoint = unquantizedPoints[id];
if (point != null && unquantizedPoint != null) {
GeoShape shape = ((PointInGeo3DShapeQuery) query).getShape();
XYZBounds bounds = new XYZBounds();
shape.getBounds(bounds);
XYZSolid solid =
XYZSolidFactory.makeXYZSolid(
planetModel,
bounds.getMinimumX(),
bounds.getMaximumX(),
bounds.getMinimumY(),
bounds.getMaximumY(),
bounds.getMinimumZ(),
bounds.getMaximumZ());
boolean expected = ((deleted.contains(id) == false) && shape.isWithin(point));
if (hits.get(docID) != expected) {
StringBuilder b = new StringBuilder();
if (expected) {
b.append("FAIL: id=" + id + " should have matched but did not\n");
} else {
b.append("FAIL: id=" + id + " should not have matched but did\n");
}
b.append(" shape=" + shape + "\n");
b.append(" bounds=" + bounds + "\n");
b.append(
" world bounds=("
+ " minX="
+ planetModel.getMinimumXValue()
+ " maxX="
+ planetModel.getMaximumXValue()
+ " minY="
+ planetModel.getMinimumYValue()
+ " maxY="
+ planetModel.getMaximumYValue()
+ " minZ="
+ planetModel.getMinimumZValue()
+ " maxZ="
+ planetModel.getMaximumZValue()
+ "\n");
b.append(
" quantized point="
+ point
+ " within shape? "
+ shape.isWithin(point)
+ " within bounds? "
+ solid.isWithin(point)
+ "\n");
b.append(
" unquantized point="
+ unquantizedPoint
+ " within shape? "
+ shape.isWithin(unquantizedPoint)
+ " within bounds? "
+ solid.isWithin(unquantizedPoint)
+ "\n");
b.append(" docID=" + docID + " deleted?=" + deleted.contains(id) + "\n");
b.append(" query=" + query + "\n");
b.append(
" explanation:\n "
+ explain("point", shape, point, unquantizedPoint, r, docID)
.replace("\n", "\n "));
fail(b.toString());
}
} else {
assertFalse(hits.get(docID));
}
}
}
IOUtils.close(r, dir);
}
public void testToString() {
// Don't compare entire strings because Java 9 and Java 8 have slightly different values
Geo3DPoint point = new Geo3DPoint("point", randomPlanetModel(), 44.244272, 7.769736);
final String stringToCompare = "Geo3DPoint <point: x=";
assertEquals(stringToCompare, point.toString().substring(0, stringToCompare.length()));
}
public void testShapeQueryToString() {
// Don't compare entire strings because Java 9 and Java 8 have slightly different values
final String stringToCompare =
"PointInGeo3DShapeQuery: field=point: Shape: GeoStandardCircle: {planetmodel=PlanetModel.WGS84, center=[lat=0.7";
assertEquals(
stringToCompare,
Geo3DPoint.newShapeQuery(
"point",
GeoCircleFactory.makeGeoCircle(
PlanetModel.WGS84, toRadians(44.244272), toRadians(7.769736), 0.1))
.toString()
.substring(0, stringToCompare.length()));
}
private static Directory getDirectory() {
return newDirectory();
}
public void testEquals() {
PlanetModel planetModel = randomPlanetModel();
GeoShape shape = randomShape(planetModel);
Query q = Geo3DPoint.newShapeQuery("point", shape);
assertEquals(q, Geo3DPoint.newShapeQuery("point", shape));
assertFalse(q.equals(Geo3DPoint.newShapeQuery("point2", shape)));
// make a different random shape:
GeoShape shape2;
do {
shape2 = randomShape(planetModel);
} while (shape.equals(shape2));
assertFalse(q.equals(Geo3DPoint.newShapeQuery("point", shape2)));
}
public void testComplexPolygons() {
final PlanetModel pm = randomPlanetModel();
// Pick a random pole
final GeoPoint randomPole =
new GeoPoint(
pm, toRadians(GeoTestUtil.nextLatitude()), toRadians(GeoTestUtil.nextLongitude()));
int iters = atLeast(100);
for (int i = 0; i < iters; i++) {
// Create a polygon that's less than 180 degrees
makePoly(pm, randomPole, true, true);
}
iters = atLeast(100);
for (int i = 0; i < iters; i++) {
// Create a polygon that's greater than 180 degrees
makePoly(pm, randomPole, false, true);
}
}
protected static double MINIMUM_EDGE_ANGLE = toRadians(5.0);
protected static double MINIMUM_ARC_ANGLE = toRadians(1.0);
/**
* Cook up a random Polygon that makes sense, with possible nested polygon within. This is part of
* testing more complex polygons with nested holes. Picking random points doesn't do it because
* it's almost impossible to come up with nested ones of the proper clockwise/counterclockwise
* rotation that way.
*/
protected static Polygon makePoly(
final PlanetModel pm,
final GeoPoint pole,
final boolean clockwiseDesired,
final boolean createHoles) {
// Polygon edges will be arranged around the provided pole, and holes will each have a pole
// selected within the parent
// polygon.
final int pointCount = TestUtil.nextInt(random(), 3, 10);
// The point angles we pick next. The only requirement is that they are not all on one side of
// the pole.
// We arrange that by picking the next point within what's left of the remaining angle, but
// never more than 180 degrees,
// and never less than what is needed to insure that the remaining point choices are less than
// 180 degrees always.
// These are all picked in the context of the pole,
final double[] angles = new double[pointCount];
final double[] arcDistance = new double[pointCount];
// Pick a set of points
while (true) {
double accumulatedAngle = 0.0;
for (int i = 0; i < pointCount; i++) {
final int remainingEdgeCount = pointCount - i;
final double remainingAngle = 2.0 * Math.PI - accumulatedAngle;
if (remainingEdgeCount == 1) {
angles[i] = remainingAngle;
} else {
// The maximum angle is 180 degrees, or what's left when you give a minimal amount to each
// edge.
double maximumAngle = remainingAngle - (remainingEdgeCount - 1) * MINIMUM_EDGE_ANGLE;
if (maximumAngle > Math.PI) {
maximumAngle = Math.PI;
}
// The minimum angle is MINIMUM_EDGE_ANGLE, or enough to be sure nobody afterwards needs
// more than 180 degrees. And since we have three points to start with, we already know
// that.
final double minimumAngle = MINIMUM_EDGE_ANGLE;
// Pick the angle
final double angle = random().nextDouble() * (maximumAngle - minimumAngle) + minimumAngle;
angles[i] = angle;
accumulatedAngle += angle;
}
// Pick the arc distance randomly; not quite the full range though
arcDistance[i] =
random().nextDouble() * (Math.PI * 0.5 - MINIMUM_ARC_ANGLE) + MINIMUM_ARC_ANGLE;
}
if (clockwiseDesired) {
// Reverse the signs
for (int i = 0; i < pointCount; i++) {
angles[i] = -angles[i];
}
}
// Now, use the pole's information plus angles and arcs to create GeoPoints in the right
// order.
final List<GeoPoint> polyPoints = convertToPoints(pm, pole, angles, arcDistance);
// Next, do some holes. No more than 2 of these. The poles for holes must always be within
// the polygon, so we're going to use Geo3D to help us select those given the points we just
// made.
final List<Polygon> holeList = new ArrayList<>();
/* Hole logic is broken and needs rethinking
final int holeCount = createHoles ? TestUtil.nextInt(random(), 0, 2) : 0;
// Create the geo3d polygon, so we can test out our poles.
final GeoPolygon poly;
try {
poly = GeoPolygonFactory.makeGeoPolygon(pm, polyPoints, null);
} catch (IllegalArgumentException e) {
// This is what happens when three adjacent points are colinear, so try again.
continue;
}
for (int i = 0; i < holeCount; i++) {
// Choose a pole. The poly has to be within the polygon, but it also cannot be on the polygon edge.
// If we can't find a good pole we have to give it up and not do the hole.
for (int k = 0; k < 500; k++) {
final GeoPoint poleChoice = new GeoPoint(pm, toRadians(GeoTestUtil.nextLatitude()), toRadians(GeoTestUtil.nextLongitude()));
if (!poly.isWithin(poleChoice)) {
continue;
}
// We have a pole within the polygon. Now try 100 times to build a polygon that does not intersect the outside ring.
// After that we give up and pick a new pole.
boolean foundOne = false;
for (int j = 0; j < 100; j++) {
final Polygon insidePoly = makePoly(pm, poleChoice, !clockwiseDesired, false);
// Verify that the inside polygon is OK. If not, discard and repeat.
if (!verifyPolygon(pm, insidePoly, poly)) {
continue;
}
holeList.add(insidePoly);
foundOne = true;
}
if (foundOne) {
break;
}
}
}
*/
final Polygon[] holes = holeList.toArray(new Polygon[0]);
// Finally, build the polygon and return it
final double[] lats = new double[polyPoints.size() + 1];
final double[] lons = new double[polyPoints.size() + 1];
for (int i = 0; i < polyPoints.size(); i++) {
lats[i] = polyPoints.get(i).getLatitude() * 180.0 / Math.PI;
lons[i] = polyPoints.get(i).getLongitude() * 180.0 / Math.PI;
}
lats[polyPoints.size()] = lats[0];
lons[polyPoints.size()] = lons[0];
return new Polygon(lats, lons, holes);
}
}
protected static List<GeoPoint> convertToPoints(
final PlanetModel pm,
final GeoPoint pole,
final double[] angles,
final double[] arcDistances) {
// To do the point rotations, we need the sine and cosine of the pole latitude and longitude.
// Get it here for performance.
final double sinLatitude = Math.sin(pole.getLatitude());
final double cosLatitude = Math.cos(pole.getLatitude());
final double sinLongitude = Math.sin(pole.getLongitude());
final double cosLongitude = Math.cos(pole.getLongitude());
final List<GeoPoint> rval = new ArrayList<>();
for (int i = 0; i < angles.length; i++) {
rval.add(
createPoint(
pm,
angles[i],
arcDistances[i],
sinLatitude,
cosLatitude,
sinLongitude,
cosLongitude));
}
return rval;
}
protected static GeoPoint createPoint(
final PlanetModel pm,
final double angle,
final double arcDistance,
final double sinLatitude,
final double cosLatitude,
final double sinLongitude,
final double cosLongitude) {
// From the angle and arc distance, convert to (x,y,z) in unit space.
// We want the perspective to be looking down the x axis. The "angle" measurement is thus in
// the Y-Z plane. The arcdistance is in X.
final double x = Math.cos(arcDistance);
final double yzScale = Math.sin(arcDistance);
final double y = Math.cos(angle) * yzScale;
final double z = Math.sin(angle) * yzScale;
// Now, rotate coordinates so that we shift everything from pole = x-axis to actual coordinates.
// This transformation should take the point (1,0,0) and transform it to the pole's actual
// (x,y,z) coordinates.
// Coordinate rotation formula:
// x1 = x0 cos T - y0 sin T
// y1 = x0 sin T + y0 cos T
// We're in essence undoing the following transformation (from GeoPolygonFactory):
// x1 = x0 cos az + y0 sin az
// y1 = - x0 sin az + y0 cos az
// z1 = z0
// x2 = x1 cos al + z1 sin al
// y2 = y1
// z2 = - x1 sin al + z1 cos al
// So, we reverse the order of the transformations, AND we transform backwards.
// Transforming backwards means using these identities: sin(-angle) = -sin(angle), cos(-angle) =
// cos(angle)
// So:
// x1 = x0 cos al - z0 sin al
// y1 = y0
// z1 = x0 sin al + z0 cos al
// x2 = x1 cos az - y1 sin az
// y2 = x1 sin az + y1 cos az
// z2 = z1
final double x1 = x * cosLatitude - z * sinLatitude;
final double y1 = y;
final double z1 = x * sinLatitude + z * cosLatitude;
final double x2 = x1 * cosLongitude - y1 * sinLongitude;
final double y2 = x1 * sinLongitude + y1 * cosLongitude;
final double z2 = z1;
// Scale to put the point on the surface
return pm.createSurfacePoint(x2, y2, z2);
}
protected static boolean verifyPolygon(
final PlanetModel pm, final Polygon polygon, final GeoPolygon outsidePolygon) {
// Each point in the new poly should be inside the outside poly, and each edge should not
// intersect the outside poly edge
final double[] lats = polygon.getPolyLats();
final double[] lons = polygon.getPolyLons();
final List<GeoPoint> polyPoints = new ArrayList<>(lats.length - 1);
for (int i = 0; i < lats.length - 1; i++) {
final GeoPoint newPoint = new GeoPoint(pm, toRadians(lats[i]), toRadians(lons[i]));
if (!outsidePolygon.isWithin(newPoint)) {
return false;
}
polyPoints.add(newPoint);
}
// We don't need to construct the world to find intersections -- just the bordering planes.
for (int planeIndex = 0; planeIndex < polyPoints.size(); planeIndex++) {
final GeoPoint startPoint = polyPoints.get(planeIndex);
final GeoPoint endPoint = polyPoints.get(legalIndex(planeIndex + 1, polyPoints.size()));
final GeoPoint beforeStartPoint =
polyPoints.get(legalIndex(planeIndex - 1, polyPoints.size()));
final GeoPoint afterEndPoint = polyPoints.get(legalIndex(planeIndex + 2, polyPoints.size()));
final SidedPlane beforePlane = new SidedPlane(endPoint, beforeStartPoint, startPoint);
final SidedPlane afterPlane = new SidedPlane(startPoint, endPoint, afterEndPoint);
final Plane plane = new Plane(startPoint, endPoint);
// Check for intersections!!
if (outsidePolygon.intersects(plane, null, beforePlane, afterPlane)) {
return false;
}
}
return true;
}
protected static int legalIndex(int index, int size) {
if (index >= size) {
index -= size;
}
if (index < 0) {
index += size;
}
return index;
}
public void testEncodeDecodeCeil() throws Exception {
PlanetModel planetModel = randomPlanetModel();
// just for testing quantization error
final double ENCODING_TOLERANCE = planetModel.DECODE;
int iters = atLeast(10000);
for (int iter = 0; iter < iters; iter++) {
GeoPoint point =
new GeoPoint(
planetModel,
toRadians(GeoTestUtil.nextLatitude()),
toRadians(GeoTestUtil.nextLongitude()));
double xEnc = planetModel.decodeValue(planetModel.encodeValue(point.x));
assertEquals(
"x=" + point.x + " xEnc=" + xEnc + " diff=" + (point.x - xEnc),
point.x,
xEnc,
ENCODING_TOLERANCE);
double yEnc = planetModel.decodeValue(planetModel.encodeValue(point.y));
assertEquals(
"y=" + point.y + " yEnc=" + yEnc + " diff=" + (point.y - yEnc),
point.y,
yEnc,
ENCODING_TOLERANCE);
double zEnc = planetModel.decodeValue(planetModel.encodeValue(point.z));
assertEquals(
"z=" + point.z + " zEnc=" + zEnc + " diff=" + (point.z - zEnc),
point.z,
zEnc,
ENCODING_TOLERANCE);
}
// check edge/interesting cases explicitly
double planetMax = planetModel.getMaximumMagnitude();
for (double value : new double[] {0.0, -planetMax, planetMax}) {
assertEquals(
value, planetModel.decodeValue(planetModel.encodeValue(value)), ENCODING_TOLERANCE);
}
}
/** make sure values always go down: this is important for edge case consistency */
public void testEncodeDecodeRoundsDown() throws Exception {
PlanetModel planetModel = randomPlanetModel();
int iters = atLeast(1000);
for (int iter = 0; iter < iters; iter++) {
final double latBase = GeoTestUtil.nextLatitude();
final double lonBase = GeoTestUtil.nextLongitude();
// test above the value
double lat = latBase;
double lon = lonBase;
for (int i = 0; i < 1000; i++) {
lat = Math.min(90, Math.nextUp(lat));
lon = Math.min(180, Math.nextUp(lon));
GeoPoint point = new GeoPoint(planetModel, toRadians(lat), toRadians(lon));
GeoPoint pointEnc =
new GeoPoint(
Geo3DUtil.decodeValueFloor(planetModel.encodeValue(point.x), planetModel),
Geo3DUtil.decodeValueFloor(planetModel.encodeValue(point.y), planetModel),
Geo3DUtil.decodeValueFloor(planetModel.encodeValue(point.z), planetModel));
assertTrue(pointEnc.x <= point.x);
assertTrue(pointEnc.y <= point.y);
assertTrue(pointEnc.z <= point.z);
}
// test below the value
lat = latBase;
lon = lonBase;
for (int i = 0; i < 1000; i++) {
lat = Math.max(-90, Math.nextDown(lat));
lon = Math.max(-180, Math.nextDown(lon));
GeoPoint point = new GeoPoint(planetModel, toRadians(lat), toRadians(lon));
GeoPoint pointEnc =
new GeoPoint(
Geo3DUtil.decodeValueFloor(planetModel.encodeValue(point.x), planetModel),
Geo3DUtil.decodeValueFloor(planetModel.encodeValue(point.y), planetModel),
Geo3DUtil.decodeValueFloor(planetModel.encodeValue(point.z), planetModel));
assertTrue(pointEnc.x <= point.x);
assertTrue(pointEnc.y <= point.y);
assertTrue(pointEnc.z <= point.z);
}
}
}
public void testMinValueQuantization() {
PlanetModel planetModel = randomPlanetModel();
int encoded = planetModel.MIN_ENCODED_VALUE;
double minValue = -planetModel.getMaximumMagnitude();
// Normal encoding
double decoded = planetModel.decodeValue(encoded);
assertEquals(minValue, decoded, 0d);
assertEquals(encoded, planetModel.encodeValue(decoded));
// Encoding floor
double decodedFloor = Geo3DUtil.decodeValueFloor(encoded, planetModel);
assertEquals(minValue, decodedFloor, 0d);
assertEquals(encoded, planetModel.encodeValue(decodedFloor));
// Encoding ceiling
double decodedCeiling = Geo3DUtil.decodeValueCeil(encoded, planetModel);
assertTrue(decodedCeiling > minValue);
assertEquals(encoded, planetModel.encodeValue(decodedCeiling));
}
public void testMaxValueQuantization() {
PlanetModel planetModel = randomPlanetModel();
int encoded = planetModel.MAX_ENCODED_VALUE;
double maxValue = planetModel.getMaximumMagnitude();
// Normal encoding
double decoded = planetModel.decodeValue(encoded);
assertEquals(maxValue, decoded, 0d);
assertEquals(encoded, planetModel.encodeValue(decoded));
// Encoding floor
double decodedFloor = Geo3DUtil.decodeValueFloor(encoded, planetModel);
assertTrue(decodedFloor < maxValue);
assertEquals(encoded, planetModel.encodeValue(decodedFloor));
// Encoding ceiling
double decodedCeiling = Geo3DUtil.decodeValueCeil(encoded, planetModel);
assertEquals(maxValue, decodedCeiling, 0d);
assertEquals(encoded, planetModel.encodeValue(decodedCeiling));
}
// poached from TestGeoEncodingUtils.testLatitudeQuantization:
/**
* step through some integers, ensuring they decode to their expected double values. double values
* start at -planetMax and increase by Geo3DUtil.DECODE for each integer. check edge cases within
* the double range and random doubles within the range too.
*/
public void testQuantization() throws Exception {
Random random = random();
PlanetModel planetModel = randomPlanetModel();
for (int i = 0; i < 10000; i++) {
int encoded = random.nextInt();
if (encoded <= planetModel.MIN_ENCODED_VALUE) {
continue;
}
if (encoded >= planetModel.MAX_ENCODED_VALUE) {
continue;
}
double min = encoded * planetModel.DECODE;
double decoded = Geo3DUtil.decodeValueFloor(encoded, planetModel);
// should exactly equal expected value
assertEquals(min, decoded, 0.0D);
// should round-trip
assertEquals(encoded, planetModel.encodeValue(decoded));
// test within the range
if (encoded != Integer.MAX_VALUE) {
// this is the next representable value
// all double values between [min .. max) should encode to the current integer
double max = min + planetModel.DECODE;
assertEquals(max, Geo3DUtil.decodeValueFloor(encoded + 1, planetModel), 0.0D);
assertEquals(encoded + 1, planetModel.encodeValue(max));
// first and last doubles in range that will be quantized
double minEdge = Math.nextUp(min);
double maxEdge = Math.nextDown(max);
assertEquals(encoded, planetModel.encodeValue(minEdge));
assertEquals(encoded, planetModel.encodeValue(maxEdge));
// check random values within the double range
long minBits = NumericUtils.doubleToSortableLong(minEdge);
long maxBits = NumericUtils.doubleToSortableLong(maxEdge);
for (int j = 0; j < 100; j++) {
double value =
NumericUtils.sortableLongToDouble(TestUtil.nextLong(random, minBits, maxBits));
// round down
assertEquals(encoded, planetModel.encodeValue(value));
}
}
}
}
public void testEncodeDecodeIsStable() throws Exception {
PlanetModel planetModel = randomPlanetModel();
int iters = atLeast(1000);
for (int iter = 0; iter < iters; iter++) {
double lat = GeoTestUtil.nextLatitude();
double lon = GeoTestUtil.nextLongitude();
GeoPoint point = new GeoPoint(planetModel, toRadians(lat), toRadians(lon));
// encode point
GeoPoint pointEnc =
new GeoPoint(
planetModel.decodeValue(planetModel.encodeValue(point.x)),
planetModel.decodeValue(planetModel.encodeValue(point.y)),
planetModel.decodeValue(planetModel.encodeValue(point.z)));
// encode it again (double encode)
GeoPoint pointEnc2 =
new GeoPoint(
planetModel.decodeValue(planetModel.encodeValue(pointEnc.x)),
planetModel.decodeValue(planetModel.encodeValue(pointEnc.y)),
planetModel.decodeValue(planetModel.encodeValue(pointEnc.z)));
// System.out.println("TEST " + iter + ":\n point =" + point + "\n pointEnc =" + pointEnc
// + "\n pointEnc2=" + pointEnc2);
assertEquals(pointEnc.x, pointEnc2.x, 0.0);
assertEquals(pointEnc.y, pointEnc2.y, 0.0);
assertEquals(pointEnc.z, pointEnc2.z, 0.0);
}
}
public void testDistanceQuery() throws Exception {
Directory dir = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(random(), dir);
PlanetModel planetModel = randomPlanetModel();
// index two points:
Document doc = new Document();
doc.add(new Geo3DPoint("field", planetModel, 0.1, 0.1));
w.addDocument(doc);
doc = new Document();
doc.add(new Geo3DPoint("field", planetModel, 90, 1));
w.addDocument(doc);
///// search //////
IndexReader reader = w.getReader();
w.close();
IndexSearcher searcher = newSearcher(reader);
// simple query, in any planet model one point should be inside and the other outside
Query q =
Geo3DPoint.newDistanceQuery("field", planetModel, 0, 0, planetModel.getMeanRadius() * 0.01);
assertEquals(1, searcher.count(q));
IOUtils.close(w, reader, dir);
}
/**
* Clips the incoming value to the allowed min/max range before encoding, instead of throwing an
* exception.
*/
private static int encodeValueLenient(double x, PlanetModel planetModel) {
double planetMax = planetModel.getMaximumMagnitude();
if (x > planetMax) {
x = planetMax;
} else if (x < -planetMax) {
x = -planetMax;
}
return planetModel.encodeValue(x);
}
private static class ExplainingVisitor implements IntersectVisitor {
final GeoShape shape;
final GeoPoint targetDocPoint;
final GeoPoint scaledDocPoint;
final IntersectVisitor in;
final List<Cell> stack = new ArrayList<>();
private List<Cell> stackToTargetDoc;
final int targetDocID;
final int numDims;
final int bytesPerDim;
private int targetStackUpto;
final StringBuilder b;
// In the first phase, we always return CROSSES to do a full scan of the BKD tree to see which
// leaf block the document lives in
boolean firstPhase = true;
public ExplainingVisitor(
GeoShape shape,
GeoPoint targetDocPoint,
GeoPoint scaledDocPoint,
IntersectVisitor in,
int targetDocID,
int numDims,
int bytesPerDim,
StringBuilder b) {
this.shape = shape;
this.targetDocPoint = targetDocPoint;
this.scaledDocPoint = scaledDocPoint;
this.in = in;
this.targetDocID = targetDocID;
this.numDims = numDims;
this.bytesPerDim = bytesPerDim;
this.b = b;
}
public void startSecondPhase() {
if (firstPhase == false) {
throw new IllegalStateException("already started second phase");
}
if (stackToTargetDoc == null) {
b.append("target docID=" + targetDocID + " was never seen in points!\n");
}
firstPhase = false;
stack.clear();
}
@Override
public void visit(int docID) throws IOException {
assert firstPhase == false;
if (docID == targetDocID) {
b.append("leaf visit docID=" + docID + "\n");
}
}
@Override
public void visit(int docID, byte[] packedValue) throws IOException {
if (firstPhase) {
if (docID == targetDocID) {
assert stackToTargetDoc == null;
stackToTargetDoc = new ArrayList<>(stack);
b.append(" full BKD path to target doc:\n");
for (Cell cell : stack) {
b.append(" " + cell + "\n");
}
}
} else {
if (docID == targetDocID) {
double x = Geo3DPoint.decodeDimension(packedValue, 0, shape.getPlanetModel());
double y = Geo3DPoint.decodeDimension(packedValue, Integer.BYTES, shape.getPlanetModel());
double z =
Geo3DPoint.decodeDimension(packedValue, 2 * Integer.BYTES, shape.getPlanetModel());
b.append("leaf visit docID=" + docID + " x=" + x + " y=" + y + " z=" + z + "\n");
in.visit(docID, packedValue);
}
}
}
@Override
public Relation compare(byte[] minPackedValue, byte[] maxPackedValue) {
Cell cell = new Cell(minPackedValue, maxPackedValue);
// System.out.println("compare: " + cell);
// TODO: this is a bit hacky, having to reverse-engineer where we are in the BKD tree's
// recursion ... but it's the lesser evil vs e.g. polluting this visitor API, or
// implementing this "under the hood" in BKDReader instead?
if (firstPhase) {
// Pop stack:
while (stack.size() > 0 && stack.get(stack.size() - 1).contains(cell) == false) {
stack.remove(stack.size() - 1);
// System.out.println(" pop");
}
// Push stack:
stack.add(cell);
// System.out.println(" push");
return Relation.CELL_CROSSES_QUERY;
} else {
Relation result = in.compare(minPackedValue, maxPackedValue);
if (targetStackUpto < stackToTargetDoc.size()
&& cell.equals(stackToTargetDoc.get(targetStackUpto))) {
b.append(
" on cell "
+ stackToTargetDoc.get(targetStackUpto)
+ ", wrapped visitor returned "
+ result
+ "\n");
targetStackUpto++;
}
return result;
}
}
private class Cell {
private final byte[] minPackedValue;
private final byte[] maxPackedValue;
public Cell(byte[] minPackedValue, byte[] maxPackedValue) {
this.minPackedValue = minPackedValue.clone();
this.maxPackedValue = maxPackedValue.clone();
}
/** Returns true if this cell fully contains the other one */
public boolean contains(Cell other) {
for (int dim = 0; dim < numDims; dim++) {
int offset = bytesPerDim * dim;
// other.min < this.min?
if (Arrays.compareUnsigned(
other.minPackedValue,
offset,
offset + bytesPerDim,
minPackedValue,
offset,
offset + bytesPerDim)
< 0) {
return false;
}
// other.max < this.max?
if (Arrays.compareUnsigned(
other.maxPackedValue,
offset,
offset + bytesPerDim,
maxPackedValue,
offset,
offset + bytesPerDim)
> 0) {
return false;
}
}
return true;
}
@Override
public String toString() {
double xMin =
Geo3DUtil.decodeValueFloor(
NumericUtils.sortableBytesToInt(minPackedValue, 0), shape.getPlanetModel());
double xMax =
Geo3DUtil.decodeValueCeil(
NumericUtils.sortableBytesToInt(maxPackedValue, 0), shape.getPlanetModel());
double yMin =
Geo3DUtil.decodeValueFloor(
NumericUtils.sortableBytesToInt(minPackedValue, 1 * Integer.BYTES),
shape.getPlanetModel());
double yMax =
Geo3DUtil.decodeValueCeil(
NumericUtils.sortableBytesToInt(maxPackedValue, 1 * Integer.BYTES),
shape.getPlanetModel());
double zMin =
Geo3DUtil.decodeValueFloor(
NumericUtils.sortableBytesToInt(minPackedValue, 2 * Integer.BYTES),
shape.getPlanetModel());
double zMax =
Geo3DUtil.decodeValueCeil(
NumericUtils.sortableBytesToInt(maxPackedValue, 2 * Integer.BYTES),
shape.getPlanetModel());
final XYZSolid xyzSolid =
XYZSolidFactory.makeXYZSolid(
shape.getPlanetModel(), xMin, xMax, yMin, yMax, zMin, zMax);
final int relationship = xyzSolid.getRelationship(shape);
final boolean pointWithinCell = xyzSolid.isWithin(targetDocPoint);
final boolean scaledWithinCell = xyzSolid.isWithin(scaledDocPoint);
final String relationshipString;
switch (relationship) {
case GeoArea.CONTAINS:
relationshipString = "CONTAINS";
break;
case GeoArea.WITHIN:
relationshipString = "WITHIN";
break;
case GeoArea.OVERLAPS:
relationshipString = "OVERLAPS";
break;
case GeoArea.DISJOINT:
relationshipString = "DISJOINT";
break;
default:
relationshipString = "UNKNOWN";
break;
}
return "Cell(x="
+ xMin
+ " TO "
+ xMax
+ " y="
+ yMin
+ " TO "
+ yMax
+ " z="
+ zMin
+ " TO "
+ zMax
+ "); Shape relationship = "
+ relationshipString
+ "; Quantized point within cell = "
+ pointWithinCell
+ "; Unquantized point within cell = "
+ scaledWithinCell;
}
@Override
public boolean equals(Object other) {
if (other instanceof Cell == false) {
return false;
}
Cell otherCell = (Cell) other;
return Arrays.equals(minPackedValue, otherCell.minPackedValue)
&& Arrays.equals(maxPackedValue, otherCell.maxPackedValue);
}
@Override
public int hashCode() {
return Arrays.hashCode(minPackedValue) + Arrays.hashCode(maxPackedValue);
}
}
}
public static String explain(
String fieldName,
GeoShape shape,
GeoPoint targetDocPoint,
GeoPoint scaledDocPoint,
IndexReader reader,
int docID)
throws Exception {
final XYZBounds bounds = new XYZBounds();
shape.getBounds(bounds);
// First find the leaf reader that owns this doc:
int subIndex = ReaderUtil.subIndex(docID, reader.leaves());
LeafReader leafReader = reader.leaves().get(subIndex).reader();
StringBuilder b = new StringBuilder();
b.append("target is in leaf " + leafReader + " of full reader " + reader + "\n");
DocIdSetBuilder hits = new DocIdSetBuilder(leafReader.maxDoc());
ExplainingVisitor visitor =
new ExplainingVisitor(
shape,
targetDocPoint,
scaledDocPoint,
new PointInShapeIntersectVisitor(hits, shape, bounds),
docID - reader.leaves().get(subIndex).docBase,
3,
Integer.BYTES,
b);
// Do first phase, where we just figure out the "path" that leads to the target docID:
leafReader.getPointValues(fieldName).intersect(visitor);
// Do second phase, where we we see how the wrapped visitor responded along that path:
visitor.startSecondPhase();
leafReader.getPointValues(fieldName).intersect(visitor);
return b.toString();
}
}
|
9231829827f311eb103300990c1286048da34bcb | 268 | java | Java | src/main/java/tech/note/tool/Colour.java | jxmau/bamboo | bfa2bf82b41e78b2bbe6964dcaeae17cc9f7fb73 | [
"CC0-1.0"
] | null | null | null | src/main/java/tech/note/tool/Colour.java | jxmau/bamboo | bfa2bf82b41e78b2bbe6964dcaeae17cc9f7fb73 | [
"CC0-1.0"
] | null | null | null | src/main/java/tech/note/tool/Colour.java | jxmau/bamboo | bfa2bf82b41e78b2bbe6964dcaeae17cc9f7fb73 | [
"CC0-1.0"
] | null | null | null | 15.764706 | 30 | 0.559701 | 995,873 | package tech.note.tool;
public enum Colour {
RED("\u001B[31m"),
GREEN("\u001B[32m"),
RESET("\u001B[0m");
private final String code;
Colour(String code) {
this.code = code;
}
public String getCode() {
return code;
}
}
|
9231847525813ab8e949489ad7b1e676ffda0ac6 | 1,894 | java | Java | bundle/edu.gemini.pot/src/main/java/edu/gemini/spModel/gemini/gnirs/blueprint/SpGnirsBlueprintImaging.java | jocelynferrara/ocs | 446c8a8e03d86bd341ac024fae6811ecb643e185 | [
"BSD-3-Clause"
] | 13 | 2015-02-04T21:33:56.000Z | 2020-04-10T01:37:41.000Z | bundle/edu.gemini.pot/src/main/java/edu/gemini/spModel/gemini/gnirs/blueprint/SpGnirsBlueprintImaging.java | jocelynferrara/ocs | 446c8a8e03d86bd341ac024fae6811ecb643e185 | [
"BSD-3-Clause"
] | 1,169 | 2015-01-02T13:20:50.000Z | 2022-03-21T12:01:59.000Z | bundle/edu.gemini.pot/src/main/java/edu/gemini/spModel/gemini/gnirs/blueprint/SpGnirsBlueprintImaging.java | jocelynferrara/ocs | 446c8a8e03d86bd341ac024fae6811ecb643e185 | [
"BSD-3-Clause"
] | 13 | 2015-04-07T18:01:55.000Z | 2021-02-03T12:57:58.000Z | 32.101695 | 125 | 0.69377 | 995,874 | package edu.gemini.spModel.gemini.gnirs.blueprint;
import edu.gemini.spModel.gemini.altair.blueprint.SpAltair;
import edu.gemini.spModel.gemini.gnirs.GNIRSParams.Filter;
import edu.gemini.spModel.gemini.gnirs.GNIRSParams.PixelScale;
import edu.gemini.spModel.pio.ParamSet;
import edu.gemini.spModel.pio.Pio;
import edu.gemini.spModel.pio.PioFactory;
public final class SpGnirsBlueprintImaging extends SpGnirsBlueprintBase {
public static final String PARAM_SET_NAME = "gnirsBlueprintImaging";
public static final String FILTER_PARAM_NAME = "filter";
public final Filter filter;
public SpGnirsBlueprintImaging(SpAltair altair, PixelScale pixelScale, Filter filter) {
super(altair, pixelScale);
this.filter = filter;
}
public SpGnirsBlueprintImaging(ParamSet paramSet) {
super(paramSet);
this.filter = Pio.getEnumValue(paramSet, FILTER_PARAM_NAME, Filter.DEFAULT);
}
public String paramSetName() { return PARAM_SET_NAME; }
@Override
public String toString() {
return String.format("GNIRS Imaging %s %s %s", altair.shortName(), pixelScale.displayValue(), filter.displayValue());
}
public ParamSet toParamSet(PioFactory factory) {
ParamSet paramSet = super.toParamSet(factory);
Pio.addEnumParam(factory, paramSet, FILTER_PARAM_NAME, filter);
return paramSet;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
SpGnirsBlueprintImaging that = (SpGnirsBlueprintImaging) o;
if (filter != that.filter) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + filter.hashCode();
return result;
}
}
|
923184c3408c02722c3d12cd08fc2b5f701bb354 | 4,820 | java | Java | src/main/java/com/melesar/gui/FingerprintsForm.java | kajapa/fingerprints-master | 466095c49d10233b7d35f535bfd8a42b0eff3693 | [
"MIT"
] | null | null | null | src/main/java/com/melesar/gui/FingerprintsForm.java | kajapa/fingerprints-master | 466095c49d10233b7d35f535bfd8a42b0eff3693 | [
"MIT"
] | null | null | null | src/main/java/com/melesar/gui/FingerprintsForm.java | kajapa/fingerprints-master | 466095c49d10233b7d35f535bfd8a42b0eff3693 | [
"MIT"
] | null | null | null | 31.096774 | 99 | 0.663071 | 995,875 | package com.melesar.gui;
import com.melesar.fingerprints.FingerprintImage;
import com.melesar.fingerprints.Utilites;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
public class FingerprintsForm extends JFrame implements ActionListener, ListSelectionListener
{
private JPanel holder;
private JLabel mainImage;
private JScrollPane scroll;
private DefaultListModel<FingerprintPresenter> fingerprintList;
private ArrayList<FingerprintImage> fingerprintModels;
private FingerprintImage currentModel;
private static FingerprintsForm instance;
private final Color BACKGROUND_COLOR = new Color(50, 50,50);
public static FingerprintsForm run ()
{
if (instance != null) {
return instance;
}
FingerprintsForm form = new FingerprintsForm();
form.setContentPane(form.holder);
form.setLocationRelativeTo(null);
form.setSize(800, 700);
form.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
form.setVisible(true);
instance = form;
return instance;
}
private FingerprintsForm ()
{
loadData();
createUIComponents();
selectModel(0);
}
private void loadData()
{
InputStream stream = Utilites.class.getResourceAsStream("images");
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
fingerprintList = new DefaultListModel<>();
fingerprintModels = new ArrayList<>();
try {
String resource;
while((resource = reader.readLine()) != null) {
URL url = Utilites.class.getResource(String.format("images/%s", resource));
FingerprintImage fingerprintImage = FingerprintImage.create(new File(url.toURI()));
FingerprintPresenter presenter = new FingerprintPresenter(fingerprintImage);
fingerprintList.addElement(presenter);
fingerprintModels.add(fingerprintImage);
}
} catch (IOException | URISyntaxException ex) {
ex.printStackTrace();
}
}
private void createUIComponents()
{
JList<FingerprintPresenter> jList = new JList<>(fingerprintList);
jList.setFixedCellHeight(300);
jList.setFixedCellWidth(300);
jList.setCellRenderer(new FingerprintPresenterDrawer());
jList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jList.addListSelectionListener(this);
scroll = new JScrollPane(jList);
holder.add(scroll, BorderLayout.WEST);
JPanel content = new JPanel(new BorderLayout());
content.setBackground(BACKGROUND_COLOR);
holder.add(content, BorderLayout.CENTER);
mainImage = new JLabel();
mainImage.setSize(250, 300);
content.add(mainImage);
JPanel buttonsPanel = new JPanel();
buttonsPanel.setBackground(BACKGROUND_COLOR);
content.add(buttonsPanel, BorderLayout.SOUTH);
JButton cmpButton = new JButton("Compare");
cmpButton.setSize(100, 70);
cmpButton.setBackground(BACKGROUND_COLOR);
cmpButton.setForeground(new Color(200, 200, 200));
cmpButton.addActionListener(this);
buttonsPanel.add(cmpButton);
JButton soundButton = new JButton("Sound");
soundButton.setSize(100, 70);
soundButton.setBackground(BACKGROUND_COLOR);
soundButton.setForeground(new Color(200, 200, 200));
soundButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
SoundForm.showForm();
}
});
buttonsPanel.add(soundButton);
}
private void compareFingerprints()
{
for (int i = 0; i < fingerprintModels.size(); i++) {
FingerprintImage fingerprint = fingerprintModels.get(i);
boolean isMatch = fingerprint.isMatch(currentModel);
fingerprintList.getElementAt(i).update(isMatch);
}
scroll.updateUI();
}
private void selectModel(int index)
{
currentModel = fingerprintModels.get(index);
mainImage.setIcon(fingerprintList.elementAt(index).getIcon());
}
@Override
public void actionPerformed(ActionEvent e)
{
compareFingerprints();
}
@Override
public void valueChanged(ListSelectionEvent e)
{
selectModel(e.getFirstIndex());
}
}
|
92318599db6c78ab4fe250b2ec4ea74f45e4bd7c | 2,394 | java | Java | src/com/scs/joustgame/ecs/systems/PlayerMovementSystem.java | SteveSmith16384/Joust | ab4f4afb93ad92c8406cc567b0340fcba330baa8 | [
"MIT"
] | 1 | 2020-04-03T14:45:02.000Z | 2020-04-03T14:45:02.000Z | src/com/scs/joustgame/ecs/systems/PlayerMovementSystem.java | SteveSmith16384/Joust | ab4f4afb93ad92c8406cc567b0340fcba330baa8 | [
"MIT"
] | null | null | null | src/com/scs/joustgame/ecs/systems/PlayerMovementSystem.java | SteveSmith16384/Joust | ab4f4afb93ad92c8406cc567b0340fcba330baa8 | [
"MIT"
] | null | null | null | 28.164706 | 105 | 0.703008 | 995,876 | package com.scs.joustgame.ecs.systems;
import com.scs.basicecs.AbstractEntity;
import com.scs.basicecs.AbstractSystem;
import com.scs.basicecs.BasicECS;
import com.scs.joustgame.JoustMain;
import com.scs.joustgame.Settings;
import com.scs.joustgame.ecs.components.JumpingComponent;
import com.scs.joustgame.ecs.components.MovementComponent;
import com.scs.joustgame.ecs.components.PlayersAvatarComponent;
public class PlayerMovementSystem extends AbstractSystem {
private JoustMain game;
public PlayerMovementSystem(JoustMain _game, BasicECS ecs) {
super(ecs);
game = _game;
}
@Override
public Class<?> getComponentClass() {
return PlayersAvatarComponent.class;
}
@Override
public void processEntity(AbstractEntity player) {
PlayersAvatarComponent uic = (PlayersAvatarComponent)player.getComponent(PlayersAvatarComponent.class);
MovementComponent mc = (MovementComponent)player.getComponent(MovementComponent.class);
if (Settings.JOUST_MOVEMENT) {
if (uic.player.jumpOrFlap) {
game.playSound("flap.wav");
mc.offY -= 50; // Flap up
}
JumpingComponent jc = (JumpingComponent)player.getComponent(JumpingComponent.class);
/*if (uic.player.moveLeft && (uic.player.jumpOrFlap || jc.canJump)) {
mc.offX -= Settings.JOUST_PLAYER_SPEED;
} else if (uic.player.moveRight && (uic.player.jumpOrFlap || jc.canJump)) {
mc.offX += Settings.JOUST_PLAYER_SPEED;
}*/
if (uic.player.moveLeft) {
if (uic.player.jumpOrFlap) {
mc.offX -= Settings.JOUST_PLAYER_SPEED * 4;
}
if (jc.canJump) {
mc.offX -= Settings.JOUST_PLAYER_SPEED;
}
}
if (uic.player.moveRight) {
if (uic.player.jumpOrFlap) {
mc.offX += Settings.JOUST_PLAYER_SPEED * 4;
}
if (jc.canJump) {
mc.offX += Settings.JOUST_PLAYER_SPEED;
}
}
if (uic.player.jumpOrFlap) {
uic.player.jumpOrFlap = false;
}
mc.offX *= 0.999f; // Drag
} else {
if (uic.player.moveLeft) {
mc.offX = -Settings.NORMAL_PLAYER_SPEED;
} else if (uic.player.moveRight) {
mc.offX = Settings.NORMAL_PLAYER_SPEED;
}
if (uic.player.jumpOrFlap) {
JumpingComponent jc = (JumpingComponent)player.getComponent(JumpingComponent.class);
if (jc.canJump) {
//game.sfx.play("BonusCube.ogg");
mc.offY = -Settings.JUMP_FORCE;
jc.canJump = false;
} else {
//JoustMain.p("Cannot jump!");
}
}
}
}
} |
9231867cf8108cc8c7276c3ba76456cd4c67bc45 | 744 | java | Java | connectors/gridgo-redis/src/main/java/io/gridgo/redis/command/list/RedisRpopLpushHandler.java | gridgo/gridgo--community | b8f8f4255b146382ffb0caa08b503130de810096 | [
"MIT"
] | 4 | 2018-11-11T07:38:34.000Z | 2019-06-29T04:45:47.000Z | connectors/gridgo-redis/src/main/java/io/gridgo/redis/command/list/RedisRpopLpushHandler.java | gridgo/gridgo--community | b8f8f4255b146382ffb0caa08b503130de810096 | [
"MIT"
] | 32 | 2019-10-17T06:18:28.000Z | 2020-05-11T03:37:18.000Z | connectors/gridgo-redis/src/main/java/io/gridgo/redis/command/list/RedisRpopLpushHandler.java | gridgo/gridgo-connector | b5ac5c972afb22b1b1edfc04f41fdea7afe8d1c7 | [
"MIT"
] | null | null | null | 31 | 107 | 0.767473 | 995,877 | package io.gridgo.redis.command.list;
import org.joo.promise4j.Promise;
import io.gridgo.bean.BElement;
import io.gridgo.bean.BObject;
import io.gridgo.redis.RedisClient;
import io.gridgo.redis.command.AbstractRedisCommandHandler;
import io.gridgo.redis.command.RedisCommand;
import io.gridgo.redis.command.RedisCommands;
@RedisCommand(RedisCommands.RPOPLPUSH)
public class RedisRpopLpushHandler extends AbstractRedisCommandHandler {
public RedisRpopLpushHandler() {
super("source", "destination");
}
@Override
protected Promise<BElement, Exception> process(RedisClient redis, BObject options, BElement[] params) {
return redis.rpoplpush(params[0].asValue().getRaw(), params[1].asValue().getRaw());
}
}
|
9231876352bc8d63a65441a7f8974b115e815e8e | 1,882 | java | Java | engine/src/main/java/org/camunda/bpm/engine/history/IncidentState.java | joansmith2/camunda-bpm-platform | fca40c811a2e3c0cdd60ec7026f845aacb790f03 | [
"Apache-2.0"
] | 4 | 2016-10-28T13:10:55.000Z | 2017-04-25T07:12:40.000Z | engine/src/main/java/org/camunda/bpm/engine/history/IncidentState.java | joansmith2/camunda-bpm-platform | fca40c811a2e3c0cdd60ec7026f845aacb790f03 | [
"Apache-2.0"
] | 1 | 2022-03-31T21:02:16.000Z | 2022-03-31T21:02:16.000Z | engine/src/main/java/org/camunda/bpm/engine/history/IncidentState.java | joansmith2/camunda-bpm-platform | fca40c811a2e3c0cdd60ec7026f845aacb790f03 | [
"Apache-2.0"
] | 1 | 2019-09-07T01:31:19.000Z | 2019-09-07T01:31:19.000Z | 25.780822 | 78 | 0.649309 | 995,878 | /* 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.camunda.bpm.engine.history;
/**
* @author Roman Smirnov
*
*/
public interface IncidentState {
IncidentState DEFAULT = new IncidentStateImpl(0, "open");
IncidentState RESOLVED = new IncidentStateImpl(1, "resolved");
IncidentState DELETED = new IncidentStateImpl(2, "deleted");
int getStateCode();
///////////////////////////////////////////////////// default implementation
static class IncidentStateImpl implements IncidentState {
public final int stateCode;
protected final String name;
public IncidentStateImpl(int suspensionCode, String string) {
this.stateCode = suspensionCode;
this.name = string;
}
public int getStateCode() {
return stateCode;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + stateCode;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
IncidentStateImpl other = (IncidentStateImpl) obj;
if (stateCode != other.stateCode)
return false;
return true;
}
@Override
public String toString() {
return name;
}
}
}
|
923187b9e9bade84d9f437ae1d4f55d2ad2d43d9 | 2,101 | java | Java | Chapter5/src/Problem5_18.java | ratnaakula/prathyusha | 03f05171617ea95b96b8bd14d3968390b77e2fc1 | [
"MIT"
] | null | null | null | Chapter5/src/Problem5_18.java | ratnaakula/prathyusha | 03f05171617ea95b96b8bd14d3968390b77e2fc1 | [
"MIT"
] | null | null | null | Chapter5/src/Problem5_18.java | ratnaakula/prathyusha | 03f05171617ea95b96b8bd14d3968390b77e2fc1 | [
"MIT"
] | null | null | null | 23.087912 | 82 | 0.485483 | 995,879 | /* (Display four patterns using loops) Use nested loops that display the following
Patterns in four separate programs:
Pattern A Pattern B Pattern C Pattern D
1 1 2 3 4 5 6 7 1 1 2 3 4 5 6 7
1 2 1 2 3 4 5 6 2 1 1 2 3 4 5 6
1 2 3 1 2 3 4 5 3 2 1 1 2 3 4 5
1 2 3 4 1 2 3 4 4 3 2 1 1 2 3 4
1 2 3 4 5 1 2 3 5 4 3 2 1 1 2 3
1 2 3 4 5 6 1 2 6 5 4 3 2 1 1 2
1 2 3 4 5 6 7 1 7 6 5 4 3 2 1 1
*/
import java.util.Scanner;
public class Problem5_18 {
public static void main(String[] args)
{
printPatternA();
printPatternB();
printPatternC();
printPatterD();
}
public static void printPatternA()
{
System.out.println("Printing Pattern A ");
for(int i = 1 ; i <= 7; i++)
{
for(int j = 1 ; j <= i; j++)
{
System.out.print(j + " ");
}
System.out.println();
}
System.out.println("Done Printing Pattern A \n ");
}
public static void printPatternB()
{
System.out.println("Printing Pattern B ");
for(int i = 7; i >= 1; i--)
{
for(int j = 1; j <= i; j++) {
System.out.print(j+ " ");
}
System.out.println();
}
System.out.println("Done Printing Pattern B \n ");
}
public static void printPatternC() {
System.out.println("Printing Pattern C");
for(int i = 1; i <= 7; i++)
{
for(int j = (7-i); j >= 1 ; j--)
{
System.out.print(" ");
}
for(int k = i ; k >= 1; k--)
{
System.out.print(k + " ");
}
System.out.println();
}
System.out.println("Done Printing Pattern C \n ");
}
public static void printPatterD()
{
System.out.println("Printing Pattern D \n");
for(int i = 7; i >= 1; i--)
{
for(int k = (7-i); k >= 1 ; k--)
{
System.out.print(" ");
}
for(int j = 1; j <= i; j++) {
System.out.print(j+ " ");
}
System.out.println();
}
System.out.println("Done Printing Pattern D \n");
}
} |
923187faa563eabf1bc2ef0c94205bb25722a7b2 | 38,809 | java | Java | src/main/java/cspstemmer/ArabicStemmer.java | swelcker/cmd.csp.stemmer | 6aca03f1b4e845e91745845ba67a27d9b3e323e5 | [
"MIT"
] | null | null | null | src/main/java/cspstemmer/ArabicStemmer.java | swelcker/cmd.csp.stemmer | 6aca03f1b4e845e91745845ba67a27d9b3e323e5 | [
"MIT"
] | null | null | null | src/main/java/cspstemmer/ArabicStemmer.java | swelcker/cmd.csp.stemmer | 6aca03f1b4e845e91745845ba67a27d9b3e323e5 | [
"MIT"
] | null | null | null | 22.11339 | 75 | 0.545724 | 995,880 |
// http://snowballstem.org/
package cspstemmer;
/**
* This class was automatically generated by a Snowball to Java compiler It
* implements the stemming algorithm defined by a snowball script.
*/
public class ArabicStemmer extends SnowballStemmer{
private static final long serialVersionUID=1L;
private final static Among a_0[]={
new Among("\u00D9\u0080",-1,1),
new Among("\u00D9\u008B",-1,1),
new Among("\u00D9\u008C",-1,1),
new Among("\u00D9\u008D",-1,1),
new Among("\u00D9\u008E",-1,1),
new Among("\u00D9\u008F",-1,1),
new Among("\u00D9\u0090",-1,1),
new Among("\u00D9\u0091",-1,1),
new Among("\u00D9\u0092",-1,1),
new Among("\u00D9\u00A0",-1,2),
new Among("\u00D9\u00A1",-1,3),
new Among("\u00D9\u00A2",-1,4),
new Among("\u00D9\u00A3",-1,5),
new Among("\u00D9\u00A4",-1,6),
new Among("\u00D9\u00A5",-1,7),
new Among("\u00D9\u00A6",-1,8),
new Among("\u00D9\u00A7",-1,9),
new Among("\u00D9\u00A8",-1,10),
new Among("\u00D9\u00A9",-1,11),
new Among("\u00EF\u00BA\u0080",-1,12),
new Among("\u00EF\u00BA\u0081",-1,16),
new Among("\u00EF\u00BA\u0082",-1,16),
new Among("\u00EF\u00BA\u0083",-1,13),
new Among("\u00EF\u00BA\u0084",-1,13),
new Among("\u00EF\u00BA\u0085",-1,17),
new Among("\u00EF\u00BA\u0086",-1,17),
new Among("\u00EF\u00BA\u0087",-1,14),
new Among("\u00EF\u00BA\u0088",-1,14),
new Among("\u00EF\u00BA\u0089",-1,15),
new Among("\u00EF\u00BA\u008A",-1,15),
new Among("\u00EF\u00BA\u008B",-1,15),
new Among("\u00EF\u00BA\u008C",-1,15),
new Among("\u00EF\u00BA\u008D",-1,18),
new Among("\u00EF\u00BA\u008E",-1,18),
new Among("\u00EF\u00BA\u008F",-1,19),
new Among("\u00EF\u00BA\u0090",-1,19),
new Among("\u00EF\u00BA\u0091",-1,19),
new Among("\u00EF\u00BA\u0092",-1,19),
new Among("\u00EF\u00BA\u0093",-1,20),
new Among("\u00EF\u00BA\u0094",-1,20),
new Among("\u00EF\u00BA\u0095",-1,21),
new Among("\u00EF\u00BA\u0096",-1,21),
new Among("\u00EF\u00BA\u0097",-1,21),
new Among("\u00EF\u00BA\u0098",-1,21),
new Among("\u00EF\u00BA\u0099",-1,22),
new Among("\u00EF\u00BA\u009A",-1,22),
new Among("\u00EF\u00BA\u009B",-1,22),
new Among("\u00EF\u00BA\u009C",-1,22),
new Among("\u00EF\u00BA\u009D",-1,23),
new Among("\u00EF\u00BA\u009E",-1,23),
new Among("\u00EF\u00BA\u009F",-1,23),
new Among("\u00EF\u00BA\u00A0",-1,23),
new Among("\u00EF\u00BA\u00A1",-1,24),
new Among("\u00EF\u00BA\u00A2",-1,24),
new Among("\u00EF\u00BA\u00A3",-1,24),
new Among("\u00EF\u00BA\u00A4",-1,24),
new Among("\u00EF\u00BA\u00A5",-1,25),
new Among("\u00EF\u00BA\u00A6",-1,25),
new Among("\u00EF\u00BA\u00A7",-1,25),
new Among("\u00EF\u00BA\u00A8",-1,25),
new Among("\u00EF\u00BA\u00A9",-1,26),
new Among("\u00EF\u00BA\u00AA",-1,26),
new Among("\u00EF\u00BA\u00AB",-1,27),
new Among("\u00EF\u00BA\u00AC",-1,27),
new Among("\u00EF\u00BA\u00AD",-1,28),
new Among("\u00EF\u00BA\u00AE",-1,28),
new Among("\u00EF\u00BA\u00AF",-1,29),
new Among("\u00EF\u00BA\u00B0",-1,29),
new Among("\u00EF\u00BA\u00B1",-1,30),
new Among("\u00EF\u00BA\u00B2",-1,30),
new Among("\u00EF\u00BA\u00B3",-1,30),
new Among("\u00EF\u00BA\u00B4",-1,30),
new Among("\u00EF\u00BA\u00B5",-1,31),
new Among("\u00EF\u00BA\u00B6",-1,31),
new Among("\u00EF\u00BA\u00B7",-1,31),
new Among("\u00EF\u00BA\u00B8",-1,31),
new Among("\u00EF\u00BA\u00B9",-1,32),
new Among("\u00EF\u00BA\u00BA",-1,32),
new Among("\u00EF\u00BA\u00BB",-1,32),
new Among("\u00EF\u00BA\u00BC",-1,32),
new Among("\u00EF\u00BA\u00BD",-1,33),
new Among("\u00EF\u00BA\u00BE",-1,33),
new Among("\u00EF\u00BA\u00BF",-1,33),
new Among("\u00EF\u00BB\u0080",-1,33),
new Among("\u00EF\u00BB\u0081",-1,34),
new Among("\u00EF\u00BB\u0082",-1,34),
new Among("\u00EF\u00BB\u0083",-1,34),
new Among("\u00EF\u00BB\u0084",-1,34),
new Among("\u00EF\u00BB\u0085",-1,35),
new Among("\u00EF\u00BB\u0086",-1,35),
new Among("\u00EF\u00BB\u0087",-1,35),
new Among("\u00EF\u00BB\u0088",-1,35),
new Among("\u00EF\u00BB\u0089",-1,36),
new Among("\u00EF\u00BB\u008A",-1,36),
new Among("\u00EF\u00BB\u008B",-1,36),
new Among("\u00EF\u00BB\u008C",-1,36),
new Among("\u00EF\u00BB\u008D",-1,37),
new Among("\u00EF\u00BB\u008E",-1,37),
new Among("\u00EF\u00BB\u008F",-1,37),
new Among("\u00EF\u00BB\u0090",-1,37),
new Among("\u00EF\u00BB\u0091",-1,38),
new Among("\u00EF\u00BB\u0092",-1,38),
new Among("\u00EF\u00BB\u0093",-1,38),
new Among("\u00EF\u00BB\u0094",-1,38),
new Among("\u00EF\u00BB\u0095",-1,39),
new Among("\u00EF\u00BB\u0096",-1,39),
new Among("\u00EF\u00BB\u0097",-1,39),
new Among("\u00EF\u00BB\u0098",-1,39),
new Among("\u00EF\u00BB\u0099",-1,40),
new Among("\u00EF\u00BB\u009A",-1,40),
new Among("\u00EF\u00BB\u009B",-1,40),
new Among("\u00EF\u00BB\u009C",-1,40),
new Among("\u00EF\u00BB\u009D",-1,41),
new Among("\u00EF\u00BB\u009E",-1,41),
new Among("\u00EF\u00BB\u009F",-1,41),
new Among("\u00EF\u00BB\u00A0",-1,41),
new Among("\u00EF\u00BB\u00A1",-1,42),
new Among("\u00EF\u00BB\u00A2",-1,42),
new Among("\u00EF\u00BB\u00A3",-1,42),
new Among("\u00EF\u00BB\u00A4",-1,42),
new Among("\u00EF\u00BB\u00A5",-1,43),
new Among("\u00EF\u00BB\u00A6",-1,43),
new Among("\u00EF\u00BB\u00A7",-1,43),
new Among("\u00EF\u00BB\u00A8",-1,43),
new Among("\u00EF\u00BB\u00A9",-1,44),
new Among("\u00EF\u00BB\u00AA",-1,44),
new Among("\u00EF\u00BB\u00AB",-1,44),
new Among("\u00EF\u00BB\u00AC",-1,44),
new Among("\u00EF\u00BB\u00AD",-1,45),
new Among("\u00EF\u00BB\u00AE",-1,45),
new Among("\u00EF\u00BB\u00AF",-1,46),
new Among("\u00EF\u00BB\u00B0",-1,46),
new Among("\u00EF\u00BB\u00B1",-1,47),
new Among("\u00EF\u00BB\u00B2",-1,47),
new Among("\u00EF\u00BB\u00B3",-1,47),
new Among("\u00EF\u00BB\u00B4",-1,47),
new Among("\u00EF\u00BB\u00B5",-1,51),
new Among("\u00EF\u00BB\u00B6",-1,51),
new Among("\u00EF\u00BB\u00B7",-1,49),
new Among("\u00EF\u00BB\u00B8",-1,49),
new Among("\u00EF\u00BB\u00B9",-1,50),
new Among("\u00EF\u00BB\u00BA",-1,50),
new Among("\u00EF\u00BB\u00BB",-1,48),
new Among("\u00EF\u00BB\u00BC",-1,48)
};
private final static Among a_1[]={
new Among("\u00D8\u00A2",-1,1),
new Among("\u00D8\u00A3",-1,1),
new Among("\u00D8\u00A4",-1,1),
new Among("\u00D8\u00A5",-1,1),
new Among("\u00D8\u00A6",-1,1)
};
private final static Among a_2[]={
new Among("\u00D8\u00A2",-1,1),
new Among("\u00D8\u00A3",-1,1),
new Among("\u00D8\u00A4",-1,2),
new Among("\u00D8\u00A5",-1,1),
new Among("\u00D8\u00A6",-1,3)
};
private final static Among a_3[]={
new Among("\u00D8\u00A7\u00D9\u0084",-1,2),
new Among("\u00D8\u00A8\u00D8\u00A7\u00D9\u0084",-1,1),
new Among("\u00D9\u0083\u00D8\u00A7\u00D9\u0084",-1,1),
new Among("\u00D9\u0084\u00D9\u0084",-1,2)
};
private final static Among a_4[]={
new Among("\u00D8\u00A3\u00D8\u00A2",-1,2),
new Among("\u00D8\u00A3\u00D8\u00A3",-1,1),
new Among("\u00D8\u00A3\u00D8\u00A4",-1,1),
new Among("\u00D8\u00A3\u00D8\u00A5",-1,4),
new Among("\u00D8\u00A3\u00D8\u00A7",-1,3)
};
private final static Among a_5[]={
new Among("\u00D9\u0081",-1,1),
new Among("\u00D9\u0088",-1,1)
};
private final static Among a_6[]={
new Among("\u00D8\u00A7\u00D9\u0084",-1,2),
new Among("\u00D8\u00A8\u00D8\u00A7\u00D9\u0084",-1,1),
new Among("\u00D9\u0083\u00D8\u00A7\u00D9\u0084",-1,1),
new Among("\u00D9\u0084\u00D9\u0084",-1,2)
};
private final static Among a_7[]={
new Among("\u00D8\u00A8",-1,1),
new Among("\u00D8\u00A8\u00D8\u00A8",0,2),
new Among("\u00D9\u0083\u00D9\u0083",-1,3)
};
private final static Among a_8[]={
new Among("\u00D8\u00B3\u00D8\u00A3",-1,4),
new Among("\u00D8\u00B3\u00D8\u00AA",-1,2),
new Among("\u00D8\u00B3\u00D9\u0086",-1,3),
new Among("\u00D8\u00B3\u00D9\u008A",-1,1)
};
private final static Among a_9[]={
new Among("\u00D8\u00AA\u00D8\u00B3\u00D8\u00AA",-1,1),
new Among("\u00D9\u0086\u00D8\u00B3\u00D8\u00AA",-1,1),
new Among("\u00D9\u008A\u00D8\u00B3\u00D8\u00AA",-1,1)
};
private final static Among a_10[]={
new Among("\u00D9\u0083",-1,1),
new Among("\u00D9\u0083\u00D9\u0085",-1,2),
new Among("\u00D9\u0087\u00D9\u0085",-1,2),
new Among("\u00D9\u0087\u00D9\u0086",-1,2),
new Among("\u00D9\u0087",-1,1),
new Among("\u00D9\u008A",-1,1),
new Among("\u00D9\u0083\u00D9\u0085\u00D8\u00A7",-1,3),
new Among("\u00D9\u0087\u00D9\u0085\u00D8\u00A7",-1,3),
new Among("\u00D9\u0086\u00D8\u00A7",-1,2),
new Among("\u00D9\u0087\u00D8\u00A7",-1,2)
};
private final static Among a_11[]={
new Among("\u00D9\u0086",-1,1)
};
private final static Among a_12[]={
new Among("\u00D9\u0088",-1,1),
new Among("\u00D9\u008A",-1,1),
new Among("\u00D8\u00A7",-1,1)
};
private final static Among a_13[]={
new Among("\u00D8\u00A7\u00D8\u00AA",-1,1)
};
private final static Among a_14[]={
new Among("\u00D8\u00AA",-1,1)
};
private final static Among a_15[]={
new Among("\u00D8\u00A9",-1,1)
};
private final static Among a_16[]={
new Among("\u00D9\u008A",-1,1)
};
private final static Among a_17[]={
new Among("\u00D9\u0083",-1,1),
new Among("\u00D9\u0083\u00D9\u0085",-1,2),
new Among("\u00D9\u0087\u00D9\u0085",-1,2),
new Among("\u00D9\u0083\u00D9\u0086",-1,2),
new Among("\u00D9\u0087\u00D9\u0086",-1,2),
new Among("\u00D9\u0087",-1,1),
new Among("\u00D9\u0083\u00D9\u0085\u00D9\u0088",-1,3),
new Among("\u00D9\u0086\u00D9\u008A",-1,2),
new Among("\u00D9\u0083\u00D9\u0085\u00D8\u00A7",-1,3),
new Among("\u00D9\u0087\u00D9\u0085\u00D8\u00A7",-1,3),
new Among("\u00D9\u0086\u00D8\u00A7",-1,2),
new Among("\u00D9\u0087\u00D8\u00A7",-1,2)
};
private final static Among a_18[]={
new Among("\u00D9\u0086",-1,1),
new Among("\u00D9\u0088\u00D9\u0086",0,3),
new Among("\u00D9\u008A\u00D9\u0086",0,3),
new Among("\u00D8\u00A7\u00D9\u0086",0,3),
new Among("\u00D8\u00AA\u00D9\u0086",0,2),
new Among("\u00D9\u008A",-1,1),
new Among("\u00D8\u00A7",-1,1),
new Among("\u00D8\u00AA\u00D9\u0085\u00D8\u00A7",6,4),
new Among("\u00D9\u0086\u00D8\u00A7",6,2),
new Among("\u00D8\u00AA\u00D8\u00A7",6,2),
new Among("\u00D8\u00AA",-1,1)
};
private final static Among a_19[]={
new Among("\u00D8\u00AA\u00D9\u0085",-1,1),
new Among("\u00D9\u0088\u00D8\u00A7",-1,1)
};
private final static Among a_20[]={
new Among("\u00D9\u0088",-1,1),
new Among("\u00D8\u00AA\u00D9\u0085\u00D9\u0088",0,2)
};
private final static Among a_21[]={
new Among("\u00D9\u0089",-1,1)
};
private boolean B_is_defined;
private boolean B_is_verb;
private boolean B_is_noun;
private int I_word_len;
private boolean r_Normalize_pre(){
int among_var;
// (, line 251
// loop, line 252
for(int v_1=current.length();v_1>0;v_1--){
// (, line 252
// or, line 316
lab0:
do{
int v_2=cursor;
lab1:
do{
// (, line 253
// [, line 254
bra=cursor;
// substring, line 254
among_var=find_among(a_0);
if(among_var==0){
break lab1;
}
// ], line 254
ket=cursor;
switch(among_var){
case 0:
break lab1;
case 1:
// (, line 255
// delete, line 255
slice_del();
break;
case 2:
// (, line 259
// <-, line 259
slice_from("0");
break;
case 3:
// (, line 260
// <-, line 260
slice_from("1");
break;
case 4:
// (, line 261
// <-, line 261
slice_from("2");
break;
case 5:
// (, line 262
// <-, line 262
slice_from("3");
break;
case 6:
// (, line 263
// <-, line 263
slice_from("4");
break;
case 7:
// (, line 264
// <-, line 264
slice_from("5");
break;
case 8:
// (, line 265
// <-, line 265
slice_from("6");
break;
case 9:
// (, line 266
// <-, line 266
slice_from("7");
break;
case 10:
// (, line 267
// <-, line 267
slice_from("8");
break;
case 11:
// (, line 268
// <-, line 268
slice_from("9");
break;
case 12:
// (, line 271
// <-, line 271
slice_from("\u00D8\u00A1");
break;
case 13:
// (, line 272
// <-, line 272
slice_from("\u00D8\u00A3");
break;
case 14:
// (, line 273
// <-, line 273
slice_from("\u00D8\u00A5");
break;
case 15:
// (, line 274
// <-, line 274
slice_from("\u00D8\u00A6");
break;
case 16:
// (, line 275
// <-, line 275
slice_from("\u00D8\u00A2");
break;
case 17:
// (, line 276
// <-, line 276
slice_from("\u00D8\u00A4");
break;
case 18:
// (, line 277
// <-, line 277
slice_from("\u00D8\u00A7");
break;
case 19:
// (, line 278
// <-, line 278
slice_from("\u00D8\u00A8");
break;
case 20:
// (, line 279
// <-, line 279
slice_from("\u00D8\u00A9");
break;
case 21:
// (, line 280
// <-, line 280
slice_from("\u00D8\u00AA");
break;
case 22:
// (, line 281
// <-, line 281
slice_from("\u00D8\u00AB");
break;
case 23:
// (, line 282
// <-, line 282
slice_from("\u00D8\u00AC");
break;
case 24:
// (, line 283
// <-, line 283
slice_from("\u00D8\u00AD");
break;
case 25:
// (, line 284
// <-, line 284
slice_from("\u00D8\u00AE");
break;
case 26:
// (, line 285
// <-, line 285
slice_from("\u00D8\u00AF");
break;
case 27:
// (, line 286
// <-, line 286
slice_from("\u00D8\u00B0");
break;
case 28:
// (, line 287
// <-, line 287
slice_from("\u00D8\u00B1");
break;
case 29:
// (, line 288
// <-, line 288
slice_from("\u00D8\u00B2");
break;
case 30:
// (, line 289
// <-, line 289
slice_from("\u00D8\u00B3");
break;
case 31:
// (, line 290
// <-, line 290
slice_from("\u00D8\u00B4");
break;
case 32:
// (, line 291
// <-, line 291
slice_from("\u00D8\u00B5");
break;
case 33:
// (, line 292
// <-, line 292
slice_from("\u00D8\u00B6");
break;
case 34:
// (, line 293
// <-, line 293
slice_from("\u00D8\u00B7");
break;
case 35:
// (, line 294
// <-, line 294
slice_from("\u00D8\u00B8");
break;
case 36:
// (, line 295
// <-, line 295
slice_from("\u00D8\u00B9");
break;
case 37:
// (, line 296
// <-, line 296
slice_from("\u00D8\u00BA");
break;
case 38:
// (, line 297
// <-, line 297
slice_from("\u00D9\u0081");
break;
case 39:
// (, line 298
// <-, line 298
slice_from("\u00D9\u0082");
break;
case 40:
// (, line 299
// <-, line 299
slice_from("\u00D9\u0083");
break;
case 41:
// (, line 300
// <-, line 300
slice_from("\u00D9\u0084");
break;
case 42:
// (, line 301
// <-, line 301
slice_from("\u00D9\u0085");
break;
case 43:
// (, line 302
// <-, line 302
slice_from("\u00D9\u0086");
break;
case 44:
// (, line 303
// <-, line 303
slice_from("\u00D9\u0087");
break;
case 45:
// (, line 304
// <-, line 304
slice_from("\u00D9\u0088");
break;
case 46:
// (, line 305
// <-, line 305
slice_from("\u00D9\u0089");
break;
case 47:
// (, line 306
// <-, line 306
slice_from("\u00D9\u008A");
break;
case 48:
// (, line 309
// <-, line 309
slice_from("\u00D9\u0084\u00D8\u00A7");
break;
case 49:
// (, line 310
// <-, line 310
slice_from("\u00D9\u0084\u00D8\u00A3");
break;
case 50:
// (, line 311
// <-, line 311
slice_from("\u00D9\u0084\u00D8\u00A5");
break;
case 51:
// (, line 312
// <-, line 312
slice_from("\u00D9\u0084\u00D8\u00A2");
break;
}
break lab0;
}while(false);
cursor=v_2;
// next, line 317
if(cursor>=limit){
return false;
}
cursor++;
}while(false);
}
return true;
}
private boolean r_Normalize_post(){
int among_var;
// (, line 321
// do, line 323
int v_1=cursor;
lab0:
do{
// (, line 323
// backwards, line 325
limit_backward=cursor;
cursor=limit;
// (, line 325
// [, line 326
ket=cursor;
// substring, line 326
among_var=find_among_b(a_1);
if(among_var==0){
break lab0;
}
// ], line 326
bra=cursor;
switch(among_var){
case 0:
break lab0;
case 1:
// (, line 327
// <-, line 327
slice_from("\u00D8\u00A1");
break;
}
cursor=limit_backward;
}while(false);
cursor=v_1;
// do, line 334
int v_2=cursor;
lab1:
do{
// loop, line 334
for(int v_3=I_word_len;v_3>0;v_3--){
// (, line 334
// or, line 343
lab2:
do{
int v_4=cursor;
lab3:
do{
// (, line 335
// [, line 337
bra=cursor;
// substring, line 337
among_var=find_among(a_2);
if(among_var==0){
break lab3;
}
// ], line 337
ket=cursor;
switch(among_var){
case 0:
break lab3;
case 1:
// (, line 338
// <-, line 338
slice_from("\u00D8\u00A7");
break;
case 2:
// (, line 339
// <-, line 339
slice_from("\u00D9\u0088");
break;
case 3:
// (, line 340
// <-, line 340
slice_from("\u00D9\u008A");
break;
}
break lab2;
}while(false);
cursor=v_4;
// next, line 344
if(cursor>=limit){
break lab1;
}
cursor++;
}while(false);
}
}while(false);
cursor=v_2;
return true;
}
private boolean r_Checks1(){
int among_var;
// (, line 349
I_word_len=current.length();
// [, line 351
bra=cursor;
// substring, line 351
among_var=find_among(a_3);
if(among_var==0){
return false;
}
// ], line 351
ket=cursor;
switch(among_var){
case 0:
return false;
case 1:
// (, line 352
if(!(I_word_len>4)){
return false;
}
// set is_noun, line 352
B_is_noun=true;
// unset is_verb, line 352
B_is_verb=false;
// set is_defined, line 352
B_is_defined=true;
break;
case 2:
// (, line 353
if(!(I_word_len>3)){
return false;
}
// set is_noun, line 353
B_is_noun=true;
// unset is_verb, line 353
B_is_verb=false;
// set is_defined, line 353
B_is_defined=true;
break;
}
return true;
}
private boolean r_Prefix_Step1(){
int among_var;
// (, line 359
I_word_len=current.length();
// [, line 361
bra=cursor;
// substring, line 361
among_var=find_among(a_4);
if(among_var==0){
return false;
}
// ], line 361
ket=cursor;
switch(among_var){
case 0:
return false;
case 1:
// (, line 362
if(!(I_word_len>3)){
return false;
}
// <-, line 362
slice_from("\u00D8\u00A3");
break;
case 2:
// (, line 363
if(!(I_word_len>3)){
return false;
}
// <-, line 363
slice_from("\u00D8\u00A2");
break;
case 3:
// (, line 365
if(!(I_word_len>3)){
return false;
}
// <-, line 365
slice_from("\u00D8\u00A7");
break;
case 4:
// (, line 366
if(!(I_word_len>3)){
return false;
}
// <-, line 366
slice_from("\u00D8\u00A5");
break;
}
return true;
}
private boolean r_Prefix_Step2(){
int among_var;
// (, line 371
I_word_len=current.length();
// not, line 373
{
int v_1=cursor;
lab0:
do{
// literal, line 373
if(!(eq_s("\u00D9\u0081\u00D8\u00A7"))){
break lab0;
}
return false;
}while(false);
cursor=v_1;
}
// not, line 374
{
int v_2=cursor;
lab1:
do{
// literal, line 374
if(!(eq_s("\u00D9\u0088\u00D8\u00A7"))){
break lab1;
}
return false;
}while(false);
cursor=v_2;
}
// [, line 375
bra=cursor;
// substring, line 375
among_var=find_among(a_5);
if(among_var==0){
return false;
}
// ], line 375
ket=cursor;
switch(among_var){
case 0:
return false;
case 1:
// (, line 376
if(!(I_word_len>3)){
return false;
}
// delete, line 376
slice_del();
break;
}
return true;
}
private boolean r_Prefix_Step3a_Noun(){
int among_var;
// (, line 381
I_word_len=current.length();
// [, line 383
bra=cursor;
// substring, line 383
among_var=find_among(a_6);
if(among_var==0){
return false;
}
// ], line 383
ket=cursor;
switch(among_var){
case 0:
return false;
case 1:
// (, line 384
if(!(I_word_len>5)){
return false;
}
// delete, line 384
slice_del();
break;
case 2:
// (, line 385
if(!(I_word_len>4)){
return false;
}
// delete, line 385
slice_del();
break;
}
return true;
}
private boolean r_Prefix_Step3b_Noun(){
int among_var;
// (, line 389
I_word_len=current.length();
// not, line 391
{
int v_1=cursor;
lab0:
do{
// literal, line 391
if(!(eq_s("\u00D8\u00A8\u00D8\u00A7"))){
break lab0;
}
return false;
}while(false);
cursor=v_1;
}
// [, line 392
bra=cursor;
// substring, line 392
among_var=find_among(a_7);
if(among_var==0){
return false;
}
// ], line 392
ket=cursor;
switch(among_var){
case 0:
return false;
case 1:
// (, line 393
if(!(I_word_len>3)){
return false;
}
// delete, line 393
slice_del();
break;
case 2:
// (, line 395
if(!(I_word_len>3)){
return false;
}
// <-, line 395
slice_from("\u00D8\u00A8");
break;
case 3:
// (, line 396
if(!(I_word_len>3)){
return false;
}
// <-, line 396
slice_from("\u00D9\u0083");
break;
}
return true;
}
private boolean r_Prefix_Step3_Verb(){
int among_var;
// (, line 401
I_word_len=current.length();
// [, line 403
bra=cursor;
// substring, line 403
among_var=find_among(a_8);
if(among_var==0){
return false;
}
// ], line 403
ket=cursor;
switch(among_var){
case 0:
return false;
case 1:
// (, line 405
if(!(I_word_len>4)){
return false;
}
// <-, line 405
slice_from("\u00D9\u008A");
break;
case 2:
// (, line 406
if(!(I_word_len>4)){
return false;
}
// <-, line 406
slice_from("\u00D8\u00AA");
break;
case 3:
// (, line 407
if(!(I_word_len>4)){
return false;
}
// <-, line 407
slice_from("\u00D9\u0086");
break;
case 4:
// (, line 408
if(!(I_word_len>4)){
return false;
}
// <-, line 408
slice_from("\u00D8\u00A3");
break;
}
return true;
}
private boolean r_Prefix_Step4_Verb(){
int among_var;
// (, line 412
I_word_len=current.length();
// [, line 414
bra=cursor;
// substring, line 414
among_var=find_among(a_9);
if(among_var==0){
return false;
}
// ], line 414
ket=cursor;
switch(among_var){
case 0:
return false;
case 1:
// (, line 415
if(!(I_word_len>4)){
return false;
}
// set is_verb, line 415
B_is_verb=true;
// unset is_noun, line 415
B_is_noun=false;
// <-, line 415
slice_from("\u00D8\u00A7\u00D8\u00B3\u00D8\u00AA");
break;
}
return true;
}
private boolean r_Suffix_Noun_Step1a(){
int among_var;
// (, line 422
I_word_len=current.length();
// [, line 424
ket=cursor;
// substring, line 424
among_var=find_among_b(a_10);
if(among_var==0){
return false;
}
// ], line 424
bra=cursor;
switch(among_var){
case 0:
return false;
case 1:
// (, line 425
if(!(I_word_len>=4)){
return false;
}
// delete, line 425
slice_del();
break;
case 2:
// (, line 426
if(!(I_word_len>=5)){
return false;
}
// delete, line 426
slice_del();
break;
case 3:
// (, line 427
if(!(I_word_len>=6)){
return false;
}
// delete, line 427
slice_del();
break;
}
return true;
}
private boolean r_Suffix_Noun_Step1b(){
int among_var;
// (, line 430
I_word_len=current.length();
// [, line 432
ket=cursor;
// substring, line 432
among_var=find_among_b(a_11);
if(among_var==0){
return false;
}
// ], line 432
bra=cursor;
switch(among_var){
case 0:
return false;
case 1:
// (, line 433
if(!(I_word_len>5)){
return false;
}
// delete, line 433
slice_del();
break;
}
return true;
}
private boolean r_Suffix_Noun_Step2a(){
int among_var;
// (, line 437
I_word_len=current.length();
// [, line 439
ket=cursor;
// substring, line 439
among_var=find_among_b(a_12);
if(among_var==0){
return false;
}
// ], line 439
bra=cursor;
switch(among_var){
case 0:
return false;
case 1:
// (, line 440
if(!(I_word_len>4)){
return false;
}
// delete, line 440
slice_del();
break;
}
return true;
}
private boolean r_Suffix_Noun_Step2b(){
int among_var;
// (, line 444
I_word_len=current.length();
// [, line 446
ket=cursor;
// substring, line 446
among_var=find_among_b(a_13);
if(among_var==0){
return false;
}
// ], line 446
bra=cursor;
switch(among_var){
case 0:
return false;
case 1:
// (, line 447
if(!(I_word_len>=5)){
return false;
}
// delete, line 447
slice_del();
break;
}
return true;
}
private boolean r_Suffix_Noun_Step2c1(){
int among_var;
// (, line 451
I_word_len=current.length();
// [, line 453
ket=cursor;
// substring, line 453
among_var=find_among_b(a_14);
if(among_var==0){
return false;
}
// ], line 453
bra=cursor;
switch(among_var){
case 0:
return false;
case 1:
// (, line 454
if(!(I_word_len>=4)){
return false;
}
// delete, line 454
slice_del();
break;
}
return true;
}
private boolean r_Suffix_Noun_Step2c2(){
int among_var;
// (, line 457
I_word_len=current.length();
// [, line 459
ket=cursor;
// substring, line 459
among_var=find_among_b(a_15);
if(among_var==0){
return false;
}
// ], line 459
bra=cursor;
switch(among_var){
case 0:
return false;
case 1:
// (, line 460
if(!(I_word_len>=4)){
return false;
}
// delete, line 460
slice_del();
break;
}
return true;
}
private boolean r_Suffix_Noun_Step3(){
int among_var;
// (, line 463
I_word_len=current.length();
// [, line 465
ket=cursor;
// substring, line 465
among_var=find_among_b(a_16);
if(among_var==0){
return false;
}
// ], line 465
bra=cursor;
switch(among_var){
case 0:
return false;
case 1:
// (, line 466
if(!(I_word_len>=3)){
return false;
}
// delete, line 466
slice_del();
break;
}
return true;
}
private boolean r_Suffix_Verb_Step1(){
int among_var;
// (, line 470
I_word_len=current.length();
// [, line 472
ket=cursor;
// substring, line 472
among_var=find_among_b(a_17);
if(among_var==0){
return false;
}
// ], line 472
bra=cursor;
switch(among_var){
case 0:
return false;
case 1:
// (, line 473
if(!(I_word_len>=4)){
return false;
}
// delete, line 473
slice_del();
break;
case 2:
// (, line 474
if(!(I_word_len>=5)){
return false;
}
// delete, line 474
slice_del();
break;
case 3:
// (, line 475
if(!(I_word_len>=6)){
return false;
}
// delete, line 475
slice_del();
break;
}
return true;
}
private boolean r_Suffix_Verb_Step2a(){
int among_var;
// (, line 478
I_word_len=current.length();
// [, line 480
ket=cursor;
// substring, line 480
among_var=find_among_b(a_18);
if(among_var==0){
return false;
}
// ], line 480
bra=cursor;
switch(among_var){
case 0:
return false;
case 1:
// (, line 481
if(!(I_word_len>=4)){
return false;
}
// delete, line 481
slice_del();
break;
case 2:
// (, line 483
if(!(I_word_len>=5)){
return false;
}
// delete, line 483
slice_del();
break;
case 3:
// (, line 484
if(!(I_word_len>5)){
return false;
}
// delete, line 484
slice_del();
break;
case 4:
// (, line 485
if(!(I_word_len>=6)){
return false;
}
// delete, line 485
slice_del();
break;
}
return true;
}
private boolean r_Suffix_Verb_Step2b(){
int among_var;
// (, line 489
I_word_len=current.length();
// [, line 491
ket=cursor;
// substring, line 491
among_var=find_among_b(a_19);
if(among_var==0){
return false;
}
// ], line 491
bra=cursor;
switch(among_var){
case 0:
return false;
case 1:
// (, line 492
if(!(I_word_len>=5)){
return false;
}
// delete, line 492
slice_del();
break;
}
return true;
}
private boolean r_Suffix_Verb_Step2c(){
int among_var;
// (, line 497
I_word_len=current.length();
// [, line 499
ket=cursor;
// substring, line 499
among_var=find_among_b(a_20);
if(among_var==0){
return false;
}
// ], line 499
bra=cursor;
switch(among_var){
case 0:
return false;
case 1:
// (, line 500
if(!(I_word_len>=4)){
return false;
}
// delete, line 500
slice_del();
break;
case 2:
// (, line 501
if(!(I_word_len>=6)){
return false;
}
// delete, line 501
slice_del();
break;
}
return true;
}
private boolean r_Suffix_All_alef_maqsura(){
int among_var;
// (, line 505
I_word_len=current.length();
// [, line 507
ket=cursor;
// substring, line 507
among_var=find_among_b(a_21);
if(among_var==0){
return false;
}
// ], line 507
bra=cursor;
switch(among_var){
case 0:
return false;
case 1:
// (, line 508
// <-, line 508
slice_from("\u00D9\u008A");
break;
}
return true;
}
public boolean stem(){
// (, line 515
// set is_noun, line 517
B_is_noun=true;
// set is_verb, line 518
B_is_verb=true;
// unset is_defined, line 519
B_is_defined=false;
// do, line 522
int v_1=cursor;
lab0:
do{
// call Checks1, line 522
if(!r_Checks1()){
break lab0;
}
}while(false);
cursor=v_1;
// do, line 525
int v_2=cursor;
lab1:
do{
// call Normalize_pre, line 525
if(!r_Normalize_pre()){
break lab1;
}
}while(false);
cursor=v_2;
// backwards, line 528
limit_backward=cursor;
cursor=limit;
// (, line 528
// do, line 530
int v_3=limit-cursor;
lab2:
do{
// (, line 530
// or, line 544
lab3:
do{
int v_4=limit-cursor;
lab4:
do{
// (, line 532
// Boolean test is_verb, line 533
if(!(B_is_verb)){
break lab4;
}
// (, line 534
// or, line 539
lab5:
do{
int v_5=limit-cursor;
lab6:
do{
// (, line 535
// (, line 536
// atleast, line 536
{
int v_6=1;
// atleast, line 536
replab7:
while(true){
int v_7=limit-cursor;
lab8:
do{
// call Suffix_Verb_Step1, line 536
if(!r_Suffix_Verb_Step1()){
break lab8;
}
v_6--;
continue replab7;
}while(false);
cursor=limit-v_7;
break replab7;
}
if(v_6>0){
break lab6;
}
}
// (, line 537
// or, line 537
lab9:
do{
int v_8=limit-cursor;
lab10:
do{
// call Suffix_Verb_Step2a, line 537
if(!r_Suffix_Verb_Step2a()){
break lab10;
}
break lab9;
}while(false);
cursor=limit-v_8;
lab11:
do{
// call Suffix_Verb_Step2c, line 537
if(!r_Suffix_Verb_Step2c()){
break lab11;
}
break lab9;
}while(false);
cursor=limit-v_8;
// next, line 537
if(cursor<=limit_backward){
break lab6;
}
cursor--;
}while(false);
break lab5;
}while(false);
cursor=limit-v_5;
lab12:
do{
// call Suffix_Verb_Step2b, line 539
if(!r_Suffix_Verb_Step2b()){
break lab12;
}
break lab5;
}while(false);
cursor=limit-v_5;
// call Suffix_Verb_Step2a, line 540
if(!r_Suffix_Verb_Step2a()){
break lab4;
}
}while(false);
break lab3;
}while(false);
cursor=limit-v_4;
lab13:
do{
// (, line 544
// Boolean test is_noun, line 545
if(!(B_is_noun)){
break lab13;
}
// (, line 546
// try, line 548
int v_9=limit-cursor;
lab14:
do{
// (, line 548
// or, line 550
lab15:
do{
int v_10=limit-cursor;
lab16:
do{
// call Suffix_Noun_Step2c2, line 549
if(!r_Suffix_Noun_Step2c2()){
break lab16;
}
break lab15;
}while(false);
cursor=limit-v_10;
lab17:
do{
// (, line 550
// not, line 550
lab18:
do{
// Boolean test is_defined, line 550
if(!(B_is_defined)){
break lab18;
}
break lab17;
}while(false);
// call Suffix_Noun_Step1a, line 550
if(!r_Suffix_Noun_Step1a()){
break lab17;
}
// (, line 550
// or, line 552
lab19:
do{
int v_12=limit-cursor;
lab20:
do{
// call Suffix_Noun_Step2a, line 551
if(!r_Suffix_Noun_Step2a()){
break lab20;
}
break lab19;
}while(false);
cursor=limit-v_12;
lab21:
do{
// call Suffix_Noun_Step2b, line 552
if(!r_Suffix_Noun_Step2b()){
break lab21;
}
break lab19;
}while(false);
cursor=limit-v_12;
lab22:
do{
// call Suffix_Noun_Step2c1, line 553
if(!r_Suffix_Noun_Step2c1()){
break lab22;
}
break lab19;
}while(false);
cursor=limit-v_12;
// next, line 554
if(cursor<=limit_backward){
break lab17;
}
cursor--;
}while(false);
break lab15;
}while(false);
cursor=limit-v_10;
lab23:
do{
// (, line 555
// call Suffix_Noun_Step1b, line 555
if(!r_Suffix_Noun_Step1b()){
break lab23;
}
// (, line 555
// or, line 557
lab24:
do{
int v_13=limit-cursor;
lab25:
do{
// call Suffix_Noun_Step2a, line 556
if(!r_Suffix_Noun_Step2a()){
break lab25;
}
break lab24;
}while(false);
cursor=limit-v_13;
lab26:
do{
// call Suffix_Noun_Step2b, line 557
if(!r_Suffix_Noun_Step2b()){
break lab26;
}
break lab24;
}while(false);
cursor=limit-v_13;
// call Suffix_Noun_Step2c1, line 558
if(!r_Suffix_Noun_Step2c1()){
break lab23;
}
}while(false);
break lab15;
}while(false);
cursor=limit-v_10;
lab27:
do{
// (, line 559
// not, line 559
lab28:
do{
// Boolean test is_defined, line 559
if(!(B_is_defined)){
break lab28;
}
break lab27;
}while(false);
// call Suffix_Noun_Step2a, line 559
if(!r_Suffix_Noun_Step2a()){
break lab27;
}
break lab15;
}while(false);
cursor=limit-v_10;
// (, line 560
// call Suffix_Noun_Step2b, line 560
if(!r_Suffix_Noun_Step2b()){
cursor=limit-v_9;
break lab14;
}
}while(false);
}while(false);
// call Suffix_Noun_Step3, line 562
if(!r_Suffix_Noun_Step3()){
break lab13;
}
break lab3;
}while(false);
cursor=limit-v_4;
// call Suffix_All_alef_maqsura, line 568
if(!r_Suffix_All_alef_maqsura()){
break lab2;
}
}while(false);
}while(false);
cursor=limit-v_3;
cursor=limit_backward;
// do, line 573
int v_15=cursor;
lab29:
do{
// (, line 573
// try, line 574
int v_16=cursor;
lab30:
do{
// call Prefix_Step1, line 574
if(!r_Prefix_Step1()){
cursor=v_16;
break lab30;
}
}while(false);
// try, line 575
int v_17=cursor;
lab31:
do{
// call Prefix_Step2, line 575
if(!r_Prefix_Step2()){
cursor=v_17;
break lab31;
}
}while(false);
// (, line 576
// or, line 577
lab32:
do{
int v_18=cursor;
lab33:
do{
// call Prefix_Step3a_Noun, line 576
if(!r_Prefix_Step3a_Noun()){
break lab33;
}
break lab32;
}while(false);
cursor=v_18;
lab34:
do{
// (, line 577
// Boolean test is_noun, line 577
if(!(B_is_noun)){
break lab34;
}
// call Prefix_Step3b_Noun, line 577
if(!r_Prefix_Step3b_Noun()){
break lab34;
}
break lab32;
}while(false);
cursor=v_18;
// (, line 578
// Boolean test is_verb, line 578
if(!(B_is_verb)){
break lab29;
}
// try, line 578
int v_19=cursor;
lab35:
do{
// call Prefix_Step3_Verb, line 578
if(!r_Prefix_Step3_Verb()){
cursor=v_19;
break lab35;
}
}while(false);
// call Prefix_Step4_Verb, line 578
if(!r_Prefix_Step4_Verb()){
break lab29;
}
}while(false);
}while(false);
cursor=v_15;
// do, line 583
lab36:
do{
// call Normalize_post, line 583
if(!r_Normalize_post()){
break lab36;
}
}while(false);
return true;
}
public boolean equals(Object o){
return o instanceof ArabicStemmer;
}
public int hashCode(){
return ArabicStemmer.class.getName().hashCode();
}
}
|
923188734f36ec874b1cef148443d5f48e724414 | 1,238 | java | Java | app/src/main/java/com/example/leetcodedemo/linkedList/easy/LinkedListCycle.java | wcxdhr/LeetCodeDemo | 20d71a4bd72a72e86f0f289cff2f6f972701c5be | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/leetcodedemo/linkedList/easy/LinkedListCycle.java | wcxdhr/LeetCodeDemo | 20d71a4bd72a72e86f0f289cff2f6f972701c5be | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/leetcodedemo/linkedList/easy/LinkedListCycle.java | wcxdhr/LeetCodeDemo | 20d71a4bd72a72e86f0f289cff2f6f972701c5be | [
"Apache-2.0"
] | null | null | null | 17.942029 | 82 | 0.53231 | 995,881 | package com.example.leetcodedemo.linkedList.easy;
/**
* 给定一个链表,判断链表中是否有环。
*
* 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
*
*
*
* 示例 1:
*
* 输入:head = [3,2,0,-4], pos = 1
* 输出:true
* 解释:链表中有一个环,其尾部连接到第二个节点。
*
*
* 示例 2:
*
* 输入:head = [1,2], pos = 0
* 输出:true
* 解释:链表中有一个环,其尾部连接到第一个节点。
*
*
* 示例 3:
*
* 输入:head = [1], pos = -1
* 输出:false
* 解释:链表中没有环。
*
*
*
*
* 进阶:
*
* 你能用 O(1)(即,常量)内存解决此问题吗?
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/linked-list-cycle
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
/**
* Created by Wcxdhr on 2019/10/8.
*/
public class LinkedListCycle {
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
/**
* 快慢指针
* @param head
* @return
*/
public boolean hasCycle(ListNode head) {
ListNode slow = new ListNode(-1);
ListNode fast = new ListNode(-2);
slow.next = fast.next = head;
while (slow.next != null && fast.next != null && fast.next.next != null) {
if (slow == fast)
return true;
slow = slow.next;
fast = fast.next.next;
}
return false;
}
}
|
9231892d77bcb9ddb6e8bed995b3d82ed5b1b741 | 2,449 | java | Java | src/main/java/App.java | cehoughton/todo | ff29802865cff7550102d55a8149ad79e85049de | [
"MIT"
] | null | null | null | src/main/java/App.java | cehoughton/todo | ff29802865cff7550102d55a8149ad79e85049de | [
"MIT"
] | null | null | null | src/main/java/App.java | cehoughton/todo | ff29802865cff7550102d55a8149ad79e85049de | [
"MIT"
] | null | null | null | 35.492754 | 79 | 0.626378 | 995,882 | import java.util.HashMap;
import java.util.ArrayList;
import spark.ModelAndView;
import spark.template.velocity.VelocityTemplateEngine;
import static spark.Spark.*;
public class App {
public static void main(String[] args) {
//RESTful ARCHITECTURE
//Use POST to create something on the server
//Use GET to retrieve something from the server
//Use PUT to change or update something on the server
//Use DELETE to remove or delete something on the server
//Keep URLs intuitive
//Each request from client contains all info necessary for that request
//ROUTES: Home Page
staticFileLocation("/public");
String layout = "templates/layout.vtl";
get("/", (request, response) -> {
HashMap<String, Object> model = new HashMap<String, Object>();
model.put("template", "templates/index.vtl");
return new ModelAndView(model, layout);
}, new VelocityTemplateEngine());
get("/tasks", (request, response) -> {
HashMap<String, Object> model = new HashMap<String, Object>();
model.put("tasks", Task.all());
model.put("template", "templates/tasks.vtl");
return new ModelAndView(model, layout);
}, new VelocityTemplateEngine());
get("tasks/new", (request, response) -> {
HashMap<String, Object> model = new HashMap<String, Object>();
model.put("template", "templates/task-form.vtl");
return new ModelAndView(model, layout);
}, new VelocityTemplateEngine());
post("/tasks", (request, response) -> {
HashMap<String, Object> model = new HashMap<String, Object>();
String description = request.queryParams("description");
Task newTask = new Task(description);
model.put("tasks", Task.all());
model.put("template", "templates/tasks.vtl");
return new ModelAndView(model, layout);
}, new VelocityTemplateEngine());
get("/tasks/:id", (request, response) -> {
HashMap<String, Object> model = new HashMap<String, Object>();
Task task = Task.find(Integer.parseInt(request.params(":id")));
model.put("task", task);
model.put("template", "templates/task.vtl");
return new ModelAndView(model, layout);
}, new VelocityTemplateEngine());
//ROUTES: Identification of Resources
//ROUTES: Changing Resources
}
}
|
92318a515cf8fba3d56790ccaf842f7f98b4288d | 359 | java | Java | src/main/java/xyz/brassgoggledcoders/transport/compat/quark/TransportQuark.java | boneskull/Transport | 01dd2b35a215a6fbedb5950be7cdb4c9242ea5fd | [
"MIT"
] | null | null | null | src/main/java/xyz/brassgoggledcoders/transport/compat/quark/TransportQuark.java | boneskull/Transport | 01dd2b35a215a6fbedb5950be7cdb4c9242ea5fd | [
"MIT"
] | null | null | null | src/main/java/xyz/brassgoggledcoders/transport/compat/quark/TransportQuark.java | boneskull/Transport | 01dd2b35a215a6fbedb5950be7cdb4c9242ea5fd | [
"MIT"
] | null | null | null | 27.615385 | 76 | 0.724234 | 995,883 | package xyz.brassgoggledcoders.transport.compat.quark;
import net.minecraftforge.fml.ModList;
import xyz.brassgoggledcoders.transport.api.TransportAPI;
public class TransportQuark {
public static void setup() {
if (ModList.get().isLoaded("quark")) {
TransportAPI.setConnectionChecker(new QuarkConnectionChecker());
}
}
}
|
92318b39a3361369df85672ceb0fa723f37b61eb | 7,080 | java | Java | app/src/main/java/wannabit/io/cosmostaion/activities/chains/cosmos/GravityWithdrawPoolActivity.java | imversed/imversed-wallet-android | 093d53e16d44014cc3f045c696f15dc53dceb9d3 | [
"MIT"
] | null | null | null | app/src/main/java/wannabit/io/cosmostaion/activities/chains/cosmos/GravityWithdrawPoolActivity.java | imversed/imversed-wallet-android | 093d53e16d44014cc3f045c696f15dc53dceb9d3 | [
"MIT"
] | null | null | null | app/src/main/java/wannabit/io/cosmostaion/activities/chains/cosmos/GravityWithdrawPoolActivity.java | imversed/imversed-wallet-android | 093d53e16d44014cc3f045c696f15dc53dceb9d3 | [
"MIT"
] | null | null | null | 36.494845 | 98 | 0.666384 | 995,884 | package wannabit.io.cosmostaion.activities.chains.cosmos;
import static wannabit.io.cosmostaion.base.BaseConstant.CONST_PW_TX_GDEX_WITHDRAW;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.fulldive.wallet.extensions.ActivityExtensionsKt;
import java.util.ArrayList;
import wannabit.io.cosmostaion.R;
import wannabit.io.cosmostaion.activities.PasswordCheckActivity;
import wannabit.io.cosmostaion.base.BaseBroadCastActivity;
import wannabit.io.cosmostaion.base.BaseConstant;
import wannabit.io.cosmostaion.base.BaseFragment;
import wannabit.io.cosmostaion.base.IRefreshTabListener;
import wannabit.io.cosmostaion.fragment.StepFeeSetFragment;
import wannabit.io.cosmostaion.fragment.StepMemoFragment;
import wannabit.io.cosmostaion.fragment.chains.cosmos.GDexWithdrawStep0Fragment;
import wannabit.io.cosmostaion.fragment.chains.cosmos.GDexWithdrawStep3Fragment;
public class GravityWithdrawPoolActivity extends BaseBroadCastActivity {
private RelativeLayout mRootView;
private Toolbar mToolbar;
private TextView mTitle;
private ImageView mIvStep;
private TextView mTvStep;
private ViewPager mViewPager;
private ExitPoolPageAdapter mPageAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_step);
mRootView = findViewById(R.id.root_view);
mToolbar = findViewById(R.id.toolbar);
mTitle = findViewById(R.id.toolbarTitleTextView);
mIvStep = findViewById(R.id.send_step);
mTvStep = findViewById(R.id.send_step_msg);
mViewPager = findViewById(R.id.view_pager);
mTitle.setText(R.string.str_title_pool_exit);
mTxType = CONST_PW_TX_GDEX_WITHDRAW;
mGDexPoolId = getIntent().getLongExtra("mPoolId", 0);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mIvStep.setImageResource(R.drawable.step_4_img_1);
mTvStep.setText(R.string.str_exit_pool_step_0);
mPageAdapter = new ExitPoolPageAdapter(getSupportFragmentManager());
mViewPager.setOffscreenPageLimit(3);
mViewPager.setAdapter(mPageAdapter);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int i, float v, int i1) {
}
@Override
public void onPageSelected(int i) {
if (i == 0) {
mIvStep.setImageResource(R.drawable.step_4_img_1);
mTvStep.setText(R.string.str_exit_pool_step_0);
((IRefreshTabListener) mPageAdapter.mCurrentFragment).onRefreshTab();
} else if (i == 1) {
mIvStep.setImageResource(R.drawable.step_4_img_2);
mTvStep.setText(R.string.str_exit_pool_step_1);
} else if (i == 2) {
mIvStep.setImageResource(R.drawable.step_4_img_3);
mTvStep.setText(R.string.str_exit_pool_step_2);
((IRefreshTabListener) mPageAdapter.mCurrentFragment).onRefreshTab();
} else if (i == 3) {
mIvStep.setImageResource(R.drawable.step_4_img_4);
mTvStep.setText(R.string.str_exit_pool_step_3);
((IRefreshTabListener) mPageAdapter.mCurrentFragment).onRefreshTab();
}
}
@Override
public void onPageScrollStateChanged(int i) {
}
});
mViewPager.setCurrentItem(0);
mRootView.setOnClickListener(v -> ActivityExtensionsKt.hideKeyboard(this));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onBackPressed() {
ActivityExtensionsKt.hideKeyboard(this);
if (mViewPager.getCurrentItem() > 0) {
mViewPager.setCurrentItem(mViewPager.getCurrentItem() - 1, true);
} else {
super.onBackPressed();
}
}
public void onNextStep() {
if (mViewPager.getCurrentItem() < mViewPager.getChildCount()) {
ActivityExtensionsKt.hideKeyboard(this);
mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1, true);
}
}
public void onBeforeStep() {
if (mViewPager.getCurrentItem() > 0) {
ActivityExtensionsKt.hideKeyboard(this);
mViewPager.setCurrentItem(mViewPager.getCurrentItem() - 1, true);
} else {
onBackPressed();
}
}
public void onStartExitPool() {
Intent intent = new Intent(GravityWithdrawPoolActivity.this, PasswordCheckActivity.class);
intent.putExtra(BaseConstant.CONST_PW_PURPOSE, CONST_PW_TX_GDEX_WITHDRAW);
intent.putExtra("mLpToken", mLpToken);
intent.putExtra("mPoolId", mGDexPoolId);
intent.putExtra("memo", mTxMemo);
intent.putExtra("fee", mTxFee);
startActivity(intent);
overridePendingTransition(R.anim.slide_in_bottom, R.anim.fade_out);
}
private class ExitPoolPageAdapter extends FragmentPagerAdapter {
private final ArrayList<BaseFragment> mFragments = new ArrayList<>();
private BaseFragment mCurrentFragment;
public ExitPoolPageAdapter(FragmentManager fm) {
super(fm);
mFragments.clear();
mFragments.add(GDexWithdrawStep0Fragment.newInstance(null));
mFragments.add(StepMemoFragment.newInstance(null));
mFragments.add(StepFeeSetFragment.newInstance(null));
mFragments.add(GDexWithdrawStep3Fragment.newInstance(null));
}
@Override
public BaseFragment getItem(int position) {
return mFragments.get(position);
}
@Override
public int getCount() {
return mFragments.size();
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
if (getCurrentFragment() != object) {
mCurrentFragment = ((BaseFragment) object);
}
super.setPrimaryItem(container, position, object);
}
public BaseFragment getCurrentFragment() {
return mCurrentFragment;
}
public ArrayList<BaseFragment> getFragments() {
return mFragments;
}
}
}
|
92318b652563f78495401e51d65ad3b633f8451f | 7,503 | java | Java | java/classes4/com/ziroom/ziroomcustomer/ziroomstation/c/a.java | gaoht/house | b9e63db1a4975b614c422fed3b5b33ee57ea23fd | [
"Apache-2.0"
] | 1 | 2020-05-08T05:35:32.000Z | 2020-05-08T05:35:32.000Z | java/classes4/com/ziroom/ziroomcustomer/ziroomstation/c/a.java | gaoht/house | b9e63db1a4975b614c422fed3b5b33ee57ea23fd | [
"Apache-2.0"
] | null | null | null | java/classes4/com/ziroom/ziroomcustomer/ziroomstation/c/a.java | gaoht/house | b9e63db1a4975b614c422fed3b5b33ee57ea23fd | [
"Apache-2.0"
] | 3 | 2018-09-07T08:15:08.000Z | 2020-05-22T03:59:12.000Z | 31.658228 | 201 | 0.590164 | 995,885 | package com.ziroom.ziroomcustomer.ziroomstation.c;
import android.content.Context;
import android.text.TextUtils;
import com.ziroom.ziroomcustomer.base.ApplicationEx;
import com.ziroom.ziroomcustomer.util.af;
import com.ziroom.ziroomcustomer.ziroomstation.dialog.a.b;
import com.ziroom.ziroomcustomer.ziroomstation.model.DaysPrice;
import com.ziroom.ziroomcustomer.ziroomstation.model.StationOrderCreateHouseEntity;
import com.ziroom.ziroomcustomer.ziroomstation.model.StationOrderCreateUserEntity;
import com.ziroom.ziroomcustomer.ziroomstation.utils.e;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class a
{
private List<String> a;
private List<String> b;
private List<StationOrderCreateHouseEntity> c;
private List<StationOrderCreateUserEntity> d;
private a e;
private List<DaysPrice> f;
private int g;
private int h;
private Context i;
public a(Context paramContext, List<String> paramList, List<StationOrderCreateHouseEntity> paramList1, a parama, List<DaysPrice> paramList2)
{
this.i = paramContext;
a(paramList, paramList1, paramList2);
this.e = parama;
}
private void a(List<String> paramList, List<StationOrderCreateHouseEntity> paramList1, List<DaysPrice> paramList2)
{
this.a = new ArrayList();
this.a.add("男");
this.a.add("女");
this.b = paramList;
if ((this.b == null) || (this.b.size() == 0))
{
this.b = new ArrayList();
this.b.add("身份证");
this.b.add("护照");
}
this.f = paramList2;
this.c = paramList1;
this.d = new ArrayList();
}
public void addOtherUser()
{
int j = 0;
while (j < this.c.size())
{
if (((StationOrderCreateHouseEntity)this.c.get(j)).getUsedSize() < ((StationOrderCreateHouseEntity)this.c.get(j)).getSize())
{
this.d.add(new StationOrderCreateUserEntity("", "", "", "", ((StationOrderCreateHouseEntity)this.c.get(j)).getName(), ((StationOrderCreateHouseEntity)this.c.get(j)).getHouseTypeId()));
((StationOrderCreateHouseEntity)this.c.get(j)).setUsedSize(((StationOrderCreateHouseEntity)this.c.get(j)).getUsedSize() + 1);
return;
}
j += 1;
}
af.showToast(ApplicationEx.c, "增加入住人数后方可继续添加入住人信息");
}
public void addRefreshListener(a parama)
{
this.e = parama;
}
public boolean checkIdentityCard()
{
int j = 0;
while (j < this.d.size())
{
if ((((StationOrderCreateUserEntity)this.d.get(j)).getCredentialsStyle().contains("身份")) && (!TextUtils.isEmpty(e.IDCardValidate(((StationOrderCreateUserEntity)this.d.get(j)).getCredentials()))))
{
af.showToast(this.i, "身份证号格式错误,请核实后重新填写");
return false;
}
j += 1;
}
return true;
}
public void clearCouponPrice()
{
this.h = 0;
}
public int getCouponPrice()
{
return this.h;
}
public List<DaysPrice> getDaysPriceList()
{
return this.f;
}
public int getTotalPrice()
{
this.g = 0;
int j = 0;
while (j < this.c.size())
{
int k = this.g;
this.g = (((StationOrderCreateHouseEntity)this.c.get(j)).getPrice() + k);
j += 1;
}
return this.g;
}
public List<StationOrderCreateHouseEntity> getmHouseLt()
{
return this.c;
}
public a getmInterface()
{
return this.e;
}
public List<StationOrderCreateUserEntity> getmUserLt()
{
return this.d;
}
public void setCouponPrice(int paramInt)
{
this.h = paramInt;
}
public void showPickerDialog(final int paramInt1, final int paramInt2, final boolean paramBoolean)
{
ArrayList localArrayList = new ArrayList();
String str;
switch (paramInt1)
{
default:
str = "选择器";
}
for (;;)
{
new com.ziroom.ziroomcustomer.ziroomstation.dialog.a(this.i, str, new a.b()
{
public void callBack(HashMap<Integer, String> paramAnonymousHashMap)
{
int j = 0;
if ((paramAnonymousHashMap.size() < 1) || (TextUtils.isEmpty((CharSequence)paramAnonymousHashMap.get(Integer.valueOf(0))))) {
return;
}
if (paramBoolean) {
switch (paramInt1)
{
}
}
label536:
for (;;)
{
a.c(a.this).refresh();
return;
((StationOrderCreateUserEntity)a.a(a.this).get(paramInt2)).setSex((String)paramAnonymousHashMap.get(Integer.valueOf(0)));
continue;
((StationOrderCreateUserEntity)a.a(a.this).get(paramInt2)).setCredentialsStyle((String)paramAnonymousHashMap.get(Integer.valueOf(0)));
continue;
paramAnonymousHashMap = (String)paramAnonymousHashMap.get(Integer.valueOf(0));
if (!paramAnonymousHashMap.equals(((StationOrderCreateUserEntity)a.a(a.this).get(paramInt2)).getHouseType()))
{
int i = 0;
for (;;)
{
if (i >= a.b(a.this).size()) {
break label536;
}
if (paramAnonymousHashMap.equals(((StationOrderCreateHouseEntity)a.b(a.this).get(i)).getName()))
{
if (((StationOrderCreateHouseEntity)a.b(a.this).get(i)).getUsedSize() < ((StationOrderCreateHouseEntity)a.b(a.this).get(i)).getSize())
{
if (!TextUtils.isEmpty(((StationOrderCreateUserEntity)a.a(a.this).get(paramInt2)).getHouseType())) {}
for (;;)
{
if (j < a.b(a.this).size())
{
if (((StationOrderCreateUserEntity)a.a(a.this).get(paramInt2)).getHouseType().equals(((StationOrderCreateHouseEntity)a.b(a.this).get(j)).getName())) {
((StationOrderCreateHouseEntity)a.b(a.this).get(j)).setUsedSize(((StationOrderCreateHouseEntity)a.b(a.this).get(j)).getUsedSize() - 1);
}
}
else
{
((StationOrderCreateUserEntity)a.a(a.this).get(paramInt2)).setHouseType(paramAnonymousHashMap);
((StationOrderCreateUserEntity)a.a(a.this).get(paramInt2)).setHouseTypeBid(((StationOrderCreateHouseEntity)a.b(a.this).get(i)).getHouseTypeId());
((StationOrderCreateHouseEntity)a.b(a.this).get(i)).setUsedSize(((StationOrderCreateHouseEntity)a.b(a.this).get(i)).getUsedSize() + 1);
break;
}
j += 1;
}
}
af.showToast(ApplicationEx.c, "增加此房型入住人数后方可继续添加入住人信息");
break;
}
i += 1;
}
}
}
}
}, new List[] { localArrayList }).show();
return;
str = "请选择性别";
localArrayList.addAll(this.a);
continue;
str = "请选择证件类型";
localArrayList.addAll(this.b);
continue;
int j = 0;
while (j < this.c.size())
{
localArrayList.add(((StationOrderCreateHouseEntity)this.c.get(j)).getName());
j += 1;
}
str = "请选择房型";
}
}
public static abstract interface a
{
public abstract void refresh();
}
}
/* Location: /Users/gaoht/Downloads/zirom/classes4-dex2jar.jar!/com/ziroom/ziroomcustomer/ziroomstation/c/a.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ |
92318c1c34ba31b4bac4beb3f2db4944656b30d7 | 430 | java | Java | todrr-backend/src/main/java/pl/szotaa/todrr/mail/exception/InvalidEmailConfirmationTokenException.java | szotaa/todrr | 4e73f0906253aa986795f94fd07bbf0a68b3f9ef | [
"MIT"
] | null | null | null | todrr-backend/src/main/java/pl/szotaa/todrr/mail/exception/InvalidEmailConfirmationTokenException.java | szotaa/todrr | 4e73f0906253aa986795f94fd07bbf0a68b3f9ef | [
"MIT"
] | null | null | null | todrr-backend/src/main/java/pl/szotaa/todrr/mail/exception/InvalidEmailConfirmationTokenException.java | szotaa/todrr | 4e73f0906253aa986795f94fd07bbf0a68b3f9ef | [
"MIT"
] | null | null | null | 28.666667 | 88 | 0.804651 | 995,886 | package pl.szotaa.todrr.mail.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
* Exception thrown on attempting to confirm email with wrong email confirmation token.
*
* @author szotaa
*/
@ResponseStatus(code = HttpStatus.CONFLICT, reason = "Invalid email confirmation token")
public class InvalidEmailConfirmationTokenException extends Exception {
}
|
92318c715120d9bb08115b580b37d154a8d9a212 | 268 | java | Java | simple-jar-b/src/main/java/com/liumapp/simple/b/constant/SimpleConstant.java | liumapp/maven-deal-multy-local-jar | 2101e3d0f9f8c0c89fda3bbfaa2c24ce443e308d | [
"Apache-2.0"
] | null | null | null | simple-jar-b/src/main/java/com/liumapp/simple/b/constant/SimpleConstant.java | liumapp/maven-deal-multy-local-jar | 2101e3d0f9f8c0c89fda3bbfaa2c24ce443e308d | [
"Apache-2.0"
] | null | null | null | simple-jar-b/src/main/java/com/liumapp/simple/b/constant/SimpleConstant.java | liumapp/maven-deal-multy-local-jar | 2101e3d0f9f8c0c89fda3bbfaa2c24ce443e308d | [
"Apache-2.0"
] | null | null | null | 18.133333 | 57 | 0.702206 | 995,887 | package com.liumapp.simple.b.constant;
/**
* @author liumapp
* @file SimpleConstant.java
* @email anpch@example.com
* @homepage http://www.liumapp.com
* @date 4/3/18
*/
public class SimpleConstant {
public static final String activeInfo = "activeInfo";
}
|
92318caa45d34c062f0476def8ca316e34208cce | 10,578 | java | Java | nuxeo-ai-pipes/src/test/java/org/nuxeo/ai/pipes/functions/FunctionsTest.java | nuxeo/nuxeo-ai | 655c1aa652d88c6bb573d6804658dd09f5060143 | [
"Apache-2.0"
] | 5 | 2018-11-26T11:57:47.000Z | 2021-03-30T03:03:26.000Z | nuxeo-ai-pipes/src/test/java/org/nuxeo/ai/pipes/functions/FunctionsTest.java | nuxeo/nuxeo-ai | 655c1aa652d88c6bb573d6804658dd09f5060143 | [
"Apache-2.0"
] | 473 | 2018-11-05T11:18:01.000Z | 2022-02-03T21:37:10.000Z | nuxeo-ai-pipes/src/test/java/org/nuxeo/ai/pipes/functions/FunctionsTest.java | nuxeo/nuxeo-ai | 655c1aa652d88c6bb573d6804658dd09f5060143 | [
"Apache-2.0"
] | 6 | 2019-09-20T19:30:27.000Z | 2021-05-04T20:55:26.000Z | 41.97619 | 119 | 0.681887 | 995,888 | /*
* (C) Copyright 2018 Nuxeo (http://nuxeo.com/) and others.
*
* 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.
*
* Contributors:
* Gethin James
*/
package org.nuxeo.ai.pipes.functions;
import static junit.framework.TestCase.fail;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.nuxeo.ai.pipes.events.EventPipesTest.TEST_MIME_TYPE;
import static org.nuxeo.ai.pipes.events.EventPipesTest.getTestEvent;
import static org.nuxeo.ai.pipes.functions.Predicates.doc;
import static org.nuxeo.ai.pipes.functions.Predicates.docEvent;
import static org.nuxeo.ai.pipes.functions.Predicates.event;
import static org.nuxeo.ai.pipes.functions.Predicates.hasFacets;
import static org.nuxeo.ai.pipes.functions.Predicates.isNotProxy;
import static org.nuxeo.ai.pipes.functions.Predicates.isPicture;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.nuxeo.ai.pipes.filters.DocumentEventFilter;
import org.nuxeo.ai.pipes.filters.DocumentPathFilter;
import org.nuxeo.ai.pipes.filters.FacetFilter;
import org.nuxeo.ai.pipes.filters.Filter;
import org.nuxeo.ai.pipes.filters.NoVersionFilter;
import org.nuxeo.ai.pipes.filters.PrimaryTypeFilter;
import org.nuxeo.ecm.core.api.Blob;
import org.nuxeo.ecm.core.api.Blobs;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.DocumentRef;
import org.nuxeo.ecm.core.api.NuxeoException;
import org.nuxeo.ecm.core.api.VersioningOption;
import org.nuxeo.ecm.core.event.Event;
import org.nuxeo.ecm.core.event.impl.DocumentEventContext;
import org.nuxeo.ecm.core.event.impl.EventContextImpl;
import org.nuxeo.ecm.platform.test.PlatformFeature;
import org.nuxeo.lib.stream.computation.Record;
import org.nuxeo.runtime.test.runner.Deploy;
import org.nuxeo.runtime.test.runner.Features;
import org.nuxeo.runtime.test.runner.FeaturesRunner;
import com.google.inject.Inject;
@RunWith(FeaturesRunner.class)
@Features({ PlatformFeature.class })
@Deploy({ "org.nuxeo.runtime.stream", "org.nuxeo.ai.nuxeo-ai-pipes" })
public class FunctionsTest {
@Inject
CoreSession session;
@Test
public void testFilterFunctions() throws Exception {
Event event = getTestEvent(session);
PreFilterFunction<Event, Event> func = new PreFilterFunction<>(event(), e -> e);
assertEquals("Filter passed so must be an event", event, func.apply(event));
func = new PreFilterFunction<>(event().and(e -> !e.isImmediate()), e -> e);
assertEquals("Filter passed so must be an event", event, func.apply(event));
func = new PreFilterFunction<>(docEvent(doc()), e -> e);
assertEquals("Filter passed so must be an event", event, func.apply(event));
func = new PreFilterFunction<>(docEvent(isNotProxy().and(d -> d.getName().equals("My Doc"))), e -> e);
assertEquals("Filter passed so must be My Doc", event, func.apply(event));
func = new PreFilterFunction<>(docEvent(isNotProxy().and(hasFacets("Versionable", "Commentable"))), e -> e);
assertEquals("Filter passed so must be an event", event, func.apply(event));
func = new PreFilterFunction<>(docEvent(isNotProxy().and(hasFacets("Folderish"))), e -> e);
assertNull("Must not have folderish", func.apply(event));
func = new PreFilterFunction<>(docEvent(isNotProxy().and(hasFacets("Folderish").negate())), e -> e);
assertEquals("Filter passed so must not have folderish", event, func.apply(event));
func = new PreFilterFunction<>(docEvent(isNotProxy().and(isPicture())), e -> e);
assertNull("It's not a picture", func.apply(event));
func = new PreFilterFunction<>(in -> true, s -> {
throw new NuxeoException("Invalid");
});
assertNull(func.apply(event));
}
@Test
public void testBasicFunction() {
PreFilterFunction<String, String> func = filterFunc(in -> true, t -> t);
assertEquals("Hello World", func.apply("Hello World"));
func = filterFunc(in -> true, String::toLowerCase);
assertEquals("hello", func.apply("Hello"));
func = filterFunc(in -> in.toLowerCase().startsWith("h"), t -> t);
long matched = Stream.of("hello ", "I", "am", "Happy ", "hopefully ").filter(func.filter).count();
assertEquals(3, matched);
StringBuffer ints = new StringBuffer();
final PreFilterFunction<Integer, Integer> function = new PreFilterFunction<>(in -> in % 2 == 0, in -> in * in);
IntStream.of(2, 3, 6, 1, 4).forEach(i -> {
Integer applied = function.apply(i);
if (applied != null) {
ints.append(applied);
}
});
assertEquals("43616", ints.toString());
}
@Test
public void testFunctions() throws Exception {
Event event = getTestEvent(session);
PreFilterFunction<Event, Collection<Record>> func = new PropertiesToStream();
try {
func.init(Collections.emptyMap());
fail();
} catch (IllegalArgumentException ignored) {
}
FacetFilter facetFilter = new FacetFilter();
facetFilter.init(Collections.singletonMap("includedFacets", "Picture"));
func.filter = docEvent(facetFilter);
func.init(Collections.singletonMap("textProperties", "dc:creator"));
assertNull("Its not a picture event", func.apply(event));
func.filter = docEvent(d -> true);
Collection<Record> applied = func.apply(event);
assertEquals("It is a document with a creator", 1, applied.size());
facetFilter.init(Collections.singletonMap("excludedFacets", "Versionable,Commentable"));
func.filter = docEvent(facetFilter);
assertNull("Versionable are excluded.", func.apply(event));
facetFilter.init(Collections.singletonMap("includedFacets", "Versionable"));
applied = func.apply(event);
assertEquals("Versionable are included", 1, applied.size());
DocumentPathFilter pathFilter = new DocumentPathFilter();
pathFilter.init(Collections.singletonMap("endsWith", "Doc"));
func.filter = docEvent(pathFilter);
applied = func.apply(event);
assertEquals("Paths ends with Doc", 1, applied.size());
Map<String, String> options = new HashMap<>();
options.put("startsWith", "/My");
options.put("contains", "My Doc");
pathFilter.init(options);
applied = func.apply(event);
assertEquals("Paths contains Doc", 1, applied.size());
options.clear();
options.put("pattern", "NO_MATCH");
pathFilter.init(options);
applied = func.apply(event);
assertNull("Pattern does not match", func.apply(event));
options.put("pattern", ".*\\s+\\w{3}");
pathFilter.init(options);
applied = func.apply(event);
assertEquals("Pattern now matches", 1, applied.size());
// Test PrimaryTypeFilter
PrimaryTypeFilter typeFilter = new PrimaryTypeFilter();
typeFilter.init(Collections.singletonMap("isType", "Picture"));
func.filter = docEvent(typeFilter);
func.init(Collections.singletonMap("textProperties", "dc:creator"));
assertNull("Its not a picture", func.apply(event));
typeFilter.init(Collections.singletonMap("isType", "File"));
func.filter = docEvent(typeFilter);
applied = func.apply(event);
assertEquals("It is a file", 1, applied.size());
}
@Test
public void shouldApplyNoVersionFilter() {
PreFilterFunction<Event, Collection<Record>> func = new PropertiesToStream();
func.init(Collections.singletonMap("textProperties", "dc:creator"));
NoVersionFilter noVersionFilter = new NoVersionFilter();
func.filter = docEvent(noVersionFilter);
DocumentModel doc = session.createDocumentModel("/", "MyDoc", "File");
assertNotNull(doc);
doc.addFacet("Publishable");
doc.addFacet("Versionable");
Blob blob = Blobs.createBlob("My text", TEST_MIME_TYPE);
doc.setPropertyValue("file:content", (Serializable) blob);
doc = session.createDocument(doc);
EventContextImpl evctx = new DocumentEventContext(session, session.getPrincipal(), doc);
Event event = evctx.newEvent("myDocEvent");
event.setInline(true);
Collection<Record> result = func.apply(event);
assertThat(result).hasSize(1);
DocumentRef verRef = session.checkIn(doc.getRef(), VersioningOption.MAJOR, "bump");
DocumentModel versionDoc = session.getDocument(verRef);
assertThat(versionDoc.isVersion()).isTrue();
evctx = new DocumentEventContext(session, session.getPrincipal(), versionDoc);
event = evctx.newEvent("myDocEvent");
event.setInline(true);
result = func.apply(event);
assertThat(result).isNullOrEmpty();
}
@Test
public void testClassCast() {
PreFilterFunction<String, Integer> ff = new PreFilterFunction<>(in -> true, null);
assertNull(ff.apply("Hello"));
}
@Test
public void testBuilder() {
Filter.EventFilter eventFilter = new DocumentEventFilter.Builder().build();
assertNotNull(eventFilter);
eventFilter = new DocumentEventFilter.Builder().withDocumentFilter(d -> d.hasSchema("schema")).build();
assertNotNull(eventFilter);
}
public static <T, R> PreFilterFunction<T, R> filterFunc(Predicate<? super T> filter,
Function<? super T, ? extends R> transformation) {
return new PreFilterFunction<>(filter, transformation);
}
}
|
92318d7afcc2399df870c7a54ebfdec4355b679f | 922 | java | Java | src/main/java/dhbwka/wwi/vertsys/javaee/recordcollecta/tasks/jpa/TaskStatus.java | FrancescoBrokkoli/Verteilte_Systeme | 96a0dc135df105a712db210fe933ac81578296d1 | [
"CC-BY-4.0"
] | null | null | null | src/main/java/dhbwka/wwi/vertsys/javaee/recordcollecta/tasks/jpa/TaskStatus.java | FrancescoBrokkoli/Verteilte_Systeme | 96a0dc135df105a712db210fe933ac81578296d1 | [
"CC-BY-4.0"
] | null | null | null | src/main/java/dhbwka/wwi/vertsys/javaee/recordcollecta/tasks/jpa/TaskStatus.java | FrancescoBrokkoli/Verteilte_Systeme | 96a0dc135df105a712db210fe933ac81578296d1 | [
"CC-BY-4.0"
] | null | null | null | 22.463415 | 59 | 0.548317 | 995,889 | /*
* Copyright © 2018 Dennis Schulmeister-Zimolong
*
* E-Mail: ychag@example.com
* Webseite: https://www.wpvs.de/
*
* Dieser Quellcode ist lizenziert unter einer
* Creative Commons Namensnennung 4.0 International Lizenz.
*/
package dhbwka.wwi.vertsys.javaee.recordcollecta.tasks.jpa;
/**
* Statuswerte einer Aufgabe.
*/
public enum TaskStatus {
OPEN, IN_PROGRESS, FINISHED, CANCELED, POSTPONED;
/**
* Bezeichnung ermitteln
*
* @return Bezeichnung
*/
public String getLabel() {
switch (this) {
case OPEN:
return "12 inch";
case IN_PROGRESS:
return "10 inch";
case FINISHED:
return "7 inch";
case CANCELED:
return "EP";
case POSTPONED:
return "2LP";
default:
return this.toString();
}
}
}
|
92318dce3223dbf56179c26954c0d70bd8811a12 | 175 | java | Java | Java/app/src/main/java/dk/coded/emia/notifications/LocalNotificationListener.java | SKrotkih/eMia-Android | c277bd010388a8d4f03292e4f2d645c43f9d9dac | [
"MIT"
] | 1 | 2021-09-16T18:09:19.000Z | 2021-09-16T18:09:19.000Z | Java/app/src/main/java/dk/coded/emia/notifications/LocalNotificationListener.java | SKrotkih/eMia-Android | c277bd010388a8d4f03292e4f2d645c43f9d9dac | [
"MIT"
] | 1 | 2018-05-30T10:28:46.000Z | 2018-05-30T10:28:46.000Z | Java/app/src/main/java/dk/coded/emia/notifications/LocalNotificationListener.java | SKrotkih/eMia-Android | c277bd010388a8d4f03292e4f2d645c43f9d9dac | [
"MIT"
] | null | null | null | 21.875 | 57 | 0.822857 | 995,890 | package dk.coded.emia.notifications;
import android.content.Intent;
public interface LocalNotificationListener {
public void onLocalNotificationUpdate(Intent intent);
}
|
92318e30d3531be7a878a551fc065c1e75e03c63 | 1,324 | java | Java | src/main/java/me/conclure/derpio/command/commands/UserInfoCommand.java | derp-development/Derpio | 5f5522114cc0c9f85a958e7bf06177998cc83960 | [
"MIT"
] | null | null | null | src/main/java/me/conclure/derpio/command/commands/UserInfoCommand.java | derp-development/Derpio | 5f5522114cc0c9f85a958e7bf06177998cc83960 | [
"MIT"
] | null | null | null | src/main/java/me/conclure/derpio/command/commands/UserInfoCommand.java | derp-development/Derpio | 5f5522114cc0c9f85a958e7bf06177998cc83960 | [
"MIT"
] | null | null | null | 28.782609 | 82 | 0.688822 | 995,891 | package me.conclure.derpio.command.commands;
import me.conclure.derpio.Bot;
import me.conclure.derpio.command.CommandExecutor;
import me.conclure.derpio.model.user.UserData;
import me.conclure.derpio.model.user.UserManager;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.MessageEmbed;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
public final class UserInfoCommand extends CommandExecutor {
@Override
public String getName() {
return "userinfo";
}
@Override
protected String[] getAliases() {
return new String[] {"userdata", "user"};
}
@Override
public Result execute(Bot bot, GuildMessageReceivedEvent event, String[] args) {
bot.awaitReady();
User author = event.getAuthor();
long userId = author.getIdLong();
UserManager userManager = bot.userManager();
UserData userData = userManager.getUserData(userId);
MessageEmbed embed =
new EmbedBuilder()
.setTitle(author.getAsTag())
.addField("Exp", String.valueOf(userData.getExp()), false)
.build();
return ResultType.SUCCESS
.toResult()
.setCallback(
() -> {
event.getChannel().sendMessage(embed).queue();
});
}
}
|
923191238823fc3a855f8fa4e2655a84b19a5508 | 870 | java | Java | barbershop-master/src/controller/helper/LoginHelper.java | DiegoDeJotaWeb/Projeto-Uninove-S2-2020 | 0564bfd5ffba4d6dc947af7ba60ec0a7f9c66768 | [
"MIT"
] | 1 | 2020-09-01T21:45:58.000Z | 2020-09-01T21:45:58.000Z | barbershop-master/src/controller/helper/LoginHelper.java | DiegoDeJotaWeb/Projeto-Uninove-S2-2020 | 0564bfd5ffba4d6dc947af7ba60ec0a7f9c66768 | [
"MIT"
] | null | null | null | barbershop-master/src/controller/helper/LoginHelper.java | DiegoDeJotaWeb/Projeto-Uninove-S2-2020 | 0564bfd5ffba4d6dc947af7ba60ec0a7f9c66768 | [
"MIT"
] | null | null | null | 21.75 | 55 | 0.591954 | 995,892 | package controller.helper;
import model.Usuario;
import view.Login;
public class LoginHelper implements IHelper {
private final Login view;
public LoginHelper(Login view) {
this.view = view;
}
@Override
public Usuario obterModelo() {
String nome = view.getTextUsuario().getText();
String senha = view.getTextSenha().getText();
Usuario modelo = new Usuario(0, nome, senha);
return modelo;
}
public void setarModelo(Usuario modelo) {
String nome = modelo.getNome();
String senha = modelo.getSenha();
view.getTextUsuario().setText(nome);
view.getTextSenha().setText(senha);
}
@Override
public void limparTela() {
view.getTextUsuario().setText("");
view.getTextSenha().setText("");
}
}
|
923191b7370e9b0c109db4d37f0b4ca1c78645af | 806 | java | Java | src/com/ityang/leetcode/Subject25.java | itYangJie/leetcode | a4f290f2658783c644ac37ae77fc672276b94432 | [
"Apache-2.0"
] | null | null | null | src/com/ityang/leetcode/Subject25.java | itYangJie/leetcode | a4f290f2658783c644ac37ae77fc672276b94432 | [
"Apache-2.0"
] | null | null | null | src/com/ityang/leetcode/Subject25.java | itYangJie/leetcode | a4f290f2658783c644ac37ae77fc672276b94432 | [
"Apache-2.0"
] | null | null | null | 17.521739 | 61 | 0.605459 | 995,893 | package com.ityang.leetcode;
import com.ityang.leetcode.Subject24.ListNode;
public class Subject25 {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public static ListNode reverseKGroup(ListNode head, int k) {
if (k <= 1 || head == null || head.next == null)
return head;
ListNode front = head, tail = head;
for (int i = 0; i < k - 1; i++) {
if (tail == null) {
break;
}
tail = tail.next;
}
if (tail == null)
return head;
ListNode pre = front,mid = front.next,next = mid.next;
while(mid!=tail){
mid.next = pre;
pre = mid;
mid = next;
next = next.next;
}
mid.next = pre;
front.next = reverseKGroup(next, k);
return tail;
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
}
|
92319201a963e45b938e295c73cb962e5c6ea7dd | 2,242 | java | Java | portfolio/src/main/java/com/google/sps/servlets/ListComments.java | hieudan225/step | c91189a772341c740eacc1a9bccccfb8d11d9dca | [
"Apache-2.0"
] | null | null | null | portfolio/src/main/java/com/google/sps/servlets/ListComments.java | hieudan225/step | c91189a772341c740eacc1a9bccccfb8d11d9dca | [
"Apache-2.0"
] | 1 | 2020-06-01T18:18:22.000Z | 2020-06-01T18:27:24.000Z | portfolio/src/main/java/com/google/sps/servlets/ListComments.java | hieudan225/step | c91189a772341c740eacc1a9bccccfb8d11d9dca | [
"Apache-2.0"
] | null | null | null | 38.655172 | 112 | 0.746209 | 995,894 | package com.google.sps.servlets;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.SortDirection;
import com.google.sps.data.Comment;
import java.util.ArrayList;
import java.util.List;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import com.google.gson.Gson;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.logging.Logger;
/** Servlet that returns a list of comments */
@WebServlet("/list-comments")
public class ListComments extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
Integer maxComments = Integer.parseInt(request.getParameter("maxComments"));
Query query = new Query("comment").addSort("timestamp", SortDirection.DESCENDING);
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
PreparedQuery results = datastore.prepare(query);
List<Comment> comments = new ArrayList<>();
int count = 0;
for (Entity entity: results.asIterable()) {
if (count >= maxComments) break;
long id = entity.getKey().getId();
String email = (String) entity.getProperty("email");
String content = (String) entity.getProperty("content");
String timestamp = (String) entity.getProperty("timestamp");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
Float sentiment = ((Double) entity.getProperty("sentiment")).floatValue();
Comment comment = new Comment(id, email, content, LocalDateTime.parse(timestamp, formatter), sentiment);
comments.add(comment);
count++;
}
Gson gson = new Gson();
response.setContentType("application/json;");
response.getWriter().println(gson.toJson(comments));
}
} |
9231930f4852a7ff4454fdc8647ff5790e215d45 | 8,900 | java | Java | scscp/src/main/java/org/symcomp/scscp/Computation.java | symcomp/org.symcomp.java | b38171c2e3acdf1a125aaee7fa67e237e2c5c0e5 | [
"Apache-2.0"
] | 1 | 2016-06-30T12:29:05.000Z | 2016-06-30T12:29:05.000Z | scscp/src/main/java/org/symcomp/scscp/Computation.java | symcomp/org.symcomp.java | b38171c2e3acdf1a125aaee7fa67e237e2c5c0e5 | [
"Apache-2.0"
] | null | null | null | scscp/src/main/java/org/symcomp/scscp/Computation.java | symcomp/org.symcomp.java | b38171c2e3acdf1a125aaee7fa67e237e2c5c0e5 | [
"Apache-2.0"
] | null | null | null | 27.412308 | 110 | 0.682231 | 995,895 | //---------------------------------------------------------------------------
// Copyright 2006-2009
// Dan Roozemond, efpyi@example.com, (TU Eindhoven, Netherlands)
// Peter Horn, dycjh@example.com (University Kassel, Germany)
//
// 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.symcomp.scscp;
import java.util.Date;
import java.io.Reader;
import java.io.StringReader;
import org.symcomp.openmath.*;
/**
* A Computation is a container that holds the request, the state and some meta-data of a computation.
*
* <p> It is internally used in SCSCPClient. There is no need to manually deal with these objects.
*
*/
public class Computation {
protected ProcedureCall procedureCall;
protected ProcedureDone procedureDone;
protected OpenMathBase result;
protected OpenMathBase request;
protected CookieStore cookies;
protected String token;
protected Date receivedAt;
protected Date startedAt;
protected Date finishedAt;
protected OpenMathBase.ENCODINGS requestEncoding;
protected Integer state = ComputationState.WAITING;
protected CASClient system;
protected final Integer lock = 0;
public Computation() { this.token = "0"; }
public Computation(CASClient system, String token, OpenMathBase command) {
this.system = system;
this.token = token;
this.request = command;
}
public void setCookieStore(CookieStore c) { cookies = c; }
public void setSystem(CASClient s) { system = s; }
public void computing() {
this.state = ComputationState.COMPUTING;
this.startedAt = new Date();
}
public void finished(OpenMathBase result) {
this.finishedAt = new Date();
this.setResult(result);
this.state = ComputationState.READY;
synchronized (lock) {
lock.notifyAll();
}
}
public void finished(String result) {
this.finishedAt = new Date();
this.setResult(result);
this.state = ComputationState.READY;
synchronized (lock) {
lock.notifyAll();
}
}
public void error(OpenMathBase result) {
this.finishedAt = new Date();
this.setResult(result);
this.state = ComputationState.ERRONEOUS;
synchronized (lock) {
lock.notifyAll();
}
}
public void error(String result) {
this.finishedAt = new Date();
this.setResult(result);
this.state = ComputationState.ERRONEOUS;
synchronized (lock) {
lock.notifyAll();
}
}
public void waitForResult() {
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException ignored) { }
}
}
public boolean isReady() {
return !this.state.equals(ComputationState.WAITING) && !this.state.equals(ComputationState.COMPUTING);
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public Date getReceivedAt() {
return receivedAt;
}
public void setReceivedAt(Date receivedAt) {
this.receivedAt = receivedAt;
}
public Date getStartedAt() {
return startedAt;
}
public void setStartedAt(Date startedAt) {
this.startedAt = startedAt;
}
public Date getFinishedAt() {
return finishedAt;
}
public void setFinishedAt(Date finishedAt) {
this.finishedAt = finishedAt;
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
synchronized (lock) {
this.state = state;
state.notifyAll();
}
}
public OpenMathBase.ENCODINGS getRequestEncoding() {
return requestEncoding;
}
public CASClient getSystem() {
return this.system;
}
/**
* Set the return type of the Procedure call: cookie, option or nothing
*/
public void setReturn(ProcedureCall.OPTION_RETURN which) {
getProcedureCall().setReturn(which);
}
/**
* Request the return type of the Procedure call
*/
public void getReturn() {
getProcedureCall().getReturn();
}
/**
* Check whether the Procedure call has a particular return type
*/
public void hasReturn(ProcedureCall.OPTION_RETURN which) {
getProcedureCall().hasReturn(which);
}
/**
* Get the computation as (OpenMath encoded) procedure call
* @return the message
*/
public ProcedureCall getProcedureCall() {
if (procedureCall == null) {
try {
procedureCall = new ProcedureCall(this.token, this.request);
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
procedureCall.setCookieStore(cookies);
return procedureCall;
}
/**
* Get the result as (OpenMath encoded) ProcedureDone
* @return the result message
* @throws org.symcomp.openmath.OpenMathException if something went wrong
*/
public ProcedureDone getProcedureDone()
throws OpenMathException {
if (this.procedureDone == null) {
if (this.result == null) throw new RuntimeException("result not set.");
if (this.state.equals(ComputationState.READY)) {
procedureDone = new ProcedureDone(getProcedureCall(), ProcedureDone.PROCEDURE_COMPLETED, result);
} else if (this.state.equals(ComputationState.ERRONEOUS)) {
procedureDone = new ProcedureDone(getProcedureCall(), ProcedureDone.PROCEDURE_TERMINATED, result);
} else {
throw new RuntimeException("this.state != READY or ERRONEOUS, still trying to getResponseMessage");
}
}
procedureDone.setCookieStore(cookies);
return procedureDone;
}
public OpenMathBase getResult() {
return result;
}
public void setResult(String result) {
try {
this.setResult(OpenMathBase.parse(result));
} catch(Exception e) {
this.setResult(new OMObject(new OMString(e.getMessage())));
}
}
public void setResult(OpenMathBase result) {
this.result = result;
}
public OpenMathBase getRequest() {
return request;
}
public void setRequest(OpenMathBase request) {
this.request = request;
}
public void setProcedureCall(ProcedureCall p) {
this.procedureCall = p;
this.setRequest(p.getPayload());
this.receivedAt = new Date();
this.state = ComputationState.WAITING;
}
public void setProcedureDone(ProcedureDone p) {
this.procedureDone = p;
if (p.which.equals(ProcedureDone.PROCEDURE_COMPLETED)) finished(p.getResult());
if (p.which.equals(ProcedureDone.PROCEDURE_TERMINATED)) error(p.getResult());
}
/**
* Calls {@link #setProcedureCall(ProcedureCall p)} or
* {@link #setProcedureDone(ProcedureDone p)}, depending on the type of message b is.
* @param b0 the message, enc the encoding the message was in (or null)
* @throws org.symcomp.openmath.OpenMathException if the message has the wrong format
*/
public void receivedMessage(OpenMathBase b0, OpenMathBase.ENCODINGS enc)
throws OpenMathException {
OpenMathBase b = b0.deOMObject();
if (b.isApplication("scscp1", "procedure_call")) {
setProcedureCall(new ProcedureCall(cookies, b));
requestEncoding = enc;
} else if (b.isApplication("scscp1", "procedure_completed")) {
setProcedureDone(new ProcedureDone(this.getProcedureCall(), b));
} else if (b.isApplication("scscp1", "procedure_terminated")) {
setProcedureDone(new ProcedureDone(this.getProcedureCall(), b));
} else {
System.out.println(b.toPopcorn());
throw new OpenMathException("Invalid message received");
}
}
/**
* Calls {@link #setProcedureCall(ProcedureCall p)} or
* {@link #setProcedureDone(ProcedureDone p)}, depending on the type of message b is.
* @param b0 the message
* @throws org.symcomp.openmath.OpenMathException if the message has the wrong format
*/
public void receivedMessage(OpenMathBase b0)
throws OpenMathException {
receivedMessage(b0, null);
}
/**
* Calls {@link #setProcedureCall(ProcedureCall p)} or
* {@link #setProcedureDone(ProcedureDone p)}, depending on the type of message b is.
* @param b0 the message as a string
* @throws org.symcomp.openmath.OpenMathException if the message has the wrong format
*/
public void receivedMessage(String m)
throws OpenMathException {
Object[] o = OpenMathBase.sniffEncoding(new StringReader(m));
OpenMathBase.ENCODINGS enc = (OpenMathBase.ENCODINGS) o[0];
Reader r = (Reader) o[1];
OpenMathBase b = enc.parse(r);
receivedMessage(b, enc);
}
}
|
92319314f3f7e03d64ddc4c91e27be33ab780436 | 1,242 | java | Java | Android-source-track/app/src/main/java/com/medlinker/track/sourcepath/demo/ShowTextActivity.java | medlinker/source-path-track | bc3a24ac6560373952a35d693c8620b72a28937f | [
"Apache-2.0"
] | 7 | 2016-05-05T09:40:38.000Z | 2016-07-21T12:47:50.000Z | Android-source-track/app/src/main/java/com/medlinker/track/sourcepath/demo/ShowTextActivity.java | medlinker/source-path-track | bc3a24ac6560373952a35d693c8620b72a28937f | [
"Apache-2.0"
] | null | null | null | Android-source-track/app/src/main/java/com/medlinker/track/sourcepath/demo/ShowTextActivity.java | medlinker/source-path-track | bc3a24ac6560373952a35d693c8620b72a28937f | [
"Apache-2.0"
] | null | null | null | 21.413793 | 69 | 0.642512 | 995,896 | package com.medlinker.track.sourcepath.demo;
import android.os.Bundle;
import android.widget.Button;
import com.medlinker.track.sourcepath.BaseActivity;
import com.medlinker.track.sourcepath.TrackFactory;
import butterknife.InjectView;
/**
* Created by heaven7 on 2016/4/28.
*/
public class ShowTextActivity extends BaseActivity {
public static final String KEY_TEXT = "text";
public static final String KEY_LEVEL = "level";
@InjectView(R.id.bt)
Button mBt;
private String mText;
private int mLevel = -1;
@Override
protected int getlayoutId() {
return R.layout.ac_show_text;
}
@Override
protected void initView() {
}
@Override
protected void initData(Bundle savedInstanceState) {
String text = getIntent().getStringExtra(KEY_TEXT);
this.mText = text;
this.mLevel = getIntent().getIntExtra(KEY_LEVEL , -1);
if(text!=null) {
mBt.setText(text);
}
}
@Override
protected void onResume() {
super.onResume();
if(mText != null){
TrackFactory.getDefaultTagTracker().track(mLevel, mText);
}
}
@Override
protected void onStop() {
super.onStop();
}
}
|
923193688b130d1d64639699578d93e8ecb89291 | 6,692 | java | Java | org/apache/http/impl/DefaultConnectionReuseStrategy.java | MewX/contendo-viewer-v1.6.3 | 69fba3cea4f9a43e48f43148774cfa61b388e7de | [
"Apache-2.0"
] | 2 | 2021-07-16T10:43:25.000Z | 2021-12-15T13:54:10.000Z | org/apache/http/impl/DefaultConnectionReuseStrategy.java | MewX/contendo-viewer-v1.6.3 | 69fba3cea4f9a43e48f43148774cfa61b388e7de | [
"Apache-2.0"
] | 1 | 2021-10-12T22:24:55.000Z | 2021-10-12T22:24:55.000Z | org/apache/http/impl/DefaultConnectionReuseStrategy.java | MewX/contendo-viewer-v1.6.3 | 69fba3cea4f9a43e48f43148774cfa61b388e7de | [
"Apache-2.0"
] | null | null | null | 28.476596 | 119 | 0.437537 | 995,897 | /* */ package org.apache.http.impl;
/* */
/* */ import org.apache.http.ConnectionReuseStrategy;
/* */ import org.apache.http.Header;
/* */ import org.apache.http.HeaderIterator;
/* */ import org.apache.http.HttpRequest;
/* */ import org.apache.http.HttpResponse;
/* */ import org.apache.http.HttpVersion;
/* */ import org.apache.http.ParseException;
/* */ import org.apache.http.ProtocolVersion;
/* */ import org.apache.http.TokenIterator;
/* */ import org.apache.http.annotation.Contract;
/* */ import org.apache.http.annotation.ThreadingBehavior;
/* */ import org.apache.http.message.BasicTokenIterator;
/* */ import org.apache.http.protocol.HttpContext;
/* */ import org.apache.http.util.Args;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ @Contract(threading = ThreadingBehavior.IMMUTABLE)
/* */ public class DefaultConnectionReuseStrategy
/* */ implements ConnectionReuseStrategy
/* */ {
/* 70 */ public static final DefaultConnectionReuseStrategy INSTANCE = new DefaultConnectionReuseStrategy();
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public boolean keepAlive(HttpResponse response, HttpContext context) {
/* 80 */ Args.notNull(response, "HTTP response");
/* 81 */ Args.notNull(context, "HTTP context");
/* */
/* */
/* */
/* */
/* 86 */ if (response.getStatusLine().getStatusCode() == 204) {
/* 87 */ Header clh = response.getFirstHeader("Content-Length");
/* 88 */ if (clh != null) {
/* */ try {
/* 90 */ int contentLen = Integer.parseInt(clh.getValue());
/* 91 */ if (contentLen > 0) {
/* 92 */ return false;
/* */ }
/* 94 */ } catch (NumberFormatException numberFormatException) {}
/* */ }
/* */
/* */
/* */
/* 99 */ Header header1 = response.getFirstHeader("Transfer-Encoding");
/* 100 */ if (header1 != null) {
/* 101 */ return false;
/* */ }
/* */ }
/* */
/* 105 */ HttpRequest request = (HttpRequest)context.getAttribute("http.request");
/* 106 */ if (request != null) {
/* */ try {
/* 108 */ BasicTokenIterator basicTokenIterator = new BasicTokenIterator(request.headerIterator("Connection"));
/* 109 */ while (basicTokenIterator.hasNext()) {
/* 110 */ String token = basicTokenIterator.nextToken();
/* 111 */ if ("Close".equalsIgnoreCase(token)) {
/* 112 */ return false;
/* */ }
/* */ }
/* 115 */ } catch (ParseException px) {
/* */
/* 117 */ return false;
/* */ }
/* */ }
/* */
/* */
/* */
/* 123 */ ProtocolVersion ver = response.getStatusLine().getProtocolVersion();
/* 124 */ Header teh = response.getFirstHeader("Transfer-Encoding");
/* 125 */ if (teh != null) {
/* 126 */ if (!"chunked".equalsIgnoreCase(teh.getValue())) {
/* 127 */ return false;
/* */ }
/* */ }
/* 130 */ else if (canResponseHaveBody(request, response)) {
/* 131 */ Header[] clhs = response.getHeaders("Content-Length");
/* */
/* 133 */ if (clhs.length == 1) {
/* 134 */ Header clh = clhs[0];
/* */ try {
/* 136 */ int contentLen = Integer.parseInt(clh.getValue());
/* 137 */ if (contentLen < 0) {
/* 138 */ return false;
/* */ }
/* 140 */ } catch (NumberFormatException ex) {
/* 141 */ return false;
/* */ }
/* */ } else {
/* 144 */ return false;
/* */ }
/* */ }
/* */
/* */
/* */
/* */
/* */
/* 152 */ HeaderIterator headerIterator = response.headerIterator("Connection");
/* 153 */ if (!headerIterator.hasNext()) {
/* 154 */ headerIterator = response.headerIterator("Proxy-Connection");
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* 180 */ if (headerIterator.hasNext()) {
/* */ try {
/* 182 */ BasicTokenIterator basicTokenIterator = new BasicTokenIterator(headerIterator);
/* 183 */ boolean keepalive = false;
/* 184 */ while (basicTokenIterator.hasNext()) {
/* 185 */ String token = basicTokenIterator.nextToken();
/* 186 */ if ("Close".equalsIgnoreCase(token))
/* 187 */ return false;
/* 188 */ if ("Keep-Alive".equalsIgnoreCase(token))
/* */ {
/* 190 */ keepalive = true;
/* */ }
/* */ }
/* 193 */ if (keepalive) {
/* 194 */ return true;
/* */
/* */ }
/* */ }
/* 198 */ catch (ParseException px) {
/* */
/* 200 */ return false;
/* */ }
/* */ }
/* */
/* */
/* 205 */ return !ver.lessEquals((ProtocolVersion)HttpVersion.HTTP_1_0);
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ protected TokenIterator createTokenIterator(HeaderIterator hit) {
/* 219 */ return (TokenIterator)new BasicTokenIterator(hit);
/* */ }
/* */
/* */ private boolean canResponseHaveBody(HttpRequest request, HttpResponse response) {
/* 223 */ if (request != null && request.getRequestLine().getMethod().equalsIgnoreCase("HEAD")) {
/* 224 */ return false;
/* */ }
/* 226 */ int status = response.getStatusLine().getStatusCode();
/* 227 */ return (status >= 200 && status != 204 && status != 304 && status != 205);
/* */ }
/* */ }
/* Location: /mnt/r/ConTenDoViewer.jar!/org/apache/http/impl/DefaultConnectionReuseStrategy.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ |
9231955ac062ef6b2d104dfc3351c2bd6e55a33a | 1,246 | java | Java | src/main/java/oosd/views/handlers/ForfeitClickHandler.java | johnnyhuy/red-alert-2-board-game | df650ae8f9a633eb143b7f36bfdd170fc6224d7d | [
"MIT"
] | null | null | null | src/main/java/oosd/views/handlers/ForfeitClickHandler.java | johnnyhuy/red-alert-2-board-game | df650ae8f9a633eb143b7f36bfdd170fc6224d7d | [
"MIT"
] | null | null | null | src/main/java/oosd/views/handlers/ForfeitClickHandler.java | johnnyhuy/red-alert-2-board-game | df650ae8f9a633eb143b7f36bfdd170fc6224d7d | [
"MIT"
] | null | null | null | 30.390244 | 125 | 0.700642 | 995,898 | package oosd.views.handlers;
import javafx.event.EventHandler;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.input.MouseEvent;
import oosd.controllers.GameController;
import oosd.models.game.Engine;
import oosd.models.player.Player;
import java.util.Optional;
public class ForfeitClickHandler implements EventHandler<MouseEvent> {
private Engine engine;
private GameController gameController;
public ForfeitClickHandler(Engine engine, GameController gameController) {
this.engine = engine;
this.gameController = gameController;
}
@Override
public void handle(MouseEvent event) {
Player player = engine.getTurnService().getTurn();
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Forfeit game");
alert.setHeaderText("Forfeiting the game");
alert.setContentText(String.format("%s wants to forfeit the game, are you sure commander?", player.getPlayerName()));
Optional<ButtonType> result = alert.showAndWait();
if (!result.isPresent()) {
return;
}
if (result.get().equals(ButtonType.OK)) {
gameController.forfeit();
}
}
}
|
923195766ab8a2d221f54d08bb7e9fcfecca9b33 | 7,265 | java | Java | src/main/java/com/billybyte/clientserver/httpserver/HttpCsvQueryServer.java | bgithub1/common-libs | 30bd6ddad880cd3da7d946ccb921d83352a2be8c | [
"MIT"
] | null | null | null | src/main/java/com/billybyte/clientserver/httpserver/HttpCsvQueryServer.java | bgithub1/common-libs | 30bd6ddad880cd3da7d946ccb921d83352a2be8c | [
"MIT"
] | null | null | null | src/main/java/com/billybyte/clientserver/httpserver/HttpCsvQueryServer.java | bgithub1/common-libs | 30bd6ddad880cd3da7d946ccb921d83352a2be8c | [
"MIT"
] | null | null | null | 29.77459 | 133 | 0.670613 | 995,899 | package com.billybyte.clientserver.httpserver;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import com.billybyte.commoninterfaces.QueryInterface;
import com.billybyte.commonstaticmethods.CollectionsStaticMethods;
import com.billybyte.commonstaticmethods.Utils;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
@SuppressWarnings("restriction")
/**
* Generalized http server which calls a QueryInterface<String,List<String[]>
* instance to get its csv data, and then sends it back to the http caller
* @author bill perlman
*
*/
public class HttpCsvQueryServer {
private final QueryInterface<String, List<String[]>> csvQuery;
private final int httpPort;
private final HttpServer server;
private final String httpPath;
private final int timeoutValue;
private final TimeUnit timeUnitType;
private final String returnFileName;
private final List<String[]> otherHeaderPairs;
private final Map<String,QueryInterface<String, List<String[]>>> altCsvQueryMap =
new ConcurrentHashMap<String, QueryInterface<String,List<String[]>>>(new HashMap<String, QueryInterface<String,List<String[]>>>());
/**
* @param httpPort
* @param httpPath
* @param csvQuery
* @param timeoutValue
* @param timeUnitType
* @param returnFileName
* @throws IOException
*/
public HttpCsvQueryServer(int httpPort, String httpPath,
QueryInterface<String, List<String[]>> csvQuery,
int timeoutValue,
TimeUnit timeUnitType,
String returnFileName,
List<String[]> otherHeaderPairs) throws IOException {
super();
this.timeoutValue = timeoutValue;
this.timeUnitType = timeUnitType;
this.httpPort = httpPort;
this.httpPath = httpPath;
this.csvQuery = csvQuery;
this.returnFileName = returnFileName;
this.otherHeaderPairs = otherHeaderPairs;
server = HttpServer.create(new InetSocketAddress(httpPort), 0);
server.createContext(httpPath, new MyHandler());
server.setExecutor(null); // creates a default executor
}
/**
*
* @param httpPort
* @param httpPath
* @param csvQuery
* @param timeoutValue
* @param timeUnitType
* @param returnFileName
* @throws IOException
*/
public HttpCsvQueryServer(int httpPort, String httpPath,
QueryInterface<String, List<String[]>> csvQuery,
int timeoutValue,
TimeUnit timeUnitType,
String returnFileName)throws IOException{
this(httpPort, httpPath, csvQuery, timeoutValue, timeUnitType, returnFileName, null);
}
/**
*
* @param httpPort
* @param httpPath
* @param csvQuery
* @param timeoutValue
* @param timeUnitType
* @throws IOException
*/
public HttpCsvQueryServer(int httpPort, String httpPath,
QueryInterface<String, List<String[]>> csvQuery,
int timeoutValue,
TimeUnit timeUnitType) throws IOException {
this(httpPort,httpPath,csvQuery,timeoutValue,timeUnitType,"myFileName.csv",null);
}
public void addAlternativePath(String httpPath,QueryInterface<String,List<String[]>> altCsvQuery){
try {
this.altCsvQueryMap.put(httpPath, altCsvQuery);
this.server.createContext(httpPath, new MyHandler());
} catch (Exception e) {
e.printStackTrace();
}
}
public void start(){
server.start();
}
private class MyHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
String path = t.getHttpContext().getPath();
String q = t.getRequestURI().getQuery();
String response = "";
List<String[]> csvList = null;
if(altCsvQueryMap.containsKey(path)){
QueryInterface<String, List<String[]>> altQuery =
altCsvQueryMap.get(path);
csvList =
altQuery.get(q,timeoutValue,timeUnitType);
}else{
csvList =
csvQuery.get(q,timeoutValue,timeUnitType);
}
// turn list of csv into a string
for(String[] csvLine: csvList){
String line = "";
for(String token: csvLine){
line += token+",";
}
line = line.substring(0,line.length()-1);
response += line + "\n";
}
// if a returnFileName has been specified, then add header info to
// the repsonse that will cause a file download rather than a display
// in the browser.
Headers headers = t.getResponseHeaders();
if(returnFileName!=null){
// This is a header to permit the download of the csv
headers.add("Content-Type", "text/csv");
headers.add("Content-Disposition", "attachment;filename="+returnFileName);
}
headers.add("Access-Control-Allow-Origin", "*");
if(otherHeaderPairs!=null && otherHeaderPairs.size()>0){
for(String[] otherHeaderPair : otherHeaderPairs){
headers.add(otherHeaderPair[0],otherHeaderPair[1]);
}
}
t.sendResponseHeaders(200,response.length());
OutputStream os=t.getResponseBody();
Utils.prt(response);
os.write(response.getBytes());
os.close();
}
}
public int getHttpPort() {
return httpPort;
}
public String getHttpPath() {
return httpPath;
}
/**
* test HttpCsvQueryServer
* @param args
*/
public static void main(String[] args) {
int httpPort = 8888;
String httpPath = "/dummyCrude";
QueryInterface<String, List<String[]>> csvQuery =
new TestQuery();
int timeoutValue = 1;
TimeUnit timeUnitType = TimeUnit.SECONDS;
try {
HttpCsvQueryServer csvs =
new HttpCsvQueryServer(
httpPort, httpPath,
csvQuery, timeoutValue, timeUnitType,null);
csvs.start();
Utils.prtObErrMess(HttpCsvQueryServer.class, "server started on port 8888.");
Utils.prtObErrMess(HttpCsvQueryServer.class, "Enter http://127.0.0.1:8888/dummyCrude?p1=data");
CollectionsStaticMethods.prtCsv(Utils.getCSVData("http://127.0.0.1:8888/dummyCrude?p1=data"));
} catch (IOException e) {
e.printStackTrace();
}
}
private static final class TestQuery
implements QueryInterface<String, List<String[]>> {
private final String[][] dummyCsv = {
{"shortName","bid","bidsize","ask","asksize"},
{"CL.FUT.NYMEX.USD.201601","65.25","100","65.30","105"},
{"CL.FUT.NYMEX.USD.201602","66.25","100","66.30","105"},
{"CL.FUT.NYMEX.USD.201603","67.25","100","67.30","105"},
{"CL.FUT.NYMEX.USD.201604","68.25","100","68.30","105"},
{"CL.FUT.NYMEX.USD.201605","69.25","100","69.30","105"},
};
private final String[][] badRet = {{"bad key"}};
@Override
public List<String[]> get(String key, int timeoutValue,
TimeUnit timeUnitType) {
String[] tokens = key.split("=");
if(tokens.length>1 && tokens[1].compareTo("data")==0){
List<String[]> ret =
Arrays.asList(dummyCsv);
return ret;
}
List<String[]> ret =
Arrays.asList(badRet);
return ret;
}
}
}
|
9231958774db0bc23e1b1c97c7324f1b3cd52499 | 419 | java | Java | BioMightWeb/src/biomight/cell/neuronglial/nueron/Axons.java | SurferJim/BioMight | 3dc2c2b21bc6ece2ca9ac44f0727a433ae9f9430 | [
"Apache-2.0"
] | 2 | 2020-05-03T07:43:18.000Z | 2020-11-28T21:02:26.000Z | BioMightWeb/src/biomight/cell/neuronglial/nueron/Axons.java | SurferJim/BioMight | 3dc2c2b21bc6ece2ca9ac44f0727a433ae9f9430 | [
"Apache-2.0"
] | null | null | null | BioMightWeb/src/biomight/cell/neuronglial/nueron/Axons.java | SurferJim/BioMight | 3dc2c2b21bc6ece2ca9ac44f0727a433ae9f9430 | [
"Apache-2.0"
] | 1 | 2020-11-07T01:36:49.000Z | 2020-11-07T01:36:49.000Z | 23.277778 | 73 | 0.701671 | 995,900 | /*
* Created on Oct 25, 2006
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package biomight.cell.neuronglial.nueron;
/**
* @author SurferJim
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class Axons {
}
|
92319617fcba30731453e64e7e553a56924f608a | 1,503 | java | Java | addressbook-web-tests/src/test/java/ru/stqa/ptf/addressbook/tests/ContactDeleteTest.java | tepalex/JAVA_T | 10f55c9990bd694cf619720ba4295c821c537a06 | [
"Apache-2.0"
] | null | null | null | addressbook-web-tests/src/test/java/ru/stqa/ptf/addressbook/tests/ContactDeleteTest.java | tepalex/JAVA_T | 10f55c9990bd694cf619720ba4295c821c537a06 | [
"Apache-2.0"
] | null | null | null | addressbook-web-tests/src/test/java/ru/stqa/ptf/addressbook/tests/ContactDeleteTest.java | tepalex/JAVA_T | 10f55c9990bd694cf619720ba4295c821c537a06 | [
"Apache-2.0"
] | null | null | null | 35.690476 | 105 | 0.715143 | 995,901 | package ru.stqa.ptf.addressbook.tests;
import org.hamcrest.CoreMatchers;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ru.stqa.ptf.addressbook.model.ContactData;
import ru.stqa.ptf.addressbook.model.Contacts;
import ru.stqa.ptf.addressbook.model.Groups;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.testng.Assert.assertEquals;
public class ContactDeleteTest extends TestBase {
@BeforeMethod
public void ensurePreconditions() {
if (app.db().contacts().size() == 0){
Groups groups = app.db().groups();
app.goTo().homePage();
app.contact().create(new ContactData()
.withFirstname("Alex").withLastname("Teplov").withAddress("Address")
.withHomephone("4951234567").withMobilePhone("2000000").withWorkPhone("3000000")
.withEmail("kenaa@example.com").withEmail2("efpyi@example.com").withEmail3("hzdkv@example.com")
.inGroup(groups.iterator().next()));
}
}
@Test
public void deleteContactTest() {
Contacts before = app.db().contacts();
ContactData deletedContact = before.iterator().next();
app.contact().delete(deletedContact);
assertThat(app.contact().count(), equalTo(before.size()-1));
Contacts after = app.db().contacts();
assertThat(after, equalTo(before.without(deletedContact)));
verifyContactListInUI();
}
}
|
923196d8d988afa7ca72ad9afb6af6770cd421b8 | 11,838 | java | Java | camera/camera-camera2/src/androidTest/java/androidx/camera/camera2/interop/Camera2InteropDeviceTest.java | LanderlYoung/androidx | d99c6ef82e67997b71b449840a8147f62f9537a8 | [
"Apache-2.0"
] | 3,799 | 2020-07-23T21:58:59.000Z | 2022-03-31T17:07:19.000Z | camera/camera-camera2/src/androidTest/java/androidx/camera/camera2/interop/Camera2InteropDeviceTest.java | LanderlYoung/androidx | d99c6ef82e67997b71b449840a8147f62f9537a8 | [
"Apache-2.0"
] | 152 | 2020-07-24T00:19:02.000Z | 2022-03-31T00:57:54.000Z | camera/camera-camera2/src/androidTest/java/androidx/camera/camera2/interop/Camera2InteropDeviceTest.java | LanderlYoung/androidx | d99c6ef82e67997b71b449840a8147f62f9537a8 | [
"Apache-2.0"
] | 582 | 2020-07-24T00:16:54.000Z | 2022-03-30T23:32:45.000Z | 41.104167 | 100 | 0.710255 | 995,902 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.camera2.interop;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assume.assumeTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import android.app.Instrumentation;
import android.content.Context;
import android.graphics.Rect;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.MeteringRectangle;
import android.util.Range;
import androidx.annotation.OptIn;
import androidx.camera.camera2.Camera2Config;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.CameraX;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.impl.utils.executor.CameraXExecutors;
import androidx.camera.core.internal.CameraUseCaseAdapter;
import androidx.camera.testing.CameraUtil;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.LargeTest;
import androidx.test.filters.SdkSuppress;
import androidx.test.platform.app.InstrumentationRegistry;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import java.util.Collections;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
@LargeTest
@RunWith(AndroidJUnit4.class)
@OptIn(markerClass = ExperimentalCamera2Interop.class)
@SdkSuppress(minSdkVersion = 21)
public final class Camera2InteropDeviceTest {
private final Instrumentation mInstrumentation = InstrumentationRegistry.getInstrumentation();
private CameraSelector mCameraSelector;
private CameraCaptureSession.CaptureCallback mMockCaptureCallback =
mock(CameraCaptureSession.CaptureCallback.class);
private Context mContext;
private CameraUseCaseAdapter mCamera;
@Rule
public TestRule mUseCamera = CameraUtil.grantCameraPermissionAndPreTest();
@Before
public void setUp() {
assumeTrue(CameraUtil.hasCameraWithLensFacing(CameraSelector.LENS_FACING_BACK));
mContext = ApplicationProvider.getApplicationContext();
CameraX.initialize(mContext, Camera2Config.defaultConfig());
mCameraSelector = new CameraSelector.Builder().requireLensFacing(
CameraSelector.LENS_FACING_BACK).build();
mMockCaptureCallback = mock(CameraCaptureSession.CaptureCallback.class);
}
@After
public void tearDown() throws ExecutionException, InterruptedException, TimeoutException {
if (mCamera != null) {
mInstrumentation.runOnMainSync(() ->
//TODO: The removeUseCases() call might be removed after clarifying the
// abortCaptures() issue in b/162314023.
mCamera.removeUseCases(mCamera.getUseCases())
);
}
CameraX.shutdown().get(10000, TimeUnit.MILLISECONDS);
}
@Test
public void canHookCallbacks() {
CameraCaptureSession.StateCallback mockSessionStateCallback =
mock(CameraCaptureSession.StateCallback.class);
CameraDevice.StateCallback mockDeviceCallback =
mock(CameraDevice.StateCallback.class);
ImageAnalysis.Builder builder = new ImageAnalysis.Builder();
new Camera2Interop.Extender<>(builder)
.setSessionCaptureCallback(mMockCaptureCallback)
.setSessionStateCallback(mockSessionStateCallback)
.setDeviceStateCallback(mockDeviceCallback);
ImageAnalysis imageAnalysis = builder.build();
// set analyzer to make it active.
imageAnalysis.setAnalyzer(CameraXExecutors.highPriorityExecutor(),
mock(ImageAnalysis.Analyzer.class));
mCamera = CameraUtil.createCameraAndAttachUseCase(mContext, mCameraSelector, imageAnalysis);
verify(mMockCaptureCallback, timeout(5000).atLeastOnce()).onCaptureCompleted(
any(CameraCaptureSession.class),
any(CaptureRequest.class),
any(TotalCaptureResult.class));
verify(mockSessionStateCallback, timeout(5000)).onActive(any(CameraCaptureSession.class));
verify(mockDeviceCallback, timeout(5000)).onOpened(any(CameraDevice.class));
}
@Test
public void canOverrideAfMode() {
bindUseCaseWithCamera2Option(
mMockCaptureCallback,
CaptureRequest.CONTROL_AF_MODE,
CaptureRequest.CONTROL_AF_MODE_OFF);
verifyCaptureRequestParameter(mMockCaptureCallback, CaptureRequest.CONTROL_AF_MODE,
CaptureRequest.CONTROL_AF_MODE_OFF);
}
@Test
public void canOverrideAeMode() {
bindUseCaseWithCamera2Option(mMockCaptureCallback,
CaptureRequest.CONTROL_AE_MODE,
CaptureRequest.CONTROL_AE_MODE_OFF);
verifyCaptureRequestParameter(mMockCaptureCallback, CaptureRequest.CONTROL_AE_MODE,
CaptureRequest.CONTROL_AE_MODE_OFF);
}
@Test
public void canOverrideAwbMode() {
bindUseCaseWithCamera2Option(mMockCaptureCallback,
CaptureRequest.CONTROL_AWB_MODE,
CaptureRequest.CONTROL_AWB_MODE_OFF);
verifyCaptureRequestParameter(mMockCaptureCallback, CaptureRequest.CONTROL_AWB_MODE,
CaptureRequest.CONTROL_AWB_MODE_OFF);
}
@Test
public void canOverrideAeFpsRange() {
bindUseCaseWithCamera2Option(mMockCaptureCallback,
CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE,
new Range<>(30, 30));
verifyCaptureRequestParameter(mMockCaptureCallback,
CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE,
new Range<>(30, 30));
}
@Test
public void canOverrideScalarCropRegion() throws Exception {
// scalar crop region must be larger than the region defined
// by SCALER_AVAILABLE_MAX_DIGITAL_ZOOM otherwise it could cause a crash on some devices.
// Thus we cannot simply specify some random crop region.
Rect cropRegion = getZoom2XCropRegion();
bindUseCaseWithCamera2Option(mMockCaptureCallback,
CaptureRequest.SCALER_CROP_REGION,
cropRegion
);
verifyCaptureRequestParameter(mMockCaptureCallback, CaptureRequest.SCALER_CROP_REGION,
cropRegion);
}
@Test
public void canOverrideAfRegion() {
MeteringRectangle[] meteringRectangles = new MeteringRectangle[]{
new MeteringRectangle(0, 0, 100, 100, MeteringRectangle.METERING_WEIGHT_MAX)
};
bindUseCaseWithCamera2Option(mMockCaptureCallback,
CaptureRequest.CONTROL_AF_REGIONS,
meteringRectangles
);
verifyCaptureRequestParameter(mMockCaptureCallback, CaptureRequest.CONTROL_AF_REGIONS,
meteringRectangles);
}
@Test
public void canOverrideAeRegion() {
MeteringRectangle[] meteringRectangles = new MeteringRectangle[]{
new MeteringRectangle(0, 0, 100, 100, MeteringRectangle.METERING_WEIGHT_MAX)
};
bindUseCaseWithCamera2Option(mMockCaptureCallback,
CaptureRequest.CONTROL_AE_REGIONS,
meteringRectangles
);
verifyCaptureRequestParameter(mMockCaptureCallback, CaptureRequest.CONTROL_AE_REGIONS,
meteringRectangles);
}
@Test
public void canOverrideAwbRegion() {
MeteringRectangle[] meteringRectangles = new MeteringRectangle[]{
new MeteringRectangle(0, 0, 100, 100, MeteringRectangle.METERING_WEIGHT_MAX)
};
bindUseCaseWithCamera2Option(mMockCaptureCallback,
CaptureRequest.CONTROL_AWB_REGIONS,
meteringRectangles
);
verifyCaptureRequestParameter(mMockCaptureCallback, CaptureRequest.CONTROL_AWB_REGIONS,
meteringRectangles);
}
private Rect getZoom2XCropRegion() throws Exception {
AtomicReference<String> cameraIdRef = new AtomicReference<>();
ImageAnalysis imageAnalysis = new ImageAnalysis.Builder().build();
mCamera = CameraUtil.createCameraAndAttachUseCase(mContext, mCameraSelector, imageAnalysis);
String cameraId = Camera2CameraInfo.from(mCamera.getCameraInfo()).getCameraId();
cameraIdRef.set(cameraId);
InstrumentationRegistry.getInstrumentation().runOnMainSync(() ->
mCamera.removeUseCases(Collections.singleton(imageAnalysis))
);
CameraManager cameraManager =
(CameraManager) mInstrumentation.getContext().getSystemService(
Context.CAMERA_SERVICE);
CameraCharacteristics characteristics =
cameraManager.getCameraCharacteristics(cameraIdRef.get());
assumeTrue(
characteristics.get(CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM)
>= 2);
Rect sensorRect = characteristics
.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE);
return new Rect(sensorRect.centerX() - sensorRect.width() / 4,
sensorRect.centerY() - sensorRect.height() / 4,
sensorRect.centerX() + sensorRect.width() / 4,
sensorRect.centerY() + sensorRect.height() / 4);
}
private <T> void bindUseCaseWithCamera2Option(CameraCaptureSession.CaptureCallback callback,
CaptureRequest.Key<T> key,
T value) {
ImageAnalysis.Builder builder = new ImageAnalysis.Builder();
new Camera2Interop.Extender<>(builder)
.setCaptureRequestOption(key, value)
.setSessionCaptureCallback(callback);
ImageAnalysis imageAnalysis = builder.build();
// set analyzer to make it active.
imageAnalysis.setAnalyzer(CameraXExecutors.highPriorityExecutor(),
mock(ImageAnalysis.Analyzer.class));
mCamera = CameraUtil.createCameraAndAttachUseCase(mContext, mCameraSelector, imageAnalysis);
}
private <T> void verifyCaptureRequestParameter(
CameraCaptureSession.CaptureCallback mockCallback,
CaptureRequest.Key<T> key,
T value) {
ArgumentCaptor<CaptureRequest> captureRequest =
ArgumentCaptor.forClass(CaptureRequest.class);
verify(mockCallback, timeout(5000).atLeastOnce()).onCaptureCompleted(
any(CameraCaptureSession.class),
captureRequest.capture(), any(TotalCaptureResult.class));
CaptureRequest request = captureRequest.getValue();
assertThat(request.get(key)).isEqualTo(value);
}
}
|
92319785e8db807e578c12cb175822f8158a016d | 8,548 | java | Java | src/main/java/cn/topca/security/bc/cms/RecipientInformation.java | dingjianhui1013/operator | 6029044c7042dfd3797d359a69d4556a3658c60f | [
"Apache-2.0"
] | null | null | null | src/main/java/cn/topca/security/bc/cms/RecipientInformation.java | dingjianhui1013/operator | 6029044c7042dfd3797d359a69d4556a3658c60f | [
"Apache-2.0"
] | null | null | null | src/main/java/cn/topca/security/bc/cms/RecipientInformation.java | dingjianhui1013/operator | 6029044c7042dfd3797d359a69d4556a3658c60f | [
"Apache-2.0"
] | null | null | null | 36.434043 | 145 | 0.658141 | 995,903 | package cn.topca.security.bc.cms;
import org.bouncycastle.asn1.DEREncodable;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.cms.CMSException;
import org.bouncycastle.cms.CMSTypedStream;
import org.bouncycastle.cms.Recipient;
import org.bouncycastle.cms.RecipientId;
import org.bouncycastle.cms.RecipientOperator;
import org.bouncycastle.util.io.Streams;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.AlgorithmParameters;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Provider;
/**
* Copyright (c) 2011-2014 北京天诚安信科技有限公司 <ychag@example.com>
* <p/>
* 扩展BouncyCastle用于支持国产算法
*
* @author 王翾旻 <anpch@example.com>
* @version 2014-04-28 19:28
*/
public abstract class RecipientInformation {
protected RecipientId rid;
protected AlgorithmIdentifier keyEncAlg;
protected AlgorithmIdentifier messageAlgorithm;
private CMSSecureReadable secureReadable;
private AuthAttributesProvider additionalData;
private byte[] resultMac;
private RecipientOperator operator;
RecipientInformation(
AlgorithmIdentifier keyEncAlg,
AlgorithmIdentifier messageAlgorithm,
CMSSecureReadable secureReadable,
AuthAttributesProvider additionalData) {
this.keyEncAlg = keyEncAlg;
this.messageAlgorithm = messageAlgorithm;
this.secureReadable = secureReadable;
this.additionalData = additionalData;
}
String getContentAlgorithmName() {
AlgorithmIdentifier algorithm = secureReadable.getAlgorithm();
return CMSEnvelopedHelper.INSTANCE.getSymmetricCipherName(algorithm.getObjectId().getId());
}
public RecipientId getRID() {
return rid;
}
private byte[] encodeObj(
DEREncodable obj)
throws IOException {
if (obj != null) {
return obj.getDERObject().getEncoded();
}
return null;
}
/**
* return the object identifier for the key encryption algorithm.
*
* @return OID for key encryption algorithm.
*/
public String getKeyEncryptionAlgOID() {
return keyEncAlg.getObjectId().getId();
}
/**
* return the ASN.1 encoded key encryption algorithm parameters, or null if
* there aren't any.
*
* @return ASN.1 encoding of key encryption algorithm parameters.
*/
public byte[] getKeyEncryptionAlgParams() {
try {
return encodeObj(keyEncAlg.getParameters());
} catch (Exception e) {
throw new RuntimeException("exception getting encryption parameters " + e);
}
}
/**
* Return an AlgorithmParameters object giving the encryption parameters
* used to encrypt the key this recipient holds.
*
* @param provider the provider to generate the parameters for.
* @return the parameters object, null if there is not one.
* @throws CMSException if the algorithm cannot be found, or the parameters can't be parsed.
* @throws java.security.NoSuchProviderException if the provider cannot be found.
*/
public AlgorithmParameters getKeyEncryptionAlgorithmParameters(
String provider)
throws CMSException, NoSuchProviderException {
return getKeyEncryptionAlgorithmParameters(CMSUtils.getProvider(provider));
}
/**
* Return an AlgorithmParameters object giving the encryption parameters
* used to encrypt the key this recipient holds.
*
* @param provider the provider to generate the parameters for.
* @return the parameters object, null if there is not one.
* @throws CMSException if the algorithm cannot be found, or the parameters can't be parsed.
*/
public AlgorithmParameters getKeyEncryptionAlgorithmParameters(
Provider provider)
throws CMSException {
try {
byte[] enc = this.encodeObj(keyEncAlg.getParameters());
if (enc == null) {
return null;
}
AlgorithmParameters params = CMSEnvelopedHelper.INSTANCE.createAlgorithmParameters(getKeyEncryptionAlgOID(), provider);
params.init(enc, "ASN.1");
return params;
} catch (NoSuchAlgorithmException e) {
throw new CMSException("can't find parameters for algorithm", e);
} catch (IOException e) {
throw new CMSException("can't find parse parameters", e);
}
}
protected CMSTypedStream getContentFromSessionKey(
Key sKey,
Provider provider)
throws CMSException {
CMSReadable readable = secureReadable.getReadable((SecretKey) sKey, provider);
try {
return new CMSTypedStream(readable.getInputStream());
} catch (IOException e) {
throw new CMSException("error getting .", e);
}
}
/**
* Return the content digest calculated during the read of the content if one has been generated. This will
* only happen if we are dealing with authenticated data and authenticated attributes are present.
*
* @return byte array containing the digest.
*/
public byte[] getContentDigest() {
if (secureReadable instanceof CMSEnvelopedHelper.CMSDigestAuthenticatedSecureReadable) {
return ((CMSEnvelopedHelper.CMSDigestAuthenticatedSecureReadable) secureReadable).getDigest();
}
return null;
}
/**
* Return the MAC calculated for the recipient. Note: this call is only meaningful once all
* the content has been read.
*
* @return byte array containing the mac.
*/
public byte[] getMac() {
if (resultMac == null) {
if (operator != null) {
if (operator.isMacBased()) {
if (additionalData != null) {
try {
Streams.drain(operator.getInputStream(new ByteArrayInputStream(additionalData.getAuthAttributes().getDEREncoded())));
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
resultMac = operator.getMac();
}
} else {
Object cryptoObject = secureReadable.getCryptoObject();
if (cryptoObject instanceof Mac) {
resultMac = ((Mac) cryptoObject).doFinal();
}
}
}
return resultMac;
}
/**
* Return the decrypted/encapsulated content in the EnvelopedData after recovering the content
* encryption/MAC key using the passed in Recipient.
*
* @param recipient recipient object to use to recover content encryption key
* @return the content inside the EnvelopedData this RecipientInformation is associated with.
* @throws CMSException if the content-encryption/MAC key cannot be recovered.
*/
public byte[] getContent(
Recipient recipient)
throws CMSException {
try {
return CMSUtils.streamToByteArray(getContentStream(recipient).getContentStream());
} catch (IOException e) {
throw new CMSException("unable to parse internal stream: " + e.getMessage(), e);
}
}
/**
* Return a CMSTypedStream representing the content in the EnvelopedData after recovering the content
* encryption/MAC key using the passed in Recipient.
*
* @param recipient recipient object to use to recover content encryption key
* @return the content inside the EnvelopedData this RecipientInformation is associated with.
* @throws CMSException if the content-encryption/MAC key cannot be recovered.
*/
public CMSTypedStream getContentStream(Recipient recipient)
throws CMSException, IOException {
operator = getRecipientOperator(recipient);
if (additionalData != null) {
return new CMSTypedStream(secureReadable.getInputStream());
}
return new CMSTypedStream(operator.getInputStream(secureReadable.getInputStream()));
}
protected abstract RecipientOperator getRecipientOperator(Recipient recipient)
throws CMSException, IOException;
}
|
9231978b081d8f6dfe20b16650eb51fc76b271ad | 15,509 | java | Java | clients/src/main/java/org/apache/kafka/clients/Metadata.java | hsfxuebao/kafka-0.10.2.0-src | 5048b4e2304dbf3efe5154cd76e9f2c05ed19c49 | [
"Apache-2.0"
] | 6 | 2021-01-29T01:13:26.000Z | 2022-02-17T06:03:03.000Z | clients/src/main/java/org/apache/kafka/clients/Metadata.java | hsfxuebao/kafka-0.10.2.0-src | 5048b4e2304dbf3efe5154cd76e9f2c05ed19c49 | [
"Apache-2.0"
] | null | null | null | clients/src/main/java/org/apache/kafka/clients/Metadata.java | hsfxuebao/kafka-0.10.2.0-src | 5048b4e2304dbf3efe5154cd76e9f2c05ed19c49 | [
"Apache-2.0"
] | null | null | null | 38.105651 | 146 | 0.658843 | 995,904 | /**
* 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.kafka.clients;
import org.apache.kafka.common.Cluster;
import org.apache.kafka.common.internals.ClusterResourceListeners;
import org.apache.kafka.common.Node;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.errors.TimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
* A class encapsulating some of the logic around metadata.
* <p>
* This class is shared by the client thread (for partitioning) and the background sender thread.
*
* Metadata is maintained for only a subset of topics, which can be added to over time. When we request metadata for a
* topic we don't have any metadata for it will trigger a metadata update.
* <p>
* If topic expiry is enabled for the metadata, any topic that has not been used within the expiry interval
* is removed from the metadata refresh set after an update. Consumers disable topic expiry since they explicitly
* manage topics while producers rely on topic expiry to limit the refresh set.
*/
/**
* 这个类被 client 线程和后台 sender 所共享,它只保存了所有 topic 的部分数据,当我们请求一个它上面没有的 topic meta 时,
* 它会通过发送 metadata update 来更新 meta 信息,
* 如果 topic meta 过期策略是允许的,那么任何 topic 过期的话都会被从集合中移除,
* 但是 consumer 是不允许 topic 过期的因为它明确地知道它需要管理哪些 topic
*/
public final class Metadata {
private static final Logger log = LoggerFactory.getLogger(Metadata.class);
public static final long TOPIC_EXPIRY_MS = 5 * 60 * 1000;
private static final long TOPIC_EXPIRY_NEEDS_UPDATE = -1L;
//两个更新元数据的请求的最小的时间间隔,默认值是100ms
//目的就是减少网络的压力
private final long refreshBackoffMs;
// 多久自动更新一次元数据,默认值是5分钟更新一次。
private final long metadataExpireMs;
// 集群元数据版本号,元数据更新成功一次,版本号就自增1
private int version;
// 上一次更新元数据的时间戳
private long lastRefreshMs;
/**
* 上一次成功更新元数据的时间戳,如果每次更新都成功,
* lastSuccessfulRefreshMs应该与lastRefreshMs相同,否则lastRefreshMs > lastSuccessfulRefreshMs
*/
private long lastSuccessfulRefreshMs;
// 记录kafka集群的元数据
private Cluster cluster;
// 表示是否强制更新Cluster
private boolean needUpdate;
/* Topics with expiry time */
// 记录当前已知的所有的主题
private final Map<String, Long> topics;
// 监听器集合,用于监听Metadata更新
private final List<Listener> listeners;
// 当接收到 metadata 更新时, ClusterResourceListeners的列表
private final ClusterResourceListeners clusterResourceListeners;
// 是否需要更新全部主题的元数据
private boolean needMetadataForAllTopics;
// 默认为 true, Producer 会定时移除过期的 topic,consumer 则不会移除
private final boolean topicExpiryEnabled;
/**
* Create a metadata instance with reasonable defaults
*/
public Metadata() {
this(100L, 60 * 60 * 1000L);
}
public Metadata(long refreshBackoffMs, long metadataExpireMs) {
this(refreshBackoffMs, metadataExpireMs, false, new ClusterResourceListeners());
}
/**
* Create a new Metadata instance
* @param refreshBackoffMs The minimum amount of time that must expire between metadata refreshes to avoid busy
* polling
* @param metadataExpireMs The maximum amount of time that metadata can be retained without refresh
* @param topicExpiryEnabled If true, enable expiry of unused topics
* @param clusterResourceListeners List of ClusterResourceListeners which will receive metadata updates.
*/
public Metadata(long refreshBackoffMs, long metadataExpireMs, boolean topicExpiryEnabled, ClusterResourceListeners clusterResourceListeners) {
this.refreshBackoffMs = refreshBackoffMs;
this.metadataExpireMs = metadataExpireMs;
this.topicExpiryEnabled = topicExpiryEnabled;
this.lastRefreshMs = 0L;
this.lastSuccessfulRefreshMs = 0L;
this.version = 0;
this.cluster = Cluster.empty();
this.needUpdate = false;
this.topics = new HashMap<>();
this.listeners = new ArrayList<>();
this.clusterResourceListeners = clusterResourceListeners;
this.needMetadataForAllTopics = false;
}
/**
* Get the current cluster info without blocking
*/
public synchronized Cluster fetch() {
return this.cluster;
}
/**
* Add the topic to maintain in the metadata. If topic expiry is enabled, expiry time
* will be reset on the next update.
*/
public synchronized void add(String topic) {
if (topics.put(topic, TOPIC_EXPIRY_NEEDS_UPDATE) == null) {
requestUpdateForNewTopics();
}
}
/**
* The next time to update the cluster info is the maximum of the time the current info will expire and the time the
* current info can be updated (i.e. backoff time has elapsed); If an update has been request then the expiry time
* is now
*/
public synchronized long timeToNextUpdate(long nowMs) {
/**
* 元数据是否过期,判断条件:
* 1. needUpdate被置为true
* 2. 上次更新时间距离当前时间已经超过了指定的元数据过期时间阈值metadataExpireMs(metadata.max.age.ms),默认是300秒
*/
long timeToExpire = needUpdate ? 0 : Math.max(this.lastSuccessfulRefreshMs + this.metadataExpireMs - nowMs, 0);
/**
* 允许更新的时间点,计算方式:
* 上次更新时间 + 退避时间 - 当前时间的间隔
* 即要求上次更新时间与当前时间的间隔不能大于退避时间,如果大于则需要等待
*/
long timeToAllowUpdate = this.lastRefreshMs + this.refreshBackoffMs - nowMs;
return Math.max(timeToExpire, timeToAllowUpdate);
}
/**
* Request an update of the current cluster metadata info, return the current version before the update
*/
public synchronized int requestUpdate() {
this.needUpdate = true; // 设置为需要强制更新
return this.version; // 返回当前集群元数据的版本号
}
/**
* Check whether an update has been explicitly requested.
* @return true if an update was requested, false otherwise
*/
public synchronized boolean updateRequested() {
return this.needUpdate;
}
/**
* Wait for metadata update until the current version is larger than the last version we know of
*/
public synchronized void awaitUpdate(final int lastVersion, final long maxWaitMs) throws InterruptedException {
if (maxWaitMs < 0) {
throw new IllegalArgumentException("Max time to wait for metadata updates should not be < 0 milli seconds");
}
long begin = System.currentTimeMillis();
//看剩余可以使用的时间,一开始是最大等待的时间。
long remainingWaitMs = maxWaitMs;
//version是元数据的版本号。
//如果当前的这个version小于等于上一次的version。
//说明元数据还没更新。
//因为如果sender线程那儿 更新元数据,如果更新成功了,sender线程肯定回去累加这个version。
while (this.version <= lastVersion) {
//如果还有剩余的时间。
if (remainingWaitMs != 0)
//让当前线程阻塞等待。
//我们这儿虽然没有去看 sender线程的源码
//但是我们知道,他那儿肯定会做这样的一个操作
//如果更新元数据成功了,会唤醒这个线程。
wait(remainingWaitMs);
//如果代码执行到这儿 说明就要么就被唤醒了,要么就到点了。
//计算一下花了多少时间。
long elapsed = System.currentTimeMillis() - begin;
// 超时,抛出超时异常
if (elapsed >= maxWaitMs)
throw new TimeoutException("Failed to update metadata after " + maxWaitMs + " ms.");
//再次计算 可以使用的时间。
remainingWaitMs = maxWaitMs - elapsed;
}
}
/**
* Replace the current set of topics maintained to the one provided.
* If topic expiry is enabled, expiry time of the topics will be
* reset on the next update.
* @param topics
*/
public synchronized void setTopics(Collection<String> topics) {
// 如果Metadata中已知的主题没有包含传入的主题,则需要更新Metadata元数据
if (!this.topics.keySet().containsAll(topics)) {
requestUpdateForNewTopics();
}
// 清空原有的已知主题
this.topics.clear();
for (String topic : topics)
// 更新已知主题
this.topics.put(topic, TOPIC_EXPIRY_NEEDS_UPDATE);
}
/**
* Get the list of topics we are currently maintaining metadata for
*/
public synchronized Set<String> topics() {
return new HashSet<>(this.topics.keySet());
}
/**
* Check if a topic is already in the topic set.
* @param topic topic to check
* @return true if the topic exists, false otherwise
*/
public synchronized boolean containsTopic(String topic) {
return this.topics.containsKey(topic);
}
/**
* Updates the cluster metadata. If topic expiry is enabled, expiry time
* is set for topics if required and expired topics are removed from the metadata.
*/
public synchronized void update(Cluster cluster, long now) {
Objects.requireNonNull(cluster, "cluster should not be null");
this.needUpdate = false;
this.lastRefreshMs = now;
this.lastSuccessfulRefreshMs = now;
/**
* 更新元数据版本 +1
*/
this.version += 1;
// 默认是true
if (topicExpiryEnabled) {
// Handle expiry of topics from the metadata refresh set.
// 场景驱动方式研究代码,第一次进来是在product初始化的时候
// 但是我们目前topics是空的
// 所以下面的代码是不会被运行的。
//到现在我们的代码是不是第二次进来了呀?
//如果第二次进来,此时此刻进来,我们 producer.send(topics,)方法
//要去拉取元数据 -》 sender -》 代码走到的这儿。
//第二次进来的时候,topics其实不为空了,因为我们已经给它赋值了
//所以这儿的代码是会继续运行的。
for (Iterator<Map.Entry<String, Long>> it = topics.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<String, Long> entry = it.next();
long expireMs = entry.getValue();
if (expireMs == TOPIC_EXPIRY_NEEDS_UPDATE)
entry.setValue(now + TOPIC_EXPIRY_MS);
else if (expireMs <= now) {
it.remove();
log.debug("Removing unused topic {} from the metadata list, expiryMs {} now {}", entry.getKey(), expireMs, now);
}
}
}
// 通知所有的监听器,数据要更新了
for (Listener listener: listeners)
listener.onMetadataUpdate(cluster);
String previousClusterId = cluster.clusterResource().clusterId();
//这个的默认值是false,所以这个分支的代码不会被运行。
if (this.needMetadataForAllTopics) {
// the listener may change the interested topics, which could cause another metadata refresh.
// If we have already fetched all topics, however, another fetch should be unnecessary.
this.needUpdate = false;
this.cluster = getClusterForCurrentTopics(cluster);
} else {
//所以代码执行的是这儿。
//直接把刚刚传进来的对象赋值给了这个cluster。
//cluster代表的是kafka集群的元数据。
//初始化的时候,update这个方法没有去服务端拉取数据。
this.cluster = cluster;
}
// The bootstrap cluster is guaranteed not to have any useful information
if (!cluster.isBootstrapConfigured()) {
String clusterId = cluster.clusterResource().clusterId();
if (clusterId == null ? previousClusterId != null : !clusterId.equals(previousClusterId))
log.info("Cluster ID: {}", cluster.clusterResource().clusterId());
clusterResourceListeners.onUpdate(cluster.clusterResource());
}
//大家发现这儿会有一个notifyAll,最重要的一个作用就是唤醒那个wait的线程。
notifyAll();
log.debug("Updated cluster metadata version {} to {}", this.version, this.cluster);
}
/**
* Record an attempt to update the metadata that failed. We need to keep track of this
* to avoid retrying immediately.
*/
public synchronized void failedUpdate(long now) {
// 更新失败的情况下,只会更新lastRefreshMs字段
this.lastRefreshMs = now;
}
/**
* @return The current metadata version
*/
public synchronized int version() {
return this.version;
}
/**
* The last time metadata was successfully updated.
*/
public synchronized long lastSuccessfulUpdate() {
return this.lastSuccessfulRefreshMs;
}
/**
* Set state to indicate if metadata for all topics in Kafka cluster is required or not.
* @param needMetadataForAllTopics boolean indicating need for metadata of all topics in cluster.
*/
public synchronized void needMetadataForAllTopics(boolean needMetadataForAllTopics) {
if (needMetadataForAllTopics && !this.needMetadataForAllTopics) {
requestUpdateForNewTopics();
}
this.needMetadataForAllTopics = needMetadataForAllTopics;
}
/**
* Get whether metadata for all topics is needed or not
*/
public synchronized boolean needMetadataForAllTopics() {
return this.needMetadataForAllTopics;
}
/**
* Add a Metadata listener that gets notified of metadata updates
*/
public synchronized void addListener(Listener listener) {
this.listeners.add(listener);
}
/**
* Stop notifying the listener of metadata updates
*/
public synchronized void removeListener(Listener listener) {
this.listeners.remove(listener);
}
/**
* MetadataUpdate Listener
*/
public interface Listener {
void onMetadataUpdate(Cluster cluster);
}
private synchronized void requestUpdateForNewTopics() {
// Override the timestamp of last refresh to let immediate update.
this.lastRefreshMs = 0;
requestUpdate();
}
// 根据传入的Cluster对象更新数据
private Cluster getClusterForCurrentTopics(Cluster cluster) {
Set<String> unauthorizedTopics = new HashSet<>();
Collection<PartitionInfo> partitionInfos = new ArrayList<>();
List<Node> nodes = Collections.emptyList();
Set<String> internalTopics = Collections.emptySet();
String clusterId = null;
if (cluster != null) {
clusterId = cluster.clusterResource().clusterId();
internalTopics = cluster.internalTopics();
// 记录未授权的主题
unauthorizedTopics.addAll(cluster.unauthorizedTopics());
// 从未授权的主题中移除当前已知可用的主题
unauthorizedTopics.retainAll(this.topics.keySet());
// 更新partition信息
for (String topic : this.topics.keySet()) {
List<PartitionInfo> partitionInfoList = cluster.partitionsForTopic(topic);
if (partitionInfoList != null) {
partitionInfos.addAll(partitionInfoList);
}
}
nodes = cluster.nodes();
}
// 构造新的Cluster
return new Cluster(clusterId, nodes, partitionInfos, unauthorizedTopics, internalTopics);
}
}
|
923198890a358226d09aabf7da56b26390d2a034 | 1,197 | java | Java | hackerrank/30-Days-of-Code/01-data-types.java | everarch/psets | 7fddb2a01ce8c4e601d63c3be3b11cd2113be035 | [
"MIT"
] | null | null | null | hackerrank/30-Days-of-Code/01-data-types.java | everarch/psets | 7fddb2a01ce8c4e601d63c3be3b11cd2113be035 | [
"MIT"
] | null | null | null | hackerrank/30-Days-of-Code/01-data-types.java | everarch/psets | 7fddb2a01ce8c4e601d63c3be3b11cd2113be035 | [
"MIT"
] | null | null | null | 24.9375 | 107 | 0.635756 | 995,905 | /*
* Day 1: Data Types
*
* https://www.hackerrank.com/challenges/30-data-types/problem
*
*/
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
int i = 4;
double d = 4.0;
String s = "HackerRank ";
Scanner scan = new Scanner(System.in);
/* Declare second integer, double, and String variables. */
int i2 = 0;
double d2 = 0.0;
String s2 = "";
/* Read and save an integer, double, and String to your variables.*/
// Note: If you have trouble reading the entire String, please go back and review the Tutorial closely.
i2 = scan.nextInt();
d2 = scan.nextDouble();
scan.nextLine(); // Flush buffer of new line character
s2 = scan.nextLine();
/* Print the sum of both integer variables on a new line. */
System.out.println(i + i2);
/* Print the sum of the double variables on a new line. */
System.out.println(d + d2);
/* Concatenate and print the String variables on a new line;
the 's' variable above should be printed first. */
System.out.println(s + s2);
scan.close();
}
}
|
9231988ee93f995d5ef4e1f4987d0d12da5b3c99 | 274 | java | Java | src/main/java/de/unistuttgart/vis/vita/analysis/results/TextMetrics.java | vita-us/ViTA | 5e620bee667f693411c417e5a62646172991a838 | [
"MIT"
] | 14 | 2015-04-22T10:22:53.000Z | 2021-04-23T13:40:45.000Z | src/main/java/de/unistuttgart/vis/vita/analysis/results/TextMetrics.java | vita-us/ViTA | 5e620bee667f693411c417e5a62646172991a838 | [
"MIT"
] | null | null | null | src/main/java/de/unistuttgart/vis/vita/analysis/results/TextMetrics.java | vita-us/ViTA | 5e620bee667f693411c417e5a62646172991a838 | [
"MIT"
] | 1 | 2020-08-26T10:33:50.000Z | 2020-08-26T10:33:50.000Z | 21.076923 | 54 | 0.711679 | 995,906 | package de.unistuttgart.vis.vita.analysis.results;
/**
* Provides metric information about the document text
*/
public interface TextMetrics {
/**
* Gets the total number of words in the document
* @return the number of words
*/
public int getWordCount();
}
|
92319a2a7e6092fa972cb2e065a2de2d1196ea2a | 2,290 | java | Java | TestImageLoader/app/src/main/java/com/teemo/testimageloader/TestAdapter.java | teemo927/hello-world | fda89ebb5b33724f2a9ffc77cb05e9ebff14d0ff | [
"Apache-2.0"
] | 2 | 2016-05-11T13:36:17.000Z | 2016-05-11T13:36:20.000Z | TestImageLoader/app/src/main/java/com/teemo/testimageloader/TestAdapter.java | demo920/hello-world | fda89ebb5b33724f2a9ffc77cb05e9ebff14d0ff | [
"Apache-2.0"
] | null | null | null | TestImageLoader/app/src/main/java/com/teemo/testimageloader/TestAdapter.java | demo920/hello-world | fda89ebb5b33724f2a9ffc77cb05e9ebff14d0ff | [
"Apache-2.0"
] | null | null | null | 28.625 | 114 | 0.673362 | 995,907 | package com.teemo.testimageloader;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.teemo.testimageloader.image.ImageLoaderFactory;
import java.util.List;
/**
* 适配器
* Created by Asus on 2017/3/13.
*/
class TestAdapter extends RecyclerView.Adapter {
private ScrollingActivity scrollingActivity;
private final List<String> mData;
public interface Listener {
void onImageClicked(View view, String drawable);
}
Listener mListener;
public TestAdapter(ScrollingActivity scrollingActivity, List<String> data, Listener listener) {
this.scrollingActivity = scrollingActivity;
this.mData = data;
this.mListener = listener;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(scrollingActivity).inflate(R.layout.adapter_image, parent, false);
return new ImageHolder(view);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final ImageView imageView = ((ImageHolder) holder).image;
// new DownImgAsyncTask(imageView).execute(mData.get(position));
// SimpleTarget viewTarget = new SimpleTarget<Bitmap>() {
// @Override
// public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
// imageView.setImageBitmap(resource);
// }
// };
((ImageHolder) holder).image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mListener.onImageClicked(view, mData.get(position));
}
});
ImageLoaderFactory.getLoader().displayImage(imageView.getContext(), imageView, mData.get(position), null);
}
@Override
public int getItemCount() {
return mData.size();
}
class ImageHolder extends RecyclerView.ViewHolder {
ImageView image;
public ImageHolder(View itemView) {
super(itemView);
image = (ImageView) itemView.findViewById(R.id.iv);
}
}
}
|
92319a92432e4b67fef081366869bcad86c9280c | 2,256 | java | Java | search/src/test/java/io/fluidity/dataflow/ClientHistoJsonConvertorTest.java | liquidlabsio/fluidity | 807d945c749b77d355bf5ba68b66033331d1b1c0 | [
"Apache-2.0"
] | 4 | 2020-05-27T18:21:28.000Z | 2020-11-27T00:32:27.000Z | search/src/test/java/io/fluidity/dataflow/ClientHistoJsonConvertorTest.java | liquidlabsio/fluidity | 807d945c749b77d355bf5ba68b66033331d1b1c0 | [
"Apache-2.0"
] | 24 | 2020-04-15T08:16:47.000Z | 2022-01-04T16:36:38.000Z | search/src/test/java/io/fluidity/dataflow/ClientHistoJsonConvertorTest.java | liquidlabsio/precognito | 807d945c749b77d355bf5ba68b66033331d1b1c0 | [
"Apache-2.0"
] | null | null | null | 38.931034 | 213 | 0.712135 | 995,908 | /*
*
* Copyright (c) 2020. Liquidlabs Ltd <upchh@example.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 io.fluidity.dataflow;
import io.fluidity.dataflow.histo.FlowStats;
import io.fluidity.search.agg.histo.Series;
import io.fluidity.search.agg.histo.TimeSeries;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class ClientHistoJsonConvertorTest {
@Test
void toFromJson() {
TimeSeries<FlowStats> stats = makeFlowStats();
ClientHistoJsonConvertor jsonConvertor = new ClientHistoJsonConvertor();
byte[] jsonBytes = jsonConvertor.toJson(stats);
TimeSeries<FlowStats> newTimeSeries = jsonConvertor.fromJson(jsonBytes);
byte[] checkingJson = jsonConvertor.toJson(newTimeSeries);
assertEquals(new String(jsonBytes), new String(checkingJson), "Reconciliation failed!");
}
@Test
void toClientJsonArrays() {
TimeSeries<FlowStats> timeSeries = makeFlowStats();
String clientJson = new ClientHistoJsonConvertor().toClientArrays(timeSeries);
System.out.println(clientJson);
assertTrue(clientJson.contains("[ 100 ]"));
}
private TimeSeries<FlowStats> makeFlowStats() {
TimeSeries<FlowStats> stats = new TimeSeries("none", "", 1000, 3000, new Series.LongOps());
FlowStats flowStats = new FlowStats();
Long[] longs = {100l, 200l};
FlowInfo flowInfo = new FlowInfo("flowId", List.of("someFile"), new ArrayList<>(Collections.singleton(longs)));
flowStats.update(flowInfo);
stats.update(1000, flowStats);
return stats;
}
} |
92319b5360dccc8874ac640e42513068de1892b7 | 776 | java | Java | src/main/java/ca/demo/converters/CategoryToCategoryCommand.java | Alexgta/Recipe | 5941784d9ad67ce738e26da4eca294e7691e7786 | [
"Apache-2.0"
] | null | null | null | src/main/java/ca/demo/converters/CategoryToCategoryCommand.java | Alexgta/Recipe | 5941784d9ad67ce738e26da4eca294e7691e7786 | [
"Apache-2.0"
] | null | null | null | src/main/java/ca/demo/converters/CategoryToCategoryCommand.java | Alexgta/Recipe | 5941784d9ad67ce738e26da4eca294e7691e7786 | [
"Apache-2.0"
] | null | null | null | 25.866667 | 88 | 0.738402 | 995,909 | package ca.demo.converters;
import ca.demo.commands.CategoryCommand;
import ca.demo.domain.Category;
import lombok.Synchronized;
import org.springframework.core.convert.converter.Converter;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
@Component
public class CategoryToCategoryCommand implements Converter<Category, CategoryCommand> {
@Synchronized
@Nullable
@Override
public CategoryCommand convert(Category source) {
if (source == null) {
return null;
}
final CategoryCommand categoryCommand = new CategoryCommand();
categoryCommand.setId(source.getId());
categoryCommand.setDescription(source.getDescription());
return categoryCommand;
}
}
|
92319b7b19c5a8f9971e60c525dbba7b1dd79255 | 11,786 | java | Java | app/src/main/java/de/karzek/diettracker/presentation/main/home/HomeFragment.java | MarjanaKarzek/android_diet_tracker | 6b4288c8d4a26876be5f98d61c0c625dd911df27 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/de/karzek/diettracker/presentation/main/home/HomeFragment.java | MarjanaKarzek/android_diet_tracker | 6b4288c8d4a26876be5f98d61c0c625dd911df27 | [
"Apache-2.0"
] | 12 | 2018-04-20T16:37:25.000Z | 2019-02-08T09:50:33.000Z | app/src/main/java/de/karzek/diettracker/presentation/main/home/HomeFragment.java | MarjanaKarzek/android_diet_tracker | 6b4288c8d4a26876be5f98d61c0c625dd911df27 | [
"Apache-2.0"
] | 1 | 2018-10-10T18:00:12.000Z | 2018-10-10T18:00:12.000Z | 36.153374 | 199 | 0.731885 | 995,910 | package de.karzek.diettracker.presentation.main.home;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.getbase.floatingactionbutton.FloatingActionsMenu;
import com.mikhaellopez.circularprogressbar.CircularProgressBar;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.karzek.diettracker.R;
import de.karzek.diettracker.data.cache.model.GroceryEntity;
import de.karzek.diettracker.presentation.TrackerApplication;
import de.karzek.diettracker.presentation.common.BaseFragment;
import de.karzek.diettracker.presentation.main.diary.meal.adapter.favoriteRecipeList.FavoriteRecipeListAdapter;
import de.karzek.diettracker.presentation.model.RecipeDisplayModel;
import de.karzek.diettracker.presentation.search.grocery.GrocerySearchActivity;
import de.karzek.diettracker.presentation.search.recipe.RecipeSearchActivity;
import de.karzek.diettracker.presentation.util.Constants;
import de.karzek.diettracker.presentation.util.StringUtils;
import de.karzek.diettracker.presentation.util.ValidationUtil;
import de.karzek.diettracker.presentation.util.ViewUtils;
import static de.karzek.diettracker.presentation.util.Constants.INVALID_ENTITY_ID;
/**
* Created by MarjanaKarzek on 12.05.2018.
*
* @author Marjana Karzek
* @version 1.0
* @date 12.05.2018
*/
public class HomeFragment extends BaseFragment implements HomeContract.View {
private static final int LOWER_BOUND_WATER_INPUT = 0;
private static final int UPPER_BOUND_WATER_INPUT = Integer.MAX_VALUE;
@BindView(R.id.circle_progress_bar_calories)
CircularProgressBar caloriesProgressBar;
@BindView(R.id.circle_progress_bar_calories_value)
TextView caloriesProgressBarValue;
@BindView(R.id.circle_progress_bar_protein)
CircularProgressBar proteinsProgressBar;
@BindView(R.id.circle_progress_bar_protein_value)
TextView proteinsProgressBarValue;
@BindView(R.id.circle_progress_bar_carbs)
CircularProgressBar carbsProgressBar;
@BindView(R.id.circle_progress_bar_carbs_value)
TextView carbsProgressBarValue;
@BindView(R.id.circle_progress_bar_fats)
CircularProgressBar fatsProgressBar;
@BindView(R.id.circle_progress_bar_fats_value)
TextView fatsProgressBarValue;
@BindView(R.id.nutrition_state)
CardView nutritionState;
@BindView(R.id.favorite_recipe_title)
TextView favoriteText;
@BindView(R.id.recycler_view)
RecyclerView recyclerView;
@BindView(R.id.drinks_section)
CardView drinksSection;
@BindView(R.id.circle_progress_bar_dinks_progress)
CircularProgressBar drinksProgressBar;
@BindView(R.id.circle_progress_bar_drinks_value)
EditText drinksProgressBarValue;
@BindView(R.id.drinks_max_value)
TextView drinksMaxValue;
@BindView(R.id.floating_action_button_menu)
FloatingActionsMenu floatingActionsMenu;
@BindView(R.id.fab_overlay)
FrameLayout overlay;
@BindView(R.id.loading_view)
FrameLayout loadingView;
private Unbinder unbinder;
@Inject
HomeContract.Presenter presenter;
private SimpleDateFormat databaseDateFormat = new SimpleDateFormat("dd-MM-yyyy", Locale.GERMANY);
private SimpleDateFormat databaseTimeFormat = new SimpleDateFormat("HH:mm:ss", Locale.GERMANY);
private Calendar date = Calendar.getInstance();
@Override
public void onResume() {
super.onResume();
showLoading();
presenter.start();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.fragment_home, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
unbinder = ButterKnife.bind(this, view);
showLoading();
setupRecyclerView();
floatingActionsMenu.setOnFloatingActionsMenuUpdateListener(new FloatingActionsMenu.OnFloatingActionsMenuUpdateListener() {
@Override
public void onMenuExpanded() {
overlay.setVisibility(View.VISIBLE);
}
@Override
public void onMenuCollapsed() {
overlay.setVisibility(View.GONE);
}
});
ViewUtils.addElevationToFABMenuLabels(getContext(), floatingActionsMenu);
drinksProgressBarValue.setOnEditorActionListener(new EditText.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
drinksProgressBarValue.clearFocus();
InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(drinksProgressBarValue.getWindowToken(), 0);
if (!StringUtils.isNullOrEmpty(drinksProgressBarValue.getText().toString())) {
if (ValidationUtil.isValid(LOWER_BOUND_WATER_INPUT, UPPER_BOUND_WATER_INPUT, Float.valueOf(drinksProgressBarValue.getText().toString()), drinksProgressBarValue, getContext()))
presenter.updateAmountOfWater(Float.valueOf(drinksProgressBarValue.getText().toString()));
} else
drinksProgressBarValue.setText(StringUtils.formatFloat(LOWER_BOUND_WATER_INPUT));
}
return true;
}
});
presenter.setView(this);
presenter.setCurrentDate(databaseDateFormat.format(date.getTime()));
presenter.setCurrentTime(databaseTimeFormat.format(date.getTime()));
presenter.start();
}
private void setupRecyclerView() {
recyclerView.setHasFixedSize(true);
LinearLayoutManager manager = new LinearLayoutManager(getContext());
manager.setOrientation(LinearLayoutManager.HORIZONTAL);
recyclerView.setLayoutManager(manager);
recyclerView.setAdapter(new FavoriteRecipeListAdapter(presenter));
}
@Override
protected void setupFragmentComponent() {
TrackerApplication.get(getContext()).createHomeComponent().inject(this);
}
@OnClick(R.id.add_food)
public void onAddFoodClicked() {
presenter.onAddFoodClicked();
}
@OnClick(R.id.add_drink)
public void onAddDrinkClicked() {
presenter.onAddDrinkClicked();
}
@OnClick(R.id.add_recipe)
public void onAddRecipeClicked() {
presenter.onAddRecipeClicked();
}
@OnClick(R.id.fab_overlay)
public void onFabOverlayClicked() {
presenter.onFabOverlayClicked();
}
@Override
public void startFoodSearchActivity(int currentMealId) {
startActivity(GrocerySearchActivity.newGrocerySearchIntent(getContext(), GroceryEntity.GroceryEntityType.TYPE_FOOD, databaseDateFormat.format(date.getTime()), currentMealId));
}
@Override
public void startDrinkSearchActivity(int currentMealId) {
startActivity(GrocerySearchActivity.newGrocerySearchIntent(getContext(), GroceryEntity.GroceryEntityType.TYPE_DRINK, databaseDateFormat.format(date.getTime()), INVALID_ENTITY_ID));
}
@Override
public void startRecipeSearchActivity(int currentMealId) {
startActivity(RecipeSearchActivity.newIntent(getContext(), databaseDateFormat.format(date.getTime()), currentMealId));
}
@Override
public void closeFabMenu() {
floatingActionsMenu.collapse();
}
@Override
public void showLoading() {
loadingView.setVisibility(View.VISIBLE);
}
@Override
public void hideLoading() {
loadingView.setVisibility(View.GONE);
}
@Override
public void showRecipeAddedInfo() {
Toast.makeText(getContext(), getString(R.string.success_message_portion_added), Toast.LENGTH_SHORT).show();
}
@Override
public void updateRecyclerView(ArrayList<RecipeDisplayModel> recipeDisplayModels) {
((FavoriteRecipeListAdapter) recyclerView.getAdapter()).setList(recipeDisplayModels);
}
@Override
public void showRecyclerView() {
recyclerView.setVisibility(View.VISIBLE);
}
@Override
public void hideRecyclerView() {
recyclerView.setVisibility(View.GONE);
}
@Override
public void setCaloryState(float sum, int maxValue) {
caloriesProgressBar.setProgress(100.0f / maxValue * sum);
caloriesProgressBarValue.setText(StringUtils.formatFloat(maxValue - sum));
}
@Override
public void showFavoriteText(String name) {
favoriteText.setVisibility(View.VISIBLE);
favoriteText.setText(getString(R.string.favorite_recipes_home_title, name));
}
@Override
public void hideFavoriteText() {
favoriteText.setVisibility(View.GONE);
}
@Override
public void setNutritionState(HashMap<String, Float> sums, int caloriesGoal, int proteinsGoal, int carbsGoal, int fatsGoal) {
caloriesProgressBar.setProgress(100.0f / caloriesGoal * sums.get(Constants.CALORIES));
caloriesProgressBarValue.setText(StringUtils.formatFloat(caloriesGoal - sums.get(Constants.CALORIES)));
proteinsProgressBar.setProgress(100.0f / proteinsGoal * sums.get(Constants.PROTEINS));
proteinsProgressBarValue.setText(StringUtils.formatFloat(proteinsGoal - sums.get(Constants.PROTEINS)));
carbsProgressBar.setProgress(100.0f / carbsGoal * sums.get(Constants.CARBS));
carbsProgressBarValue.setText(StringUtils.formatFloat(carbsGoal - sums.get(Constants.CARBS)));
fatsProgressBar.setProgress(100.0f / fatsGoal * sums.get(Constants.FATS));
fatsProgressBarValue.setText(StringUtils.formatFloat(fatsGoal - sums.get(Constants.FATS)));
}
@Override
public void hideNutritionState() {
nutritionState.setVisibility(View.GONE);
}
@Override
public void hideDrinksSection() {
drinksSection.setVisibility(View.GONE);
}
@Override
public void setLiquidStatus(float sum, float liquidGoal) {
drinksProgressBar.setProgress(100.0f / liquidGoal * sum);
drinksProgressBarValue.setText(StringUtils.formatFloat(sum));
drinksMaxValue.setText(getString(R.string.generic_drinks_max_value, StringUtils.formatFloat(liquidGoal)));
}
@OnClick(R.id.add_bottle)
public void onAddBottleWaterClicked() {
presenter.addBottleWaterClicked();
}
@OnClick(R.id.add_glass)
public void onAddGlassWaterClicked() {
presenter.addGlassWaterClicked();
}
@Override
public void onDestroyView() {
super.onDestroyView();
presenter.finish();
unbinder.unbind();
}
@Override
public void onDestroy() {
super.onDestroy();
TrackerApplication.get(getContext()).releaseHomeComponent();
}
}
|
92319c75ec58813be4620d69c98df6c0cb3c6318 | 3,221 | java | Java | src/sorts/concurrent/PairwiseSortIterative.java | mg-2018/ArrayV-v4.0 | 647e0c8bc4fee1efec1a5c20215864ed9a3e02df | [
"MIT"
] | 48 | 2021-04-21T17:43:42.000Z | 2022-02-15T19:55:22.000Z | src/sorts/concurrent/PairwiseSortIterative.java | mg-2018/ArrayV-v4.0 | 647e0c8bc4fee1efec1a5c20215864ed9a3e02df | [
"MIT"
] | 32 | 2021-04-17T16:16:12.000Z | 2022-01-30T18:38:51.000Z | src/sorts/concurrent/PairwiseSortIterative.java | mg-2018/ArrayV-v4.0 | 647e0c8bc4fee1efec1a5c20215864ed9a3e02df | [
"MIT"
] | 20 | 2021-04-17T15:23:18.000Z | 2022-02-14T04:20:30.000Z | 34.634409 | 88 | 0.557901 | 995,911 | package sorts.concurrent;
import main.ArrayVisualizer;
import sorts.templates.Sort;
/*
*
MIT License
Copyright (c) 2019 PiotrGrochowski
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.
*
*/
final public class PairwiseSortIterative extends Sort {
public PairwiseSortIterative(ArrayVisualizer arrayVisualizer) {
super(arrayVisualizer);
this.setSortListName("Pairwise (Iterative)");
this.setRunAllSortsName("Iterative Pairwise Sorting Network");
this.setRunSortName("Iterative Pairwise Sort");
this.setCategory("Concurrent Sorts");
this.setComparisonBased(true);
this.setBucketSort(false);
this.setRadixSort(false);
this.setUnreasonablySlow(false);
this.setUnreasonableLimit(0);
this.setBogoSort(false);
}
private void iterativepairwise(int[] array, int length, double sleep) {
int a = 1;
int b = 0;
int c = 0;
int d = 0;
int e = 0;
while (a < length){
b = a;
c = 0;
while (b < length){
if(Reads.compareIndices(array, b - a, b, sleep, true) == 1) {
Writes.swap(array, b - a, b, sleep, true, false);
}
c = (c + 1) % a;
b++;
if (c == 0){
b += a;
}
}
a *= 2;
}
a /= 4;
e = 1;
while (a > 0){
d = e;
while (d > 0){
b = ((d + 1) * a);
c = 0;
while (b < length){
if(Reads.compareIndices(array, b - (d * a), b, sleep, true) == 1) {
Writes.swap(array, b - (d * a), b, sleep, true, false);
}
c = (c + 1) % a;
b++;
if (c == 0){
b += a;
}
}
d /= 2;
}
a /= 2;
e = (e * 2) + 1;
}
}
@Override
public void runSort(int[] array, int sortLength, int bucketCount) throws Exception {
this.iterativepairwise(array, sortLength, 0.5);
}
} |
92319d447f670c05ef04cc07eb515d266b93c4ec | 23,069 | java | Java | src/main/java/com/thinkgem/jeesite/modules/gsbx/entity/GsUnitPay.java | wangbosxly/private_wang | d0afba688b45c4e1f8f393b5f1acbfce0d9e2d10 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/thinkgem/jeesite/modules/gsbx/entity/GsUnitPay.java | wangbosxly/private_wang | d0afba688b45c4e1f8f393b5f1acbfce0d9e2d10 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/thinkgem/jeesite/modules/gsbx/entity/GsUnitPay.java | wangbosxly/private_wang | d0afba688b45c4e1f8f393b5f1acbfce0d9e2d10 | [
"Apache-2.0"
] | null | null | null | 26.516092 | 629 | 0.545971 | 995,912 | package com.thinkgem.jeesite.modules.gsbx.entity;
import java.io.Serializable;
import java.util.Objects;
/**
* 单位缴费
* @author sl_su
*/
public class GsUnitPay implements Serializable {
private static final long serialVersionUID = 1667758958109108295L;
private String BAA005;//审核编号
private String AAE140;//险种类型
private String AAE002;//费款所属期
private String AAB121;//单位缴费基数总额
private String BAB701;//单位应缴
private String BAE742;//滞纳金金额
private String AAB137;//应缴合计
private String AAE170;//操作人
private String AAB001;//单位编号
private String BAA001;//数据分区
private String AAE041;//开始费款所属期
private String AAE042;//结束费款所属期
private String BAE746;//是否计算利息
private String BAE747;//是否计算滞纳金
private String PersonCount ;//人数
private String BAB501;// 双基数标志
private String AAB050;// 参保日期
private String AAB051;// 参保状态
private String BAB510;// 最近参保时间
private String AAA040;// 缴费比例类别
private String AAB004;// 单位名称
private String BAB519;// 行业企业代码
private String AAB019;// 单位类型
private String AAB020;// 经济类型
private String AAB021;// 隶属关系
private String AAB022;// 行业代码
private String BAE703;//主体编号
private String AAE003;//对应费款所属期
private String BAE702;//主体类型
private String AAE143;//缴费类型
private String BAB706;//应收核定类别
private String AAB083;//在职职工人次
private String AAB082;//离退休(职)人次
private String AAB120;//个人缴费基数总额
private String AAB122;//本期个人应缴金额
private String BAC701;//本期个人应缴划入统筹金额
private String BAC702;//本期个人应缴划入帐户金额
private String BAC703;//审核时个人缴费部分应补帐户利息
private String BAC704;//审核时个人缴费部分应补统筹利息
private String AAB123;//本期单位缴费应划入个人帐户金额
private String AAB124;//本期单位缴费应划入统筹金额
private String BAB702;//审核时单位缴费应划入个人帐户部分应补利息
private String BAB703;//审核时单位缴费划入统筹金利息
private String BAC705;//核销个人应缴划入帐户金额
private String BAC706;//核销个人应缴划入统筹金额
private String AAD003;//核销单位欠缴应划入帐户金额
private String AAD004;//核销单位欠缴统筹金额
private String BAC707;//核销个人帐户做实金额
private String BAC708;//本期个人帐户做实金额
private String BAC709;//核销在职人数
private String BAC710;//核销离退休(职)人数
private String BAC711;//征集时个人缴费部分应补帐户利息
private String BAC712;//征集时个人缴费部分应补统筹利息
private String BAB704;//征集时单位缴费应划入个人帐户部分应补利息
private String BAB705;//征集时单位缴费划入统筹金利息
private String BAE740;//审核时利息计算截止月份
private String BAE741;//审核时滞纳金计算截止日期
private String BAE743;//审核时减免滞纳金金额
private String BAE744;//征集时滞纳金计算截止日期
private String BAE749;//征集时滞纳金金额
private String BAE745;//征集时减免滞纳金金额
private String BAE748;//核销小计
private String AAB033;//缴费方式
private String BAE750;//缓缴截止日期
private String AAE063;//征集通知流水号
private String BAE707;//基金配置流水号
private String AAB034;//社会保险经办机构编码
private String AAE011;//经办人
private String AAE036;//经办时间
private String BAB812;//煤炭企业年设计产量(万吨)
private String AAE013;//备注
private String BAE706;//到账日期
private String AAB121_1;// 财政缴费基数总额
private String BAB701_1;// 本期财政应缴金额
private String startAAE002; //startAAE002 开始费款所属期 否
private String endAAE002; //endAAE002 结束费款所属期 否
@Override
public String toString() {
return "GsUnitPay{" +
"BAA005='" + BAA005 + '\'' +
", AAE140='" + AAE140 + '\'' +
", AAE002='" + AAE002 + '\'' +
", AAB121='" + AAB121 + '\'' +
", BAB701='" + BAB701 + '\'' +
", BAE742='" + BAE742 + '\'' +
", AAB137='" + AAB137 + '\'' +
", AAE170='" + AAE170 + '\'' +
", AAB001='" + AAB001 + '\'' +
", BAA001='" + BAA001 + '\'' +
", AAE041='" + AAE041 + '\'' +
", AAE042='" + AAE042 + '\'' +
", BAE746='" + BAE746 + '\'' +
", BAE747='" + BAE747 + '\'' +
", PersonCount='" + PersonCount + '\'' +
", BAB501='" + BAB501 + '\'' +
", AAB050='" + AAB050 + '\'' +
", AAB051='" + AAB051 + '\'' +
", BAB510='" + BAB510 + '\'' +
", AAA040='" + AAA040 + '\'' +
", AAB004='" + AAB004 + '\'' +
", BAB519='" + BAB519 + '\'' +
", AAB019='" + AAB019 + '\'' +
", AAB020='" + AAB020 + '\'' +
", AAB021='" + AAB021 + '\'' +
", AAB022='" + AAB022 + '\'' +
", BAE703='" + BAE703 + '\'' +
", AAE003='" + AAE003 + '\'' +
", BAE702='" + BAE702 + '\'' +
", AAE143='" + AAE143 + '\'' +
", BAB706='" + BAB706 + '\'' +
", AAB083='" + AAB083 + '\'' +
", AAB082='" + AAB082 + '\'' +
", AAB120='" + AAB120 + '\'' +
", AAB122='" + AAB122 + '\'' +
", BAC701='" + BAC701 + '\'' +
", BAC702='" + BAC702 + '\'' +
", BAC703='" + BAC703 + '\'' +
", BAC704='" + BAC704 + '\'' +
", AAB123='" + AAB123 + '\'' +
", AAB124='" + AAB124 + '\'' +
", BAB702='" + BAB702 + '\'' +
", BAB703='" + BAB703 + '\'' +
", BAC705='" + BAC705 + '\'' +
", BAC706='" + BAC706 + '\'' +
", AAD003='" + AAD003 + '\'' +
", AAD004='" + AAD004 + '\'' +
", BAC707='" + BAC707 + '\'' +
", BAC708='" + BAC708 + '\'' +
", BAC709='" + BAC709 + '\'' +
", BAC710='" + BAC710 + '\'' +
", BAC711='" + BAC711 + '\'' +
", BAC712='" + BAC712 + '\'' +
", BAB704='" + BAB704 + '\'' +
", BAB705='" + BAB705 + '\'' +
", BAE740='" + BAE740 + '\'' +
", BAE741='" + BAE741 + '\'' +
", BAE743='" + BAE743 + '\'' +
", BAE744='" + BAE744 + '\'' +
", BAE749='" + BAE749 + '\'' +
", BAE745='" + BAE745 + '\'' +
", BAE748='" + BAE748 + '\'' +
", AAB033='" + AAB033 + '\'' +
", BAE750='" + BAE750 + '\'' +
", AAE063='" + AAE063 + '\'' +
", BAE707='" + BAE707 + '\'' +
", AAB034='" + AAB034 + '\'' +
", AAE011='" + AAE011 + '\'' +
", AAE036='" + AAE036 + '\'' +
", BAB812='" + BAB812 + '\'' +
", AAE013='" + AAE013 + '\'' +
", BAE706='" + BAE706 + '\'' +
", AAB121_1='" + AAB121_1 + '\'' +
", BAB701_1='" + BAB701_1 + '\'' +
", startAAE002='" + startAAE002 + '\'' +
", endAAE002='" + endAAE002 + '\'' +
'}';
}
public String getStartAAE002() {
return startAAE002;
}
public void setStartAAE002(String startAAE002) {
this.startAAE002 = startAAE002;
}
public String getEndAAE002() {
return endAAE002;
}
public void setEndAAE002(String endAAE002) {
this.endAAE002 = endAAE002;
}
public String getBAE703() {
return BAE703;
}
public void setBAE703(String BAE703) {
this.BAE703 = BAE703;
}
public String getAAE003() {
return AAE003;
}
public void setAAE003(String AAE003) {
this.AAE003 = AAE003;
}
public String getBAE702() {
return BAE702;
}
public void setBAE702(String BAE702) {
this.BAE702 = BAE702;
}
public String getAAE143() {
return AAE143;
}
public void setAAE143(String AAE143) {
this.AAE143 = AAE143;
}
public String getBAB706() {
return BAB706;
}
public void setBAB706(String BAB706) {
this.BAB706 = BAB706;
}
public String getAAB083() {
return AAB083;
}
public void setAAB083(String AAB083) {
this.AAB083 = AAB083;
}
public String getAAB082() {
return AAB082;
}
public void setAAB082(String AAB082) {
this.AAB082 = AAB082;
}
public String getAAB120() {
return AAB120;
}
public void setAAB120(String AAB120) {
this.AAB120 = AAB120;
}
public String getAAB122() {
return AAB122;
}
public void setAAB122(String AAB122) {
this.AAB122 = AAB122;
}
public String getBAC701() {
return BAC701;
}
public void setBAC701(String BAC701) {
this.BAC701 = BAC701;
}
public String getBAC702() {
return BAC702;
}
public void setBAC702(String BAC702) {
this.BAC702 = BAC702;
}
public String getBAC703() {
return BAC703;
}
public void setBAC703(String BAC703) {
this.BAC703 = BAC703;
}
public String getBAC704() {
return BAC704;
}
public void setBAC704(String BAC704) {
this.BAC704 = BAC704;
}
public String getAAB123() {
return AAB123;
}
public void setAAB123(String AAB123) {
this.AAB123 = AAB123;
}
public String getAAB124() {
return AAB124;
}
public void setAAB124(String AAB124) {
this.AAB124 = AAB124;
}
public String getBAB702() {
return BAB702;
}
public void setBAB702(String BAB702) {
this.BAB702 = BAB702;
}
public String getBAB703() {
return BAB703;
}
public void setBAB703(String BAB703) {
this.BAB703 = BAB703;
}
public String getBAC705() {
return BAC705;
}
public void setBAC705(String BAC705) {
this.BAC705 = BAC705;
}
public String getBAC706() {
return BAC706;
}
public void setBAC706(String BAC706) {
this.BAC706 = BAC706;
}
public String getAAD003() {
return AAD003;
}
public void setAAD003(String AAD003) {
this.AAD003 = AAD003;
}
public String getAAD004() {
return AAD004;
}
public void setAAD004(String AAD004) {
this.AAD004 = AAD004;
}
public String getBAC707() {
return BAC707;
}
public void setBAC707(String BAC707) {
this.BAC707 = BAC707;
}
public String getBAC708() {
return BAC708;
}
public void setBAC708(String BAC708) {
this.BAC708 = BAC708;
}
public String getBAC709() {
return BAC709;
}
public void setBAC709(String BAC709) {
this.BAC709 = BAC709;
}
public String getBAC710() {
return BAC710;
}
public void setBAC710(String BAC710) {
this.BAC710 = BAC710;
}
public String getBAC711() {
return BAC711;
}
public void setBAC711(String BAC711) {
this.BAC711 = BAC711;
}
public String getBAC712() {
return BAC712;
}
public void setBAC712(String BAC712) {
this.BAC712 = BAC712;
}
public String getBAB704() {
return BAB704;
}
public void setBAB704(String BAB704) {
this.BAB704 = BAB704;
}
public String getBAB705() {
return BAB705;
}
public void setBAB705(String BAB705) {
this.BAB705 = BAB705;
}
public String getBAE740() {
return BAE740;
}
public void setBAE740(String BAE740) {
this.BAE740 = BAE740;
}
public String getBAE741() {
return BAE741;
}
public void setBAE741(String BAE741) {
this.BAE741 = BAE741;
}
public String getBAE743() {
return BAE743;
}
public void setBAE743(String BAE743) {
this.BAE743 = BAE743;
}
public String getBAE744() {
return BAE744;
}
public void setBAE744(String BAE744) {
this.BAE744 = BAE744;
}
public String getBAE749() {
return BAE749;
}
public void setBAE749(String BAE749) {
this.BAE749 = BAE749;
}
public String getBAE745() {
return BAE745;
}
public void setBAE745(String BAE745) {
this.BAE745 = BAE745;
}
public String getBAE748() {
return BAE748;
}
public void setBAE748(String BAE748) {
this.BAE748 = BAE748;
}
public String getAAB033() {
return AAB033;
}
public void setAAB033(String AAB033) {
this.AAB033 = AAB033;
}
public String getBAE750() {
return BAE750;
}
public void setBAE750(String BAE750) {
this.BAE750 = BAE750;
}
public String getAAE063() {
return AAE063;
}
public void setAAE063(String AAE063) {
this.AAE063 = AAE063;
}
public String getBAE707() {
return BAE707;
}
public void setBAE707(String BAE707) {
this.BAE707 = BAE707;
}
public String getAAB034() {
return AAB034;
}
public void setAAB034(String AAB034) {
this.AAB034 = AAB034;
}
public String getAAE011() {
return AAE011;
}
public void setAAE011(String AAE011) {
this.AAE011 = AAE011;
}
public String getAAE036() {
return AAE036;
}
public void setAAE036(String AAE036) {
this.AAE036 = AAE036;
}
public String getBAB812() {
return BAB812;
}
public void setBAB812(String BAB812) {
this.BAB812 = BAB812;
}
public String getAAE013() {
return AAE013;
}
public void setAAE013(String AAE013) {
this.AAE013 = AAE013;
}
public String getBAE706() {
return BAE706;
}
public void setBAE706(String BAE706) {
this.BAE706 = BAE706;
}
public String getAAB121_1() {
return AAB121_1;
}
public void setAAB121_1(String AAB121_1) {
this.AAB121_1 = AAB121_1;
}
public String getBAB701_1() {
return BAB701_1;
}
public void setBAB701_1(String BAB701_1) {
this.BAB701_1 = BAB701_1;
}
public String getBAB501() {
return BAB501;
}
public void setBAB501(String BAB501) {
this.BAB501 = BAB501;
}
public String getAAB050() {
return AAB050;
}
public void setAAB050(String AAB050) {
this.AAB050 = AAB050;
}
public String getAAB051() {
return AAB051;
}
public void setAAB051(String AAB051) {
this.AAB051 = AAB051;
}
public String getBAB510() {
return BAB510;
}
public void setBAB510(String BAB510) {
this.BAB510 = BAB510;
}
public String getAAA040() {
return AAA040;
}
public void setAAA040(String AAA040) {
this.AAA040 = AAA040;
}
public String getAAB004() {
return AAB004;
}
public void setAAB004(String AAB004) {
this.AAB004 = AAB004;
}
public String getBAB519() {
return BAB519;
}
public void setBAB519(String BAB519) {
this.BAB519 = BAB519;
}
public String getAAB019() {
return AAB019;
}
public void setAAB019(String AAB019) {
this.AAB019 = AAB019;
}
public String getAAB020() {
return AAB020;
}
public void setAAB020(String AAB020) {
this.AAB020 = AAB020;
}
public String getAAB021() {
return AAB021;
}
public void setAAB021(String AAB021) {
this.AAB021 = AAB021;
}
public String getAAB022() {
return AAB022;
}
public void setAAB022(String AAB022) {
this.AAB022 = AAB022;
}
public String getBAA005() {
return BAA005;
}
public void setBAA005(String BAA005) {
this.BAA005 = BAA005;
}
public String getAAE140() {
return AAE140;
}
public void setAAE140(String AAE140) {
this.AAE140 = AAE140;
}
public String getAAE002() {
return AAE002;
}
public void setAAE002(String AAE002) {
this.AAE002 = AAE002;
}
public String getAAB121() {
return AAB121;
}
public void setAAB121(String AAB121) {
this.AAB121 = AAB121;
}
public String getBAB701() {
return BAB701;
}
public void setBAB701(String BAB701) {
this.BAB701 = BAB701;
}
public String getBAE742() {
return BAE742;
}
public void setBAE742(String BAE742) {
this.BAE742 = BAE742;
}
public String getAAB137() {
return AAB137;
}
public void setAAB137(String AAB137) {
this.AAB137 = AAB137;
}
public String getAAE170() {
return AAE170;
}
public void setAAE170(String AAE170) {
this.AAE170 = AAE170;
}
public String getAAB001() {
return AAB001;
}
public void setAAB001(String AAB001) {
this.AAB001 = AAB001;
}
public String getBAA001() {
return BAA001;
}
public void setBAA001(String BAA001) {
this.BAA001 = BAA001;
}
public String getAAE041() {
return AAE041;
}
public void setAAE041(String AAE041) {
this.AAE041 = AAE041;
}
public String getAAE042() {
return AAE042;
}
public void setAAE042(String AAE042) {
this.AAE042 = AAE042;
}
public String getBAE746() {
return BAE746;
}
public void setBAE746(String BAE746) {
this.BAE746 = BAE746;
}
public String getBAE747() {
return BAE747;
}
public void setBAE747(String BAE747) {
this.BAE747 = BAE747;
}
public String getPersonCount() {
return PersonCount;
}
public void setPersonCount(String personCount) {
PersonCount = personCount;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
GsUnitPay gsUnitPay = (GsUnitPay) o;
return Objects.equals(BAA005, gsUnitPay.BAA005) &&
Objects.equals(AAE140, gsUnitPay.AAE140) &&
Objects.equals(AAE002, gsUnitPay.AAE002) &&
Objects.equals(AAB121, gsUnitPay.AAB121) &&
Objects.equals(BAB701, gsUnitPay.BAB701) &&
Objects.equals(BAE742, gsUnitPay.BAE742) &&
Objects.equals(AAB137, gsUnitPay.AAB137) &&
Objects.equals(AAE170, gsUnitPay.AAE170) &&
Objects.equals(AAB001, gsUnitPay.AAB001) &&
Objects.equals(BAA001, gsUnitPay.BAA001) &&
Objects.equals(AAE041, gsUnitPay.AAE041) &&
Objects.equals(AAE042, gsUnitPay.AAE042) &&
Objects.equals(BAE746, gsUnitPay.BAE746) &&
Objects.equals(BAE747, gsUnitPay.BAE747) &&
Objects.equals(PersonCount, gsUnitPay.PersonCount) &&
Objects.equals(BAB501, gsUnitPay.BAB501) &&
Objects.equals(AAB050, gsUnitPay.AAB050) &&
Objects.equals(AAB051, gsUnitPay.AAB051) &&
Objects.equals(BAB510, gsUnitPay.BAB510) &&
Objects.equals(AAA040, gsUnitPay.AAA040) &&
Objects.equals(AAB004, gsUnitPay.AAB004) &&
Objects.equals(BAB519, gsUnitPay.BAB519) &&
Objects.equals(AAB019, gsUnitPay.AAB019) &&
Objects.equals(AAB020, gsUnitPay.AAB020) &&
Objects.equals(AAB021, gsUnitPay.AAB021) &&
Objects.equals(AAB022, gsUnitPay.AAB022) &&
Objects.equals(BAE703, gsUnitPay.BAE703) &&
Objects.equals(AAE003, gsUnitPay.AAE003) &&
Objects.equals(BAE702, gsUnitPay.BAE702) &&
Objects.equals(AAE143, gsUnitPay.AAE143) &&
Objects.equals(BAB706, gsUnitPay.BAB706) &&
Objects.equals(AAB083, gsUnitPay.AAB083) &&
Objects.equals(AAB082, gsUnitPay.AAB082) &&
Objects.equals(AAB120, gsUnitPay.AAB120) &&
Objects.equals(AAB122, gsUnitPay.AAB122) &&
Objects.equals(BAC701, gsUnitPay.BAC701) &&
Objects.equals(BAC702, gsUnitPay.BAC702) &&
Objects.equals(BAC703, gsUnitPay.BAC703) &&
Objects.equals(BAC704, gsUnitPay.BAC704) &&
Objects.equals(AAB123, gsUnitPay.AAB123) &&
Objects.equals(AAB124, gsUnitPay.AAB124) &&
Objects.equals(BAB702, gsUnitPay.BAB702) &&
Objects.equals(BAB703, gsUnitPay.BAB703) &&
Objects.equals(BAC705, gsUnitPay.BAC705) &&
Objects.equals(BAC706, gsUnitPay.BAC706) &&
Objects.equals(AAD003, gsUnitPay.AAD003) &&
Objects.equals(AAD004, gsUnitPay.AAD004) &&
Objects.equals(BAC707, gsUnitPay.BAC707) &&
Objects.equals(BAC708, gsUnitPay.BAC708) &&
Objects.equals(BAC709, gsUnitPay.BAC709) &&
Objects.equals(BAC710, gsUnitPay.BAC710) &&
Objects.equals(BAC711, gsUnitPay.BAC711) &&
Objects.equals(BAC712, gsUnitPay.BAC712) &&
Objects.equals(BAB704, gsUnitPay.BAB704) &&
Objects.equals(BAB705, gsUnitPay.BAB705) &&
Objects.equals(BAE740, gsUnitPay.BAE740) &&
Objects.equals(BAE741, gsUnitPay.BAE741) &&
Objects.equals(BAE743, gsUnitPay.BAE743) &&
Objects.equals(BAE744, gsUnitPay.BAE744) &&
Objects.equals(BAE749, gsUnitPay.BAE749) &&
Objects.equals(BAE745, gsUnitPay.BAE745) &&
Objects.equals(BAE748, gsUnitPay.BAE748) &&
Objects.equals(AAB033, gsUnitPay.AAB033) &&
Objects.equals(BAE750, gsUnitPay.BAE750) &&
Objects.equals(AAE063, gsUnitPay.AAE063) &&
Objects.equals(BAE707, gsUnitPay.BAE707) &&
Objects.equals(AAB034, gsUnitPay.AAB034) &&
Objects.equals(AAE011, gsUnitPay.AAE011) &&
Objects.equals(AAE036, gsUnitPay.AAE036) &&
Objects.equals(BAB812, gsUnitPay.BAB812) &&
Objects.equals(AAE013, gsUnitPay.AAE013) &&
Objects.equals(BAE706, gsUnitPay.BAE706) &&
Objects.equals(AAB121_1, gsUnitPay.AAB121_1) &&
Objects.equals(BAB701_1, gsUnitPay.BAB701_1);
}
@Override
public int hashCode() {
return Objects.hash(BAA005, AAE140, AAE002, AAB121, BAB701, BAE742, AAB137, AAE170, AAB001, BAA001, AAE041, AAE042, BAE746, BAE747, PersonCount, BAB501, AAB050, AAB051, BAB510, AAA040, AAB004, BAB519, AAB019, AAB020, AAB021, AAB022, BAE703, AAE003, BAE702, AAE143, BAB706, AAB083, AAB082, AAB120, AAB122, BAC701, BAC702, BAC703, BAC704, AAB123, AAB124, BAB702, BAB703, BAC705, BAC706, AAD003, AAD004, BAC707, BAC708, BAC709, BAC710, BAC711, BAC712, BAB704, BAB705, BAE740, BAE741, BAE743, BAE744, BAE749, BAE745, BAE748, AAB033, BAE750, AAE063, BAE707, AAB034, AAE011, AAE036, BAB812, AAE013, BAE706, AAB121_1, BAB701_1);
}
}
|
92319e71a1d1c2a94179d11052b03590383bd712 | 24,057 | java | Java | dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/UsersService.java | runningdata/incubator-dolphinscheduler | 917230d40e350d5d3db7ecdf2847c57b3450d889 | [
"Apache-2.0"
] | 30 | 2019-09-12T04:15:57.000Z | 2021-08-10T02:20:21.000Z | dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/UsersService.java | runningdata/incubator-dolphinscheduler | 917230d40e350d5d3db7ecdf2847c57b3450d889 | [
"Apache-2.0"
] | null | null | null | dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/UsersService.java | runningdata/incubator-dolphinscheduler | 917230d40e350d5d3db7ecdf2847c57b3450d889 | [
"Apache-2.0"
] | 11 | 2019-09-16T13:00:51.000Z | 2020-03-02T07:20:40.000Z | 33.273859 | 138 | 0.597331 | 995,913 | /*
* 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.dolphinscheduler.api.service;
import org.apache.dolphinscheduler.api.enums.Status;
import org.apache.dolphinscheduler.api.utils.CheckUtils;
import org.apache.dolphinscheduler.api.utils.PageInfo;
import org.apache.dolphinscheduler.api.utils.Result;
import org.apache.dolphinscheduler.common.Constants;
import org.apache.dolphinscheduler.common.enums.ResourceType;
import org.apache.dolphinscheduler.common.enums.UserType;
import org.apache.dolphinscheduler.common.utils.CollectionUtils;
import org.apache.dolphinscheduler.common.utils.EncryptionUtils;
import org.apache.dolphinscheduler.common.utils.HadoopUtils;
import org.apache.dolphinscheduler.common.utils.PropertyUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.apache.dolphinscheduler.dao.entity.*;
import org.apache.dolphinscheduler.dao.mapper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
/**
* user service
*/
@Service
public class UsersService extends BaseService {
private static final Logger logger = LoggerFactory.getLogger(UsersService.class);
@Autowired
private UserMapper userMapper;
@Autowired
private TenantMapper tenantMapper;
@Autowired
private ProjectUserMapper projectUserMapper;
@Autowired
private ResourceUserMapper resourcesUserMapper;
@Autowired
private ResourceMapper resourceMapper;
@Autowired
private DataSourceUserMapper datasourceUserMapper;
@Autowired
private UDFUserMapper udfUserMapper;
@Autowired
private AlertGroupMapper alertGroupMapper;
/**
* create user, only system admin have permission
*
* @param loginUser login user
* @param userName user name
* @param userPassword user password
* @param email email
* @param tenantId tenant id
* @param phone phone
* @param queue queue
* @return create result code
* @throws Exception exception
*/
@Transactional(rollbackFor = Exception.class)
public Map<String, Object> createUser(User loginUser,
String userName,
String userPassword,
String email,
int tenantId,
String phone,
String queue) throws Exception {
Map<String, Object> result = new HashMap<>(5);
//check all user params
String msg = this.checkUserParams(userName, userPassword, email, phone);
if (!StringUtils.isEmpty(msg)) {
putMsg(result, Status.REQUEST_PARAMS_NOT_VALID_ERROR,msg);
return result;
}
if (!isAdmin(loginUser)) {
putMsg(result, Status.USER_NO_OPERATION_PERM);
return result;
}
if (!checkTenantExists(tenantId)) {
putMsg(result, Status.TENANT_NOT_EXIST);
return result;
}
User user = new User();
Date now = new Date();
user.setUserName(userName);
user.setUserPassword(EncryptionUtils.getMd5(userPassword));
user.setEmail(email);
user.setTenantId(tenantId);
user.setPhone(phone);
// create general users, administrator users are currently built-in
user.setUserType(UserType.GENERAL_USER);
user.setCreateTime(now);
user.setUpdateTime(now);
if (StringUtils.isEmpty(queue)){
queue = "";
}
user.setQueue(queue);
// save user
userMapper.insert(user);
Tenant tenant = tenantMapper.queryById(tenantId);
// resource upload startup
if (PropertyUtils.getResUploadStartupState()){
// if tenant not exists
if (!HadoopUtils.getInstance().exists(HadoopUtils.getHdfsTenantDir(tenant.getTenantCode()))){
createTenantDirIfNotExists(tenant.getTenantCode());
}
String userPath = HadoopUtils.getHdfsUserDir(tenant.getTenantCode(),user.getId());
HadoopUtils.getInstance().mkdir(userPath);
}
putMsg(result, Status.SUCCESS);
return result;
}
/**
* query user
*
* @param name name
* @param password password
* @return user info
*/
public User queryUser(String name, String password) {
String md5 = EncryptionUtils.getMd5(password);
return userMapper.queryUserByNamePassword(name, md5);
}
/**
* query user list
*
* @param loginUser login user
* @param pageNo page number
* @param searchVal search avlue
* @param pageSize page size
* @return user list page
*/
public Map<String, Object> queryUserList(User loginUser, String searchVal, Integer pageNo, Integer pageSize) {
Map<String, Object> result = new HashMap<>(5);
if (check(result, !isAdmin(loginUser), Status.USER_NO_OPERATION_PERM)) {
return result;
}
Page<User> page = new Page(pageNo, pageSize);
IPage<User> scheduleList = userMapper.queryUserPaging(page, searchVal);
PageInfo<User> pageInfo = new PageInfo<>(pageNo, pageSize);
pageInfo.setTotalCount((int)scheduleList.getTotal());
pageInfo.setLists(scheduleList.getRecords());
result.put(Constants.DATA_LIST, pageInfo);
putMsg(result, Status.SUCCESS);
return result;
}
/**
* updateProcessInstance user
*
* @param userId user id
* @param userName user name
* @param userPassword user password
* @param email email
* @param tenantId tennat id
* @param phone phone
* @param queue queue
* @return update result code
* @throws Exception exception
*/
public Map<String, Object> updateUser(int userId,
String userName,
String userPassword,
String email,
int tenantId,
String phone,
String queue) throws Exception {
Map<String, Object> result = new HashMap<>(5);
result.put(Constants.STATUS, false);
User user = userMapper.selectById(userId);
if (user == null) {
putMsg(result, Status.USER_NOT_EXIST, userId);
return result;
}
Date now = new Date();
if (StringUtils.isNotEmpty(userName)) {
User tempUser = userMapper.queryByUserNameAccurately(userName);
if (tempUser != null && tempUser.getId() != userId) {
putMsg(result, Status.USER_NAME_EXIST);
return result;
}
user.setUserName(userName);
}
if (StringUtils.isNotEmpty(userPassword)) {
user.setUserPassword(EncryptionUtils.getMd5(userPassword));
}
if (StringUtils.isNotEmpty(email)) {
user.setEmail(email);
}
user.setQueue(queue);
user.setPhone(phone);
user.setUpdateTime(now);
//if user switches the tenant, the user's resources need to be copied to the new tenant
if (user.getTenantId() != tenantId) {
Tenant oldTenant = tenantMapper.queryById(user.getTenantId());
//query tenant
Tenant newTenant = tenantMapper.queryById(tenantId);
if (newTenant != null) {
// if hdfs startup
if (PropertyUtils.getResUploadStartupState() && oldTenant != null){
String newTenantCode = newTenant.getTenantCode();
String oldResourcePath = HadoopUtils.getHdfsResDir(oldTenant.getTenantCode());
String oldUdfsPath = HadoopUtils.getHdfsUdfDir(oldTenant.getTenantCode());
// if old tenant dir exists
if (HadoopUtils.getInstance().exists(oldResourcePath)){
String newResourcePath = HadoopUtils.getHdfsResDir(newTenantCode);
String newUdfsPath = HadoopUtils.getHdfsUdfDir(newTenantCode);
//file resources list
List<Resource> fileResourcesList = resourceMapper.queryResourceList(
null, userId, ResourceType.FILE.ordinal());
if (CollectionUtils.isNotEmpty(fileResourcesList)) {
for (Resource resource : fileResourcesList) {
HadoopUtils.getInstance().copy(oldResourcePath + "/" + resource.getAlias(), newResourcePath, false, true);
}
}
//udf resources
List<Resource> udfResourceList = resourceMapper.queryResourceList(
null, userId, ResourceType.UDF.ordinal());
if (CollectionUtils.isNotEmpty(udfResourceList)) {
for (Resource resource : udfResourceList) {
HadoopUtils.getInstance().copy(oldUdfsPath + "/" + resource.getAlias(), newUdfsPath, false, true);
}
}
//Delete the user from the old tenant directory
String oldUserPath = HadoopUtils.getHdfsUserDir(oldTenant.getTenantCode(),userId);
HadoopUtils.getInstance().delete(oldUserPath, true);
}else {
// if old tenant dir not exists , create
createTenantDirIfNotExists(oldTenant.getTenantCode());
}
if (HadoopUtils.getInstance().exists(HadoopUtils.getHdfsTenantDir(newTenant.getTenantCode()))){
//create user in the new tenant directory
String newUserPath = HadoopUtils.getHdfsUserDir(newTenant.getTenantCode(),user.getId());
HadoopUtils.getInstance().mkdir(newUserPath);
}else {
// if new tenant dir not exists , create
createTenantDirIfNotExists(newTenant.getTenantCode());
}
}
}
user.setTenantId(tenantId);
}
// updateProcessInstance user
userMapper.updateById(user);
putMsg(result, Status.SUCCESS);
return result;
}
/**
* delete user
*
* @param loginUser login user
* @param id user id
* @return delete result code
* @throws Exception exception when operate hdfs
*/
public Map<String, Object> deleteUserById(User loginUser, int id) throws Exception {
Map<String, Object> result = new HashMap<>(5);
//only admin can operate
if (!isAdmin(loginUser)) {
putMsg(result, Status.USER_NOT_EXIST, id);
return result;
}
// delete user
User user = userMapper.queryTenantCodeByUserId(id);
if (user != null) {
if (PropertyUtils.getResUploadStartupState()) {
String userPath = HadoopUtils.getHdfsUserDir(user.getTenantCode(),id);
if (HadoopUtils.getInstance().exists(userPath)) {
HadoopUtils.getInstance().delete(userPath, true);
}
}
}
userMapper.deleteById(id);
putMsg(result, Status.SUCCESS);
return result;
}
/**
* grant project
*
* @param loginUser login user
* @param userId user id
* @param projectIds project id array
* @return grant result code
*/
public Map<String, Object> grantProject(User loginUser, int userId, String projectIds) {
Map<String, Object> result = new HashMap<>(5);
result.put(Constants.STATUS, false);
//only admin can operate
if (check(result, !isAdmin(loginUser), Status.USER_NO_OPERATION_PERM)) {
return result;
}
//if the selected projectIds are empty, delete all items associated with the user
projectUserMapper.deleteProjectRelation(0, userId);
if (check(result, StringUtils.isEmpty(projectIds), Status.SUCCESS)) {
return result;
}
String[] projectIdArr = projectIds.split(",");
for (String projectId : projectIdArr) {
Date now = new Date();
ProjectUser projectUser = new ProjectUser();
projectUser.setUserId(userId);
projectUser.setProjectId(Integer.parseInt(projectId));
projectUser.setPerm(7);
projectUser.setCreateTime(now);
projectUser.setUpdateTime(now);
projectUserMapper.insert(projectUser);
}
putMsg(result, Status.SUCCESS);
return result;
}
/**
* grant resource
*
* @param loginUser login user
* @param userId user id
* @param resourceIds resource id array
* @return grant result code
*/
public Map<String, Object> grantResources(User loginUser, int userId, String resourceIds) {
Map<String, Object> result = new HashMap<>(5);
//only admin can operate
if (check(result, !isAdmin(loginUser), Status.USER_NO_OPERATION_PERM)) {
return result;
}
User user = userMapper.selectById(userId);
if(user == null){
putMsg(result, Status.USER_NOT_EXIST, userId);
return result;
}
resourcesUserMapper.deleteResourceUser(userId, 0);
if (check(result, StringUtils.isEmpty(resourceIds), Status.SUCCESS)) {
return result;
}
String[] resourcesIdArr = resourceIds.split(",");
for (String resourceId : resourcesIdArr) {
Date now = new Date();
ResourcesUser resourcesUser = new ResourcesUser();
resourcesUser.setUserId(userId);
resourcesUser.setResourcesId(Integer.parseInt(resourceId));
resourcesUser.setPerm(7);
resourcesUser.setCreateTime(now);
resourcesUser.setUpdateTime(now);
resourcesUserMapper.insert(resourcesUser);
}
putMsg(result, Status.SUCCESS);
return result;
}
/**
* grant udf function
*
* @param loginUser login user
* @param userId user id
* @param udfIds udf id array
* @return grant result code
*/
public Map<String, Object> grantUDFFunction(User loginUser, int userId, String udfIds) {
Map<String, Object> result = new HashMap<>(5);
//only admin can operate
if (check(result, !isAdmin(loginUser), Status.USER_NO_OPERATION_PERM)) {
return result;
}
udfUserMapper.deleteByUserId(userId);
if (check(result, StringUtils.isEmpty(udfIds), Status.SUCCESS)) {
return result;
}
String[] resourcesIdArr = udfIds.split(",");
for (String udfId : resourcesIdArr) {
Date now = new Date();
UDFUser udfUser = new UDFUser();
udfUser.setUserId(userId);
udfUser.setUdfId(Integer.parseInt(udfId));
udfUser.setPerm(7);
udfUser.setCreateTime(now);
udfUser.setUpdateTime(now);
udfUserMapper.insert(udfUser);
}
putMsg(result, Status.SUCCESS);
return result;
}
/**
* grant datasource
*
* @param loginUser login user
* @param userId user id
* @param datasourceIds data source id array
* @return grant result code
*/
public Map<String, Object> grantDataSource(User loginUser, int userId, String datasourceIds) {
Map<String, Object> result = new HashMap<>(5);
result.put(Constants.STATUS, false);
//only admin can operate
if (check(result, !isAdmin(loginUser), Status.USER_NO_OPERATION_PERM)) {
return result;
}
datasourceUserMapper.deleteByUserId(userId);
if (check(result, StringUtils.isEmpty(datasourceIds), Status.SUCCESS)) {
return result;
}
String[] datasourceIdArr = datasourceIds.split(",");
for (String datasourceId : datasourceIdArr) {
Date now = new Date();
DatasourceUser datasourceUser = new DatasourceUser();
datasourceUser.setUserId(userId);
datasourceUser.setDatasourceId(Integer.parseInt(datasourceId));
datasourceUser.setPerm(7);
datasourceUser.setCreateTime(now);
datasourceUser.setUpdateTime(now);
datasourceUserMapper.insert(datasourceUser);
}
putMsg(result, Status.SUCCESS);
return result;
}
/**
* query user info
*
* @param loginUser login user
* @return user info
*/
public Map<String, Object> getUserInfo(User loginUser) {
Map<String, Object> result = new HashMap<>();
User user = null;
if (loginUser.getUserType() == UserType.ADMIN_USER) {
user = loginUser;
} else {
user = userMapper.queryDetailsById(loginUser.getId());
List<AlertGroup> alertGroups = alertGroupMapper.queryByUserId(loginUser.getId());
StringBuilder sb = new StringBuilder();
if (alertGroups != null && alertGroups.size() > 0) {
for (int i = 0; i < alertGroups.size() - 1; i++) {
sb.append(alertGroups.get(i).getGroupName() + ",");
}
sb.append(alertGroups.get(alertGroups.size() - 1));
user.setAlertGroup(sb.toString());
}
}
result.put(Constants.DATA_LIST, user);
putMsg(result, Status.SUCCESS);
return result;
}
/**
* query user list
*
* @param loginUser login user
* @return user list
*/
public Map<String, Object> queryAllGeneralUsers(User loginUser) {
Map<String, Object> result = new HashMap<>(5);
//only admin can operate
if (check(result, !isAdmin(loginUser), Status.USER_NO_OPERATION_PERM)) {
return result;
}
List<User> userList = userMapper.queryAllGeneralUser();
result.put(Constants.DATA_LIST, userList);
putMsg(result, Status.SUCCESS);
return result;
}
/**
* query user list
*
* @param loginUser login user
* @return user list
*/
public Map<String, Object> queryUserList(User loginUser) {
Map<String, Object> result = new HashMap<>(5);
//only admin can operate
if (check(result, !isAdmin(loginUser), Status.USER_NO_OPERATION_PERM)) {
return result;
}
List<User> userList = userMapper.selectList(null );
result.put(Constants.DATA_LIST, userList);
putMsg(result, Status.SUCCESS);
return result;
}
/**
* verify user name exists
*
* @param userName user name
* @return true if user name not exists, otherwise return false
*/
public Result verifyUserName(String userName) {
Result result = new Result();
User user = userMapper.queryByUserNameAccurately(userName);
if (user != null) {
logger.error("user {} has exist, can't create again.", userName);
putMsg(result, Status.USER_NAME_EXIST);
} else {
putMsg(result, Status.SUCCESS);
}
return result;
}
/**
* unauthorized user
*
* @param loginUser login user
* @param alertgroupId alert group id
* @return unauthorize result code
*/
public Map<String, Object> unauthorizedUser(User loginUser, Integer alertgroupId) {
Map<String, Object> result = new HashMap<>(5);
//only admin can operate
if (check(result, !isAdmin(loginUser), Status.USER_NO_OPERATION_PERM)) {
return result;
}
List<User> userList = userMapper.selectList(null );
List<User> resultUsers = new ArrayList<>();
Set<User> userSet = null;
if (userList != null && userList.size() > 0) {
userSet = new HashSet<>(userList);
List<User> authedUserList = userMapper.queryUserListByAlertGroupId(alertgroupId);
Set<User> authedUserSet = null;
if (authedUserList != null && authedUserList.size() > 0) {
authedUserSet = new HashSet<>(authedUserList);
userSet.removeAll(authedUserSet);
}
resultUsers = new ArrayList<>(userSet);
}
result.put(Constants.DATA_LIST, resultUsers);
putMsg(result, Status.SUCCESS);
return result;
}
/**
* authorized user
*
* @param loginUser login user
* @param alertgroupId alert group id
* @return authorized result code
*/
public Map<String, Object> authorizedUser(User loginUser, Integer alertgroupId) {
Map<String, Object> result = new HashMap<>(5);
//only admin can operate
if (check(result, !isAdmin(loginUser), Status.USER_NO_OPERATION_PERM)) {
return result;
}
List<User> userList = userMapper.queryUserListByAlertGroupId(alertgroupId);
result.put(Constants.DATA_LIST, userList);
putMsg(result, Status.SUCCESS);
return result;
}
/**
* check
*
* @param result result
* @param bool bool
* @param userNoOperationPerm status
* @return check result
*/
private boolean check(Map<String, Object> result, boolean bool, Status userNoOperationPerm) {
//only admin can operate
if (bool) {
result.put(Constants.STATUS, userNoOperationPerm);
result.put(Constants.MSG, userNoOperationPerm.getMsg());
return true;
}
return false;
}
/**
* @param tenantId tenant id
* @return true if tenant exists, otherwise return false
*/
private boolean checkTenantExists(int tenantId) {
return tenantMapper.queryById(tenantId) != null ? true : false;
}
/**
*
* @param userName
* @param password
* @param email
* @param phone
* @return if check failed return the field, otherwise return null
*/
private String checkUserParams(String userName, String password, String email, String phone) {
String msg = null;
if (!CheckUtils.checkUserName(userName)) {
msg = userName;
} else if (!CheckUtils.checkPassword(password)) {
msg = password;
} else if (!CheckUtils.checkEmail(email)) {
msg = email;
} else if (!CheckUtils.checkPhone(phone)) {
msg = phone;
}
return msg;
}
}
|
92319e73c6a0fe1a5e3363d791ac81aab2e513b0 | 2,114 | java | Java | sistemaParqueadero/src/Modelo/vVehiculo.java | enviniom/parqueadero | 2aa93522e3527ebf73f23b375bb746ae4d4ab002 | [
"MIT"
] | null | null | null | sistemaParqueadero/src/Modelo/vVehiculo.java | enviniom/parqueadero | 2aa93522e3527ebf73f23b375bb746ae4d4ab002 | [
"MIT"
] | 2 | 2016-11-21T00:47:54.000Z | 2016-11-21T05:27:06.000Z | sistemaParqueadero/src/Modelo/vVehiculo.java | enviniom/parqueadero | 2aa93522e3527ebf73f23b375bb746ae4d4ab002 | [
"MIT"
] | 1 | 2021-08-10T00:42:37.000Z | 2021-08-10T00:42:37.000Z | 20.326923 | 155 | 0.596026 | 995,914 | /*
* 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 Modelo;
/**
*
* @author Jhon
*/
public class vVehiculo {
private int idVehiculo;
private String tipo, placa, marca, modelo, ano, color, propietario, estado;
public vVehiculo(int idVehiculo, String tipo, String placa, String marca, String modelo, String ano, String color, String propietario, String estado) {
this.idVehiculo = idVehiculo;
this.tipo = tipo;
this.placa = placa;
this.marca = marca;
this.modelo = modelo;
this.ano = ano;
this.color = color;
this.propietario = propietario;
this.estado = estado;
}
public vVehiculo() {
}
public int getIdVehiculo() {
return idVehiculo;
}
public void setIdVehiculo(int idVehiculo) {
this.idVehiculo = idVehiculo;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
public String getPlaca() {
return placa;
}
public void setPlaca(String placa) {
this.placa = placa;
}
public String getMarca() {
return marca;
}
public void setMarca(String marca) {
this.marca = marca;
}
public String getModelo() {
return modelo;
}
public void setModelo(String modelo) {
this.modelo = modelo;
}
public String getAno() {
return ano;
}
public void setAno(String ano) {
this.ano = ano;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getPropietario() {
return propietario;
}
public void setPropietario(String propietario) {
this.propietario = propietario;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
}
|
92319f1720295619b4e026ecc0bd24a901898965 | 272 | java | Java | febs-server/febs-server-system/src/main/java/com/yonyou/etl/mapper/ReportGeneralledgerCalcInfoMapper.java | yhaoooooooo/FEBS-Cloud | 68255e7b3930361a1f22a4c261c8592a02e9b84d | [
"Apache-2.0"
] | null | null | null | febs-server/febs-server-system/src/main/java/com/yonyou/etl/mapper/ReportGeneralledgerCalcInfoMapper.java | yhaoooooooo/FEBS-Cloud | 68255e7b3930361a1f22a4c261c8592a02e9b84d | [
"Apache-2.0"
] | null | null | null | febs-server/febs-server-system/src/main/java/com/yonyou/etl/mapper/ReportGeneralledgerCalcInfoMapper.java | yhaoooooooo/FEBS-Cloud | 68255e7b3930361a1f22a4c261c8592a02e9b84d | [
"Apache-2.0"
] | null | null | null | 24.727273 | 100 | 0.830882 | 995,915 | package com.yonyou.etl.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yonyou.etl.entity.ReportGeneralledgerCalcInfo;
/**
* @author yhao
*/
public interface ReportGeneralledgerCalcInfoMapper extends BaseMapper<ReportGeneralledgerCalcInfo> {
}
|
9231a07d349dd8723896562a43f7d99b972dad19 | 7,549 | java | Java | app/src/main/java/com/example/android/quakereport/EarthquakeActivity.java | cetceeve/QuakeReport | 0b2e4825225b3b3d7b58d848a05a7eec0df12098 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/android/quakereport/EarthquakeActivity.java | cetceeve/QuakeReport | 0b2e4825225b3b3d7b58d848a05a7eec0df12098 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/android/quakereport/EarthquakeActivity.java | cetceeve/QuakeReport | 0b2e4825225b3b3d7b58d848a05a7eec0df12098 | [
"Apache-2.0"
] | null | null | null | 38.319797 | 130 | 0.656378 | 995,916 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.quakereport;
import android.content.Context;
import android.content.Intent;
import android.content.Loader;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class EarthquakeActivity extends AppCompatActivity implements android.app.LoaderManager.LoaderCallbacks<List<Earthquake>> {
public static final String LOG_TAG = EarthquakeActivity.class.getName();
private static final String USGS_REQUEST_URL = "http://earthquake.usgs.gov/fdsnws/event/1/query";
private EarthquakeAdapter mAdapter;
private TextView mEmptyView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.earthquake_activity);
// Find a reference to the {@link ListView} in the layout
ListView earthquakeListView = (ListView) findViewById(R.id.list);
//set empty view if Adapter is Empty
mEmptyView = (TextView) findViewById(R.id.empty_view);
if (earthquakeListView != null) {
earthquakeListView.setEmptyView(mEmptyView);
}
//Check for Network connection
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
//Initialize Loader
getLoaderManager().initLoader(0, null, this);
Log.i(LOG_TAG, "Loader initialized!");
} else {
//Hide ProgressBar
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar);
if (progressBar != null) {
progressBar.setVisibility(View.GONE);
}
//Display "No Internet connection."
if (mEmptyView != null) {
mEmptyView.setText(R.string.no_connection);
}
}
// Create a new {@link ArrayAdapter} of earthquakes
mAdapter = new EarthquakeAdapter(this, new ArrayList<Earthquake>());
// Set the adapter on the {@link ListView}
// so the list can be populated in the user interface
if (earthquakeListView != null) {
earthquakeListView.setAdapter(mAdapter);
} else {
Toast.makeText(EarthquakeActivity.this, "Could not find any earthquakes to display", Toast.LENGTH_LONG).show();
}
//ClickListener for the Earthquake objects in the List
if (earthquakeListView != null) {
earthquakeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//the clicked item is found by position and its url obtained
Earthquake earthquake = mAdapter.getItem(position);
if (earthquake != null) {
String earthquakeUrl = earthquake.getUrl();
//this method sends implicit intent to open a website
openWebPage(earthquakeUrl);
} else {
Log.e(LOG_TAG, "Not able to get earthquake object from Adapter");
Toast.makeText(EarthquakeActivity.this, "Sry, no URL available", Toast.LENGTH_LONG).show();
}
}
});
}
}
//Create new earthquake loader for this activity
@Override
public Loader<List<Earthquake>> onCreateLoader(int i, Bundle bundle) {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
String minMagnitude = sharedPrefs.getString(
getString(R.string.settings_min_magnitude_key),
getString(R.string.settings_min_magnitude_default));
String orderBy = sharedPrefs.getString(
getString(R.string.settings_order_by_key),
getString(R.string.settings_order_by_default)
);
Uri baseUri = Uri.parse(USGS_REQUEST_URL);
Uri.Builder uriBuilder = baseUri.buildUpon();
uriBuilder.appendQueryParameter("format", "geojson");
uriBuilder.appendQueryParameter("limit", "100");
uriBuilder.appendQueryParameter("minmag", minMagnitude);
uriBuilder.appendQueryParameter("orderby", orderBy);
Log.i(LOG_TAG, "Loader created!");
return new EarthquakeLoader(this, uriBuilder.toString());
}
//update UI when loader is finished
@Override
public void onLoadFinished(Loader<List<Earthquake>> loader, List<Earthquake> earthquakeList) {
//Clear the Adapter before updating UI with new data
mAdapter.clear();
if (earthquakeList != null && !earthquakeList.isEmpty()) {
mAdapter.addAll(earthquakeList);
}
Log.i(LOG_TAG, "Loader finished. UI updated!");
//Hide ProgressBar
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar);
if (progressBar != null) {
progressBar.setVisibility(View.GONE);
}
//set Text for empty view in case the adapter is empty
if (mEmptyView != null) {
mEmptyView.setText(R.string.empty_view);
}
}
//clears data on loader reset
@Override
public void onLoaderReset(Loader<List<Earthquake>> loader) {
mAdapter.clear();
Log.i(LOG_TAG, "LOADER RESET!");
}
//implicit intent to load a web page
public void openWebPage(String url) {
Uri webpage = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
//Infalting the menu icon in AppBar at activity launch
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent settingsIntent = new Intent(this, SettingsActivity.class);
startActivity(settingsIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
9231a0cc305d338afa262616c6140c55415c7e65 | 1,791 | java | Java | acl/src/main/java/org/springframework/security/acls/model/MutableAcl.java | elliedori/spring-security | 02d1516c566a58574af0a1d0391fd2ec8c5ad774 | [
"Apache-2.0"
] | 6,992 | 2015-01-02T15:38:39.000Z | 2022-03-31T05:57:56.000Z | acl/src/main/java/org/springframework/security/acls/model/MutableAcl.java | elliedori/spring-security | 02d1516c566a58574af0a1d0391fd2ec8c5ad774 | [
"Apache-2.0"
] | 7,823 | 2015-01-05T15:04:20.000Z | 2022-03-31T21:38:32.000Z | acl/src/main/java/org/springframework/security/acls/model/MutableAcl.java | elliedori/spring-security | 02d1516c566a58574af0a1d0391fd2ec8c5ad774 | [
"Apache-2.0"
] | 5,393 | 2015-01-04T14:29:19.000Z | 2022-03-31T02:16:35.000Z | 28.887097 | 112 | 0.734785 | 995,917 | /*
* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.acls.model;
import java.io.Serializable;
/**
* A mutable <tt>Acl</tt>.
* <p>
* A mutable ACL must ensure that appropriate security checks are performed before
* allowing access to its methods.
*
* @author Ben Alex
*/
public interface MutableAcl extends Acl {
void deleteAce(int aceIndex) throws NotFoundException;
/**
* Obtains an identifier that represents this <tt>MutableAcl</tt>.
* @return the identifier, or <tt>null</tt> if unsaved
*/
Serializable getId();
void insertAce(int atIndexLocation, Permission permission, Sid sid, boolean granting) throws NotFoundException;
/**
* Changes the present owner to a different owner.
* @param newOwner the new owner (mandatory; cannot be null)
*/
void setOwner(Sid newOwner);
/**
* Change the value returned by {@link Acl#isEntriesInheriting()}.
* @param entriesInheriting the new value
*/
void setEntriesInheriting(boolean entriesInheriting);
/**
* Changes the parent of this ACL.
* @param newParent the new parent
*/
void setParent(Acl newParent);
void updateAce(int aceIndex, Permission permission) throws NotFoundException;
}
|
9231a1b53df3813637e89c3d6769bb4ced209897 | 6,621 | java | Java | de.mhus.hair/hair3/de.mhus.cap.ui/src/de/mhus/cap/ui/oleditor/ObjectList.java | mhus/mhus-inka | dbb9e908700b3d922849b2ead1ba2409f08cb4a3 | [
"Apache-2.0"
] | 1 | 2021-07-01T11:50:17.000Z | 2021-07-01T11:50:17.000Z | de.mhus.hair/hair3/de.mhus.cap.ui/src/de/mhus/cap/ui/oleditor/ObjectList.java | mhus/mhus-inka | dbb9e908700b3d922849b2ead1ba2409f08cb4a3 | [
"Apache-2.0"
] | null | null | null | de.mhus.hair/hair3/de.mhus.cap.ui/src/de/mhus/cap/ui/oleditor/ObjectList.java | mhus/mhus-inka | dbb9e908700b3d922849b2ead1ba2409f08cb4a3 | [
"Apache-2.0"
] | null | null | null | 29.039474 | 149 | 0.723305 | 995,918 | package de.mhus.cap.ui.oleditor;
import java.util.LinkedList;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import de.mhus.cap.core.Activator;
import de.mhus.cap.core.CapCore;
import de.mhus.cap.core.dnd.CaoTransfer;
import de.mhus.cap.core.dnd.CapDragListener;
import de.mhus.cap.core.dnd.CapDropListener;
import de.mhus.cap.core.dnd.CapDropListener.LOCATION;
import de.mhus.cap.core.dnd.CapDropListener.OPERATION;
import de.mhus.cap.core.dnd.ICaoExchange;
import de.mhus.cap.core.ui.ICaoImageProvider;
import de.mhus.lib.cao.CaoElement;
import de.mhus.lib.cao.CaoException;
import de.mhus.lib.cao.CaoList;
import de.mhus.lib.cao.CaoMetaDefinition;
import de.mhus.lib.cao.CaoMetaDefinition.TYPE;
import de.mhus.lib.cao.CaoObserver;
import de.mhus.lib.config.IConfig;
import de.mhus.lib.logging.MLog;
public class ObjectList extends Composite {
private static de.mhus.lib.logging.Log log = de.mhus.lib.logging.Log.getLog(ObjectList.class);
private TableViewer tableViewer;
private CaoList list;
private CaoObserver observer;
private static final Image CHECKED = Activator.getImageDescriptor("icons/checked.gif").createImage();
private static final Image UNCHECKED = Activator.getImageDescriptor("icons/unchecked.gif").createImage();
public ObjectList(Composite parent, CaoList list, CaoObserver observer) {
super(parent, SWT.NONE);
this.list = list;
this.observer = observer;
try {
initUI();
} catch (CaoException e) {
e.printStackTrace();
//TODO do something
}
}
public TableViewer getTableViewer() {
return tableViewer;
}
protected void initUI() throws CaoException {
FillLayout layout = new FillLayout(SWT.HORIZONTAL);
setLayout(layout);
tableViewer = new TableViewer(this, SWT.MULTI | SWT.H_SCROLL
| SWT.V_SCROLL | SWT.FULL_SELECTION);
tableViewer.setUseHashlookup(true);
createColumns(tableViewer);
tableViewer.setContentProvider(new MyContentProvider());
tableViewer.setLabelProvider(new MyLabelProvider());
tableViewer.setInput(list);
int operations = DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK | DND.DROP_TARGET_MOVE;
Transfer[] transferTypes = new Transfer[]{CaoTransfer.getInstance(), FileTransfer.getInstance()};
tableViewer.addDropSupport(operations, transferTypes, new CapDropListener(tableViewer));
tableViewer.addDragSupport(operations, transferTypes, new CapDragListener(tableViewer));
}
// This will create the columns for the table
protected void createColumns(TableViewer viewer) throws CaoException {
IConfig[] headers = list.getApplication().getConfig().getConfig(CapCore.LIST_LIST_HEADERS).getConfigBundle("header");
for ( IConfig data : headers) {
MyColumnData columnData = new MyColumnData();
columnData.config = data;
columnData.imageProvider = CapCore.getInstance().getImageProvider(data.getString("imageprovider",null));
TableViewerColumn column = new TableViewerColumn(viewer, SWT.NONE);
column.getColumn().setText(data.getString("title","?"));
column.getColumn().setWidth((int)data.getLong("width",400));
column.getColumn().setResizable(true);
column.getColumn().setMoveable(true);
column.getColumn().setData(columnData);
}
Table table = viewer.getTable();
table.setHeaderVisible(true);
table.setLinesVisible(true);
}
private class MyContentProvider implements IStructuredContentProvider {
CaoList list;
@Override
public Object[] getElements(Object inputElement) {
list = (CaoList)inputElement;
LinkedList<MyData> out = new LinkedList<MyData>();
try {
for ( CaoElement data : list.getElements() ) {
out.add(new MyData(data));
if (observer!=null) observer.add(data);
}
} catch (CaoException e) {
MLog.e(e);
}
return out.toArray();
}
@Override
public void dispose() {
try {
for ( CaoElement data : list.getElements() ) {
if (observer != null) observer.remove(data);
}
} catch (CaoException e) {
MLog.e(e);
}
}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
}
private class MyLabelProvider extends LabelProvider implements ITableLabelProvider {
@Override
public Image getColumnImage(Object element, int columnIndex) {
try {
CaoElement data = ((MyData)element).element;
MyColumnData config = (MyColumnData)tableViewer.getTable().getColumn(columnIndex).getData();
String name = config.config.getString("name","?");
CaoMetaDefinition def = data.getMetadata().getDefinition( name );
if (def != null) {
if (def.getType() == TYPE.BOOLEAN) {
return data.getBoolean(name,false) ? CHECKED : UNCHECKED;
}
}
if (config.imageProvider != null) {
return config.imageProvider.getImage(data, null);
}
} catch (Exception he) {
log.debug(he);
}
return null;
}
@Override
public String getColumnText(Object element, int columnIndex) {
CaoElement data = ((MyData)element).element;
try {
MyColumnData config = (MyColumnData)tableViewer.getTable().getColumn(columnIndex).getData();
String name = config.config.getString("name","?");
if ("**name".equals(name))
return data.getName();
if ("**id".equals(name))
return data.getId();
return data.getString( name );
} catch (CaoException he) {
//he.printStackTrace(); //TODO do something ....
return "?";
}
}
}
public class MyData implements ICaoExchange {
public CaoElement element;
public MyData(CaoElement data) {
element = data;
}
@Override
public CaoElement getElement() {
return element;
}
@Override
public boolean doDrop(LOCATION loc, OPERATION oper,
ICaoExchange[] providers) {
if (log.isTraceEnabled()) try {log.trace("doDrop: " + loc.toString() + " " + oper.toString() + " " + element.getId() );} catch (CaoException e) {}
return CapCore.getInstance().doDrop(loc, oper, providers, this);
}
}
public class MyColumnData {
public IConfig config;
public ICaoImageProvider imageProvider;
}
}
|
9231a2105ab26a6ffd1c95748f06766b7e666809 | 1,110 | java | Java | common-util/src/main/java/kevsn/util/fns/SafeLockTasks.java | KevinShen620/kbase | 94f697518f69319a5d3715bcf48a90ebb9043566 | [
"MIT"
] | null | null | null | common-util/src/main/java/kevsn/util/fns/SafeLockTasks.java | KevinShen620/kbase | 94f697518f69319a5d3715bcf48a90ebb9043566 | [
"MIT"
] | null | null | null | common-util/src/main/java/kevsn/util/fns/SafeLockTasks.java | KevinShen620/kbase | 94f697518f69319a5d3715bcf48a90ebb9043566 | [
"MIT"
] | null | null | null | 17.34375 | 86 | 0.663964 | 995,919 | /*
* @(#) SafeLockTask.java 2015年6月9日
*
*/
package kevsn.util.fns;
import java.util.concurrent.locks.Lock;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* @author Kevin
*
*/
public class SafeLockTasks {
public static void executeTask(Lock lock, Procedure task) {
try {
_lock(lock);
task.execute();
} finally {
_unlock(lock);
}
}
public static <T, R> R executeFunction(Lock lock, Function<T, R> function, T param) {
try {
_lock(lock);
return function.apply(param);
} finally {
_unlock(lock);
}
}
public static <T> void executeConsumer(Lock lock, Consumer<T> consumer, T param) {
try {
_lock(lock);
consumer.accept(param);
} finally {
_unlock(lock);
}
}
public static <T> T executeSupplier(Lock lock, Supplier<T> supplier) {
try {
_lock(lock);
return supplier.get();
} finally {
_unlock(lock);
}
}
private static void _lock(Lock lock) {
lock.lock();
}
private static void _unlock(Lock lock) {
lock.unlock();
}
}
|
9231a47d2a50b0aabf143d38c01fb65d927e9aa5 | 1,068 | java | Java | cloud-reactor-api/src/main/java/com/sequenceiq/cloudbreak/cloud/event/credential/CredentialVerificationResult.java | drorke/cloudbreak | 8a1d4749fe9d1d683f5bec3102e8b86f59928f67 | [
"Apache-2.0"
] | 174 | 2017-07-14T03:20:42.000Z | 2022-03-25T05:03:18.000Z | cloud-reactor-api/src/main/java/com/sequenceiq/cloudbreak/cloud/event/credential/CredentialVerificationResult.java | drorke/cloudbreak | 8a1d4749fe9d1d683f5bec3102e8b86f59928f67 | [
"Apache-2.0"
] | 2,242 | 2017-07-12T05:52:01.000Z | 2022-03-31T15:50:08.000Z | cloud-reactor-api/src/main/java/com/sequenceiq/cloudbreak/cloud/event/credential/CredentialVerificationResult.java | drorke/cloudbreak | 8a1d4749fe9d1d683f5bec3102e8b86f59928f67 | [
"Apache-2.0"
] | 172 | 2017-07-12T08:53:48.000Z | 2022-03-24T12:16:33.000Z | 38.142857 | 148 | 0.796816 | 995,920 | package com.sequenceiq.cloudbreak.cloud.event.credential;
import com.sequenceiq.cloudbreak.cloud.event.CloudPlatformResult;
import com.sequenceiq.cloudbreak.cloud.model.CloudCredentialStatus;
public class CredentialVerificationResult extends CloudPlatformResult {
private CloudCredentialStatus cloudCredentialStatus;
public CredentialVerificationResult(Long resourceId, CloudCredentialStatus cloudCredentialStatus) {
super(resourceId);
this.cloudCredentialStatus = cloudCredentialStatus;
}
public CredentialVerificationResult(String statusReason, Exception errorDetails, Long resourceId, CloudCredentialStatus cloudCredentialStatus) {
super(statusReason, errorDetails, resourceId);
this.cloudCredentialStatus = cloudCredentialStatus;
}
public CredentialVerificationResult(String statusReason, Exception errorDetails, Long resourceId) {
super(statusReason, errorDetails, resourceId);
}
public CloudCredentialStatus getCloudCredentialStatus() {
return cloudCredentialStatus;
}
}
|
9231a48d6be4a1be1f28c0db1b387d799c65632a | 264 | java | Java | src/main/java/ibm/ra/integration/dao/PurchaseOrderDAO.java | angry-tony/refarch-integration-services | 78c87727245b605c4cbd51c614d2761e7d5bb8bb | [
"Apache-2.0"
] | null | null | null | src/main/java/ibm/ra/integration/dao/PurchaseOrderDAO.java | angry-tony/refarch-integration-services | 78c87727245b605c4cbd51c614d2761e7d5bb8bb | [
"Apache-2.0"
] | null | null | null | src/main/java/ibm/ra/integration/dao/PurchaseOrderDAO.java | angry-tony/refarch-integration-services | 78c87727245b605c4cbd51c614d2761e7d5bb8bb | [
"Apache-2.0"
] | null | null | null | 24 | 75 | 0.829545 | 995,921 | package ibm.ra.integration.dao;
import ibm.ra.customer.DALException;
import po.model.PurchaseOrder;
public interface PurchaseOrderDAO {
PurchaseOrder createPurchaseOrder(PurchaseOrder poIn) throws DALException;
String deletePO(long id) throws DALException;
}
|
9231a6508e6a78d2966ff94fc52996213d7b036b | 1,627 | java | Java | src/main/java/demo/sicau/datamanagementplatform/util/HmacSHA256Utils.java | tzfun/data-management-platform | 15667d409d4ab4b4b5cd8d471db2fac1fc12bb6e | [
"MIT"
] | 13 | 2019-04-10T03:41:26.000Z | 2021-12-11T08:18:30.000Z | src/main/java/demo/sicau/datamanagementplatform/util/HmacSHA256Utils.java | tzfun/data-management-platform | 15667d409d4ab4b4b5cd8d471db2fac1fc12bb6e | [
"MIT"
] | 2 | 2021-05-08T17:51:52.000Z | 2022-02-09T22:13:36.000Z | src/main/java/demo/sicau/datamanagementplatform/util/HmacSHA256Utils.java | tzfun/data-management-platform | 15667d409d4ab4b4b5cd8d471db2fac1fc12bb6e | [
"MIT"
] | 2 | 2019-10-16T17:11:13.000Z | 2020-08-24T11:35:47.000Z | 30.12963 | 75 | 0.566687 | 995,922 | package demo.sicau.datamanagementplatform.util;
import org.apache.commons.codec.binary.Hex;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.List;
import java.util.Map;
/**
* Java 加密解密之消息摘要算法
* @Author beifengtz
* @Site www.beifengtz.com
* @Date Created in 20:27 2018/11/2
* @Description:
*/
public class HmacSHA256Utils {
public static String digest(String key, String content) {
try {
Mac mac = Mac.getInstance("HmacSHA256");
byte[] secretByte = key.getBytes("utf-8");
byte[] dataBytes = content.getBytes("utf-8");
SecretKey secret = new SecretKeySpec(secretByte, "HMACSHA256");
mac.init(secret);
byte[] doFinal = mac.doFinal(dataBytes);
byte[] hexB = new Hex().encode(doFinal);
return new String(hexB, "utf-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("unchecked")
public static String digest(String key, Map<String, ?> map) {
StringBuilder s = new StringBuilder();
for(Object values : map.values()) {
if(values instanceof String[]) {
for(String value : (String[])values) {
s.append(value);
}
} else if(values instanceof List) {
for(String value : (List<String>)values) {
s.append(value);
}
} else {
s.append(values);
}
}
return digest(key, s.toString());
}
}
|
9231a6e44393ecff829a8b2cdfb2ed502b0fcd70 | 6,510 | java | Java | src/artisynth/core/materials/ScaledFemMaterial.java | aaltolab/artisynth_core | ce01443e067f20a3f5874c05e9b97019ca7c7ca7 | [
"Apache-2.0",
"BSD-3-Clause"
] | 30 | 2018-03-14T17:19:31.000Z | 2022-02-08T15:02:38.000Z | src/artisynth/core/materials/ScaledFemMaterial.java | aaltolab/artisynth_core | ce01443e067f20a3f5874c05e9b97019ca7c7ca7 | [
"Apache-2.0",
"BSD-3-Clause"
] | 6 | 2018-05-02T21:17:34.000Z | 2021-11-30T04:17:57.000Z | src/artisynth/core/materials/ScaledFemMaterial.java | aaltolab/artisynth_core | ce01443e067f20a3f5874c05e9b97019ca7c7ca7 | [
"Apache-2.0",
"BSD-3-Clause"
] | 18 | 2018-04-11T13:37:51.000Z | 2022-02-01T21:17:57.000Z | 29.457014 | 79 | 0.667742 | 995,923 | package artisynth.core.materials;
import artisynth.core.modelbase.*;
import java.util.*;
import maspack.matrix.Matrix6d;
import maspack.matrix.Matrix3d;
import maspack.matrix.SymmetricMatrix3d;
import maspack.util.InternalErrorException;
import maspack.util.DynamicArray;
import maspack.util.DataBuffer;
import maspack.properties.*;
public class ScaledFemMaterial extends FemMaterial {
protected static FemMaterial DEFAULT_BASE_MATERIAL = new LinearMaterial();
protected static double DEFAULT_SCALING = 1.0;
static ArrayList<Class<?>> myBaseClasses;
static {
myBaseClasses = new ArrayList<>(FemMaterial.mySubclasses.size());
for (Class<?> clazz : FemMaterial.mySubclasses) {
if (!ScaledFemMaterial.class.isAssignableFrom (clazz)) {
myBaseClasses.add (clazz);
}
}
}
FemMaterial myBaseMaterial = DEFAULT_BASE_MATERIAL;
double myScaling = DEFAULT_SCALING;
ScalarFieldPointFunction myScalingFunction;
public static FunctionPropertyList myProps =
new FunctionPropertyList(ScaledFemMaterial.class, FemMaterial.class);
static {
myProps.addWithFunction (
"scaling", "scaling factor for the base material", DEFAULT_SCALING);
PropertyDesc desc = myProps.add (
"baseMaterial",
"base material providing the elasticity", DEFAULT_BASE_MATERIAL);
desc.setAllowedTypes (myBaseClasses);
}
public FunctionPropertyList getAllPropertyInfo() {
return myProps;
}
public ScaledFemMaterial() {
setBaseMaterial (DEFAULT_BASE_MATERIAL);
setScaling (DEFAULT_SCALING);
}
public ScaledFemMaterial (FemMaterial baseMat, double scaling) {
setBaseMaterial (baseMat);
setScaling (scaling);
}
public double getScaling() {
return myScaling;
}
public void setScaling (double scaling) {
myScaling = scaling;
notifyHostOfPropertyChange();
}
public double getScaling (FieldPoint dp) {
if (myScalingFunction == null) {
return getScaling();
}
else {
return myScalingFunction.eval (dp);
}
}
public ScalarFieldPointFunction getScalingFunction() {
return myScalingFunction;
}
public void setScalingFunction (ScalarFieldPointFunction func) {
myScalingFunction = func;
notifyHostOfPropertyChange();
}
public void setScalingField (
ScalarField field, boolean useRestPos) {
myScalingFunction = FieldUtils.setFunctionFromField (field, useRestPos);
notifyHostOfPropertyChange();
}
public ScalarField getScalingField () {
return FieldUtils.getFieldFromFunction (myScalingFunction);
}
/**
* If possible, initializes the baseMaterial property in this
* ScaledFemMaterial from another FemMaterial.
*
* <p>This method is called via reflection in the CompositePropertyPanel
* code, to help initialize the ScaledFemMaterial from any previous
* material that had been selected. It returns an array of the names of the
* properties that were set, if any.
*/
public String[] initializePropertyValues (FemMaterial mat) {
if (mat instanceof ScaledFemMaterial) {
setBaseMaterial (((ScaledFemMaterial)mat).getBaseMaterial());
}
else {
setBaseMaterial (mat);
}
// baseMaterial property was set
return new String[] {"baseMaterial"};
}
protected void doSetBaseMaterial (FemMaterial baseMat) {
myBaseMaterial = (FemMaterial)MaterialBase.updateMaterial (
this, "baseMaterial", myBaseMaterial, baseMat);
}
public void setBaseMaterial (FemMaterial baseMat) {
if (baseMat == null) {
throw new IllegalArgumentException ("Base material cannot be null");
}
else if (baseMat instanceof ScaledFemMaterial) {
throw new IllegalArgumentException (
"Base material cannot be another ScaledFemMaterial");
}
// don't do equality check unless equals also tests for function settings
//if (!baseMat.equals (myBaseMaterial)) {
FemMaterial old = myBaseMaterial;
doSetBaseMaterial (baseMat);
notifyHostOfPropertyChange ("baseMaterial", baseMat, old);
//}
}
public FemMaterial getBaseMaterial() {
return myBaseMaterial;
}
public boolean equals (FemMaterial mat) {
if (mat instanceof ScaledFemMaterial) {
ScaledFemMaterial smat = (ScaledFemMaterial)mat;
return (myScaling == smat.myScaling &&
myBaseMaterial.equals (smat.myBaseMaterial));
}
else {
return false;
}
}
public ScaledFemMaterial clone() {
ScaledFemMaterial smat = (ScaledFemMaterial)super.clone();
smat.doSetBaseMaterial (myBaseMaterial);
return smat;
}
public boolean hasState() {
return myBaseMaterial.hasState();
}
public MaterialStateObject createStateObject() {
return myBaseMaterial.createStateObject();
}
public void advanceState (MaterialStateObject state, double t0, double t1) {
if (myBaseMaterial.hasState()) {
myBaseMaterial.advanceState (state, t0, t1);
}
}
/**
* {@inheritDoc}
*/
public void computeStressAndTangent (
SymmetricMatrix3d sigma, Matrix6d D, DeformedPoint def,
Matrix3d Q, double excitation, MaterialStateObject state) {
double scaling = getScaling (def);
IncompressibleMaterialBase imat =
myBaseMaterial.getIncompressibleComponent();
if (imat != null) {
imat.computeDevStressAndTangent (
sigma, D, def, Q, excitation, state);
sigma.scale (scaling);
double p = def.getAveragePressure();
imat.addPressureStress (sigma, p);
if (D != null) {
D.scale (scaling);
imat.addPressureTangent (D, p);
}
}
else {
myBaseMaterial.computeStressAndTangent (
sigma, D, def, Q, excitation, state);
sigma.scale (scaling);
if (D != null) {
D.scale (scaling);
}
}
}
public boolean isIncompressible() {
return myBaseMaterial.isIncompressible();
}
public boolean isLinear() {
return myBaseMaterial.isLinear();
}
public boolean isCorotated() {
return myBaseMaterial.isCorotated();
}
public IncompressibleMaterialBase getIncompressibleComponent() {
return myBaseMaterial.getIncompressibleComponent();
}
}
|
9231a8874d0ee6a787d8a32213dc8cd682971f8c | 1,384 | java | Java | src/main/java/com/pinterest/secor/uploader/S3UploadHandle.java | dfdf/secor | 73f061b5bb025789baadc370001675e31a1cc39d | [
"Apache-2.0"
] | 1,647 | 2015-01-11T20:28:42.000Z | 2022-03-25T17:08:45.000Z | src/main/java/com/pinterest/secor/uploader/S3UploadHandle.java | ksingh7/secor | 6152b41ee5311fa7a78c552ab018402a80ca83c5 | [
"Apache-2.0"
] | 892 | 2015-01-05T22:54:17.000Z | 2022-03-30T05:28:18.000Z | src/main/java/com/pinterest/secor/uploader/S3UploadHandle.java | ksingh7/secor | 6152b41ee5311fa7a78c552ab018402a80ca83c5 | [
"Apache-2.0"
] | 635 | 2015-01-08T11:59:53.000Z | 2022-03-20T03:55:51.000Z | 33.878049 | 70 | 0.740821 | 995,924 | /*
* 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 com.pinterest.secor.uploader;
import com.amazonaws.services.s3.transfer.Upload;
import com.amazonaws.services.s3.transfer.model.UploadResult;
/**
* Wraps an Upload being managed by the AWS SDK TransferManager. `get`
* blocks until the upload completes.
*
* @author Liam Stewart (hzdkv@example.com)
*/
public class S3UploadHandle implements Handle<UploadResult> {
private Upload mUpload;
public S3UploadHandle(Upload u) {
mUpload = u;
}
public UploadResult get() throws Exception {
return mUpload.waitForUploadResult();
}
}
|
9231a8b61cc0f652ca716dd02349e4b92b0f0e22 | 3,141 | java | Java | MediaCodecTest18/src/jp/morihirosoft/mediacodectest18/MainActivity.java | hongge372/Android_MediaCodecTest | 66667e1776d685f719e0f1243c394114d604a19d | [
"Apache-2.0"
] | 23 | 2015-06-03T09:55:48.000Z | 2021-02-22T08:29:50.000Z | MediaCodecTest18/src/jp/morihirosoft/mediacodectest18/MainActivity.java | MorihiroSoft/Android_MediaCodecTest | 66667e1776d685f719e0f1243c394114d604a19d | [
"Apache-2.0"
] | null | null | null | MediaCodecTest18/src/jp/morihirosoft/mediacodectest18/MainActivity.java | MorihiroSoft/Android_MediaCodecTest | 66667e1776d685f719e0f1243c394114d604a19d | [
"Apache-2.0"
] | 9 | 2015-11-19T09:21:23.000Z | 2019-07-10T06:40:54.000Z | 28.044643 | 75 | 0.628144 | 995,925 | /*
* Copyright (C) 2013 MorihiroSoft
* Copyright 2013 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.morihirosoft.mediacodectest18;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
public class MainActivity extends Activity implements
View.OnClickListener
{
//---------------------------------------------------------------------
// MEMBERS
//---------------------------------------------------------------------
private CameraView mCameraView = null;
private Button mBtnStart = null;
private Button mBtnStop = null;
private Button mBtnPlay = null;
//---------------------------------------------------------------------
// PUBLIC METHODS
//---------------------------------------------------------------------
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main_activity);
mCameraView = (CameraView)findViewById(R.id.cameraview);
mBtnStart = (Button)findViewById(R.id.start);
mBtnStop = (Button)findViewById(R.id.stop);
mBtnPlay = (Button)findViewById(R.id.play);
mBtnStart.setOnClickListener(this);
mBtnStop.setOnClickListener(this);
mBtnPlay.setOnClickListener(this);
mBtnStart.setEnabled(true);
mBtnStop.setEnabled(false);
}
@Override
protected void onResume() {
super.onResume();
mCameraView.onResume();
}
@Override
protected void onPause() {
stopVideo();
mCameraView.onPause();
super.onPause();
}
@Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.start:
startVideo();
break;
case R.id.stop:
stopVideo();
break;
case R.id.play:
playVideo();
break;
}
}
//---------------------------------------------------------------------
// PRIVATE...
//---------------------------------------------------------------------
private void startVideo() {
mBtnStart.setEnabled(false);
mBtnStop.setEnabled(true);
mCameraView.startVideo();
}
private void stopVideo() {
mBtnStart.setEnabled(true);
mBtnStop.setEnabled(false);
mCameraView.stopVideo();
}
private void playVideo() {
Uri uri = Uri.parse("file://"+VideoParam.getInstance().mOutput);
Intent i = new Intent(Intent.ACTION_VIEW, uri);
i.setDataAndType(uri, "video/mp4");
startActivity(i);
}
}
|
9231a8d926ae2f26f6b2cbf2213417318dd41d24 | 1,782 | java | Java | checkstyle/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/illegaltype/InputIllegalTypeTestExtendsImplements.java | spoole167/java-static-analysis-samples | 880f9b394e531d8c03af425b1b4e5a95302a3359 | [
"Apache-2.0"
] | null | null | null | checkstyle/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/illegaltype/InputIllegalTypeTestExtendsImplements.java | spoole167/java-static-analysis-samples | 880f9b394e531d8c03af425b1b4e5a95302a3359 | [
"Apache-2.0"
] | null | null | null | checkstyle/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/illegaltype/InputIllegalTypeTestExtendsImplements.java | spoole167/java-static-analysis-samples | 880f9b394e531d8c03af425b1b4e5a95302a3359 | [
"Apache-2.0"
] | 1 | 2021-09-15T05:49:41.000Z | 2021-09-15T05:49:41.000Z | 27.84375 | 92 | 0.628507 | 995,926 | /*
IllegalType
validateAbstractClassNames = (default)false
illegalClassNames = Boolean, Foo, Hashtable, Serializable
legalAbstractClassNames = (default)
ignoredMethodNames = (default)getEnvironment, getInitialContext
illegalAbstractClassNameFormat = (default)^(.*[.])?Abstract.*$
memberModifiers = LITERAL_PUBLIC
tokens = (default)ANNOTATION_FIELD_DEF, CLASS_DEF, INTERFACE_DEF, METHOD_CALL, METHOD_DEF, \
METHOD_REF, PARAMETER_DEF, VARIABLE_DEF, PATTERN_VARIABLE_DEF, RECORD_DEF, \
RECORD_COMPONENT_DEF
*/
package com.puppycrawl.tools.checkstyle.checks.coding.illegaltype;
import java.io.Serializable;
import java.util.*;
public abstract class InputIllegalTypeTestExtendsImplements {
public abstract class Bar
extends Hashtable // violation
<Boolean, // violation
Bar> { // OK
}
public abstract class Foo<
T extends Boolean> // violation
implements Cloneable, // OK
Serializable, // violation
Comparator, // OK
Comparable<Foo< // violation
? extends Boolean>> { // violation
}
public interface Interface<Foo> // violation
extends Comparable<Boolean>, // violation
Serializable { // violation
}
abstract class NonPublicBar
extends Hashtable // OK
<Boolean, // OK
Bar> { // OK
}
abstract class NonPublicFoo<
T extends Boolean> // OK
implements Cloneable, // OK
Serializable, // OK
Comparator, // OK
Comparable<Foo< // OK
? extends Boolean>> { // OK
}
interface NonPublicInterface<Foo>
extends Comparable<Boolean>, // OK
Serializable { // OK
}
}
|
9231a92f84a778e74b1f3c2d5a3e04489a2ec118 | 3,684 | java | Java | hazelcast/src/main/java/com/hazelcast/map/impl/mapstore/MapStoreContextFactory.java | ldziedziul-gh-tests/hazelcast | 3a7382ac8164bc17836fc9b1f852b2667e7bef96 | [
"ECL-2.0",
"Apache-2.0"
] | 4,283 | 2015-01-02T03:56:10.000Z | 2022-03-29T23:07:45.000Z | hazelcast/src/main/java/com/hazelcast/map/impl/mapstore/MapStoreContextFactory.java | ldziedziul-gh-tests/hazelcast | 3a7382ac8164bc17836fc9b1f852b2667e7bef96 | [
"ECL-2.0",
"Apache-2.0"
] | 14,014 | 2015-01-01T04:29:38.000Z | 2022-03-31T21:47:55.000Z | hazelcast/src/main/java/com/hazelcast/map/impl/mapstore/MapStoreContextFactory.java | ldziedziul-gh-tests/hazelcast | 3a7382ac8164bc17836fc9b1f852b2667e7bef96 | [
"ECL-2.0",
"Apache-2.0"
] | 1,608 | 2015-01-04T09:57:08.000Z | 2022-03-31T12:05:26.000Z | 32.60177 | 116 | 0.685668 | 995,927 | /*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.map.impl.mapstore;
import com.hazelcast.config.MapConfig;
import com.hazelcast.config.MapStoreConfig;
import com.hazelcast.logging.ILogger;
import com.hazelcast.map.impl.MapContainer;
import com.hazelcast.map.impl.MapServiceContext;
import com.hazelcast.map.impl.MapStoreWrapper;
import com.hazelcast.internal.serialization.SerializationService;
import java.util.Collections;
import static com.hazelcast.map.impl.mapstore.MapStoreManagers.emptyMapStoreManager;
/**
* A factory which creates {@link com.hazelcast.map.impl.mapstore.MapStoreContext} objects
* according to {@link com.hazelcast.config.MapStoreConfig}.
*/
public final class MapStoreContextFactory {
private static final MapStoreContext EMPTY_MAP_STORE_CONTEXT = new EmptyMapStoreContext();
private MapStoreContextFactory() {
}
public static MapStoreContext createMapStoreContext(MapContainer mapContainer) {
final MapConfig mapConfig = mapContainer.getMapConfig();
final MapStoreConfig mapStoreConfig = mapConfig.getMapStoreConfig();
if (mapStoreConfig == null || !mapStoreConfig.isEnabled()) {
return EMPTY_MAP_STORE_CONTEXT;
}
return BasicMapStoreContext.create(mapContainer);
}
private static final class EmptyMapStoreContext implements MapStoreContext {
@Override
public MapStoreManager getMapStoreManager() {
return emptyMapStoreManager();
}
@Override
public MapStoreWrapper getMapStoreWrapper() {
// keep it null. do not throw exception.
return null;
}
@Override
public void start() {
}
@Override
public void stop() {
}
@Override
public boolean isWriteBehindMapStoreEnabled() {
return false;
}
@Override
public SerializationService getSerializationService() {
throw new UnsupportedOperationException("This method must not be called. No defined map store exists.");
}
@Override
public ILogger getLogger(Class clazz) {
throw new UnsupportedOperationException("This method must not be called. No defined map store exists.");
}
@Override
public String getMapName() {
throw new UnsupportedOperationException("This method must not be called. No defined map store exists.");
}
@Override
public MapServiceContext getMapServiceContext() {
throw new UnsupportedOperationException("This method must not be called. No defined map store exists.");
}
@Override
public MapStoreConfig getMapStoreConfig() {
throw new UnsupportedOperationException("This method must not be called. No defined map store exists.");
}
@Override
public Iterable<Object> loadAllKeys() {
return Collections.emptyList();
}
@Override
public boolean isMapLoader() {
return false;
}
}
}
|
9231a9685aec83a039582910fe318b43b7905abb | 4,362 | java | Java | Core/src/org/sleuthkit/autopsy/report/ReportWizardPanel1.java | karlmortensen/autopsy | c52929c017d742781f60e3195782661c8825369a | [
"Apache-2.0"
] | 2 | 2016-06-20T15:00:28.000Z | 2021-01-03T14:17:46.000Z | Core/src/org/sleuthkit/autopsy/report/ReportWizardPanel1.java | karlmortensen/autopsy | c52929c017d742781f60e3195782661c8825369a | [
"Apache-2.0"
] | 4 | 2016-06-20T15:04:22.000Z | 2016-06-20T15:07:39.000Z | Core/src/org/sleuthkit/autopsy/report/ReportWizardPanel1.java | karlmortensen/autopsy | c52929c017d742781f60e3195782661c8825369a | [
"Apache-2.0"
] | 1 | 2020-05-25T17:22:01.000Z | 2020-05-25T17:22:01.000Z | 31.157143 | 129 | 0.669876 | 995,928 | /*
* Autopsy Forensic Browser
*
* Copyright 2012 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> 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.sleuthkit.autopsy.report;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collection;
import java.util.Map;
import java.util.prefs.Preferences;
import javax.swing.JButton;
import javax.swing.event.ChangeListener;
import org.openide.WizardDescriptor;
import org.openide.util.HelpCtx;
import org.openide.util.NbBundle;
import org.openide.util.NbPreferences;
class ReportWizardPanel1 implements WizardDescriptor.FinishablePanel<WizardDescriptor> {
private WizardDescriptor wiz;
private ReportVisualPanel1 component;
private JButton nextButton;
private JButton finishButton;
ReportWizardPanel1() {
nextButton = new JButton(NbBundle.getMessage(this.getClass(), "ReportWizardPanel1.nextButton.text"));
finishButton = new JButton(NbBundle.getMessage(this.getClass(), "ReportWizardPanel1.finishButton.text"));
finishButton.setEnabled(false);
// Initialize our custom next and finish buttons
nextButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
wiz.doNextClick();
}
});
finishButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
wiz.doFinishClick();
}
});
}
@Override
public ReportVisualPanel1 getComponent() {
if (component == null) {
component = new ReportVisualPanel1(this);
}
return component;
}
@Override
public HelpCtx getHelp() {
return HelpCtx.DEFAULT_HELP;
}
@Override
public boolean isValid() {
// Always valid, but we control the enabled state
// of our custom buttons
return true;
}
@Override
public boolean isFinishPanel() {
return true;
}
public void setNext(boolean enabled) {
nextButton.setEnabled(enabled);
}
public void setFinish(boolean enabled) {
finishButton.setEnabled(enabled);
}
@Override
public void addChangeListener(ChangeListener l) {
}
@Override
public void removeChangeListener(ChangeListener l) {
}
@Override
public void readSettings(WizardDescriptor wiz) {
// Add out custom buttons in place of the regular ones
this.wiz = wiz;
wiz.setOptions(new Object[]{WizardDescriptor.PREVIOUS_OPTION, nextButton, finishButton, WizardDescriptor.CANCEL_OPTION});
}
@Override
public void storeSettings(WizardDescriptor wiz) {
Map<TableReportModule, Boolean> tables = getComponent().getTableModuleStates();
Map<GeneralReportModule, Boolean> generals = getComponent().getGeneralModuleStates();
wiz.putProperty("tableModuleStates", tables); //NON-NLS
wiz.putProperty("generalModuleStates", generals); //NON-NLS
wiz.putProperty("fileModuleStates", getComponent().getFileModuleStates()); //NON-NLS
// Store preferences that WizardIterator will use to determine what
// panels need to be shown
Preferences prefs = NbPreferences.forModule(ReportWizardPanel1.class);
prefs.putBoolean("tableModule", any(tables.values())); //NON-NLS
prefs.putBoolean("generalModule", any(generals.values())); //NON-NLS
}
/**
* Are any of the given booleans true?
*
* @param bools
*
* @return
*/
private boolean any(Collection<Boolean> bools) {
for (Boolean b : bools) {
if (b) {
return true;
}
}
return false;
}
}
|
9231a9c77dee7f04ac56211102f30fdc801821b3 | 1,809 | java | Java | projecteuler.net/Ariel/src/util/BitBucketOutputStream.java | goeckeler/puzzles | 978a14e6e006ceef6c8e4ce3752c27a4cd002fb5 | [
"Apache-2.0"
] | null | null | null | projecteuler.net/Ariel/src/util/BitBucketOutputStream.java | goeckeler/puzzles | 978a14e6e006ceef6c8e4ce3752c27a4cd002fb5 | [
"Apache-2.0"
] | null | null | null | projecteuler.net/Ariel/src/util/BitBucketOutputStream.java | goeckeler/puzzles | 978a14e6e006ceef6c8e4ce3752c27a4cd002fb5 | [
"Apache-2.0"
] | null | null | null | 23.802632 | 77 | 0.693753 | 995,929 | /**
* Ariel
* BitBucketOutputStream.java
*
* TODO a short description of the class
*
*
* @author nicholasink
* @version May 12, 2009
*/
package util;
import java.io.*;
/**
* A repository for unwanted bytes. Basically a replacement for
* <code>/dev/null</code>
*/
public class BitBucketOutputStream extends OutputStream {
/**
* Sets System.out to use the BitBucketOutputStream as the output stream. In
* effect, redirecting standard out to oblivion.
*
* @see restoreSystemOut
*/
public static void nullSystemOut() {
System.setOut(new PrintStream(new BitBucketOutputStream(), true));
}
/**
* Recreates a System.out similar to the default System.out, and restores
* the default behavior.
*
* @see #nullSystemOut
*/
public static void restoreSystemOut() {
FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
System.setOut(new PrintStream(new BufferedOutputStream(fdOut, 128),
true));
}
/**
* Sets System.err to use the BitBucketOutputStream as the output stream. In
* effect redirecting standard error to oblivion.
*
* @see restoreSystemErr
*/
public static void nullSystemErr() {
System.setErr(new PrintStream(new BitBucketOutputStream(), true));
}
/**
* Recreates a System.err similar to the default System.err, and restores
* the default behavior.
*
* @see #nullSystemErr
*/
public static void restoreSystemErr() {
FileOutputStream fdErr = new FileOutputStream(FileDescriptor.err);
System.setErr(new PrintStream(new BufferedOutputStream(fdErr, 128),
true));
}
/**
* Does nothing with the specified byte.
*
* @param b
* the <code>byte</code> to ignore.
* @exception IOException
* if an I/O error occurs.
*/
public void write(int b) throws IOException {
}
}
|
9231ac1132ae5efc4617dd08cabeab7585923768 | 4,075 | java | Java | app/src/main/java/it/and/stez78/popularmovies/app/adapter/ElementTrailerAdapter.java | stez/popularmovies-stage2 | 8e351669da8042019db701b32e35700c9ce8874e | [
"CC-BY-3.0"
] | null | null | null | app/src/main/java/it/and/stez78/popularmovies/app/adapter/ElementTrailerAdapter.java | stez/popularmovies-stage2 | 8e351669da8042019db701b32e35700c9ce8874e | [
"CC-BY-3.0"
] | null | null | null | app/src/main/java/it/and/stez78/popularmovies/app/adapter/ElementTrailerAdapter.java | stez/popularmovies-stage2 | 8e351669da8042019db701b32e35700c9ce8874e | [
"CC-BY-3.0"
] | null | null | null | 33.958333 | 101 | 0.65546 | 995,930 | package it.and.stez78.popularmovies.app.adapter;
import android.net.Uri;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import java.util.List;
import it.and.stez78.popularmovies.R;
import it.and.stez78.popularmovies.model.MovieVideo;
import it.and.stez78.popularmovies.utils.TheMovieDbUtils;
/**
* Created by stefano on 05/03/18.
*/
public class ElementTrailerAdapter extends RecyclerView.Adapter<ElementTrailerAdapter.ViewHolder> {
private static final String TAG = "ElTrailerAdapter";
private List<MovieVideo> mDataSet;
private Picasso p;
private OnItemClickListener listener;
public static class ViewHolder extends RecyclerView.ViewHolder {
private ConstraintLayout container;
private ImageView poster;
private ProgressBar progressBar;
private ImageView errorIcon;
private TextView trailerTitle;
private ImageView play;
public ViewHolder(View v) {
super(v);
container = v.findViewById(R.id.list_element_trailer_container);
poster = v.findViewById(R.id.list_element_trailer_imageview);
progressBar = v.findViewById(R.id.list_element_trailer_progbar);
errorIcon = v.findViewById(R.id.list_element_trailer_error);
trailerTitle = v.findViewById(R.id.list_element_trailer_title);
play = v.findViewById(R.id.list_element_trailer_play_imageview);
}
public ImageView getPoster() {
return poster;
}
public ProgressBar getProgressBar() {
return progressBar;
}
public ImageView getErrorIcon() {
return errorIcon;
}
public TextView getTrailerTitle() {
return trailerTitle;
}
public ImageView getPlay() {
return play;
}
public void bindItemClickListener(MovieVideo el, OnItemClickListener listener) {
container.setOnClickListener(v -> listener.onItemClick(el));
}
}
public ElementTrailerAdapter(List<MovieVideo> dataSet, Picasso p, OnItemClickListener listener) {
mDataSet = dataSet;
this.p = p;
this.listener = listener;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.list_element_trailer, viewGroup, false);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
MovieVideo el = mDataSet.get(position);
viewHolder.getProgressBar().setVisibility(View.VISIBLE);
viewHolder.getPlay().setVisibility(View.INVISIBLE);
p.load(Uri.parse(TheMovieDbUtils.getVideoThumbnailUrl(el.getKey())))
.into(viewHolder.getPoster(), new Callback() {
@Override
public void onSuccess() {
viewHolder.getProgressBar().setVisibility(View.GONE);
viewHolder.getPoster().setVisibility(View.VISIBLE);
viewHolder.getPlay().setVisibility(View.VISIBLE);
}
@Override
public void onError() {
viewHolder.getProgressBar().setVisibility(View.GONE);
viewHolder.getErrorIcon().setVisibility(View.VISIBLE);
}
});
viewHolder.getTrailerTitle().setText(el.getName());
viewHolder.getTrailerTitle().setVisibility(View.VISIBLE);
viewHolder.bindItemClickListener(el, listener);
}
@Override
public int getItemCount() {
return mDataSet.size();
}
}
|
9231ad82028b85f584157676eb4029c8ae4e6031 | 1,379 | java | Java | bio/sources/human/clinvar/test/src/org/intermine/bio/dataconversion/ClinvarConverterTest.java | chenyian-nibio/intermine | d8a5403a02b853df42f1b9f0faf2b002ade7568f | [
"PostgreSQL",
"MIT"
] | 4 | 2017-12-22T06:04:46.000Z | 2020-10-05T02:39:07.000Z | bio/sources/human/clinvar/test/src/org/intermine/bio/dataconversion/ClinvarConverterTest.java | mgijax/intermine | 1caa1cff2df438c4062e2112ac64d627fc98192c | [
"PostgreSQL"
] | 16 | 2015-10-29T15:04:16.000Z | 2021-02-08T20:16:50.000Z | bio/sources/human/clinvar/test/src/org/intermine/bio/dataconversion/ClinvarConverterTest.java | mgijax/intermine | 1caa1cff2df438c4062e2112ac64d627fc98192c | [
"PostgreSQL"
] | 5 | 2016-08-01T18:54:24.000Z | 2021-04-15T12:43:53.000Z | 31.340909 | 96 | 0.718637 | 995,931 | package org.intermine.bio.dataconversion;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.HashMap;
import java.util.Set;
import org.intermine.dataconversion.ItemsTestCase;
import org.intermine.dataconversion.MockItemWriter;
import org.intermine.metadata.Model;
import org.intermine.model.fulldata.Item;
public class ClinvarConverterTest extends ItemsTestCase
{
Model model = Model.getInstanceByName("genomic");
ClinvarConverter converter;
MockItemWriter itemWriter;
private final String currentFile = "variant_summary.txt";
public ClinvarConverterTest(String arg) {
super(arg);
}
public void setUp() throws Exception {
super.setUp();
itemWriter = new MockItemWriter(new HashMap<String, Item>());
converter = new ClinvarConverter(itemWriter, model);
}
public void testProcess() throws Exception {
Reader reader = new InputStreamReader(getClass().getClassLoader()
.getResourceAsStream(currentFile));
converter.process(reader);
converter.close();
// uncomment to write out a new target items file
//writeItemsFile(itemWriter.getItems(), "clinvar-tgt-items.xml");
Set<org.intermine.xml.full.Item> expected = readItemSet("ClinVarConverterTest_tgt.xml");
assertEquals(expected, itemWriter.getItems());
}
}
|
9231adce9e9d57002d9f36fcaf6be9548ffd1cb0 | 1,573 | java | Java | metrics-facade-base/src/main/java/com/ringcentral/platform/metrics/timer/Timer.java | ringcentral/metrics-facade | c26ee52e11bbb3603b83c0ac430c8fc9772bd70e | [
"MIT"
] | 9 | 2021-09-23T10:42:15.000Z | 2022-03-06T09:42:48.000Z | metrics-facade-base/src/main/java/com/ringcentral/platform/metrics/timer/Timer.java | ringcentral/metrics-facade | c26ee52e11bbb3603b83c0ac430c8fc9772bd70e | [
"MIT"
] | 8 | 2021-09-27T10:24:15.000Z | 2022-03-21T07:15:44.000Z | metrics-facade-base/src/main/java/com/ringcentral/platform/metrics/timer/Timer.java | ringcentral/metrics-facade | c26ee52e11bbb3603b83c0ac430c8fc9772bd70e | [
"MIT"
] | 3 | 2021-12-17T10:16:58.000Z | 2022-03-05T09:23:57.000Z | 28.6 | 94 | 0.698029 | 995,932 | package com.ringcentral.platform.metrics.timer;
import com.ringcentral.platform.metrics.Meter;
import com.ringcentral.platform.metrics.dimensions.*;
import com.ringcentral.platform.metrics.measurables.MeasurableType;
import java.util.concurrent.TimeUnit;
import static com.ringcentral.platform.metrics.dimensions.MetricDimensionValues.*;
import static com.ringcentral.platform.metrics.measurables.MeasurableType.*;
public interface Timer extends Meter {
class DurationUnit implements TimerMeasurable {
static final int HASH_CODE = "Timer.DurationUnit".hashCode();
@Override
public MeasurableType type() {
return STRING;
}
@Override
public boolean equals(Object other) {
return this == other || (other != null && getClass() == other.getClass());
}
@Override
public int hashCode() {
return HASH_CODE;
}
}
DurationUnit DURATION_UNIT = new DurationUnit();
default void update(long duration) {
update(duration, NO_DIMENSION_VALUES);
}
default void update(long duration, TimeUnit unit) {
update(duration, unit, NO_DIMENSION_VALUES);
}
default void update(long duration, TimeUnit unit, MetricDimensionValues dimensionValues) {
update(unit.toNanos(duration), dimensionValues);
}
void update(long duration, MetricDimensionValues dimensionValues);
default Stopwatch stopwatch() {
return stopwatch(null);
}
Stopwatch stopwatch(MetricDimensionValues dimensionValues);
}
|
9231b083058bd594ec5fc052c1d61b81a705e9fd | 14,285 | java | Java | core/src/main/java/com/dianaui/universal/core/client/ui/base/form/AbstractForm.java | donbeave/dianaui-universal | dc46008eb1c902bf3e9039f6ff92f4a1489c8fd9 | [
"Apache-2.0"
] | null | null | null | core/src/main/java/com/dianaui/universal/core/client/ui/base/form/AbstractForm.java | donbeave/dianaui-universal | dc46008eb1c902bf3e9039f6ff92f4a1489c8fd9 | [
"Apache-2.0"
] | null | null | null | core/src/main/java/com/dianaui/universal/core/client/ui/base/form/AbstractForm.java | donbeave/dianaui-universal | dc46008eb1c902bf3e9039f6ff92f4a1489c8fd9 | [
"Apache-2.0"
] | null | null | null | 30.20296 | 144 | 0.612418 | 995,933 | /*
* #%L
* Diana UI Core
* %%
* Copyright (C) 2014 Diana UI
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.dianaui.universal.core.client.ui.base.form;
import com.dianaui.universal.core.client.ui.constants.Attributes;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.FormElement;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.safehtml.client.SafeHtmlTemplates;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeUri;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.impl.FormPanelImpl;
import com.google.gwt.user.client.ui.impl.FormPanelImplHost;
/**
* @author Sven Jacobs
* @author Dominik Mayer
* @author ohashi keisuke
* @author <a href='mailto:dycjh@example.com'>Alexey Zhokhov</a>
*/
public abstract class AbstractForm extends FormElementContainer implements FormPanelImplHost {
/**
* Fired when a form has been submitted successfully.
*/
public static class SubmitCompleteEvent extends GwtEvent<SubmitCompleteHandler> {
/**
* The event type.
*/
private static Type<SubmitCompleteHandler> TYPE;
/**
* Handler hook.
*
* @return the handler hook
*/
public static Type<SubmitCompleteHandler> getType() {
if (TYPE == null)
TYPE = new Type<SubmitCompleteHandler>();
return TYPE;
}
private final String resultHtml;
/**
* Create a submit complete event.
*
* @param resultsHtml the results from submitting the form
*/
protected SubmitCompleteEvent(String resultsHtml) {
this.resultHtml = resultsHtml;
}
@Override
public final Type<SubmitCompleteHandler> getAssociatedType() {
return getType();
}
/**
* Gets the result text of the form submission.
*
* @return the result html, or <code>null</code> if there was an error
* reading it
* @tip The result html can be <code>null</code> as a result of
* submitting a form to a different domain.
*/
public String getResults() {
return resultHtml;
}
@Override
protected void dispatch(SubmitCompleteHandler handler) {
handler.onSubmitComplete(this);
}
}
/**
* Handler for {@link SubmitCompleteEvent} events.
*/
public interface SubmitCompleteHandler extends EventHandler {
/**
* Fired when a form has been submitted successfully.
*
* @param event the event
*/
void onSubmitComplete(SubmitCompleteEvent event);
}
/**
* Fired when the form is submitted.
*/
public static class SubmitEvent extends GwtEvent<SubmitHandler> {
/**
* The event type.
*/
private static Type<SubmitHandler> TYPE;
/**
* Handler hook.
*
* @return the handler hook
*/
public static Type<SubmitHandler> getType() {
if (TYPE == null)
TYPE = new Type<SubmitHandler>();
return TYPE;
}
private boolean canceled = false;
/**
* Cancel the form submit. Firing this will prevent a subsequent
* {@link SubmitCompleteEvent} from being fired.
*/
public void cancel() {
this.canceled = true;
}
@Override
public final Type<SubmitHandler> getAssociatedType() {
return getType();
}
/**
* Gets whether this form submit will be canceled.
*
* @return <code>true</code> if the form submit will be canceled
*/
public boolean isCanceled() {
return canceled;
}
@Override
protected void dispatch(SubmitHandler handler) {
handler.onSubmit(this);
}
/**
* This method is used for legacy support and should be removed when
* {@link FormHandler} is removed.
*
* @deprecated Use {@link com.google.gwt.user.client.ui.FormPanel.SubmitEvent#cancel()} instead
*/
@Deprecated
void setCanceled(boolean canceled) {
this.canceled = canceled;
}
}
/**
* Handler for {@link com.google.gwt.user.client.ui.FormPanel.SubmitEvent} events.
*/
public interface SubmitHandler extends EventHandler {
/**
* Fired when the form is submitted.
* <p/>
* <p>
* The FormPanel must <em>not</em> be detached (i.e. removed from its
* parent or otherwise disconnected from a {@link RootPanel}) until the
* submission is complete. Otherwise, notification of submission will
* fail.
* </p>
*
* @param event the event
*/
void onSubmit(SubmitEvent event);
}
interface IFrameTemplate extends SafeHtmlTemplates {
static final IFrameTemplate INSTANCE = GWT.create(IFrameTemplate.class);
@Template("<iframe src=\"javascript:''\" name='{0}' tabindex='-1' "
+ "style='position:absolute;width:0;height:0;border:0'>")
SafeHtml get(String name);
}
private static final String FORM = "form";
private static int formId = 0;
private static final FormPanelImpl impl = GWT.create(FormPanelImpl.class);
private String frameName;
private Element synthesizedFrame;
public AbstractForm() {
this(true);
}
public AbstractForm(boolean createIFrame) {
this(Document.get().createFormElement(), createIFrame);
getElement().setAttribute(Attributes.ROLE, FORM);
}
/**
* This constructor may be used by subclasses to explicitly use an existing
* element. This element must be a <form> element.
* <p>
* If the createIFrame parameter is set to <code>true</code>, then the
* wrapped form's target attribute will be set to a hidden iframe. If not,
* the form's target will be left alone, and the FormSubmitComplete event
* will not be fired.
* </p>
*
* @param element the element to be used
* @param createIFrame <code>true</code> to create an <iframe> element that
* will be targeted by this form
*/
protected AbstractForm(Element element, boolean createIFrame) {
setElement(element);
FormElement.as(element);
if (createIFrame) {
assert getTarget() == null || getTarget().trim().length() == 0 : "Cannot create target iframe if the form's target is already set.";
// We use the module name as part of the unique ID to ensure that
// ids are
// unique across modules.
frameName = "FormPanel_" + GWT.getModuleName() + "_" + (++formId);
setTarget(frameName);
sinkEvents(Event.ONLOAD);
}
}
@Override
protected void onAttach() {
super.onAttach();
if (frameName != null) {
// Create and attach a hidden iframe to the body element.
createFrame();
Document.get().getBody().appendChild(synthesizedFrame);
}
// Hook up the underlying iframe's onLoad event when attached to the
// DOM.
// Making this connection only when attached avoids memory-leak issues.
// The FormPanel cannot use the built-in GWT event-handling mechanism
// because there is no standard onLoad event on iframes that works
// across
// browsers.
impl.hookEvents(synthesizedFrame, getElement(), this);
}
@Override
protected void onDetach() {
super.onDetach();
// Unhook the iframe's onLoad when detached.
impl.unhookEvents(synthesizedFrame, getElement());
if (synthesizedFrame != null) {
// And remove it from the document.
Document.get().getBody().removeChild(synthesizedFrame);
synthesizedFrame = null;
}
}
@Override
public boolean onFormSubmit() {
return onFormSubmitImpl();
}
@Override
public void onFrameLoad() {
onFrameLoadImpl();
}
/**
* Adds a {@link SubmitCompleteEvent} handler.
*
* @param handler the handler
* @return the handler registration used to remove the handler
*/
public HandlerRegistration addSubmitCompleteHandler(SubmitCompleteHandler handler) {
return addHandler(handler, SubmitCompleteEvent.getType());
}
/**
* Adds a {@link SubmitEvent} handler.
*
* @param handler the handler
* @return the handler registration used to remove the handler
*/
public HandlerRegistration addSubmitHandler(SubmitHandler handler) {
return addHandler(handler, SubmitEvent.getType());
}
/**
* Gets the 'action' associated with this form. This is the URL to which it
* will be submitted.
*
* @return the form's action
*/
public String getAction() {
return getFormElement().getAction();
}
/**
* Sets the 'action' associated with this form. This is the URL to which it
* will be submitted.
*
* @param url the form's action
*/
public void setAction(final String action) {
getFormElement().setAction(action);
}
/**
* Sets the 'action' associated with this form. This is the URL to which it
* will be submitted.
*
* @param url the form's action
*/
public void setAction(SafeUri url) {
getFormElement().setAction(url);
}
/**
* Gets the HTTP method used for submitting this form. This should be either
* {@link #METHOD_GET} or {@link #METHOD_POST}.
*
* @return the form's method
*/
public String getMethod() {
return getFormElement().getMethod();
}
/**
* Sets the HTTP method used for submitting this form. This should be either
* {@link #METHOD_GET} or {@link #METHOD_POST}.
*
* @param method the form's method
*/
public void setMethod(final String method) {
getFormElement().setMethod(method);
}
/**
* Gets the form's 'target'. This is the name of the {@link NamedFrame} that
* will receive the results of submission, or <code>null</code> if none has
* been specified.
*
* @return the form's target.
*/
public String getTarget() {
return getFormElement().getTarget();
}
/**
* Gets the encoding used for submitting this form. This should be either
* {@link #ENCODING_MULTIPART} or {@link #ENCODING_URLENCODED}.
*
* @return the form's encoding
*/
public String getEncoding() {
return impl.getEncoding(getElement());
}
/**
* Sets the encoding used for submitting this form. This should be either
* {@link #ENCODING_MULTIPART} or {@link #ENCODING_URLENCODED}.
*
* @param encodingType the form's encoding
*/
public void setEncoding(String encodingType) {
impl.setEncoding(getElement(), encodingType);
}
/**
* Submits form
*/
public void submit() {
// Fire the onSubmit event, because javascript's form.submit() does not
// fire the built-in onsubmit event.
if (!fireSubmitEvent()) {
return;
}
impl.submit(getElement(), synthesizedFrame);
}
/**
* Resets form
*/
public void reset() {
impl.reset(getElement());
}
private void createFrame() {
// Attach a hidden IFrame to the form. This is the target iframe to
// which the form will be submitted. We have to create the iframe using
// innerHTML, because setting an iframe's 'name' property dynamically
// doesn't work on most browsers.
Element dummy = Document.get().createDivElement();
dummy.setInnerSafeHtml(IFrameTemplate.INSTANCE.get(frameName));
synthesizedFrame = dummy.getFirstChildElement();
}
/**
* Fire a {@link com.google.gwt.user.client.ui.FormPanel.SubmitEvent}.
*
* @return true to continue, false if canceled
*/
private boolean fireSubmitEvent() {
FormPanel.SubmitEvent event = new FormPanel.SubmitEvent();
fireEvent(event);
return !event.isCanceled();
}
FormElement getFormElement() {
return FormElement.as(getElement());
}
/**
* Returns true if the form is submitted, false if canceled.
*/
private boolean onFormSubmitImpl() {
return fireSubmitEvent();
}
private void onFrameLoadImpl() {
// Fire onComplete events in a deferred command. This is necessary
// because clients that detach the form panel when submission is
// complete can cause some browsers (i.e. Mozilla) to go into an
// 'infinite loading' state. See issue 916.
Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
@Override
public void execute() {
fireEvent(new SubmitCompleteEvent(impl
.getContents(synthesizedFrame)));
}
});
}
private void setTarget(String target) {
getFormElement().setTarget(target);
}
}
|
9231b11814c1719950dc89bbd9b780685a1e0bc7 | 2,958 | java | Java | src/main/java/com/xthena/gcgl/domain/PjSubmit.java | jianbingfang/xhf | a9f008c904943e8a2cbed9c67e03e5c18c659444 | [
"Apache-2.0"
] | 2 | 2015-09-16T12:23:50.000Z | 2015-09-26T04:31:19.000Z | src/main/java/com/xthena/gcgl/domain/PjSubmit.java | jianbingfang/xhf | a9f008c904943e8a2cbed9c67e03e5c18c659444 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/xthena/gcgl/domain/PjSubmit.java | jianbingfang/xhf | a9f008c904943e8a2cbed9c67e03e5c18c659444 | [
"Apache-2.0"
] | 5 | 2015-09-26T00:59:09.000Z | 2018-08-07T08:57:53.000Z | 19.986486 | 128 | 0.622718 | 995,934 | package com.xthena.gcgl.domain;
// default package
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* PjSubmit entity. @author MyEclipse Persistence Tools
*/
@Entity
@Table(name="t_pj_submit"
,catalog="xhf"
)
public class PjSubmit implements java.io.Serializable {
// Fields
private Long fid;
private Long fxmid;
private String fjiangx;
private String fry;
private Date fsubdate;
private Long fyijiaorenid;
private String fmemo;
private String fyijiaoren;
// Constructors
/** default constructor */
public PjSubmit() {
}
/** full constructor */
public PjSubmit(Long fxmid, String fjiangx, String fry, Date fsubdate, Long fyijiaorenid, String fmemo, String fyijiaoren) {
this.fxmid = fxmid;
this.fjiangx = fjiangx;
this.fry = fry;
this.fsubdate = fsubdate;
this.fyijiaorenid = fyijiaorenid;
this.fmemo = fmemo;
this.fyijiaoren = fyijiaoren;
}
// Property accessors
@Id @GeneratedValue(strategy=IDENTITY)
@Column(name="fid", unique=true, nullable=false)
public Long getFid() {
return this.fid;
}
public void setFid(Long fid) {
this.fid = fid;
}
@Column(name="fxmid")
public Long getFxmid() {
return this.fxmid;
}
public void setFxmid(Long fxmid) {
this.fxmid = fxmid;
}
@Column(name="fjiangx", length=64)
public String getFjiangx() {
return this.fjiangx;
}
public void setFjiangx(String fjiangx) {
this.fjiangx = fjiangx;
}
@Column(name="fry", length=500)
public String getFry() {
return this.fry;
}
public void setFry(String fry) {
this.fry = fry;
}
@Temporal(TemporalType.DATE)
@Column(name="fsubdate", length=10)
public Date getFsubdate() {
return this.fsubdate;
}
public void setFsubdate(Date fsubdate) {
this.fsubdate = fsubdate;
}
@Column(name="fyijiaorenid")
public Long getFyijiaorenid() {
return this.fyijiaorenid;
}
public void setFyijiaorenid(Long fyijiaorenid) {
this.fyijiaorenid = fyijiaorenid;
}
@Column(name="fmemo", length=500)
public String getFmemo() {
return this.fmemo;
}
public void setFmemo(String fmemo) {
this.fmemo = fmemo;
}
@Column(name="fyijiaoren", length=64)
public String getFyijiaoren() {
return this.fyijiaoren;
}
public void setFyijiaoren(String fyijiaoren) {
this.fyijiaoren = fyijiaoren;
}
} |
9231b125f58ef08ae588df45dce4c201d860c709 | 648 | java | Java | GEP-Components/framework/processor/message-processor/src/main/java/com/esri/ges/processor/message/MessageDefinition.java | tmatinde/route-monitor-for-geoevent | ea9483760e2782d86ea14d3f54ad9c50128bbb21 | [
"Apache-2.0"
] | null | null | null | GEP-Components/framework/processor/message-processor/src/main/java/com/esri/ges/processor/message/MessageDefinition.java | tmatinde/route-monitor-for-geoevent | ea9483760e2782d86ea14d3f54ad9c50128bbb21 | [
"Apache-2.0"
] | null | null | null | GEP-Components/framework/processor/message-processor/src/main/java/com/esri/ges/processor/message/MessageDefinition.java | tmatinde/route-monitor-for-geoevent | ea9483760e2782d86ea14d3f54ad9c50128bbb21 | [
"Apache-2.0"
] | null | null | null | 18.514286 | 76 | 0.737654 | 995,935 | package com.esri.ges.processor.message;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.esri.ges.processor.GeoEventProcessorDefinitionBase;
public class MessageDefinition extends GeoEventProcessorDefinitionBase
{
final private static Log LOG = LogFactory.getLog(MessageDefinition.class);
public MessageDefinition()
{
}
@Override
public String getName()
{
return "MessageProcessor";
}
@Override
public String getLabel()
{
return "MessageProcessor";
}
@Override
public String getDescription()
{
return "Performs operations on messages.";
}
}
|
9231b3932c7d886ae3be2f956e696e8b81505d38 | 1,159 | java | Java | src/main/java/com/aaa/project/system/evaluation/mapper/EvaluationMapper.java | xrqccjjyy/ccyx | 30960020244a6e6cf3a983c8c776ebfc17acfbe2 | [
"MIT"
] | null | null | null | src/main/java/com/aaa/project/system/evaluation/mapper/EvaluationMapper.java | xrqccjjyy/ccyx | 30960020244a6e6cf3a983c8c776ebfc17acfbe2 | [
"MIT"
] | 2 | 2021-04-22T16:53:32.000Z | 2021-09-20T20:50:48.000Z | src/main/java/com/aaa/project/system/evaluation/mapper/EvaluationMapper.java | xrqccjjyy/ccyx | 30960020244a6e6cf3a983c8c776ebfc17acfbe2 | [
"MIT"
] | null | null | null | 18.693548 | 69 | 0.6195 | 995,936 | package com.aaa.project.system.evaluation.mapper;
import com.aaa.project.system.evaluation.domain.Evaluation;
import java.util.List;
/**
* 客户评价/投诉 数据层
*
* @author teacherChen
* @date 2019-07-29
*/
public interface EvaluationMapper
{
/**
* 查询客户评价/投诉信息
*
* @param clientid 客户评价/投诉ID
* @return 客户评价/投诉信息
*/
public Evaluation selectEvaluationById(Integer clientid);
/**
* 查询客户评价/投诉列表
*
* @param evaluation 客户评价/投诉信息
* @return 客户评价/投诉集合
*/
public List<Evaluation> selectEvaluationList(Evaluation evaluation);
/**
* 新增客户评价/投诉
*
* @param evaluation 客户评价/投诉信息
* @return 结果
*/
public int insertEvaluation(Evaluation evaluation);
/**
* 修改客户评价/投诉
*
* @param evaluation 客户评价/投诉信息
* @return 结果
*/
public int updateEvaluation(Evaluation evaluation);
/**
* 删除客户评价/投诉
*
* @param clientid 客户评价/投诉ID
* @return 结果
*/
public int deleteEvaluationById(Integer clientid);
/**
* 批量删除客户评价/投诉
*
* @param clientids 需要删除的数据ID
* @return 结果
*/
public int deleteEvaluationByIds(String[] clientids);
} |
9231b3ad60d06e454fe79a4faf9bc60a11af0480 | 7,961 | java | Java | wdtk-wikibaseapi/src/test/java/org/wikidata/wdtk/wikibaseapi/WikibaseDataFetcherTest.java | GlorimarCastro/glorimar-wikidata-toolkit | 8b0cf3a5fa892f8b0ab43a1b09411c7f6560f6ac | [
"Apache-2.0"
] | null | null | null | wdtk-wikibaseapi/src/test/java/org/wikidata/wdtk/wikibaseapi/WikibaseDataFetcherTest.java | GlorimarCastro/glorimar-wikidata-toolkit | 8b0cf3a5fa892f8b0ab43a1b09411c7f6560f6ac | [
"Apache-2.0"
] | null | null | null | wdtk-wikibaseapi/src/test/java/org/wikidata/wdtk/wikibaseapi/WikibaseDataFetcherTest.java | GlorimarCastro/glorimar-wikidata-toolkit | 8b0cf3a5fa892f8b0ab43a1b09411c7f6560f6ac | [
"Apache-2.0"
] | null | null | null | 33.170833 | 193 | 0.756061 | 995,937 | package org.wikidata.wdtk.wikibaseapi;
/*
* #%L
* Wikidata Toolkit Wikibase API
* %%
* Copyright (C) 2014 - 2015 Wikidata Toolkit Developers
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.wikidata.wdtk.datamodel.helpers.Datamodel;
import org.wikidata.wdtk.datamodel.interfaces.EntityDocument;
import org.wikidata.wdtk.datamodel.interfaces.PropertyIdValue;
import org.wikidata.wdtk.testing.MockWebResourceFetcher;
public class WikibaseDataFetcherTest {
@Test
public void testWbGetEntities() throws IOException {
List<String> entityIds = Arrays.asList("Q6", "Q42", "P31");
WikibaseDataFetcher wdf = new WikibaseDataFetcher();
MockWebResourceFetcher wrf = new MockWebResourceFetcher();
wrf.setWebResourceContentsFromResource(
wdf.getWbGetEntitiesUrl(entityIds),
"/wbgetentities-Q6-Q42-P31.json", this.getClass());
wdf.webResourceFetcher = wrf;
Map<String, EntityDocument> results = wdf.getEntityDocuments("Q6",
"Q42", "P31");
assertEquals(2, results.size());
assertFalse(results.containsKey("Q6"));
assertTrue(results.containsKey("Q42"));
assertTrue(results.containsKey("P31"));
}
@Test
public void testGetEntityDocument() throws IOException {
List<String> entityIds = Arrays.asList("Q42");
WikibaseDataFetcher wdf = new WikibaseDataFetcher();
// We use the mock answer as for a multi request; no problem
MockWebResourceFetcher wrf = new MockWebResourceFetcher();
wrf.setWebResourceContentsFromResource(
wdf.getWbGetEntitiesUrl(entityIds),
"/wbgetentities-Q6-Q42-P31.json", this.getClass());
wdf.webResourceFetcher = wrf;
EntityDocument result = wdf.getEntityDocument("Q42");
assertTrue(result != null);
}
@Test
public void testGetMissingEntityDocument() throws IOException {
List<String> entityIds = Arrays.asList("Q6");
WikibaseDataFetcher wdf = new WikibaseDataFetcher();
// We use the mock answer as for a multi request; no problem
MockWebResourceFetcher wrf = new MockWebResourceFetcher();
wrf.setWebResourceContentsFromResource(
wdf.getWbGetEntitiesUrl(entityIds),
"/wbgetentities-Q6-Q42-P31.json", this.getClass());
wdf.webResourceFetcher = wrf;
EntityDocument result = wdf.getEntityDocument("Q6");
assertTrue(result == null);
}
@Test
public void testWbGetEntitiesError() throws IOException {
List<String> entityIds = Arrays.asList("bogus");
WikibaseDataFetcher wdf = new WikibaseDataFetcher();
MockWebResourceFetcher wrf = new MockWebResourceFetcher();
wrf.setWebResourceContentsFromResource(
wdf.getWbGetEntitiesUrl(entityIds),
"/wbgetentities-bogus.json", this.getClass());
wdf.webResourceFetcher = wrf;
Map<String, EntityDocument> results = wdf.getEntityDocuments("bogus");
assertEquals(0, results.size());
}
@Test
public void testWbGetEntitiesEmpty() throws IOException {
MockWebResourceFetcher wrf = new MockWebResourceFetcher();
WikibaseDataFetcher wdf = new WikibaseDataFetcher();
wdf.webResourceFetcher = wrf;
Map<String, EntityDocument> results = wdf
.getEntityDocuments(Collections.<String> emptyList());
assertEquals(0, results.size());
}
@Test
public void testWbGetEntitiesNoWebAccess() throws IOException {
MockWebResourceFetcher wrf = new MockWebResourceFetcher();
wrf.setReturnFailingReaders(true);
WikibaseDataFetcher wdf = new WikibaseDataFetcher();
wdf.webResourceFetcher = wrf;
Map<String, EntityDocument> results = wdf.getEntityDocuments("Q6",
"Q42", "P31");
// No data mocked, no results (but also no exception thrown)
assertEquals(0, results.size());
}
@Test
public void testWbGetEntitiesApiUrlError() throws IOException {
MockWebResourceFetcher wrf = new MockWebResourceFetcher();
WikibaseDataFetcher wdf = new WikibaseDataFetcher("invalid URL",
Datamodel.SITE_WIKIDATA);
wdf.webResourceFetcher = wrf;
Map<String, EntityDocument> results = wdf.getEntityDocuments("Q6",
"Q42", "P31");
assertEquals(0, results.size());
}
@Test
public void testWbGetEntitiesUrl() throws IOException {
List<String> entityIds = Arrays.asList("Q6", "Q42", "P31");
WikibaseDataFetcher wdf = new WikibaseDataFetcher();
assertEquals(
"http://www.wikidata.org/w/api.php?action=wbgetentities&format=json&props=datatype%7Clabels%7Caliases%7Cdescriptions%7Cclaims%7Csitelinks&ids=Q6%7CQ42%7CP31",
wdf.getWbGetEntitiesUrl(entityIds));
}
@Test
public void testWbGetEntitiesUrlTitle() throws IOException {
List<String> titles = Collections
.<String> singletonList("Douglas Adams");
String siteKey = "enwiki";
WikibaseDataFetcher wdf = new WikibaseDataFetcher();
assertEquals(
"http://www.wikidata.org/w/api.php?action=wbgetentities&format=json&props=datatype%7Clabels%7Caliases%7Cdescriptions%7Cclaims%7Csitelinks&sites=enwiki&titles=Douglas+Adams",
wdf.getWbGetEntitiesUrl(siteKey, titles));
}
@Test
public void testWbGetEntitiesTitle() throws IOException {
WikibaseDataFetcher wdf = new WikibaseDataFetcher();
MockWebResourceFetcher wrf = new MockWebResourceFetcher();
wrf.setWebResourceContentsFromResource(
wdf.getWbGetEntitiesUrl("enwiki",
Collections.<String> singletonList("Douglas Adams")),
"/wbgetentities-Douglas-Adams.json", this.getClass());
wdf.webResourceFetcher = wrf;
EntityDocument result = wdf
.getEntityDocumentByTitle("enwiki", "Douglas Adams");
assertEquals("Q42", result.getEntityId().getId());
}
@Test
public void testWbGetEntitiesTitleEmpty() throws IOException {
WikibaseDataFetcher wdf = new WikibaseDataFetcher();
MockWebResourceFetcher wrf = new MockWebResourceFetcher();
wrf.setWebResourceContentsFromResource(
wdf.getWbGetEntitiesUrl("dewiki",
Collections.<String> singletonList("1234567890")),
"/wbgetentities-1234567890-missing.json", this.getClass());
wdf.webResourceFetcher = wrf;
EntityDocument result = wdf.getEntityDocumentByTitle("dewiki", "1234567890");
assertEquals(null, result);
}
@Test
public void testWbGetEntitiesUrlFilterAll() throws IOException {
List<String> entityIds = Arrays.asList("Q6", "Q42", "P31");
WikibaseDataFetcher wdf = new WikibaseDataFetcher();
wdf.getFilter().setLanguageFilter(Collections.<String> emptySet());
wdf.getFilter().setPropertyFilter(
Collections.<PropertyIdValue> emptySet());
wdf.getFilter().setSiteLinkFilter(Collections.<String> emptySet());
assertEquals(
"http://www.wikidata.org/w/api.php?action=wbgetentities&format=json&props=datatype&ids=Q6%7CQ42%7CP31",
wdf.getWbGetEntitiesUrl(entityIds));
}
@Test
public void testWbGetEntitiesUrlFilterSome() throws IOException {
List<String> entityIds = Arrays.asList("Q6", "Q42", "P31");
WikibaseDataFetcher wdf = new WikibaseDataFetcher();
wdf.getFilter().setLanguageFilter(Collections.<String> singleton("zh"));
wdf.getFilter().setSiteLinkFilter(
Collections.<String> singleton("dewiki"));
assertEquals(
"http://www.wikidata.org/w/api.php?action=wbgetentities&format=json&props=datatype%7Clabels%7Caliases%7Cdescriptions%7Cclaims%7Csitelinks&languages=zh&sitefilter=dewiki&ids=Q6%7CQ42%7CP31",
wdf.getWbGetEntitiesUrl(entityIds));
}
}
|
9231b420468771238d000fd934f778239b47c82a | 14,213 | java | Java | easy_core/src/main/java/com/uwei/easy_core/QueryCacheGrpc.java | zhuwenshen/YCSB-TS | d09f1a22b0fe7707af47725a8c55609b6cbaf4bf | [
"Apache-2.0"
] | null | null | null | easy_core/src/main/java/com/uwei/easy_core/QueryCacheGrpc.java | zhuwenshen/YCSB-TS | d09f1a22b0fe7707af47725a8c55609b6cbaf4bf | [
"Apache-2.0"
] | null | null | null | easy_core/src/main/java/com/uwei/easy_core/QueryCacheGrpc.java | zhuwenshen/YCSB-TS | d09f1a22b0fe7707af47725a8c55609b6cbaf4bf | [
"Apache-2.0"
] | null | null | null | 40.149718 | 152 | 0.722508 | 995,938 | package com.uwei.easy_core;
import static io.grpc.MethodDescriptor.generateFullMethodName;
import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ClientCalls.asyncClientStreamingCall;
import static io.grpc.stub.ClientCalls.asyncServerStreamingCall;
import static io.grpc.stub.ClientCalls.asyncUnaryCall;
import static io.grpc.stub.ClientCalls.blockingServerStreamingCall;
import static io.grpc.stub.ClientCalls.blockingUnaryCall;
import static io.grpc.stub.ClientCalls.futureUnaryCall;
import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ServerCalls.asyncClientStreamingCall;
import static io.grpc.stub.ServerCalls.asyncServerStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnaryCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;
/**
*/
@javax.annotation.Generated(
value = "by gRPC proto compiler (version 1.23.0)",
comments = "Source: query_cache.proto")
public final class QueryCacheGrpc {
private QueryCacheGrpc() {}
public static final String SERVICE_NAME = "query_cache.QueryCache";
// Static method descriptors that strictly reflect the proto.
private static volatile io.grpc.MethodDescriptor<com.uwei.easy_core.QueryCacheProto.CreateRequest,
com.uwei.easy_core.QueryCacheProto.CreateResponse> getCreateMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "create",
requestType = com.uwei.easy_core.QueryCacheProto.CreateRequest.class,
responseType = com.uwei.easy_core.QueryCacheProto.CreateResponse.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<com.uwei.easy_core.QueryCacheProto.CreateRequest,
com.uwei.easy_core.QueryCacheProto.CreateResponse> getCreateMethod() {
io.grpc.MethodDescriptor<com.uwei.easy_core.QueryCacheProto.CreateRequest, com.uwei.easy_core.QueryCacheProto.CreateResponse> getCreateMethod;
if ((getCreateMethod = QueryCacheGrpc.getCreateMethod) == null) {
synchronized (QueryCacheGrpc.class) {
if ((getCreateMethod = QueryCacheGrpc.getCreateMethod) == null) {
QueryCacheGrpc.getCreateMethod = getCreateMethod =
io.grpc.MethodDescriptor.<com.uwei.easy_core.QueryCacheProto.CreateRequest, com.uwei.easy_core.QueryCacheProto.CreateResponse>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "create"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
com.uwei.easy_core.QueryCacheProto.CreateRequest.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
com.uwei.easy_core.QueryCacheProto.CreateResponse.getDefaultInstance()))
.setSchemaDescriptor(new QueryCacheMethodDescriptorSupplier("create"))
.build();
}
}
}
return getCreateMethod;
}
private static volatile io.grpc.MethodDescriptor<com.uwei.easy_core.QueryCacheProto.GetAllRequest,
com.uwei.easy_core.QueryCacheProto.GetAllResponse> getGetAllMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "get_all",
requestType = com.uwei.easy_core.QueryCacheProto.GetAllRequest.class,
responseType = com.uwei.easy_core.QueryCacheProto.GetAllResponse.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<com.uwei.easy_core.QueryCacheProto.GetAllRequest,
com.uwei.easy_core.QueryCacheProto.GetAllResponse> getGetAllMethod() {
io.grpc.MethodDescriptor<com.uwei.easy_core.QueryCacheProto.GetAllRequest, com.uwei.easy_core.QueryCacheProto.GetAllResponse> getGetAllMethod;
if ((getGetAllMethod = QueryCacheGrpc.getGetAllMethod) == null) {
synchronized (QueryCacheGrpc.class) {
if ((getGetAllMethod = QueryCacheGrpc.getGetAllMethod) == null) {
QueryCacheGrpc.getGetAllMethod = getGetAllMethod =
io.grpc.MethodDescriptor.<com.uwei.easy_core.QueryCacheProto.GetAllRequest, com.uwei.easy_core.QueryCacheProto.GetAllResponse>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "get_all"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
com.uwei.easy_core.QueryCacheProto.GetAllRequest.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
com.uwei.easy_core.QueryCacheProto.GetAllResponse.getDefaultInstance()))
.setSchemaDescriptor(new QueryCacheMethodDescriptorSupplier("get_all"))
.build();
}
}
}
return getGetAllMethod;
}
/**
* Creates a new async stub that supports all call types for the service
*/
public static QueryCacheStub newStub(io.grpc.Channel channel) {
return new QueryCacheStub(channel);
}
/**
* Creates a new blocking-style stub that supports unary and streaming output calls on the service
*/
public static QueryCacheBlockingStub newBlockingStub(
io.grpc.Channel channel) {
return new QueryCacheBlockingStub(channel);
}
/**
* Creates a new ListenableFuture-style stub that supports unary calls on the service
*/
public static QueryCacheFutureStub newFutureStub(
io.grpc.Channel channel) {
return new QueryCacheFutureStub(channel);
}
/**
*/
public static abstract class QueryCacheImplBase implements io.grpc.BindableService {
/**
*/
public void create(com.uwei.easy_core.QueryCacheProto.CreateRequest request,
io.grpc.stub.StreamObserver<com.uwei.easy_core.QueryCacheProto.CreateResponse> responseObserver) {
asyncUnimplementedUnaryCall(getCreateMethod(), responseObserver);
}
/**
*/
public void getAll(com.uwei.easy_core.QueryCacheProto.GetAllRequest request,
io.grpc.stub.StreamObserver<com.uwei.easy_core.QueryCacheProto.GetAllResponse> responseObserver) {
asyncUnimplementedUnaryCall(getGetAllMethod(), responseObserver);
}
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
.addMethod(
getCreateMethod(),
asyncUnaryCall(
new MethodHandlers<
com.uwei.easy_core.QueryCacheProto.CreateRequest,
com.uwei.easy_core.QueryCacheProto.CreateResponse>(
this, METHODID_CREATE)))
.addMethod(
getGetAllMethod(),
asyncUnaryCall(
new MethodHandlers<
com.uwei.easy_core.QueryCacheProto.GetAllRequest,
com.uwei.easy_core.QueryCacheProto.GetAllResponse>(
this, METHODID_GET_ALL)))
.build();
}
}
/**
*/
public static final class QueryCacheStub extends io.grpc.stub.AbstractStub<QueryCacheStub> {
private QueryCacheStub(io.grpc.Channel channel) {
super(channel);
}
private QueryCacheStub(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected QueryCacheStub build(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
return new QueryCacheStub(channel, callOptions);
}
/**
*/
public void create(com.uwei.easy_core.QueryCacheProto.CreateRequest request,
io.grpc.stub.StreamObserver<com.uwei.easy_core.QueryCacheProto.CreateResponse> responseObserver) {
asyncUnaryCall(
getChannel().newCall(getCreateMethod(), getCallOptions()), request, responseObserver);
}
/**
*/
public void getAll(com.uwei.easy_core.QueryCacheProto.GetAllRequest request,
io.grpc.stub.StreamObserver<com.uwei.easy_core.QueryCacheProto.GetAllResponse> responseObserver) {
asyncUnaryCall(
getChannel().newCall(getGetAllMethod(), getCallOptions()), request, responseObserver);
}
}
/**
*/
public static final class QueryCacheBlockingStub extends io.grpc.stub.AbstractStub<QueryCacheBlockingStub> {
private QueryCacheBlockingStub(io.grpc.Channel channel) {
super(channel);
}
private QueryCacheBlockingStub(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected QueryCacheBlockingStub build(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
return new QueryCacheBlockingStub(channel, callOptions);
}
/**
*/
public com.uwei.easy_core.QueryCacheProto.CreateResponse create(com.uwei.easy_core.QueryCacheProto.CreateRequest request) {
return blockingUnaryCall(
getChannel(), getCreateMethod(), getCallOptions(), request);
}
/**
*/
public com.uwei.easy_core.QueryCacheProto.GetAllResponse getAll(com.uwei.easy_core.QueryCacheProto.GetAllRequest request) {
return blockingUnaryCall(
getChannel(), getGetAllMethod(), getCallOptions(), request);
}
}
/**
*/
public static final class QueryCacheFutureStub extends io.grpc.stub.AbstractStub<QueryCacheFutureStub> {
private QueryCacheFutureStub(io.grpc.Channel channel) {
super(channel);
}
private QueryCacheFutureStub(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected QueryCacheFutureStub build(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
return new QueryCacheFutureStub(channel, callOptions);
}
/**
*/
public com.google.common.util.concurrent.ListenableFuture<com.uwei.easy_core.QueryCacheProto.CreateResponse> create(
com.uwei.easy_core.QueryCacheProto.CreateRequest request) {
return futureUnaryCall(
getChannel().newCall(getCreateMethod(), getCallOptions()), request);
}
/**
*/
public com.google.common.util.concurrent.ListenableFuture<com.uwei.easy_core.QueryCacheProto.GetAllResponse> getAll(
com.uwei.easy_core.QueryCacheProto.GetAllRequest request) {
return futureUnaryCall(
getChannel().newCall(getGetAllMethod(), getCallOptions()), request);
}
}
private static final int METHODID_CREATE = 0;
private static final int METHODID_GET_ALL = 1;
private static final class MethodHandlers<Req, Resp> implements
io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
private final QueryCacheImplBase serviceImpl;
private final int methodId;
MethodHandlers(QueryCacheImplBase serviceImpl, int methodId) {
this.serviceImpl = serviceImpl;
this.methodId = methodId;
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
case METHODID_CREATE:
serviceImpl.create((com.uwei.easy_core.QueryCacheProto.CreateRequest) request,
(io.grpc.stub.StreamObserver<com.uwei.easy_core.QueryCacheProto.CreateResponse>) responseObserver);
break;
case METHODID_GET_ALL:
serviceImpl.getAll((com.uwei.easy_core.QueryCacheProto.GetAllRequest) request,
(io.grpc.stub.StreamObserver<com.uwei.easy_core.QueryCacheProto.GetAllResponse>) responseObserver);
break;
default:
throw new AssertionError();
}
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public io.grpc.stub.StreamObserver<Req> invoke(
io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
default:
throw new AssertionError();
}
}
}
private static abstract class QueryCacheBaseDescriptorSupplier
implements io.grpc.protobuf.ProtoFileDescriptorSupplier, io.grpc.protobuf.ProtoServiceDescriptorSupplier {
QueryCacheBaseDescriptorSupplier() {}
@java.lang.Override
public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() {
return com.uwei.easy_core.QueryCacheProto.getDescriptor();
}
@java.lang.Override
public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() {
return getFileDescriptor().findServiceByName("QueryCache");
}
}
private static final class QueryCacheFileDescriptorSupplier
extends QueryCacheBaseDescriptorSupplier {
QueryCacheFileDescriptorSupplier() {}
}
private static final class QueryCacheMethodDescriptorSupplier
extends QueryCacheBaseDescriptorSupplier
implements io.grpc.protobuf.ProtoMethodDescriptorSupplier {
private final String methodName;
QueryCacheMethodDescriptorSupplier(String methodName) {
this.methodName = methodName;
}
@java.lang.Override
public com.google.protobuf.Descriptors.MethodDescriptor getMethodDescriptor() {
return getServiceDescriptor().findMethodByName(methodName);
}
}
private static volatile io.grpc.ServiceDescriptor serviceDescriptor;
public static io.grpc.ServiceDescriptor getServiceDescriptor() {
io.grpc.ServiceDescriptor result = serviceDescriptor;
if (result == null) {
synchronized (QueryCacheGrpc.class) {
result = serviceDescriptor;
if (result == null) {
serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME)
.setSchemaDescriptor(new QueryCacheFileDescriptorSupplier())
.addMethod(getCreateMethod())
.addMethod(getGetAllMethod())
.build();
}
}
}
return result;
}
}
|
9231b436b5ca32f1bf2a8e3ca226a202ae2599ef | 131 | java | Java | src/backend/parser/LangType.java | inan1993/Slogo_CS308 | 7919c7a46e84d8363bafc870136304c1a973a371 | [
"MIT"
] | null | null | null | src/backend/parser/LangType.java | inan1993/Slogo_CS308 | 7919c7a46e84d8363bafc870136304c1a973a371 | [
"MIT"
] | null | null | null | src/backend/parser/LangType.java | inan1993/Slogo_CS308 | 7919c7a46e84d8363bafc870136304c1a973a371 | [
"MIT"
] | null | null | null | 10.076923 | 23 | 0.725191 | 995,939 | package backend.parser;
public enum LangType {
CHINESE,
ENGLISH,
FRENCH,
GERMAN,
ITALIAN,
PORTUGUESE,
RUSSIAN,
SPANISH;
}
|
9231b5922130bce8c48e4425b173f19cf441559e | 454 | java | Java | Tetris-master/src/com/ok/ai/UserList.java | CSID-DGU/2020-2-OSSP-HotSource-3 | 7de76c88da7b48888b112531346d9064c2d320a1 | [
"MIT"
] | 1 | 2020-12-02T04:48:53.000Z | 2020-12-02T04:48:53.000Z | Tetris-master/src/com/ok/ai/UserList.java | CSID-DGU/2020-2-OSSP-HotSource-3 | 7de76c88da7b48888b112531346d9064c2d320a1 | [
"MIT"
] | 3 | 2019-11-12T07:34:43.000Z | 2019-12-12T02:14:01.000Z | Tetris-master/src/com/ok/ai/UserList.java | CSID-DGU/2020-2-OSSP-HotSource-3 | 7de76c88da7b48888b112531346d9064c2d320a1 | [
"MIT"
] | 5 | 2019-09-24T05:13:50.000Z | 2020-10-31T12:05:55.000Z | 16.214286 | 74 | 0.660793 | 995,940 | package com.ok.ai;
import com.ok.ai.UserList;
public class UserList implements Comparable<UserList>{
String id;
int score;
public UserList(String name, int sc){ //get user ID & Score, return them
id = name;
score = sc;
}
public String getID(){
return id;
}
public int getScore(){
return score;
}
public int compareTo(UserList r2){
return r2.score - this.score;
}
public String toString(){
return id + ", " + score;
}
}
|
9231b5a45b4769281e1fe4ceba125060c1b46c6b | 2,563 | java | Java | boot/kafka/src/test/java/com/truthbean/debbie/kafka/test/KafkaConsumerTest.java | TruthBean/debbie-cloud | 96de5e72411f3d3bb9125f17f3333c202ab0513d | [
"MulanPSL-1.0"
] | 1 | 2021-05-23T15:35:30.000Z | 2021-05-23T15:35:30.000Z | boot/kafka/src/test/java/com/truthbean/debbie/kafka/test/KafkaConsumerTest.java | TruthBean/debbie-cloud | 96de5e72411f3d3bb9125f17f3333c202ab0513d | [
"MulanPSL-1.0"
] | null | null | null | boot/kafka/src/test/java/com/truthbean/debbie/kafka/test/KafkaConsumerTest.java | TruthBean/debbie-cloud | 96de5e72411f3d3bb9125f17f3333c202ab0513d | [
"MulanPSL-1.0"
] | null | null | null | 43.440678 | 204 | 0.701912 | 995,941 | /**
* Copyright (c) 2021 TruthBean(Rogar·Q)
* Debbie is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
package com.truthbean.debbie.kafka.test;
import com.truthbean.Logger;
import com.truthbean.LoggerFactory;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;
import java.time.Duration;
import java.util.Collections;
import java.util.Properties;
/**
* @author TruthBean/Rogar·Q
* @since 0.1.0
* Created on 2020-09-21 14:47
*/
public class KafkaConsumerTest {
public static void main(String[] args) {
Properties p = new Properties();
p.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.1.12:19092");
p.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
p.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
p.put(ConsumerConfig.GROUP_ID_CONFIG, "hkvs");
p.put(ConsumerConfig.CLIENT_ID_CONFIG, "hkvs-ehome-consumer");
p.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, true);
p.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "100");
p.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
p.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "15000");
try (KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<>(p)) {
kafkaConsumer.subscribe(Collections.singletonList("hkvs-alarm"));
while (true) {
ConsumerRecords<String, String> records = kafkaConsumer.poll(Duration.ofMillis(100));
for (ConsumerRecord<String, String> record : records) {
logger.info(() -> "topic: " + record.topic());
logger.info(() -> "offset: " + record.offset());
logger.info(() -> "message: " + record.value());
}
}
}
}
private static final Logger logger = LoggerFactory.getLogger(KafkaConsumerTest.class);
}
|
9231b5bda0b83b30d79d3dc9402c21991694f05e | 1,624 | java | Java | backend/src/main/java/com/itacademy/services/UserConverter.java | VadimHolder/home-project-blog | bdf01c72c9e392620beb2a91481d89852578a468 | [
"MIT"
] | null | null | null | backend/src/main/java/com/itacademy/services/UserConverter.java | VadimHolder/home-project-blog | bdf01c72c9e392620beb2a91481d89852578a468 | [
"MIT"
] | null | null | null | backend/src/main/java/com/itacademy/services/UserConverter.java | VadimHolder/home-project-blog | bdf01c72c9e392620beb2a91481d89852578a468 | [
"MIT"
] | null | null | null | 30.074074 | 63 | 0.589286 | 995,942 | package com.itacademy.services;
import com.itacademy.dto.UserDto;
import com.itacademy.entities.User;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Component;
import java.util.List;
//Для того, чтобы спринг создал бин моего класса UsersConverter
// навесим на него аннотацию @Component.
@Component
public class UserConverter {
public User fromUserDtoToUser(UserDto userDto) {
User user = new User();
user.setId(userDto.getId());
user.setName(userDto.getName());
user.setFirstName(userDto.getFirstName());
user.setLastName(userDto.getLastName());
user.setEmail(userDto.getEmail());
user.setPassword(userDto.getPassword());
user.setRole(userDto.getRole());
return user;
}
public UserDto fromUserToUserDto(User user) {
return UserDto.builder()
.id(user.getId())
.name(user.getName())
.firstName(user.getFirstName())
.lastName(user.getLastName())
.email(user.getEmail())
.password(user.getPassword())
.role(user.getRole())
.build();
}
/*public List<UserDto> fromUserToUserDto(Page<User> user) {
return UserDto.builder()
.id(user.getId())
.name(user.getName())
.firstName(user.getFirstName())
.lastName(user.getLastName())
.email(user.getEmail())
.password(user.getPassword())
.role(user.getRole())
.build();
}*/
}
|
9231b65ef981d6caeee57d004af021c19b0b3ed7 | 273 | java | Java | realityshowweb/src/main/java/com/example/realityshowweb/application/web/model/VoteRequest.java | diegocamara/reality-show | 9e21da7d3e0a1eb637beda7d9740b9c393a7fb72 | [
"MIT"
] | null | null | null | realityshowweb/src/main/java/com/example/realityshowweb/application/web/model/VoteRequest.java | diegocamara/reality-show | 9e21da7d3e0a1eb637beda7d9740b9c393a7fb72 | [
"MIT"
] | null | null | null | realityshowweb/src/main/java/com/example/realityshowweb/application/web/model/VoteRequest.java | diegocamara/reality-show | 9e21da7d3e0a1eb637beda7d9740b9c393a7fb72 | [
"MIT"
] | null | null | null | 18.2 | 57 | 0.827839 | 995,943 | package com.example.realityshowweb.application.web.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.UUID;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class VoteRequest {
private UUID participant;
}
|
9231b7a43e4206a205e2dcce6f181cefe7897f16 | 2,730 | java | Java | ldap/codec/core/src/main/java/org/apache/directory/api/ldap/codec/factory/BindResponseFactory.java | mlbiam/directory-ldap-api | 8cdfa031e92f62387e1a0aef7e7157651f1c3c44 | [
"Apache-2.0"
] | 26 | 2017-10-24T12:50:26.000Z | 2022-02-02T15:10:22.000Z | ldap/codec/core/src/main/java/org/apache/directory/api/ldap/codec/factory/BindResponseFactory.java | mlbiam/directory-ldap-api | 8cdfa031e92f62387e1a0aef7e7157651f1c3c44 | [
"Apache-2.0"
] | 9 | 2018-03-18T17:05:46.000Z | 2022-01-03T16:00:27.000Z | ldap/codec/core/src/main/java/org/apache/directory/api/ldap/codec/factory/BindResponseFactory.java | mlbiam/directory-ldap-api | 8cdfa031e92f62387e1a0aef7e7157651f1c3c44 | [
"Apache-2.0"
] | 29 | 2017-12-04T15:15:13.000Z | 2022-02-11T02:42:07.000Z | 33.378049 | 103 | 0.693095 | 995,944 | /*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.api.ldap.codec.factory;
import org.apache.directory.api.asn1.ber.tlv.BerValue;
import org.apache.directory.api.asn1.util.Asn1Buffer;
import org.apache.directory.api.ldap.codec.api.LdapApiService;
import org.apache.directory.api.ldap.codec.api.LdapCodecConstants;
import org.apache.directory.api.ldap.model.message.BindResponse;
import org.apache.directory.api.ldap.model.message.Message;
/**
* The BindResponse factory.
*
* @author <a href="mailto:envkt@example.com">Apache Directory Project</a>
*/
public final class BindResponseFactory extends ResponseFactory
{
/** The static instance */
public static final BindResponseFactory INSTANCE = new BindResponseFactory();
private BindResponseFactory()
{
super();
}
/**
* Encode the BindResponse message to a PDU.
* <br>
* BindResponse :
* <pre>
* 0x61 L1
* |
* +--> LdapResult
* [+--0x87 LL serverSaslCreds]
* </pre>
*
* @param codec The LdapApiService instance
* @param buffer The buffer where to put the PDU
* @param message the BindResponse to encode
*/
@Override
public void encodeReverse( LdapApiService codec, Asn1Buffer buffer, Message message )
{
int start = buffer.getPos();
BindResponse bindResponse = ( ( BindResponse ) message );
// The serverSASL creds, if any
byte[] serverSaslCreds = bindResponse.getServerSaslCreds();
if ( serverSaslCreds != null )
{
BerValue.encodeOctetString( buffer, ( byte ) LdapCodecConstants.SERVER_SASL_CREDENTIAL_TAG,
serverSaslCreds );
}
// The LDAPResult part
encodeLdapResultReverse( buffer, bindResponse.getLdapResult() );
// The BindResponse Tag
BerValue.encodeSequence( buffer, LdapCodecConstants.BIND_RESPONSE_TAG, start );
}
}
|
9231b7c19f0a7553d2684ec96939ec0ab94d59a8 | 512 | java | Java | src/main/java/shittymcsuggestions/block/ICustomHopper.java | Earthcomputer/ShittyMinecraftSuggestions | c5b726094fca3657877f7363cad44e7d2e410bb1 | [
"CC0-1.0"
] | 5 | 2020-02-10T18:46:59.000Z | 2020-07-27T22:01:34.000Z | src/main/java/shittymcsuggestions/block/ICustomHopper.java | Earthcomputer/ShittyMinecraftSuggestions | c5b726094fca3657877f7363cad44e7d2e410bb1 | [
"CC0-1.0"
] | null | null | null | src/main/java/shittymcsuggestions/block/ICustomHopper.java | Earthcomputer/ShittyMinecraftSuggestions | c5b726094fca3657877f7363cad44e7d2e410bb1 | [
"CC0-1.0"
] | null | null | null | 25.6 | 111 | 0.771484 | 995,945 | package shittymcsuggestions.block;
import net.fabricmc.fabric.api.util.TriState;
import net.minecraft.block.BlockState;
import net.minecraft.block.entity.HopperBlockEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
public interface ICustomHopper {
default TriState doCustomInsertion(World world, BlockPos pos, BlockState state, HopperBlockEntity hopper) {
return TriState.DEFAULT;
}
default String getCustomContainerName() {
return null;
}
}
|
9231b8d6de422e0238d032e5cd79316fff0135ec | 1,835 | java | Java | src/main/java/io/github/ealenxie/gitlab/vo/EraseJob.java | EalenXie/gitlab-webhook-dingrobot | 6b1f301bd736ef3d74ff0677924466fb4c77c731 | [
"MIT"
] | null | null | null | src/main/java/io/github/ealenxie/gitlab/vo/EraseJob.java | EalenXie/gitlab-webhook-dingrobot | 6b1f301bd736ef3d74ff0677924466fb4c77c731 | [
"MIT"
] | null | null | null | src/main/java/io/github/ealenxie/gitlab/vo/EraseJob.java | EalenXie/gitlab-webhook-dingrobot | 6b1f301bd736ef3d74ff0677924466fb4c77c731 | [
"MIT"
] | null | null | null | 25.486111 | 53 | 0.673025 | 995,946 | package io.github.ealenxie.gitlab.vo;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
* Created by EalenXie on 2022/3/23 13:22
*/
@NoArgsConstructor
@Data
public class EraseJob {
@JsonProperty("commit")
private Commit commit;
@JsonProperty("coverage")
private Object coverage;
@JsonProperty("allow_failure")
private Boolean allowFailure;
@JsonProperty("download_url")
private Object downloadUrl;
@JsonProperty("id")
private Integer id;
@JsonProperty("name")
private String name;
@JsonProperty("ref")
private String ref;
@JsonProperty("artifacts")
private List<?> artifacts;
@JsonProperty("runner")
private Object runner;
@JsonProperty("stage")
private String stage;
@JsonProperty("created_at")
private String createdAt;
@JsonProperty("started_at")
private String startedAt;
@JsonProperty("finished_at")
private String finishedAt;
@JsonProperty("duration")
private Double duration;
@JsonProperty("status")
private String status;
@JsonProperty("tag")
private Boolean tag;
@JsonProperty("web_url")
private String webUrl;
@JsonProperty("user")
private Object user;
@NoArgsConstructor
@Data
public static class Commit {
@JsonProperty("author_email")
private String authorEmail;
@JsonProperty("author_name")
private String authorName;
@JsonProperty("created_at")
private String createdAt;
@JsonProperty("id")
private String id;
@JsonProperty("message")
private String message;
@JsonProperty("short_id")
private String shortId;
@JsonProperty("title")
private String title;
}
}
|
9231b9e81c17d49530a113ca379bb6cb6bcc2f4d | 12,217 | java | Java | runescape-client/src/main/java/class219.java | mikeester/runelite | 091c46ac23a38146a6d84808105da1ebd6c8f191 | [
"BSD-2-Clause"
] | 1 | 2020-09-04T02:20:59.000Z | 2020-09-04T02:20:59.000Z | runescape-client/src/main/java/class219.java | mikeester/runelite | 091c46ac23a38146a6d84808105da1ebd6c8f191 | [
"BSD-2-Clause"
] | null | null | null | runescape-client/src/main/java/class219.java | mikeester/runelite | 091c46ac23a38146a6d84808105da1ebd6c8f191 | [
"BSD-2-Clause"
] | 2 | 2020-01-28T16:03:06.000Z | 2020-04-04T03:51:59.000Z | 55.280543 | 203 | 0.709421 | 995,947 | import net.runelite.mapping.Export;
import net.runelite.mapping.ObfuscatedName;
import net.runelite.mapping.ObfuscatedSignature;
import net.runelite.rs.ScriptOpcodes;
@ObfuscatedName("hh")
public class class219 {
@ObfuscatedName("n")
@ObfuscatedSignature(
descriptor = "Lhp;"
)
@Export("huffman")
public static Huffman huffman;
@ObfuscatedName("aq")
@ObfuscatedSignature(
descriptor = "(ILcl;ZI)I",
garbageValue = "-1015901506"
)
static int method4173(int var0, Script var1, boolean var2) {
int var3;
if (var0 == ScriptOpcodes.STOCKMARKET_GETOFFERTYPE) { // L: 2341
var3 = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize]; // L: 2342
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = Client.grandExchangeOffers[var3].type(); // L: 2343
return 1; // L: 2344
} else if (var0 == ScriptOpcodes.STOCKMARKET_GETOFFERITEM) { // L: 2346
var3 = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize]; // L: 2347
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = Client.grandExchangeOffers[var3].id; // L: 2348
return 1; // L: 2349
} else if (var0 == ScriptOpcodes.STOCKMARKET_GETOFFERPRICE) { // L: 2351
var3 = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize]; // L: 2352
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = Client.grandExchangeOffers[var3].unitPrice; // L: 2353
return 1; // L: 2354
} else if (var0 == ScriptOpcodes.STOCKMARKET_GETOFFERCOUNT) { // L: 2356
var3 = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize]; // L: 2357
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = Client.grandExchangeOffers[var3].totalQuantity; // L: 2358
return 1; // L: 2359
} else if (var0 == ScriptOpcodes.STOCKMARKET_GETOFFERCOMPLETEDCOUNT) { // L: 2361
var3 = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize]; // L: 2362
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = Client.grandExchangeOffers[var3].currentQuantity; // L: 2363
return 1; // L: 2364
} else if (var0 == ScriptOpcodes.STOCKMARKET_GETOFFERCOMPLETEDGOLD) { // L: 2366
var3 = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize]; // L: 2367
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = Client.grandExchangeOffers[var3].currentPrice; // L: 2368
return 1; // L: 2369
} else {
int var13;
if (var0 == ScriptOpcodes.STOCKMARKET_ISOFFEREMPTY) { // L: 2371
var3 = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize]; // L: 2372
var13 = Client.grandExchangeOffers[var3].status(); // L: 2373
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = var13 == 0 ? 1 : 0; // L: 2374
return 1; // L: 2375
} else if (var0 == ScriptOpcodes.STOCKMARKET_ISOFFERSTABLE) { // L: 2377
var3 = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize]; // L: 2378
var13 = Client.grandExchangeOffers[var3].status(); // L: 2379
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = var13 == 2 ? 1 : 0; // L: 2380
return 1; // L: 2381
} else if (var0 == ScriptOpcodes.STOCKMARKET_ISOFFERFINISHED) { // L: 2383
var3 = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize]; // L: 2384
var13 = Client.grandExchangeOffers[var3].status(); // L: 2385
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = var13 == 5 ? 1 : 0; // L: 2386
return 1; // L: 2387
} else if (var0 == ScriptOpcodes.STOCKMARKET_ISOFFERADDING) { // L: 2389
var3 = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize]; // L: 2390
var13 = Client.grandExchangeOffers[var3].status(); // L: 2391
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = var13 == 1 ? 1 : 0; // L: 2392
return 1; // L: 2393
} else {
boolean var12;
if (var0 == ScriptOpcodes.TRADINGPOST_SORTBY_NAME) { // L: 2395
var12 = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize] == 1; // L: 2396
if (WorldMapSectionType.grandExchangeEvents != null) { // L: 2397
WorldMapSectionType.grandExchangeEvents.sort(GrandExchangeEvents.GrandExchangeEvents_nameComparator, var12); // L: 2398
}
return 1; // L: 2400
} else if (var0 == ScriptOpcodes.TRADINGPOST_SORTBY_PRICE) { // L: 2402
var12 = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize] == 1; // L: 2403
if (WorldMapSectionType.grandExchangeEvents != null) { // L: 2404
WorldMapSectionType.grandExchangeEvents.sort(GrandExchangeEvents.GrandExchangeEvents_priceComparator, var12); // L: 2405
}
return 1; // L: 2407
} else if (var0 == ScriptOpcodes.TRADINGPOST_SORTFILTERBY_WORLD) { // L: 2409
Interpreter.Interpreter_intStackSize -= 2; // L: 2410
var12 = Interpreter.Interpreter_intStack[Interpreter.Interpreter_intStackSize] == 1; // L: 2411
boolean var11 = Interpreter.Interpreter_intStack[Interpreter.Interpreter_intStackSize + 1] == 1; // L: 2412
if (WorldMapSectionType.grandExchangeEvents != null) { // L: 2413
Client.GrandExchangeEvents_worldComparator.filterWorlds = var11; // L: 2414
WorldMapSectionType.grandExchangeEvents.sort(Client.GrandExchangeEvents_worldComparator, var12); // L: 2415
}
return 1; // L: 2417
} else if (var0 == ScriptOpcodes.TRADINGPOST_SORTBY_AGE) { // L: 2419
var12 = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize] == 1; // L: 2420
if (WorldMapSectionType.grandExchangeEvents != null) { // L: 2421
WorldMapSectionType.grandExchangeEvents.sort(GrandExchangeEvents.GrandExchangeEvents_ageComparator, var12); // L: 2422
}
return 1; // L: 2424
} else if (var0 == ScriptOpcodes.TRADINGPOST_SORTBY_COUNT) { // L: 2426
var12 = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize] == 1; // L: 2427
if (WorldMapSectionType.grandExchangeEvents != null) { // L: 2428
WorldMapSectionType.grandExchangeEvents.sort(GrandExchangeEvents.GrandExchangeEvents_quantityComparator, var12); // L: 2429
}
return 1; // L: 2431
} else if (var0 == ScriptOpcodes.TRADINGPOST_GETTOTALOFFERS) { // L: 2433
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = WorldMapSectionType.grandExchangeEvents == null ? 0 : WorldMapSectionType.grandExchangeEvents.events.size(); // L: 2434
return 1; // L: 2435
} else {
GrandExchangeEvent var4;
if (var0 == ScriptOpcodes.TRADINGPOST_GETOFFERWORLD) { // L: 2437
var3 = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize]; // L: 2438
var4 = (GrandExchangeEvent)WorldMapSectionType.grandExchangeEvents.events.get(var3); // L: 2439
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = var4.world; // L: 2440
return 1; // L: 2441
} else if (var0 == ScriptOpcodes.TRADINGPOST_GETOFFERNAME) { // L: 2443
var3 = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize]; // L: 2444
var4 = (GrandExchangeEvent)WorldMapSectionType.grandExchangeEvents.events.get(var3); // L: 2445
Interpreter.Interpreter_stringStack[++Interpreter.Interpreter_stringStackSize - 1] = var4.getOfferName(); // L: 2446
return 1; // L: 2447
} else if (var0 == ScriptOpcodes.TRADINGPOST_GETOFFERPREVIOUSNAME) { // L: 2449
var3 = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize]; // L: 2450
var4 = (GrandExchangeEvent)WorldMapSectionType.grandExchangeEvents.events.get(var3); // L: 2451
Interpreter.Interpreter_stringStack[++Interpreter.Interpreter_stringStackSize - 1] = var4.getPreviousOfferName(); // L: 2452
return 1; // L: 2453
} else if (var0 == ScriptOpcodes.TRADINGPOST_GETOFFERAGE) { // L: 2455
var3 = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize]; // L: 2456
var4 = (GrandExchangeEvent)WorldMapSectionType.grandExchangeEvents.events.get(var3); // L: 2457
long var5 = Tiles.currentTimeMillis() - class9.field57 - var4.age; // L: 2458
int var7 = (int)(var5 / 3600000L); // L: 2459
int var8 = (int)((var5 - (long)(var7 * 3600000)) / 60000L); // L: 2460
int var9 = (int)((var5 - (long)(var7 * 3600000) - (long)(var8 * 60000)) / 1000L); // L: 2461
String var10 = var7 + ":" + var8 / 10 + var8 % 10 + ":" + var9 / 10 + var9 % 10; // L: 2462
Interpreter.Interpreter_stringStack[++Interpreter.Interpreter_stringStackSize - 1] = var10; // L: 2463
return 1; // L: 2464
} else if (var0 == ScriptOpcodes.TRADINGPOST_GETOFFERCOUNT) { // L: 2466
var3 = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize]; // L: 2467
var4 = (GrandExchangeEvent)WorldMapSectionType.grandExchangeEvents.events.get(var3); // L: 2468
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = var4.grandExchangeOffer.totalQuantity; // L: 2469
return 1; // L: 2470
} else if (var0 == ScriptOpcodes.TRADINGPOST_GETOFFERPRICE) { // L: 2472
var3 = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize]; // L: 2473
var4 = (GrandExchangeEvent)WorldMapSectionType.grandExchangeEvents.events.get(var3); // L: 2474
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = var4.grandExchangeOffer.unitPrice; // L: 2475
return 1; // L: 2476
} else if (var0 == ScriptOpcodes.TRADINGPOST_GETOFFERITEM) { // L: 2478
var3 = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize]; // L: 2479
var4 = (GrandExchangeEvent)WorldMapSectionType.grandExchangeEvents.events.get(var3); // L: 2480
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = var4.grandExchangeOffer.id; // L: 2481
return 1; // L: 2482
} else {
return 2; // L: 2484
}
}
}
}
}
@ObfuscatedName("jf")
@ObfuscatedSignature(
descriptor = "(I)V",
garbageValue = "74818443"
)
static void method4171() {
for (InterfaceParent var0 = (InterfaceParent)Client.interfaceParents.first(); var0 != null; var0 = (InterfaceParent)Client.interfaceParents.next()) { // L: 11000
int var1 = var0.group; // L: 11001
if (WorldMapCacheName.loadInterface(var1)) { // L: 11002
boolean var2 = true; // L: 11003
Widget[] var3 = DefaultsGroup.Widget_interfaceComponents[var1]; // L: 11004
int var4;
for (var4 = 0; var4 < var3.length; ++var4) { // L: 11005
if (var3[var4] != null) { // L: 11006
var2 = var3[var4].isIf3; // L: 11007
break;
}
}
if (!var2) { // L: 11011
var4 = (int)var0.key; // L: 11012
Widget var5 = class237.getWidget(var4); // L: 11013
if (var5 != null) { // L: 11014
IsaacCipher.invalidateWidget(var5);
}
}
}
}
} // L: 11018
@ObfuscatedName("kp")
@ObfuscatedSignature(
descriptor = "(IIII)Lbs;",
garbageValue = "-1314120201"
)
static final InterfaceParent method4172(int var0, int var1, int var2) {
InterfaceParent var3 = new InterfaceParent(); // L: 11230
var3.group = var1; // L: 11231
var3.type = var2; // L: 11232
Client.interfaceParents.put(var3, (long)var0); // L: 11233
GrandExchangeEvent.Widget_resetModelFrames(var1); // L: 11234
Widget var4 = class237.getWidget(var0); // L: 11235
IsaacCipher.invalidateWidget(var4); // L: 11236
if (Client.meslayerContinueWidget != null) { // L: 11237
IsaacCipher.invalidateWidget(Client.meslayerContinueWidget); // L: 11238
Client.meslayerContinueWidget = null; // L: 11239
}
AbstractWorldMapData.method352(); // L: 11241
class182.revalidateWidgetScroll(DefaultsGroup.Widget_interfaceComponents[var0 >> 16], var4, false); // L: 11242
SoundSystem.runWidgetOnLoadListener(var1); // L: 11243
if (Client.rootInterface != -1) { // L: 11244
class228.runIntfCloseListeners(Client.rootInterface, 1);
}
return var3; // L: 11245
}
}
|
9231bb816215e514e9692cc9c4eb675f885d7195 | 921 | java | Java | src/main/java/datastructure/graph/topo/TopoApp.java | UncleMelon/algorithms | 7333cbbea399a82ca5021326fddce1bcf11f38f6 | [
"MIT"
] | null | null | null | src/main/java/datastructure/graph/topo/TopoApp.java | UncleMelon/algorithms | 7333cbbea399a82ca5021326fddce1bcf11f38f6 | [
"MIT"
] | null | null | null | src/main/java/datastructure/graph/topo/TopoApp.java | UncleMelon/algorithms | 7333cbbea399a82ca5021326fddce1bcf11f38f6 | [
"MIT"
] | null | null | null | 31.758621 | 44 | 0.48317 | 995,948 | package datastructure.graph.topo;
/**
* Created by Administrator on 2018/1/11.
*/
public class TopoApp {
public static void main(String[] args) {
Graph theGraph = new Graph();
theGraph.addVertex('A'); // 0
theGraph.addVertex('B'); // 1
theGraph.addVertex('C'); // 2
theGraph.addVertex('D'); // 3
theGraph.addVertex('E'); // 4
theGraph.addVertex('F'); // 5
theGraph.addVertex('G'); // 6
theGraph.addVertex('H'); // 7
theGraph.addEdge(0, 3); // AD
theGraph.addEdge(0, 4); // AE
theGraph.addEdge(1, 4); // BE
theGraph.addEdge(2, 5); // CF
theGraph.addEdge(3, 6); // DG
theGraph.addEdge(4, 6); // EG
theGraph.addEdge(5, 7); // FH
theGraph.addEdge(6, 7); // GH
theGraph.topo();
}
}
|
9231bbf8f55a9704a060e89caa03ef7d42f6a4cd | 118,943 | java | Java | src/main/java/com/fasterxml/jackson/databind/deser/BasicDeserializerFactory.java | morganga/jackson-databind | a8a233f2b860e4f3652f528564a4f9da9a666b33 | [
"Apache-2.0"
] | 2,900 | 2015-01-04T09:47:00.000Z | 2022-03-31T09:44:36.000Z | src/main/java/com/fasterxml/jackson/databind/deser/BasicDeserializerFactory.java | morganga/jackson-databind | a8a233f2b860e4f3652f528564a4f9da9a666b33 | [
"Apache-2.0"
] | 2,856 | 2015-01-01T23:33:11.000Z | 2022-03-31T18:06:18.000Z | src/main/java/com/fasterxml/jackson/databind/deser/BasicDeserializerFactory.java | morganga/jackson-databind | a8a233f2b860e4f3652f528564a4f9da9a666b33 | [
"Apache-2.0"
] | 1,416 | 2015-01-01T16:44:44.000Z | 2022-03-30T12:27:06.000Z | 45.311619 | 158 | 0.593301 | 995,949 | package com.fasterxml.jackson.databind.deser;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicReference;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.cfg.ConfigOverride;
import com.fasterxml.jackson.databind.cfg.ConstructorDetector;
import com.fasterxml.jackson.databind.cfg.DeserializerFactoryConfig;
import com.fasterxml.jackson.databind.cfg.HandlerInstantiator;
import com.fasterxml.jackson.databind.deser.impl.CreatorCandidate;
import com.fasterxml.jackson.databind.deser.impl.CreatorCollector;
import com.fasterxml.jackson.databind.deser.impl.JDKValueInstantiators;
import com.fasterxml.jackson.databind.deser.impl.JavaUtilCollectionsDeserializers;
import com.fasterxml.jackson.databind.deser.std.*;
import com.fasterxml.jackson.databind.exc.InvalidDefinitionException;
import com.fasterxml.jackson.databind.ext.OptionalHandlerFactory;
import com.fasterxml.jackson.databind.introspect.*;
import com.fasterxml.jackson.databind.jdk14.JDK14Util;
import com.fasterxml.jackson.databind.jsontype.NamedType;
import com.fasterxml.jackson.databind.jsontype.TypeDeserializer;
import com.fasterxml.jackson.databind.jsontype.TypeResolverBuilder;
import com.fasterxml.jackson.databind.type.*;
import com.fasterxml.jackson.databind.util.*;
/**
* Abstract factory base class that can provide deserializers for standard
* JDK classes, including collection classes and simple heuristics for
* "upcasting" common collection interface types
* (such as {@link java.util.Collection}).
*<p>
* Since all simple deserializers are eagerly instantiated, and there is
* no additional introspection or customizability of these types,
* this factory is stateless.
*/
@SuppressWarnings("serial")
public abstract class BasicDeserializerFactory
extends DeserializerFactory
implements java.io.Serializable
{
private final static Class<?> CLASS_OBJECT = Object.class;
private final static Class<?> CLASS_STRING = String.class;
private final static Class<?> CLASS_CHAR_SEQUENCE = CharSequence.class;
private final static Class<?> CLASS_ITERABLE = Iterable.class;
private final static Class<?> CLASS_MAP_ENTRY = Map.Entry.class;
private final static Class<?> CLASS_SERIALIZABLE = Serializable.class;
/**
* We need a placeholder for creator properties that don't have name
* but are marked with `@JsonWrapped` annotation.
*/
protected final static PropertyName UNWRAPPED_CREATOR_PARAM_NAME = new PropertyName("@JsonUnwrapped");
/*
/**********************************************************
/* Config
/**********************************************************
*/
/**
* Configuration settings for this factory; immutable instance (just like this
* factory), new version created via copy-constructor (fluent-style)
*/
protected final DeserializerFactoryConfig _factoryConfig;
/*
/**********************************************************
/* Life cycle
/**********************************************************
*/
protected BasicDeserializerFactory(DeserializerFactoryConfig config) {
_factoryConfig = config;
}
/**
* Method for getting current {@link DeserializerFactoryConfig}.
*<p>
* Note that since instances are immutable, you can NOT change settings
* by accessing an instance and calling methods: this will simply create
* new instance of config object.
*/
public DeserializerFactoryConfig getFactoryConfig() {
return _factoryConfig;
}
protected abstract DeserializerFactory withConfig(DeserializerFactoryConfig config);
/*
/********************************************************
/* Configuration handling: fluent factories
/********************************************************
*/
/**
* Convenience method for creating a new factory instance with additional deserializer
* provider.
*/
@Override
public final DeserializerFactory withAdditionalDeserializers(Deserializers additional) {
return withConfig(_factoryConfig.withAdditionalDeserializers(additional));
}
/**
* Convenience method for creating a new factory instance with additional
* {@link KeyDeserializers}.
*/
@Override
public final DeserializerFactory withAdditionalKeyDeserializers(KeyDeserializers additional) {
return withConfig(_factoryConfig.withAdditionalKeyDeserializers(additional));
}
/**
* Convenience method for creating a new factory instance with additional
* {@link BeanDeserializerModifier}.
*/
@Override
public final DeserializerFactory withDeserializerModifier(BeanDeserializerModifier modifier) {
return withConfig(_factoryConfig.withDeserializerModifier(modifier));
}
/**
* Convenience method for creating a new factory instance with additional
* {@link AbstractTypeResolver}.
*/
@Override
public final DeserializerFactory withAbstractTypeResolver(AbstractTypeResolver resolver) {
return withConfig(_factoryConfig.withAbstractTypeResolver(resolver));
}
/**
* Convenience method for creating a new factory instance with additional
* {@link ValueInstantiators}.
*/
@Override
public final DeserializerFactory withValueInstantiators(ValueInstantiators instantiators) {
return withConfig(_factoryConfig.withValueInstantiators(instantiators));
}
/*
/**********************************************************
/* DeserializerFactory impl (partial): type mappings
/**********************************************************
*/
@Override
public JavaType mapAbstractType(DeserializationConfig config, JavaType type) throws JsonMappingException
{
// first, general mappings
while (true) {
JavaType next = _mapAbstractType2(config, type);
if (next == null) {
return type;
}
// Should not have to worry about cycles; but better verify since they will invariably occur... :-)
// (also: guard against invalid resolution to a non-related type)
Class<?> prevCls = type.getRawClass();
Class<?> nextCls = next.getRawClass();
if ((prevCls == nextCls) || !prevCls.isAssignableFrom(nextCls)) {
throw new IllegalArgumentException("Invalid abstract type resolution from "+type+" to "+next+": latter is not a subtype of former");
}
type = next;
}
}
/**
* Method that will find abstract type mapping for specified type, doing a single
* lookup through registered abstract type resolvers; will not do recursive lookups.
*/
private JavaType _mapAbstractType2(DeserializationConfig config, JavaType type)
throws JsonMappingException
{
Class<?> currClass = type.getRawClass();
if (_factoryConfig.hasAbstractTypeResolvers()) {
for (AbstractTypeResolver resolver : _factoryConfig.abstractTypeResolvers()) {
JavaType concrete = resolver.findTypeMapping(config, type);
if ((concrete != null) && !concrete.hasRawClass(currClass)) {
return concrete;
}
}
}
return null;
}
/*
/**********************************************************
/* DeserializerFactory impl (partial): ValueInstantiators
/**********************************************************
*/
/**
* Value instantiator is created both based on creator annotations,
* and on optional externally provided instantiators (registered through
* module interface).
*/
@Override
public ValueInstantiator findValueInstantiator(DeserializationContext ctxt,
BeanDescription beanDesc)
throws JsonMappingException
{
final DeserializationConfig config = ctxt.getConfig();
ValueInstantiator instantiator = null;
// Check @JsonValueInstantiator before anything else
AnnotatedClass ac = beanDesc.getClassInfo();
Object instDef = ctxt.getAnnotationIntrospector().findValueInstantiator(ac);
if (instDef != null) {
instantiator = _valueInstantiatorInstance(config, ac, instDef);
}
if (instantiator == null) {
// Second: see if some of standard Jackson/JDK types might provide value
// instantiators.
instantiator = JDKValueInstantiators.findStdValueInstantiator(config, beanDesc.getBeanClass());
if (instantiator == null) {
instantiator = _constructDefaultValueInstantiator(ctxt, beanDesc);
}
}
// finally: anyone want to modify ValueInstantiator?
if (_factoryConfig.hasValueInstantiators()) {
for (ValueInstantiators insts : _factoryConfig.valueInstantiators()) {
instantiator = insts.findValueInstantiator(config, beanDesc, instantiator);
// let's do sanity check; easier to spot buggy handlers
if (instantiator == null) {
ctxt.reportBadTypeDefinition(beanDesc,
"Broken registered ValueInstantiators (of type %s): returned null ValueInstantiator",
insts.getClass().getName());
}
}
}
if (instantiator != null) {
instantiator = instantiator.createContextual(ctxt, beanDesc);
}
return instantiator;
}
/**
* Method that will construct standard default {@link ValueInstantiator}
* using annotations (like @JsonCreator) and visibility rules
*/
protected ValueInstantiator _constructDefaultValueInstantiator(DeserializationContext ctxt,
BeanDescription beanDesc)
throws JsonMappingException
{
final CreatorCollectionState ccState;
final ConstructorDetector ctorDetector;
{
final DeserializationConfig config = ctxt.getConfig();
// need to construct suitable visibility checker:
final VisibilityChecker<?> vchecker = config.getDefaultVisibilityChecker(beanDesc.getBeanClass(),
beanDesc.getClassInfo());
ctorDetector = config.getConstructorDetector();
// 24-Sep-2014, tatu: Tricky part first; need to merge resolved property information
// (which has creator parameters sprinkled around) with actual creator
// declarations (which are needed to access creator annotation, amongst other things).
// Easiest to combine that info first, then pass it to remaining processing.
// 15-Mar-2015, tatu: Alas, this won't help with constructors that only have implicit
// names. Those will need to be resolved later on.
final CreatorCollector creators = new CreatorCollector(beanDesc, config);
Map<AnnotatedWithParams,BeanPropertyDefinition[]> creatorDefs = _findCreatorsFromProperties(ctxt,
beanDesc);
ccState = new CreatorCollectionState(ctxt, beanDesc, vchecker,
creators, creatorDefs);
}
// Start with explicitly annotated factory methods
_addExplicitFactoryCreators(ctxt, ccState, !ctorDetector.requireCtorAnnotation());
// constructors only usable on concrete types:
if (beanDesc.getType().isConcrete()) {
// [databind#2709]: Record support
if (beanDesc.getType().isRecordType()) {
final List<String> names = new ArrayList<>();
// NOTE: this does verify that there is no explicitly annotated alternatives
AnnotatedConstructor canonical = JDK14Util.findRecordConstructor(ctxt, beanDesc, names);
if (canonical != null) {
_addRecordConstructor(ctxt, ccState, canonical, names);
return ccState.creators.constructValueInstantiator(ctxt);
}
}
// 25-Jan-2017, tatu: As per [databind#1501], [databind#1502], [databind#1503], best
// for now to skip attempts at using anything but no-args constructor (see
// `InnerClassProperty` construction for that)
final boolean isNonStaticInnerClass = beanDesc.isNonStaticInnerClass();
if (isNonStaticInnerClass) {
// TODO: look for `@JsonCreator` annotated ones, throw explicit exception?
;
} else {
// 18-Sep-2020, tatu: Although by default implicit introspection is allowed, 2.12
// has settings to prevent that either generally, or at least for JDK types
final boolean findImplicit = ctorDetector.shouldIntrospectorImplicitConstructors(beanDesc.getBeanClass());
_addExplicitConstructorCreators(ctxt, ccState, findImplicit);
if (ccState.hasImplicitConstructorCandidates()
// 05-Dec-2020, tatu: [databind#2962] explicit annotation of
// a factory should not block implicit constructor, for backwards
// compatibility (minor regression in 2.12.0)
//&& !ccState.hasExplicitFactories()
// ... explicit constructor should prevent, however
&& !ccState.hasExplicitConstructors()) {
_addImplicitConstructorCreators(ctxt, ccState, ccState.implicitConstructorCandidates());
}
}
}
// and finally, implicitly found factory methods if nothing explicit found
if (ccState.hasImplicitFactoryCandidates()
&& !ccState.hasExplicitFactories() && !ccState.hasExplicitConstructors()) {
_addImplicitFactoryCreators(ctxt, ccState, ccState.implicitFactoryCandidates());
}
return ccState.creators.constructValueInstantiator(ctxt);
}
protected Map<AnnotatedWithParams,BeanPropertyDefinition[]> _findCreatorsFromProperties(DeserializationContext ctxt,
BeanDescription beanDesc) throws JsonMappingException
{
Map<AnnotatedWithParams,BeanPropertyDefinition[]> result = Collections.emptyMap();
for (BeanPropertyDefinition propDef : beanDesc.findProperties()) {
Iterator<AnnotatedParameter> it = propDef.getConstructorParameters();
while (it.hasNext()) {
AnnotatedParameter param = it.next();
AnnotatedWithParams owner = param.getOwner();
BeanPropertyDefinition[] defs = result.get(owner);
final int index = param.getIndex();
if (defs == null) {
if (result.isEmpty()) { // since emptyMap is immutable need to create a 'real' one
result = new LinkedHashMap<AnnotatedWithParams,BeanPropertyDefinition[]>();
}
defs = new BeanPropertyDefinition[owner.getParameterCount()];
result.put(owner, defs);
} else {
if (defs[index] != null) {
ctxt.reportBadTypeDefinition(beanDesc,
"Conflict: parameter #%d of %s bound to more than one property; %s vs %s",
index, owner, defs[index], propDef);
}
}
defs[index] = propDef;
}
}
return result;
}
public ValueInstantiator _valueInstantiatorInstance(DeserializationConfig config,
Annotated annotated, Object instDef)
throws JsonMappingException
{
if (instDef == null) {
return null;
}
ValueInstantiator inst;
if (instDef instanceof ValueInstantiator) {
return (ValueInstantiator) instDef;
}
if (!(instDef instanceof Class)) {
throw new IllegalStateException("AnnotationIntrospector returned key deserializer definition of type "
+instDef.getClass().getName()
+"; expected type KeyDeserializer or Class<KeyDeserializer> instead");
}
Class<?> instClass = (Class<?>)instDef;
if (ClassUtil.isBogusClass(instClass)) {
return null;
}
if (!ValueInstantiator.class.isAssignableFrom(instClass)) {
throw new IllegalStateException("AnnotationIntrospector returned Class "+instClass.getName()
+"; expected Class<ValueInstantiator>");
}
HandlerInstantiator hi = config.getHandlerInstantiator();
if (hi != null) {
inst = hi.valueInstantiatorInstance(config, annotated, instClass);
if (inst != null) {
return inst;
}
}
return (ValueInstantiator) ClassUtil.createInstance(instClass,
config.canOverrideAccessModifiers());
}
/*
/**********************************************************************
/* Creator introspection: Record introspection (Jackson 2.12+, Java 14+)
/**********************************************************************
*/
/**
* Helper method called when a {@code java.lang.Record} definition's "canonical"
* constructor is to be used: if so, we have implicit names to consider.
*
* @since 2.12
*/
protected void _addRecordConstructor(DeserializationContext ctxt, CreatorCollectionState ccState,
AnnotatedConstructor canonical, List<String> implicitNames)
throws JsonMappingException
{
final int argCount = canonical.getParameterCount();
final AnnotationIntrospector intr = ctxt.getAnnotationIntrospector();
final SettableBeanProperty[] properties = new SettableBeanProperty[argCount];
for (int i = 0; i < argCount; ++i) {
final AnnotatedParameter param = canonical.getParameter(i);
JacksonInject.Value injectable = intr.findInjectableValue(param);
PropertyName name = intr.findNameForDeserialization(param);
if (name == null || name.isEmpty()) {
name = PropertyName.construct(implicitNames.get(i));
}
properties[i] = constructCreatorProperty(ctxt, ccState.beanDesc, name, i, param, injectable);
}
ccState.creators.addPropertyCreator(canonical, false, properties);
}
/*
/**********************************************************************
/* Creator introspection: constructor creator introspection
/**********************************************************************
*/
protected void _addExplicitConstructorCreators(DeserializationContext ctxt,
CreatorCollectionState ccState, boolean findImplicit)
throws JsonMappingException
{
final BeanDescription beanDesc = ccState.beanDesc;
final CreatorCollector creators = ccState.creators;
final AnnotationIntrospector intr = ccState.annotationIntrospector();
final VisibilityChecker<?> vchecker = ccState.vchecker;
final Map<AnnotatedWithParams, BeanPropertyDefinition[]> creatorParams = ccState.creatorParams;
// First things first: the "default constructor" (zero-arg
// constructor; whether implicit or explicit) is NOT included
// in list of constructors, so needs to be handled separately.
AnnotatedConstructor defaultCtor = beanDesc.findDefaultConstructor();
if (defaultCtor != null) {
if (!creators.hasDefaultCreator() || _hasCreatorAnnotation(ctxt, defaultCtor)) {
creators.setDefaultCreator(defaultCtor);
}
}
// 21-Sep-2017, tatu: First let's handle explicitly annotated ones
for (AnnotatedConstructor ctor : beanDesc.getConstructors()) {
JsonCreator.Mode creatorMode = intr.findCreatorAnnotation(ctxt.getConfig(), ctor);
if (JsonCreator.Mode.DISABLED == creatorMode) {
continue;
}
if (creatorMode == null) {
// let's check Visibility here, to avoid further processing for non-visible?
if (findImplicit && vchecker.isCreatorVisible(ctor)) {
ccState.addImplicitConstructorCandidate(CreatorCandidate.construct(intr,
ctor, creatorParams.get(ctor)));
}
continue;
}
switch (creatorMode) {
case DELEGATING:
_addExplicitDelegatingCreator(ctxt, beanDesc, creators,
CreatorCandidate.construct(intr, ctor, null));
break;
case PROPERTIES:
_addExplicitPropertyCreator(ctxt, beanDesc, creators,
CreatorCandidate.construct(intr, ctor, creatorParams.get(ctor)));
break;
default:
_addExplicitAnyCreator(ctxt, beanDesc, creators,
CreatorCandidate.construct(intr, ctor, creatorParams.get(ctor)),
ctxt.getConfig().getConstructorDetector());
break;
}
ccState.increaseExplicitConstructorCount();
}
}
protected void _addImplicitConstructorCreators(DeserializationContext ctxt,
CreatorCollectionState ccState, List<CreatorCandidate> ctorCandidates)
throws JsonMappingException
{
final DeserializationConfig config = ctxt.getConfig();
final BeanDescription beanDesc = ccState.beanDesc;
final CreatorCollector creators = ccState.creators;
final AnnotationIntrospector intr = ccState.annotationIntrospector();
final VisibilityChecker<?> vchecker = ccState.vchecker;
List<AnnotatedWithParams> implicitCtors = null;
final boolean preferPropsBased = config.getConstructorDetector().singleArgCreatorDefaultsToProperties();
for (CreatorCandidate candidate : ctorCandidates) {
final int argCount = candidate.paramCount();
final AnnotatedWithParams ctor = candidate.creator();
// some single-arg factory methods (String, number) are auto-detected
if (argCount == 1) {
final BeanPropertyDefinition propDef = candidate.propertyDef(0);
final boolean useProps = preferPropsBased || _checkIfCreatorPropertyBased(intr, ctor, propDef);
if (useProps) {
SettableBeanProperty[] properties = new SettableBeanProperty[1];
final JacksonInject.Value injection = candidate.injection(0);
// 18-Sep-2020, tatu: [databind#1498] looks like implicit name not linked
// unless annotation found, so try again from here
PropertyName name = candidate.paramName(0);
if (name == null) {
name = candidate.findImplicitParamName(0);
if ((name == null) && (injection == null)) {
continue;
}
}
properties[0] = constructCreatorProperty(ctxt, beanDesc, name, 0,
candidate.parameter(0), injection);
creators.addPropertyCreator(ctor, false, properties);
} else {
/*boolean added = */ _handleSingleArgumentCreator(creators,
ctor, false,
vchecker.isCreatorVisible(ctor));
// one more thing: sever link to creator property, to avoid possible later
// problems with "unresolved" constructor property
if (propDef != null) {
((POJOPropertyBuilder) propDef).removeConstructors();
}
}
// regardless, fully handled
continue;
}
// 2 or more args; all params must have names or be injectable
// 14-Mar-2015, tatu (2.6): Or, as per [#725], implicit names will also
// do, with some constraints. But that will require bit post processing...
int nonAnnotatedParamIndex = -1;
SettableBeanProperty[] properties = new SettableBeanProperty[argCount];
int explicitNameCount = 0;
int implicitWithCreatorCount = 0;
int injectCount = 0;
for (int i = 0; i < argCount; ++i) {
final AnnotatedParameter param = ctor.getParameter(i);
BeanPropertyDefinition propDef = candidate.propertyDef(i);
JacksonInject.Value injectable = intr.findInjectableValue(param);
final PropertyName name = (propDef == null) ? null : propDef.getFullName();
if (propDef != null && propDef.isExplicitlyNamed()) {
++explicitNameCount;
properties[i] = constructCreatorProperty(ctxt, beanDesc, name, i, param, injectable);
continue;
}
if (injectable != null) {
++injectCount;
properties[i] = constructCreatorProperty(ctxt, beanDesc, name, i, param, injectable);
continue;
}
NameTransformer unwrapper = intr.findUnwrappingNameTransformer(param);
if (unwrapper != null) {
_reportUnwrappedCreatorProperty(ctxt, beanDesc, param);
/*
properties[i] = constructCreatorProperty(ctxt, beanDesc, UNWRAPPED_CREATOR_PARAM_NAME, i, param, null);
++explicitNameCount;
*/
continue;
}
// One more thing: implicit names are ok iff ctor has creator annotation
/*
if (isCreator && (name != null && !name.isEmpty())) {
++implicitWithCreatorCount;
properties[i] = constructCreatorProperty(ctxt, beanDesc, name, i, param, injectId);
continue;
}
*/
if (nonAnnotatedParamIndex < 0) {
nonAnnotatedParamIndex = i;
}
}
final int namedCount = explicitNameCount + implicitWithCreatorCount;
// Ok: if named or injectable, we have more work to do
if ((explicitNameCount > 0) || (injectCount > 0)) {
// simple case; everything covered:
if ((namedCount + injectCount) == argCount) {
creators.addPropertyCreator(ctor, false, properties);
continue;
}
if ((explicitNameCount == 0) && ((injectCount + 1) == argCount)) {
// Secondary: all but one injectable, one un-annotated (un-named)
creators.addDelegatingCreator(ctor, false, properties, 0);
continue;
}
// otherwise, epic fail?
// 16-Mar-2015, tatu: due to [#725], need to be more permissive. For now let's
// only report problem if there's no implicit name
PropertyName impl = candidate.findImplicitParamName(nonAnnotatedParamIndex);
if (impl == null || impl.isEmpty()) {
// Let's consider non-static inner class as a special case...
// 25-Jan-2017, tatu: Non-static inner classes skipped altogether, now
/*
if ((nonAnnotatedParamIndex == 0) && isNonStaticInnerClass) {
throw new IllegalArgumentException("Non-static inner classes like "
+ctor.getDeclaringClass().getName()+" cannot use @JsonCreator for constructors");
}
*/
ctxt.reportBadTypeDefinition(beanDesc,
"Argument #%d of constructor %s has no property name annotation; must have name when multiple-parameter constructor annotated as Creator",
nonAnnotatedParamIndex, ctor);
}
}
// [#725]: as a fallback, all-implicit names may work as well
if (!creators.hasDefaultCreator()) {
if (implicitCtors == null) {
implicitCtors = new LinkedList<>();
}
implicitCtors.add(ctor);
}
}
// last option, as per [#725]: consider implicit-names-only, visible constructor,
// if just one found
if ((implicitCtors != null) && !creators.hasDelegatingCreator()
&& !creators.hasPropertyBasedCreator()) {
_checkImplicitlyNamedConstructors(ctxt, beanDesc, vchecker, intr,
creators, implicitCtors);
}
}
/*
/**********************************************************************
/* Creator introspection: factory creator introspection
/**********************************************************************
*/
protected void _addExplicitFactoryCreators(DeserializationContext ctxt,
CreatorCollectionState ccState, boolean findImplicit)
throws JsonMappingException
{
final BeanDescription beanDesc = ccState.beanDesc;
final CreatorCollector creators = ccState.creators;
final AnnotationIntrospector intr = ccState.annotationIntrospector();
final VisibilityChecker<?> vchecker = ccState.vchecker;
final Map<AnnotatedWithParams, BeanPropertyDefinition[]> creatorParams = ccState.creatorParams;
// 21-Sep-2017, tatu: First let's handle explicitly annotated ones
for (AnnotatedMethod factory : beanDesc.getFactoryMethods()) {
JsonCreator.Mode creatorMode = intr.findCreatorAnnotation(ctxt.getConfig(), factory);
final int argCount = factory.getParameterCount();
if (creatorMode == null) {
// Only potentially accept 1-argument factory methods
if (findImplicit && (argCount == 1) && vchecker.isCreatorVisible(factory)) {
ccState.addImplicitFactoryCandidate(CreatorCandidate.construct(intr, factory, null));
}
continue;
}
if (creatorMode == JsonCreator.Mode.DISABLED) {
continue;
}
// zero-arg method factory methods fine, as long as explicit
if (argCount == 0) {
creators.setDefaultCreator(factory);
continue;
}
switch (creatorMode) {
case DELEGATING:
_addExplicitDelegatingCreator(ctxt, beanDesc, creators,
CreatorCandidate.construct(intr, factory, null));
break;
case PROPERTIES:
_addExplicitPropertyCreator(ctxt, beanDesc, creators,
CreatorCandidate.construct(intr, factory, creatorParams.get(factory)));
break;
case DEFAULT:
default:
_addExplicitAnyCreator(ctxt, beanDesc, creators,
CreatorCandidate.construct(intr, factory, creatorParams.get(factory)),
// 13-Sep-2020, tatu: Factory methods do not follow config settings
// (as of Jackson 2.12)
ConstructorDetector.DEFAULT);
break;
}
ccState.increaseExplicitFactoryCount();
}
}
protected void _addImplicitFactoryCreators(DeserializationContext ctxt,
CreatorCollectionState ccState, List<CreatorCandidate> factoryCandidates)
throws JsonMappingException
{
final BeanDescription beanDesc = ccState.beanDesc;
final CreatorCollector creators = ccState.creators;
final AnnotationIntrospector intr = ccState.annotationIntrospector();
final VisibilityChecker<?> vchecker = ccState.vchecker;
final Map<AnnotatedWithParams, BeanPropertyDefinition[]> creatorParams = ccState.creatorParams;
// And then implicitly found
for (CreatorCandidate candidate : factoryCandidates) {
final int argCount = candidate.paramCount();
AnnotatedWithParams factory = candidate.creator();
final BeanPropertyDefinition[] propDefs = creatorParams.get(factory);
// some single-arg factory methods (String, number) are auto-detected
if (argCount != 1) {
continue; // 2 and more args? Must be explicit, handled earlier
}
BeanPropertyDefinition argDef = candidate.propertyDef(0);
boolean useProps = _checkIfCreatorPropertyBased(intr, factory, argDef);
if (!useProps) { // not property based but delegating
/*boolean added=*/ _handleSingleArgumentCreator(creators,
factory, false, vchecker.isCreatorVisible(factory));
// 23-Sep-2016, tatu: [databind#1383]: Need to also sever link to avoid possible
// later problems with "unresolved" constructor property
if (argDef != null) {
((POJOPropertyBuilder) argDef).removeConstructors();
}
continue;
}
AnnotatedParameter nonAnnotatedParam = null;
SettableBeanProperty[] properties = new SettableBeanProperty[argCount];
int implicitNameCount = 0;
int explicitNameCount = 0;
int injectCount = 0;
for (int i = 0; i < argCount; ++i) {
final AnnotatedParameter param = factory.getParameter(i);
BeanPropertyDefinition propDef = (propDefs == null) ? null : propDefs[i];
JacksonInject.Value injectable = intr.findInjectableValue(param);
final PropertyName name = (propDef == null) ? null : propDef.getFullName();
if (propDef != null && propDef.isExplicitlyNamed()) {
++explicitNameCount;
properties[i] = constructCreatorProperty(ctxt, beanDesc, name, i, param, injectable);
continue;
}
if (injectable != null) {
++injectCount;
properties[i] = constructCreatorProperty(ctxt, beanDesc, name, i, param, injectable);
continue;
}
NameTransformer unwrapper = intr.findUnwrappingNameTransformer(param);
if (unwrapper != null) {
_reportUnwrappedCreatorProperty(ctxt, beanDesc, param);
/*
properties[i] = constructCreatorProperty(ctxt, beanDesc, UNWRAPPED_CREATOR_PARAM_NAME, i, param, null);
++implicitNameCount;
*/
continue;
}
// One more thing: implicit names are ok iff ctor has creator annotation
/*
if (isCreator) {
if (name != null && !name.isEmpty()) {
++implicitNameCount;
properties[i] = constructCreatorProperty(ctxt, beanDesc, name, i, param, injectable);
continue;
}
}
*/
/* 25-Sep-2014, tatu: Actually, we may end up "losing" naming due to higher-priority constructor
* (see TestCreators#testConstructorCreator() test). And just to avoid running into that problem,
* let's add one more work around
*/
/*
PropertyName name2 = _findExplicitParamName(param, intr);
if (name2 != null && !name2.isEmpty()) {
// Hmmh. Ok, fine. So what are we to do with it... ?
// For now... skip. May need to revisit this, should this become problematic
continue main_loop;
}
*/
if (nonAnnotatedParam == null) {
nonAnnotatedParam = param;
}
}
final int namedCount = explicitNameCount + implicitNameCount;
// Ok: if named or injectable, we have more work to do
if (explicitNameCount > 0 || injectCount > 0) {
// simple case; everything covered:
if ((namedCount + injectCount) == argCount) {
creators.addPropertyCreator(factory, false, properties);
} else if ((explicitNameCount == 0) && ((injectCount + 1) == argCount)) {
// secondary: all but one injectable, one un-annotated (un-named)
creators.addDelegatingCreator(factory, false, properties, 0);
} else { // otherwise, epic fail
ctxt.reportBadTypeDefinition(beanDesc,
"Argument #%d of factory method %s has no property name annotation; must have name when multiple-parameter constructor annotated as Creator",
(nonAnnotatedParam == null) ? -1 : nonAnnotatedParam.getIndex(),
factory);
}
}
}
}
/*
/**********************************************************************
/* Creator introspection: helper methods
/**********************************************************************
*/
/**
* Helper method called when there is the explicit "is-creator" with mode of "delegating"
*
* @since 2.9.2
*/
protected void _addExplicitDelegatingCreator(DeserializationContext ctxt,
BeanDescription beanDesc, CreatorCollector creators,
CreatorCandidate candidate)
throws JsonMappingException
{
// Somewhat simple: find injectable values, if any, ensure there is one
// and just one delegated argument; report violations if any
int ix = -1;
final int argCount = candidate.paramCount();
SettableBeanProperty[] properties = new SettableBeanProperty[argCount];
for (int i = 0; i < argCount; ++i) {
AnnotatedParameter param = candidate.parameter(i);
JacksonInject.Value injectId = candidate.injection(i);
if (injectId != null) {
properties[i] = constructCreatorProperty(ctxt, beanDesc, null, i, param, injectId);
continue;
}
if (ix < 0) {
ix = i;
continue;
}
// Illegal to have more than one value to delegate to
ctxt.reportBadTypeDefinition(beanDesc,
"More than one argument (#%d and #%d) left as delegating for Creator %s: only one allowed",
ix, i, candidate);
}
// Also, let's require that one Delegating argument does eixt
if (ix < 0) {
ctxt.reportBadTypeDefinition(beanDesc,
"No argument left as delegating for Creator %s: exactly one required", candidate);
}
// 17-Jan-2018, tatu: as per [databind#1853] need to ensure we will distinguish
// "well-known" single-arg variants (String, int/long, boolean) from "generic" delegating...
if (argCount == 1) {
_handleSingleArgumentCreator(creators, candidate.creator(), true, true);
// one more thing: sever link to creator property, to avoid possible later
// problems with "unresolved" constructor property
BeanPropertyDefinition paramDef = candidate.propertyDef(0);
if (paramDef != null) {
((POJOPropertyBuilder) paramDef).removeConstructors();
}
return;
}
creators.addDelegatingCreator(candidate.creator(), true, properties, ix);
}
/**
* Helper method called when there is the explicit "is-creator" annotation with mode
* of "properties-based"
*
* @since 2.9.2
*/
protected void _addExplicitPropertyCreator(DeserializationContext ctxt,
BeanDescription beanDesc, CreatorCollector creators,
CreatorCandidate candidate)
throws JsonMappingException
{
final int paramCount = candidate.paramCount();
SettableBeanProperty[] properties = new SettableBeanProperty[paramCount];
for (int i = 0; i < paramCount; ++i) {
JacksonInject.Value injectId = candidate.injection(i);
AnnotatedParameter param = candidate.parameter(i);
PropertyName name = candidate.paramName(i);
if (name == null) {
// 21-Sep-2017, tatu: Looks like we want to block accidental use of Unwrapped,
// as that will not work with Creators well at all
NameTransformer unwrapper = ctxt.getAnnotationIntrospector().findUnwrappingNameTransformer(param);
if (unwrapper != null) {
_reportUnwrappedCreatorProperty(ctxt, beanDesc, param);
/*
properties[i] = constructCreatorProperty(ctxt, beanDesc, UNWRAPPED_CREATOR_PARAM_NAME, i, param, null);
++explicitNameCount;
*/
}
name = candidate.findImplicitParamName(i);
_validateNamedPropertyParameter(ctxt, beanDesc, candidate, i,
name, injectId);
}
properties[i] = constructCreatorProperty(ctxt, beanDesc, name, i, param, injectId);
}
creators.addPropertyCreator(candidate.creator(), true, properties);
}
@Deprecated // since 2.12, remove from 2.13 or later
protected void _addExplicitAnyCreator(DeserializationContext ctxt,
BeanDescription beanDesc, CreatorCollector creators,
CreatorCandidate candidate)
throws JsonMappingException
{
_addExplicitAnyCreator(ctxt, beanDesc, creators, candidate,
ctxt.getConfig().getConstructorDetector());
}
/**
* Helper method called when there is explicit "is-creator" marker,
* but no mode declaration.
*
* @since 2.12
*/
protected void _addExplicitAnyCreator(DeserializationContext ctxt,
BeanDescription beanDesc, CreatorCollector creators,
CreatorCandidate candidate, ConstructorDetector ctorDetector)
throws JsonMappingException
{
// Looks like there's bit of magic regarding 1-parameter creators; others simpler:
if (1 != candidate.paramCount()) {
// Ok: for delegates, we want one and exactly one parameter without
// injection AND without name
// 13-Sep-2020, tatu: Can only be delegating if not forced to be properties-based
if (!ctorDetector.singleArgCreatorDefaultsToProperties()) {
int oneNotInjected = candidate.findOnlyParamWithoutInjection();
if (oneNotInjected >= 0) {
// getting close; but most not have name (or be explicitly specified
// as default-to-delegate)
if (ctorDetector.singleArgCreatorDefaultsToDelegating()
|| candidate.paramName(oneNotInjected) == null) {
_addExplicitDelegatingCreator(ctxt, beanDesc, creators, candidate);
return;
}
}
}
_addExplicitPropertyCreator(ctxt, beanDesc, creators, candidate);
return;
}
// And here be the "simple" single-argument construct
final AnnotatedParameter param = candidate.parameter(0);
final JacksonInject.Value injectId = candidate.injection(0);
PropertyName paramName = null;
boolean useProps;
switch (ctorDetector.singleArgMode()) {
case DELEGATING:
useProps = false;
break;
case PROPERTIES:
useProps = true;
// 13-Sep-2020, tatu: since we are configured to prefer Properties-style,
// any name (explicit OR implicit does):
paramName = candidate.paramName(0);
// [databind#2977]: Need better exception if name missing
if (paramName == null) {
_validateNamedPropertyParameter(ctxt, beanDesc, candidate, 0,
paramName, injectId);
}
break;
case REQUIRE_MODE:
ctxt.reportBadTypeDefinition(beanDesc,
"Single-argument constructor (%s) is annotated but no 'mode' defined; `CreatorDetector`"
+ "configured with `SingleArgConstructor.REQUIRE_MODE`",
candidate.creator());
return;
case HEURISTIC:
default:
{ // Note: behavior pre-Jackson-2.12
final BeanPropertyDefinition paramDef = candidate.propertyDef(0);
// with heuristic, need to start with just explicit name
paramName = candidate.explicitParamName(0);
// If there's injection or explicit name, should be properties-based
useProps = (paramName != null) || (injectId != null);
if (!useProps && (paramDef != null)) {
// One more thing: if implicit name matches property with a getter
// or field, we'll consider it property-based as well
// 25-May-2018, tatu: as per [databind#2051], looks like we have to get
// not implicit name, but name with possible strategy-based-rename
// paramName = candidate.findImplicitParamName(0);
paramName = candidate.paramName(0);
useProps = (paramName != null) && paramDef.couldSerialize();
}
}
}
if (useProps) {
SettableBeanProperty[] properties = new SettableBeanProperty[] {
constructCreatorProperty(ctxt, beanDesc, paramName, 0, param, injectId)
};
creators.addPropertyCreator(candidate.creator(), true, properties);
return;
}
_handleSingleArgumentCreator(creators, candidate.creator(), true, true);
// one more thing: sever link to creator property, to avoid possible later
// problems with "unresolved" constructor property
final BeanPropertyDefinition paramDef = candidate.propertyDef(0);
if (paramDef != null) {
((POJOPropertyBuilder) paramDef).removeConstructors();
}
}
private boolean _checkIfCreatorPropertyBased(AnnotationIntrospector intr,
AnnotatedWithParams creator, BeanPropertyDefinition propDef)
{
// If explicit name, or inject id, property-based
if (((propDef != null) && propDef.isExplicitlyNamed())
|| (intr.findInjectableValue(creator.getParameter(0)) != null)) {
return true;
}
if (propDef != null) {
// One more thing: if implicit name matches property with a getter
// or field, we'll consider it property-based as well
String implName = propDef.getName();
if (implName != null && !implName.isEmpty()) {
if (propDef.couldSerialize()) {
return true;
}
}
}
// in absence of everything else, default to delegating
return false;
}
private void _checkImplicitlyNamedConstructors(DeserializationContext ctxt,
BeanDescription beanDesc, VisibilityChecker<?> vchecker,
AnnotationIntrospector intr, CreatorCollector creators,
List<AnnotatedWithParams> implicitCtors) throws JsonMappingException
{
AnnotatedWithParams found = null;
SettableBeanProperty[] foundProps = null;
// Further checks: (a) must have names for all parameters, (b) only one visible
// Also, since earlier matching of properties and creators relied on existence of
// `@JsonCreator` (or equivalent) annotation, we need to do bit more re-inspection...
main_loop:
for (AnnotatedWithParams ctor : implicitCtors) {
if (!vchecker.isCreatorVisible(ctor)) {
continue;
}
// as per earlier notes, only end up here if no properties associated with creator
final int argCount = ctor.getParameterCount();
SettableBeanProperty[] properties = new SettableBeanProperty[argCount];
for (int i = 0; i < argCount; ++i) {
final AnnotatedParameter param = ctor.getParameter(i);
final PropertyName name = _findParamName(param, intr);
// must have name (implicit fine)
if (name == null || name.isEmpty()) {
continue main_loop;
}
properties[i] = constructCreatorProperty(ctxt, beanDesc, name, param.getIndex(),
param, /*injectId*/ null);
}
if (found != null) { // only one allowed; but multiple not an error
found = null;
break;
}
found = ctor;
foundProps = properties;
}
// found one and only one visible? Ship it!
if (found != null) {
creators.addPropertyCreator(found, /*isCreator*/ false, foundProps);
BasicBeanDescription bbd = (BasicBeanDescription) beanDesc;
// Also: add properties, to keep error messages complete wrt known properties...
for (SettableBeanProperty prop : foundProps) {
PropertyName pn = prop.getFullName();
if (!bbd.hasProperty(pn)) {
BeanPropertyDefinition newDef = SimpleBeanPropertyDefinition.construct(
ctxt.getConfig(), prop.getMember(), pn);
bbd.addProperty(newDef);
}
}
}
}
protected boolean _handleSingleArgumentCreator(CreatorCollector creators,
AnnotatedWithParams ctor, boolean isCreator, boolean isVisible)
{
// otherwise either 'simple' number, String, or general delegate:
Class<?> type = ctor.getRawParameterType(0);
if (type == String.class || type == CLASS_CHAR_SEQUENCE) {
if (isCreator || isVisible) {
creators.addStringCreator(ctor, isCreator);
}
return true;
}
if (type == int.class || type == Integer.class) {
if (isCreator || isVisible) {
creators.addIntCreator(ctor, isCreator);
}
return true;
}
if (type == long.class || type == Long.class) {
if (isCreator || isVisible) {
creators.addLongCreator(ctor, isCreator);
}
return true;
}
if (type == double.class || type == Double.class) {
if (isCreator || isVisible) {
creators.addDoubleCreator(ctor, isCreator);
}
return true;
}
if (type == boolean.class || type == Boolean.class) {
if (isCreator || isVisible) {
creators.addBooleanCreator(ctor, isCreator);
}
return true;
}
if (type == BigInteger.class) {
if (isCreator || isVisible) {
creators.addBigIntegerCreator(ctor, isCreator);
}
}
if (type == BigDecimal.class) {
if (isCreator || isVisible) {
creators.addBigDecimalCreator(ctor, isCreator);
}
}
// Delegating Creator ok iff it has @JsonCreator (etc)
if (isCreator) {
creators.addDelegatingCreator(ctor, isCreator, null, 0);
return true;
}
return false;
}
// Helper method to check that parameter of Property-based creator either
// has name or is marked as Injectable
//
// @since 2.12.1
protected void _validateNamedPropertyParameter(DeserializationContext ctxt,
BeanDescription beanDesc,
CreatorCandidate candidate, int paramIndex,
PropertyName name, JacksonInject.Value injectId)
throws JsonMappingException
{
// Must be injectable or have name; without either won't work
if ((name == null) && (injectId == null)) {
ctxt.reportBadTypeDefinition(beanDesc,
"Argument #%d of constructor %s has no property name (and is not Injectable): can not use as property-based Creator",
paramIndex, candidate);
}
}
// 01-Dec-2016, tatu: As per [databind#265] we cannot yet support passing
// of unwrapped values through creator properties, so fail fast
protected void _reportUnwrappedCreatorProperty(DeserializationContext ctxt,
BeanDescription beanDesc, AnnotatedParameter param)
throws JsonMappingException
{
ctxt.reportBadTypeDefinition(beanDesc,
"Cannot define Creator parameter %d as `@JsonUnwrapped`: combination not yet supported",
param.getIndex());
}
/**
* Method that will construct a property object that represents
* a logical property passed via Creator (constructor or static
* factory method)
*/
protected SettableBeanProperty constructCreatorProperty(DeserializationContext ctxt,
BeanDescription beanDesc, PropertyName name, int index,
AnnotatedParameter param,
JacksonInject.Value injectable)
throws JsonMappingException
{
final DeserializationConfig config = ctxt.getConfig();
final AnnotationIntrospector intr = ctxt.getAnnotationIntrospector();
PropertyMetadata metadata;
final PropertyName wrapperName;
{
if (intr == null) {
metadata = PropertyMetadata.STD_REQUIRED_OR_OPTIONAL;
wrapperName = null;
} else {
Boolean b = intr.hasRequiredMarker(param);
String desc = intr.findPropertyDescription(param);
Integer idx = intr.findPropertyIndex(param);
String def = intr.findPropertyDefaultValue(param);
metadata = PropertyMetadata.construct(b, desc, idx, def);
wrapperName = intr.findWrapperName(param);
}
}
JavaType type = resolveMemberAndTypeAnnotations(ctxt, param, param.getType());
BeanProperty.Std property = new BeanProperty.Std(name, type,
wrapperName, param, metadata);
// Type deserializer: either comes from property (and already resolved)
TypeDeserializer typeDeser = (TypeDeserializer) type.getTypeHandler();
// or if not, based on type being referenced:
if (typeDeser == null) {
typeDeser = findTypeDeserializer(config, type);
}
// 22-Sep-2019, tatu: for [databind#2458] need more work on getting metadata
// about SetterInfo, mergeability
metadata = _getSetterInfo(ctxt, property, metadata);
// Note: contextualization of typeDeser _should_ occur in constructor of CreatorProperty
// so it is not called directly here
SettableBeanProperty prop = CreatorProperty.construct(name, type, property.getWrapperName(),
typeDeser, beanDesc.getClassAnnotations(), param, index, injectable,
metadata);
JsonDeserializer<?> deser = findDeserializerFromAnnotation(ctxt, param);
if (deser == null) {
deser = type.getValueHandler();
}
if (deser != null) {
// As per [databind#462] need to ensure we contextualize deserializer before passing it on
deser = ctxt.handlePrimaryContextualization(deser, prop, type);
prop = prop.withValueDeserializer(deser);
}
return prop;
}
private PropertyName _findParamName(AnnotatedParameter param, AnnotationIntrospector intr)
{
if (intr != null) {
PropertyName name = intr.findNameForDeserialization(param);
if (name != null) {
// 16-Nov-2020, tatu: One quirk, wrt [databind#2932]; may get "use implicit"
// marker; should not return that
if (!name.isEmpty()) {
return name;
}
}
// 14-Apr-2014, tatu: Need to also consider possible implicit name
// (for JDK8, or via paranamer)
String str = intr.findImplicitPropertyName(param);
if (str != null && !str.isEmpty()) {
return PropertyName.construct(str);
}
}
return null;
}
/**
* Helper method copied from {@code POJOPropertyBuilder} since that won't be
* applied to creator parameters
*
* @since 2.10
*/
protected PropertyMetadata _getSetterInfo(DeserializationContext ctxt,
BeanProperty prop, PropertyMetadata metadata)
{
final AnnotationIntrospector intr = ctxt.getAnnotationIntrospector();
final DeserializationConfig config = ctxt.getConfig();
boolean needMerge = true;
Nulls valueNulls = null;
Nulls contentNulls = null;
// NOTE: compared to `POJOPropertyBuilder`, we only have access to creator
// parameter, not other accessors, so code bit simpler
AnnotatedMember prim = prop.getMember();
if (prim != null) {
// Ok, first: does property itself have something to say?
if (intr != null) {
JsonSetter.Value setterInfo = intr.findSetterInfo(prim);
if (setterInfo != null) {
valueNulls = setterInfo.nonDefaultValueNulls();
contentNulls = setterInfo.nonDefaultContentNulls();
}
}
// If not, config override?
// 25-Oct-2016, tatu: Either this, or type of accessor...
if (needMerge || (valueNulls == null) || (contentNulls == null)) {
ConfigOverride co = config.getConfigOverride(prop.getType().getRawClass());
JsonSetter.Value setterInfo = co.getSetterInfo();
if (setterInfo != null) {
if (valueNulls == null) {
valueNulls = setterInfo.nonDefaultValueNulls();
}
if (contentNulls == null) {
contentNulls = setterInfo.nonDefaultContentNulls();
}
}
}
}
if (needMerge || (valueNulls == null) || (contentNulls == null)) {
JsonSetter.Value setterInfo = config.getDefaultSetterInfo();
if (valueNulls == null) {
valueNulls = setterInfo.nonDefaultValueNulls();
}
if (contentNulls == null) {
contentNulls = setterInfo.nonDefaultContentNulls();
}
}
if ((valueNulls != null) || (contentNulls != null)) {
metadata = metadata.withNulls(valueNulls, contentNulls);
}
return metadata;
}
/*
/**********************************************************
/* DeserializerFactory impl: array deserializers
/**********************************************************
*/
@Override
public JsonDeserializer<?> createArrayDeserializer(DeserializationContext ctxt,
ArrayType type, final BeanDescription beanDesc)
throws JsonMappingException
{
final DeserializationConfig config = ctxt.getConfig();
JavaType elemType = type.getContentType();
// Very first thing: is deserializer hard-coded for elements?
JsonDeserializer<Object> contentDeser = elemType.getValueHandler();
// Then optional type info: if type has been resolved, we may already know type deserializer:
TypeDeserializer elemTypeDeser = elemType.getTypeHandler();
// but if not, may still be possible to find:
if (elemTypeDeser == null) {
elemTypeDeser = findTypeDeserializer(config, elemType);
}
// 23-Nov-2010, tatu: Custom array deserializer?
JsonDeserializer<?> deser = _findCustomArrayDeserializer(type,
config, beanDesc, elemTypeDeser, contentDeser);
if (deser == null) {
if (contentDeser == null) {
Class<?> raw = elemType.getRawClass();
if (elemType.isPrimitive()) {
return PrimitiveArrayDeserializers.forType(raw);
}
if (raw == String.class) {
return StringArrayDeserializer.instance;
}
}
deser = new ObjectArrayDeserializer(type, contentDeser, elemTypeDeser);
}
// and then new with 2.2: ability to post-process it too (databind#120)
if (_factoryConfig.hasDeserializerModifiers()) {
for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
deser = mod.modifyArrayDeserializer(config, type, beanDesc, deser);
}
}
return deser;
}
/*
/**********************************************************************
/* DeserializerFactory impl: Collection(-like) deserializers
/**********************************************************************
*/
@Override
public JsonDeserializer<?> createCollectionDeserializer(DeserializationContext ctxt,
CollectionType type, BeanDescription beanDesc)
throws JsonMappingException
{
JavaType contentType = type.getContentType();
// Very first thing: is deserializer hard-coded for elements?
JsonDeserializer<Object> contentDeser = contentType.getValueHandler();
final DeserializationConfig config = ctxt.getConfig();
// Then optional type info: if type has been resolved, we may already know type deserializer:
TypeDeserializer contentTypeDeser = contentType.getTypeHandler();
// but if not, may still be possible to find:
if (contentTypeDeser == null) {
contentTypeDeser = findTypeDeserializer(config, contentType);
}
// 23-Nov-2010, tatu: Custom deserializer?
JsonDeserializer<?> deser = _findCustomCollectionDeserializer(type,
config, beanDesc, contentTypeDeser, contentDeser);
if (deser == null) {
Class<?> collectionClass = type.getRawClass();
if (contentDeser == null) { // not defined by annotation
// One special type: EnumSet:
if (EnumSet.class.isAssignableFrom(collectionClass)) {
deser = new EnumSetDeserializer(contentType, null);
}
}
}
/* One twist: if we are being asked to instantiate an interface or
* abstract Collection, we need to either find something that implements
* the thing, or give up.
*
* Note that we do NOT try to guess based on secondary interfaces
* here; that would probably not work correctly since casts would
* fail later on (as the primary type is not the interface we'd
* be implementing)
*/
if (deser == null) {
if (type.isInterface() || type.isAbstract()) {
CollectionType implType = _mapAbstractCollectionType(type, config);
if (implType == null) {
// [databind#292]: Actually, may be fine, but only if polymorphich deser enabled
if (type.getTypeHandler() == null) {
throw new IllegalArgumentException("Cannot find a deserializer for non-concrete Collection type "+type);
}
deser = AbstractDeserializer.constructForNonPOJO(beanDesc);
} else {
type = implType;
// But if so, also need to re-check creators...
beanDesc = config.introspectForCreation(type);
}
}
if (deser == null) {
ValueInstantiator inst = findValueInstantiator(ctxt, beanDesc);
if (!inst.canCreateUsingDefault()) {
// [databind#161]: No default constructor for ArrayBlockingQueue...
if (type.hasRawClass(ArrayBlockingQueue.class)) {
return new ArrayBlockingQueueDeserializer(type, contentDeser, contentTypeDeser, inst);
}
// 10-Jan-2017, tatu: `java.util.Collections` types need help:
deser = JavaUtilCollectionsDeserializers.findForCollection(ctxt, type);
if (deser != null) {
return deser;
}
}
// Can use more optimal deserializer if content type is String, so:
if (contentType.hasRawClass(String.class)) {
// no value type deserializer because Strings are one of natural/native types:
deser = new StringCollectionDeserializer(type, contentDeser, inst);
} else {
deser = new CollectionDeserializer(type, contentDeser, contentTypeDeser, inst);
}
}
}
// allow post-processing it too
if (_factoryConfig.hasDeserializerModifiers()) {
for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
deser = mod.modifyCollectionDeserializer(config, type, beanDesc, deser);
}
}
return deser;
}
protected CollectionType _mapAbstractCollectionType(JavaType type, DeserializationConfig config)
{
final Class<?> collectionClass = ContainerDefaultMappings.findCollectionFallback(type);
if (collectionClass != null) {
return (CollectionType) config.getTypeFactory()
.constructSpecializedType(type, collectionClass, true);
}
return null;
}
// Copied almost verbatim from "createCollectionDeserializer" -- should try to share more code
@Override
public JsonDeserializer<?> createCollectionLikeDeserializer(DeserializationContext ctxt,
CollectionLikeType type, final BeanDescription beanDesc)
throws JsonMappingException
{
JavaType contentType = type.getContentType();
// Very first thing: is deserializer hard-coded for elements?
JsonDeserializer<Object> contentDeser = contentType.getValueHandler();
final DeserializationConfig config = ctxt.getConfig();
// Then optional type info (1.5): if type has been resolved, we may already know type deserializer:
TypeDeserializer contentTypeDeser = contentType.getTypeHandler();
// but if not, may still be possible to find:
if (contentTypeDeser == null) {
contentTypeDeser = findTypeDeserializer(config, contentType);
}
JsonDeserializer<?> deser = _findCustomCollectionLikeDeserializer(type, config, beanDesc,
contentTypeDeser, contentDeser);
if (deser != null) {
// and then new with 2.2: ability to post-process it too (Issue#120)
if (_factoryConfig.hasDeserializerModifiers()) {
for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
deser = mod.modifyCollectionLikeDeserializer(config, type, beanDesc, deser);
}
}
}
return deser;
}
/*
/**********************************************************
/* DeserializerFactory impl: Map(-like) deserializers
/**********************************************************
*/
@Override
public JsonDeserializer<?> createMapDeserializer(DeserializationContext ctxt,
MapType type, BeanDescription beanDesc)
throws JsonMappingException
{
final DeserializationConfig config = ctxt.getConfig();
JavaType keyType = type.getKeyType();
JavaType contentType = type.getContentType();
// First: is there annotation-specified deserializer for values?
@SuppressWarnings("unchecked")
JsonDeserializer<Object> contentDeser = (JsonDeserializer<Object>) contentType.getValueHandler();
// Ok: need a key deserializer (null indicates 'default' here)
KeyDeserializer keyDes = (KeyDeserializer) keyType.getValueHandler();
// Then optional type info; either attached to type, or resolved separately:
TypeDeserializer contentTypeDeser = contentType.getTypeHandler();
// but if not, may still be possible to find:
if (contentTypeDeser == null) {
contentTypeDeser = findTypeDeserializer(config, contentType);
}
// 23-Nov-2010, tatu: Custom deserializer?
JsonDeserializer<?> deser = _findCustomMapDeserializer(type, config, beanDesc,
keyDes, contentTypeDeser, contentDeser);
if (deser == null) {
// Value handling is identical for all, but EnumMap requires special handling for keys
Class<?> mapClass = type.getRawClass();
if (EnumMap.class.isAssignableFrom(mapClass)) {
ValueInstantiator inst;
// 06-Mar-2017, tatu: Should only need to check ValueInstantiator for
// custom sub-classes, see [databind#1544]
if (mapClass == EnumMap.class) {
inst = null;
} else {
inst = findValueInstantiator(ctxt, beanDesc);
}
if (!keyType.isEnumImplType()) {
throw new IllegalArgumentException("Cannot construct EnumMap; generic (key) type not available");
}
deser = new EnumMapDeserializer(type, inst, null,
contentDeser, contentTypeDeser, null);
}
// Otherwise, generic handler works ok.
/* But there is one more twist: if we are being asked to instantiate
* an interface or abstract Map, we need to either find something
* that implements the thing, or give up.
*
* Note that we do NOT try to guess based on secondary interfaces
* here; that would probably not work correctly since casts would
* fail later on (as the primary type is not the interface we'd
* be implementing)
*/
if (deser == null) {
if (type.isInterface() || type.isAbstract()) {
MapType fallback = _mapAbstractMapType(type, config);
if (fallback != null) {
type = (MapType) fallback;
mapClass = type.getRawClass();
// But if so, also need to re-check creators...
beanDesc = config.introspectForCreation(type);
} else {
// [databind#292]: Actually, may be fine, but only if polymorphic deser enabled
if (type.getTypeHandler() == null) {
throw new IllegalArgumentException("Cannot find a deserializer for non-concrete Map type "+type);
}
deser = AbstractDeserializer.constructForNonPOJO(beanDesc);
}
} else {
// 10-Jan-2017, tatu: `java.util.Collections` types need help:
deser = JavaUtilCollectionsDeserializers.findForMap(ctxt, type);
if (deser != null) {
return deser;
}
}
if (deser == null) {
ValueInstantiator inst = findValueInstantiator(ctxt, beanDesc);
// 01-May-2016, tatu: Which base type to use here gets tricky, since
// most often it ought to be `Map` or `EnumMap`, but due to abstract
// mapping it will more likely be concrete type like `HashMap`.
// So, for time being, just pass `Map.class`
MapDeserializer md = new MapDeserializer(type, inst, keyDes, contentDeser, contentTypeDeser);
JsonIgnoreProperties.Value ignorals = config.getDefaultPropertyIgnorals(Map.class,
beanDesc.getClassInfo());
Set<String> ignored = (ignorals == null) ? null
: ignorals.findIgnoredForDeserialization();
md.setIgnorableProperties(ignored);
JsonIncludeProperties.Value inclusions = config.getDefaultPropertyInclusions(Map.class,
beanDesc.getClassInfo());
Set<String> included = inclusions == null ? null : inclusions.getIncluded();
md.setIncludableProperties(included);
deser = md;
}
}
}
if (_factoryConfig.hasDeserializerModifiers()) {
for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
deser = mod.modifyMapDeserializer(config, type, beanDesc, deser);
}
}
return deser;
}
protected MapType _mapAbstractMapType(JavaType type, DeserializationConfig config)
{
final Class<?> mapClass = ContainerDefaultMappings.findMapFallback(type);
if (mapClass != null) {
return (MapType) config.getTypeFactory()
.constructSpecializedType(type, mapClass, true);
}
return null;
}
// Copied almost verbatim from "createMapDeserializer" -- should try to share more code
@Override
public JsonDeserializer<?> createMapLikeDeserializer(DeserializationContext ctxt,
MapLikeType type, final BeanDescription beanDesc)
throws JsonMappingException
{
JavaType keyType = type.getKeyType();
JavaType contentType = type.getContentType();
final DeserializationConfig config = ctxt.getConfig();
// First: is there annotation-specified deserializer for values?
@SuppressWarnings("unchecked")
JsonDeserializer<Object> contentDeser = (JsonDeserializer<Object>) contentType.getValueHandler();
// Ok: need a key deserializer (null indicates 'default' here)
KeyDeserializer keyDes = (KeyDeserializer) keyType.getValueHandler();
/* !!! 24-Jan-2012, tatu: NOTE: impls MUST use resolve() to find key deserializer!
if (keyDes == null) {
keyDes = p.findKeyDeserializer(config, keyType, property);
}
*/
// Then optional type info (1.5); either attached to type, or resolve separately:
TypeDeserializer contentTypeDeser = contentType.getTypeHandler();
// but if not, may still be possible to find:
if (contentTypeDeser == null) {
contentTypeDeser = findTypeDeserializer(config, contentType);
}
JsonDeserializer<?> deser = _findCustomMapLikeDeserializer(type, config,
beanDesc, keyDes, contentTypeDeser, contentDeser);
if (deser != null) {
// and then new with 2.2: ability to post-process it too (Issue#120)
if (_factoryConfig.hasDeserializerModifiers()) {
for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
deser = mod.modifyMapLikeDeserializer(config, type, beanDesc, deser);
}
}
}
return deser;
}
/*
/**********************************************************
/* DeserializerFactory impl: other types
/**********************************************************
*/
/**
* Factory method for constructing serializers of {@link Enum} types.
*/
@Override
public JsonDeserializer<?> createEnumDeserializer(DeserializationContext ctxt,
JavaType type, BeanDescription beanDesc)
throws JsonMappingException
{
final DeserializationConfig config = ctxt.getConfig();
final Class<?> enumClass = type.getRawClass();
// 23-Nov-2010, tatu: Custom deserializer?
JsonDeserializer<?> deser = _findCustomEnumDeserializer(enumClass, config, beanDesc);
if (deser == null) {
// 12-Feb-2020, tatu: while we can't really create real deserializer for `Enum.class`,
// it is necessary to allow it in one specific case: see [databind#2605] for details
// but basically it can be used as polymorphic base.
// We could check `type.getTypeHandler()` to look for that case but seems like we
// may as well simply create placeholder (AbstractDeserializer) regardless
if (enumClass == Enum.class) {
return AbstractDeserializer.constructForNonPOJO(beanDesc);
}
ValueInstantiator valueInstantiator = _constructDefaultValueInstantiator(ctxt, beanDesc);
SettableBeanProperty[] creatorProps = (valueInstantiator == null) ? null
: valueInstantiator.getFromObjectArguments(ctxt.getConfig());
// May have @JsonCreator for static factory method:
for (AnnotatedMethod factory : beanDesc.getFactoryMethods()) {
if (_hasCreatorAnnotation(ctxt, factory)) {
if (factory.getParameterCount() == 0) { // [databind#960]
deser = EnumDeserializer.deserializerForNoArgsCreator(config, enumClass, factory);
break;
}
Class<?> returnType = factory.getRawReturnType();
// usually should be class, but may be just plain Enum<?> (for Enum.valueOf()?)
if (!returnType.isAssignableFrom(enumClass)) {
ctxt.reportBadDefinition(type, String.format(
"Invalid `@JsonCreator` annotated Enum factory method [%s]: needs to return compatible type",
factory.toString()));
}
deser = EnumDeserializer.deserializerForCreator(config, enumClass, factory, valueInstantiator, creatorProps);
break;
}
}
// Need to consider @JsonValue if one found
if (deser == null) {
deser = new EnumDeserializer(constructEnumResolver(enumClass,
config, beanDesc.findJsonValueAccessor()),
config.isEnabled(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS));
}
}
// and then post-process it too
if (_factoryConfig.hasDeserializerModifiers()) {
for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
deser = mod.modifyEnumDeserializer(config, type, beanDesc, deser);
}
}
return deser;
}
@Override
public JsonDeserializer<?> createTreeDeserializer(DeserializationConfig config,
JavaType nodeType, BeanDescription beanDesc)
throws JsonMappingException
{
@SuppressWarnings("unchecked")
Class<? extends JsonNode> nodeClass = (Class<? extends JsonNode>) nodeType.getRawClass();
// 23-Nov-2010, tatu: Custom deserializer?
JsonDeserializer<?> custom = _findCustomTreeNodeDeserializer(nodeClass, config,
beanDesc);
if (custom != null) {
return custom;
}
return JsonNodeDeserializer.getDeserializer(nodeClass);
}
@Override
public JsonDeserializer<?> createReferenceDeserializer(DeserializationContext ctxt,
ReferenceType type, BeanDescription beanDesc)
throws JsonMappingException
{
JavaType contentType = type.getContentType();
// Very first thing: is deserializer hard-coded for elements?
JsonDeserializer<Object> contentDeser = contentType.getValueHandler();
final DeserializationConfig config = ctxt.getConfig();
// Then optional type info: if type has been resolved, we may already know type deserializer:
TypeDeserializer contentTypeDeser = contentType.getTypeHandler();
if (contentTypeDeser == null) { // or if not, may be able to find:
contentTypeDeser = findTypeDeserializer(config, contentType);
}
JsonDeserializer<?> deser = _findCustomReferenceDeserializer(type, config, beanDesc,
contentTypeDeser, contentDeser);
if (deser == null) {
// Just one referential type as of JDK 1.7 / Java 7: AtomicReference (Java 8 adds Optional)
if (type.isTypeOrSubTypeOf(AtomicReference.class)) {
Class<?> rawType = type.getRawClass();
ValueInstantiator inst;
if (rawType == AtomicReference.class) {
inst = null;
} else {
/* 23-Oct-2016, tatu: Note that subtypes are probably not supportable
* without either forcing merging (to avoid having to create instance)
* or something else...
*/
inst = findValueInstantiator(ctxt, beanDesc);
}
return new AtomicReferenceDeserializer(type, inst, contentTypeDeser, contentDeser);
}
}
if (deser != null) {
// and then post-process
if (_factoryConfig.hasDeserializerModifiers()) {
for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
deser = mod.modifyReferenceDeserializer(config, type, beanDesc, deser);
}
}
}
return deser;
}
/*
/**********************************************************
/* DeserializerFactory impl (partial): type deserializers
/**********************************************************
*/
@Override
public TypeDeserializer findTypeDeserializer(DeserializationConfig config,
JavaType baseType)
throws JsonMappingException
{
BeanDescription bean = config.introspectClassAnnotations(baseType.getRawClass());
AnnotatedClass ac = bean.getClassInfo();
AnnotationIntrospector ai = config.getAnnotationIntrospector();
TypeResolverBuilder<?> b = ai.findTypeResolver(config, ac, baseType);
// Ok: if there is no explicit type info handler, we may want to
// use a default. If so, config object knows what to use.
Collection<NamedType> subtypes = null;
if (b == null) {
b = config.getDefaultTyper(baseType);
if (b == null) {
return null;
}
} else {
subtypes = config.getSubtypeResolver().collectAndResolveSubtypesByTypeId(config, ac);
}
// May need to figure out default implementation, if none found yet
// (note: check for abstract type is not 100% mandatory, more of an optimization)
if ((b.getDefaultImpl() == null) && baseType.isAbstract()) {
JavaType defaultType = mapAbstractType(config, baseType);
// 18-Sep-2021, tatu: We have a shared instance, MUST NOT call mutating method
// but the new "mutant factory":
if ((defaultType != null) && !defaultType.hasRawClass(baseType.getRawClass())) {
b = b.withDefaultImpl(defaultType.getRawClass());
}
}
// 05-Apt-2018, tatu: Since we get non-mapping exception due to various limitations,
// map to better type here
try {
return b.buildTypeDeserializer(config, baseType, subtypes);
} catch (IllegalArgumentException | IllegalStateException e0) {
throw InvalidDefinitionException.from((JsonParser) null,
ClassUtil.exceptionMessage(e0), baseType)
.withCause(e0);
}
}
/**
* Overridable method called after checking all other types.
*
* @since 2.2
*/
protected JsonDeserializer<?> findOptionalStdDeserializer(DeserializationContext ctxt,
JavaType type, BeanDescription beanDesc)
throws JsonMappingException
{
return OptionalHandlerFactory.instance.findDeserializer(type, ctxt.getConfig(), beanDesc);
}
/*
/**********************************************************
/* DeserializerFactory impl (partial): key deserializers
/**********************************************************
*/
@Override
public KeyDeserializer createKeyDeserializer(DeserializationContext ctxt,
JavaType type)
throws JsonMappingException
{
final DeserializationConfig config = ctxt.getConfig();
BeanDescription beanDesc = null;
KeyDeserializer deser = null;
if (_factoryConfig.hasKeyDeserializers()) {
beanDesc = config.introspectClassAnnotations(type);
for (KeyDeserializers d : _factoryConfig.keyDeserializers()) {
deser = d.findKeyDeserializer(type, config, beanDesc);
if (deser != null) {
break;
}
}
}
// the only non-standard thing is this:
if (deser == null) {
// [databind#2452]: Support `@JsonDeserialize(keyUsing = ...)`
if (beanDesc == null) {
beanDesc = config.introspectClassAnnotations(type.getRawClass());
}
deser = findKeyDeserializerFromAnnotation(ctxt, beanDesc.getClassInfo());
if (deser == null) {
if (type.isEnumType()) {
deser = _createEnumKeyDeserializer(ctxt, type);
} else {
deser = StdKeyDeserializers.findStringBasedKeyDeserializer(config, type);
}
}
}
// and then post-processing
if (deser != null) {
if (_factoryConfig.hasDeserializerModifiers()) {
for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
deser = mod.modifyKeyDeserializer(config, type, deser);
}
}
}
return deser;
}
private KeyDeserializer _createEnumKeyDeserializer(DeserializationContext ctxt,
JavaType type)
throws JsonMappingException
{
final DeserializationConfig config = ctxt.getConfig();
Class<?> enumClass = type.getRawClass();
BeanDescription beanDesc = config.introspect(type);
// 24-Sep-2015, bim: a key deserializer is the preferred thing.
KeyDeserializer des = findKeyDeserializerFromAnnotation(ctxt, beanDesc.getClassInfo());
if (des != null) {
return des;
} else {
// 24-Sep-2015, bim: if no key deser, look for enum deserializer first, then a plain deser.
JsonDeserializer<?> custom = _findCustomEnumDeserializer(enumClass, config, beanDesc);
if (custom != null) {
return StdKeyDeserializers.constructDelegatingKeyDeserializer(config, type, custom);
}
JsonDeserializer<?> valueDesForKey = findDeserializerFromAnnotation(ctxt, beanDesc.getClassInfo());
if (valueDesForKey != null) {
return StdKeyDeserializers.constructDelegatingKeyDeserializer(config, type, valueDesForKey);
}
}
EnumResolver enumRes = constructEnumResolver(enumClass, config, beanDesc.findJsonValueAccessor());
// May have @JsonCreator for static factory method
for (AnnotatedMethod factory : beanDesc.getFactoryMethods()) {
if (_hasCreatorAnnotation(ctxt, factory)) {
int argCount = factory.getParameterCount();
if (argCount == 1) {
Class<?> returnType = factory.getRawReturnType();
// usually should be class, but may be just plain Enum<?> (for Enum.valueOf()?)
if (returnType.isAssignableFrom(enumClass)) {
// note: mostly copied from 'EnumDeserializer.deserializerForCreator(...)'
if (factory.getRawParameterType(0) != String.class) {
// [databind#2725]: Should not error out because (1) there may be good creator
// method and (2) this method may be valid for "regular" enum value deserialization
// (leaving aside potential for multiple conflicting creators)
// throw new IllegalArgumentException("Parameter #0 type for factory method ("+factory+") not suitable, must be java.lang.String");
continue;
}
if (config.canOverrideAccessModifiers()) {
ClassUtil.checkAndFixAccess(factory.getMember(),
ctxt.isEnabled(MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS));
}
return StdKeyDeserializers.constructEnumKeyDeserializer(enumRes, factory);
}
}
throw new IllegalArgumentException("Unsuitable method ("+factory+") decorated with @JsonCreator (for Enum type "
+enumClass.getName()+")");
}
}
// Also, need to consider @JsonValue, if one found
return StdKeyDeserializers.constructEnumKeyDeserializer(enumRes);
}
/*
/**********************************************************
/* DeserializerFactory impl: checking explicitly registered desers
/**********************************************************
*/
@Override
public boolean hasExplicitDeserializerFor(DeserializationConfig config,
Class<?> valueType)
{
// First things first: unpeel Array types as the element type is
// what we are interested in -- this because we will always support array
// types via composition, and since array types are JDK provided (and hence
// can not be custom or customized).
while (valueType.isArray()) {
valueType = valueType.getComponentType();
}
// Yes, we handle all Enum types
if (Enum.class.isAssignableFrom(valueType)) {
return true;
}
// Numbers?
final String clsName = valueType.getName();
if (clsName.startsWith("java.")) {
if (Collection.class.isAssignableFrom(valueType)) {
return true;
}
if (Map.class.isAssignableFrom(valueType)) {
return true;
}
if (Number.class.isAssignableFrom(valueType)) {
return NumberDeserializers.find(valueType, clsName) != null;
}
if (JdkDeserializers.hasDeserializerFor(valueType)
|| (valueType == CLASS_STRING)
|| (valueType == Boolean.class)
|| (valueType == EnumMap.class)
|| (valueType == AtomicReference.class)
) {
return true;
}
if (DateDeserializers.hasDeserializerFor(valueType)) {
return true;
}
} else if (clsName.startsWith("com.fasterxml.")) {
return JsonNode.class.isAssignableFrom(valueType)
|| (valueType == TokenBuffer.class);
} else {
return OptionalHandlerFactory.instance.hasDeserializerFor(valueType);
}
return false;
}
/*
/**********************************************************
/* Extended API
/**********************************************************
*/
/**
* Method called to create a type information deserializer for values of
* given non-container property, if one is needed.
* If not needed (no polymorphic handling configured for property), should return null.
*<p>
* Note that this method is only called for non-container bean properties,
* and not for values in container types or root values (or container properties)
*
* @param baseType Declared base type of the value to deserializer (actual
* deserializer type will be this type or its subtype)
*
* @return Type deserializer to use for given base type, if one is needed; null if not.
*/
public TypeDeserializer findPropertyTypeDeserializer(DeserializationConfig config,
JavaType baseType, AnnotatedMember annotated)
throws JsonMappingException
{
AnnotationIntrospector ai = config.getAnnotationIntrospector();
TypeResolverBuilder<?> b = ai.findPropertyTypeResolver(config, annotated, baseType);
// Defaulting: if no annotations on member, check value class
if (b == null) {
return findTypeDeserializer(config, baseType);
}
// but if annotations found, may need to resolve subtypes:
Collection<NamedType> subtypes = config.getSubtypeResolver().collectAndResolveSubtypesByTypeId(
config, annotated, baseType);
try {
return b.buildTypeDeserializer(config, baseType, subtypes);
} catch (IllegalArgumentException | IllegalStateException e0) {
throw InvalidDefinitionException.from((JsonParser) null,
ClassUtil.exceptionMessage(e0), baseType)
.withCause(e0);
}
}
/**
* Method called to find and create a type information deserializer for values of
* given container (list, array, map) property, if one is needed.
* If not needed (no polymorphic handling configured for property), should return null.
*<p>
* Note that this method is only called for container bean properties,
* and not for values in container types or root values (or non-container properties)
*
* @param containerType Type of property; must be a container type
* @param propertyEntity Field or method that contains container property
*/
public TypeDeserializer findPropertyContentTypeDeserializer(DeserializationConfig config,
JavaType containerType, AnnotatedMember propertyEntity)
throws JsonMappingException
{
AnnotationIntrospector ai = config.getAnnotationIntrospector();
TypeResolverBuilder<?> b = ai.findPropertyContentTypeResolver(config, propertyEntity, containerType);
JavaType contentType = containerType.getContentType();
// Defaulting: if no annotations on member, check class
if (b == null) {
return findTypeDeserializer(config, contentType);
}
// but if annotations found, may need to resolve subtypes:
Collection<NamedType> subtypes = config.getSubtypeResolver().collectAndResolveSubtypesByTypeId(
config, propertyEntity, contentType);
return b.buildTypeDeserializer(config, contentType, subtypes);
}
/**
* Helper method called to find one of default serializers for "well-known"
* platform types: JDK-provided types, and small number of public Jackson
* API types.
*
* @since 2.2
*/
public JsonDeserializer<?> findDefaultDeserializer(DeserializationContext ctxt,
JavaType type, BeanDescription beanDesc)
throws JsonMappingException
{
Class<?> rawType = type.getRawClass();
// Object ("untyped"), and as of 2.10 (see [databind#2115]), `java.io.Serializable`
if ((rawType == CLASS_OBJECT) || (rawType == CLASS_SERIALIZABLE)) {
// 11-Feb-2015, tatu: As per [databind#700] need to be careful wrt non-default Map, List.
DeserializationConfig config = ctxt.getConfig();
JavaType lt, mt;
if (_factoryConfig.hasAbstractTypeResolvers()) {
lt = _findRemappedType(config, List.class);
mt = _findRemappedType(config, Map.class);
} else {
lt = mt = null;
}
return new UntypedObjectDeserializer(lt, mt);
}
// String and equivalents
if (rawType == CLASS_STRING || rawType == CLASS_CHAR_SEQUENCE) {
return StringDeserializer.instance;
}
if (rawType == CLASS_ITERABLE) {
// [databind#199]: Can and should 'upgrade' to a Collection type:
TypeFactory tf = ctxt.getTypeFactory();
JavaType[] tps = tf.findTypeParameters(type, CLASS_ITERABLE);
JavaType elemType = (tps == null || tps.length != 1) ? TypeFactory.unknownType() : tps[0];
CollectionType ct = tf.constructCollectionType(Collection.class, elemType);
// Should we re-introspect beanDesc? For now let's not...
return createCollectionDeserializer(ctxt, ct, beanDesc);
}
if (rawType == CLASS_MAP_ENTRY) {
// 28-Apr-2015, tatu: TypeFactory does it all for us already so
JavaType kt = type.containedTypeOrUnknown(0);
JavaType vt = type.containedTypeOrUnknown(1);
TypeDeserializer vts = (TypeDeserializer) vt.getTypeHandler();
if (vts == null) {
vts = findTypeDeserializer(ctxt.getConfig(), vt);
}
JsonDeserializer<Object> valueDeser = vt.getValueHandler();
KeyDeserializer keyDes = (KeyDeserializer) kt.getValueHandler();
return new MapEntryDeserializer(type, keyDes, valueDeser, vts);
}
String clsName = rawType.getName();
if (rawType.isPrimitive() || clsName.startsWith("java.")) {
// Primitives/wrappers, other Numbers:
JsonDeserializer<?> deser = NumberDeserializers.find(rawType, clsName);
if (deser == null) {
deser = DateDeserializers.find(rawType, clsName);
}
if (deser != null) {
return deser;
}
}
// and a few Jackson types as well:
if (rawType == TokenBuffer.class) {
return new TokenBufferDeserializer();
}
JsonDeserializer<?> deser = findOptionalStdDeserializer(ctxt, type, beanDesc);
if (deser != null) {
return deser;
}
return JdkDeserializers.find(rawType, clsName);
}
protected JavaType _findRemappedType(DeserializationConfig config, Class<?> rawType) throws JsonMappingException {
JavaType type = mapAbstractType(config, config.constructType(rawType));
return (type == null || type.hasRawClass(rawType)) ? null : type;
}
/*
/**********************************************************
/* Helper methods, finding custom deserializers
/**********************************************************
*/
protected JsonDeserializer<?> _findCustomTreeNodeDeserializer(Class<? extends JsonNode> type,
DeserializationConfig config, BeanDescription beanDesc)
throws JsonMappingException
{
for (Deserializers d : _factoryConfig.deserializers()) {
JsonDeserializer<?> deser = d.findTreeNodeDeserializer(type, config, beanDesc);
if (deser != null) {
return deser;
}
}
return null;
}
protected JsonDeserializer<?> _findCustomReferenceDeserializer(ReferenceType type,
DeserializationConfig config, BeanDescription beanDesc,
TypeDeserializer contentTypeDeserializer, JsonDeserializer<?> contentDeserializer)
throws JsonMappingException
{
for (Deserializers d : _factoryConfig.deserializers()) {
JsonDeserializer<?> deser = d.findReferenceDeserializer(type, config, beanDesc,
contentTypeDeserializer, contentDeserializer);
if (deser != null) {
return deser;
}
}
return null;
}
@SuppressWarnings("unchecked")
protected JsonDeserializer<Object> _findCustomBeanDeserializer(JavaType type,
DeserializationConfig config, BeanDescription beanDesc)
throws JsonMappingException
{
for (Deserializers d : _factoryConfig.deserializers()) {
JsonDeserializer<?> deser = d.findBeanDeserializer(type, config, beanDesc);
if (deser != null) {
return (JsonDeserializer<Object>) deser;
}
}
return null;
}
protected JsonDeserializer<?> _findCustomArrayDeserializer(ArrayType type,
DeserializationConfig config, BeanDescription beanDesc,
TypeDeserializer elementTypeDeserializer, JsonDeserializer<?> elementDeserializer)
throws JsonMappingException
{
for (Deserializers d : _factoryConfig.deserializers()) {
JsonDeserializer<?> deser = d.findArrayDeserializer(type, config,
beanDesc, elementTypeDeserializer, elementDeserializer);
if (deser != null) {
return deser;
}
}
return null;
}
protected JsonDeserializer<?> _findCustomCollectionDeserializer(CollectionType type,
DeserializationConfig config, BeanDescription beanDesc,
TypeDeserializer elementTypeDeserializer, JsonDeserializer<?> elementDeserializer)
throws JsonMappingException
{
for (Deserializers d : _factoryConfig.deserializers()) {
JsonDeserializer<?> deser = d.findCollectionDeserializer(type, config, beanDesc,
elementTypeDeserializer, elementDeserializer);
if (deser != null) {
return deser;
}
}
return null;
}
protected JsonDeserializer<?> _findCustomCollectionLikeDeserializer(CollectionLikeType type,
DeserializationConfig config, BeanDescription beanDesc,
TypeDeserializer elementTypeDeserializer, JsonDeserializer<?> elementDeserializer)
throws JsonMappingException
{
for (Deserializers d : _factoryConfig.deserializers()) {
JsonDeserializer<?> deser = d.findCollectionLikeDeserializer(type, config, beanDesc,
elementTypeDeserializer, elementDeserializer);
if (deser != null) {
return deser;
}
}
return null;
}
protected JsonDeserializer<?> _findCustomEnumDeserializer(Class<?> type,
DeserializationConfig config, BeanDescription beanDesc)
throws JsonMappingException
{
for (Deserializers d : _factoryConfig.deserializers()) {
JsonDeserializer<?> deser = d.findEnumDeserializer(type, config, beanDesc);
if (deser != null) {
return deser;
}
}
return null;
}
protected JsonDeserializer<?> _findCustomMapDeserializer(MapType type,
DeserializationConfig config, BeanDescription beanDesc,
KeyDeserializer keyDeserializer,
TypeDeserializer elementTypeDeserializer, JsonDeserializer<?> elementDeserializer)
throws JsonMappingException
{
for (Deserializers d : _factoryConfig.deserializers()) {
JsonDeserializer<?> deser = d.findMapDeserializer(type, config, beanDesc,
keyDeserializer, elementTypeDeserializer, elementDeserializer);
if (deser != null) {
return deser;
}
}
return null;
}
protected JsonDeserializer<?> _findCustomMapLikeDeserializer(MapLikeType type,
DeserializationConfig config, BeanDescription beanDesc,
KeyDeserializer keyDeserializer,
TypeDeserializer elementTypeDeserializer, JsonDeserializer<?> elementDeserializer)
throws JsonMappingException
{
for (Deserializers d : _factoryConfig.deserializers()) {
JsonDeserializer<?> deser = d.findMapLikeDeserializer(type, config, beanDesc,
keyDeserializer, elementTypeDeserializer, elementDeserializer);
if (deser != null) {
return deser;
}
}
return null;
}
/*
/**********************************************************
/* Helper methods, value/content/key type introspection
/**********************************************************
*/
/**
* Helper method called to check if a class or method
* has annotation that tells which class to use for deserialization; and if
* so, to instantiate, that deserializer to use.
* Note that deserializer will NOT yet be contextualized so caller needs to
* take care to call contextualization appropriately.
* Returns null if no such annotation found.
*/
protected JsonDeserializer<Object> findDeserializerFromAnnotation(DeserializationContext ctxt,
Annotated ann)
throws JsonMappingException
{
AnnotationIntrospector intr = ctxt.getAnnotationIntrospector();
if (intr != null) {
Object deserDef = intr.findDeserializer(ann);
if (deserDef != null) {
return ctxt.deserializerInstance(ann, deserDef);
}
}
return null;
}
/**
* Helper method called to check if a class or method
* has annotation that tells which class to use for deserialization of {@link java.util.Map} keys.
* Returns null if no such annotation found.
*/
protected KeyDeserializer findKeyDeserializerFromAnnotation(DeserializationContext ctxt,
Annotated ann)
throws JsonMappingException
{
AnnotationIntrospector intr = ctxt.getAnnotationIntrospector();
if (intr != null) {
Object deserDef = intr.findKeyDeserializer(ann);
if (deserDef != null) {
return ctxt.keyDeserializerInstance(ann, deserDef);
}
}
return null;
}
/**
* @since 2.9
*/
protected JsonDeserializer<Object> findContentDeserializerFromAnnotation(DeserializationContext ctxt,
Annotated ann)
throws JsonMappingException
{
AnnotationIntrospector intr = ctxt.getAnnotationIntrospector();
if (intr != null) {
Object deserDef = intr.findContentDeserializer(ann);
if (deserDef != null) {
return ctxt.deserializerInstance(ann, deserDef);
}
}
return null;
}
/**
* Helper method used to resolve additional type-related annotation information
* like type overrides, or handler (serializer, deserializer) overrides,
* so that from declared field, property or constructor parameter type
* is used as the base and modified based on annotations, if any.
*
* @since 2.8 Combines functionality of <code>modifyTypeByAnnotation</code>
* and <code>resolveType</code>
*/
protected JavaType resolveMemberAndTypeAnnotations(DeserializationContext ctxt,
AnnotatedMember member, JavaType type)
throws JsonMappingException
{
AnnotationIntrospector intr = ctxt.getAnnotationIntrospector();
if (intr == null) {
return type;
}
// First things first: see if we can find annotations on declared
// type
if (type.isMapLikeType()) {
JavaType keyType = type.getKeyType();
if (keyType != null) {
Object kdDef = intr.findKeyDeserializer(member);
KeyDeserializer kd = ctxt.keyDeserializerInstance(member, kdDef);
if (kd != null) {
type = ((MapLikeType) type).withKeyValueHandler(kd);
keyType = type.getKeyType(); // just in case it's used below
}
}
}
if (type.hasContentType()) { // that is, is either container- or reference-type
Object cdDef = intr.findContentDeserializer(member);
JsonDeserializer<?> cd = ctxt.deserializerInstance(member, cdDef);
if (cd != null) {
type = type.withContentValueHandler(cd);
}
TypeDeserializer contentTypeDeser = findPropertyContentTypeDeserializer(
ctxt.getConfig(), type, (AnnotatedMember) member);
if (contentTypeDeser != null) {
type = type.withContentTypeHandler(contentTypeDeser);
}
}
TypeDeserializer valueTypeDeser = findPropertyTypeDeserializer(ctxt.getConfig(),
type, (AnnotatedMember) member);
if (valueTypeDeser != null) {
type = type.withTypeHandler(valueTypeDeser);
}
// Second part: find actual type-override annotations on member, if any
// 18-Jun-2016, tatu: Should we re-do checks for annotations on refined
// subtypes as well? Code pre-2.8 did not do this, but if we get bug
// reports may need to consider
type = intr.refineDeserializationType(ctxt.getConfig(), member, type);
return type;
}
protected EnumResolver constructEnumResolver(Class<?> enumClass,
DeserializationConfig config, AnnotatedMember jsonValueAccessor)
{
if (jsonValueAccessor != null) {
if (config.canOverrideAccessModifiers()) {
ClassUtil.checkAndFixAccess(jsonValueAccessor.getMember(),
config.isEnabled(MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS));
}
return EnumResolver.constructUsingMethod(config, enumClass, jsonValueAccessor);
}
// 14-Mar-2016, tatu: We used to check `DeserializationFeature.READ_ENUMS_USING_TO_STRING`
// here, but that won't do: it must be dynamically changeable...
return EnumResolver.constructFor(config, enumClass);
}
/**
* @since 2.9
*/
protected boolean _hasCreatorAnnotation(DeserializationContext ctxt,
Annotated ann) {
AnnotationIntrospector intr = ctxt.getAnnotationIntrospector();
if (intr != null) {
JsonCreator.Mode mode = intr.findCreatorAnnotation(ctxt.getConfig(), ann);
return (mode != null) && (mode != JsonCreator.Mode.DISABLED);
}
return false;
}
/*
/**********************************************************
/* Deprecated helper methods
/**********************************************************
*/
/**
* Method called to see if given method has annotations that indicate
* a more specific type than what the argument specifies.
*
* @deprecated Since 2.8; call {@link #resolveMemberAndTypeAnnotations} instead
*/
@Deprecated
protected JavaType modifyTypeByAnnotation(DeserializationContext ctxt,
Annotated a, JavaType type)
throws JsonMappingException
{
AnnotationIntrospector intr = ctxt.getAnnotationIntrospector();
if (intr == null) {
return type;
}
return intr.refineDeserializationType(ctxt.getConfig(), a, type);
}
/**
* @deprecated since 2.8 call {@link #resolveMemberAndTypeAnnotations} instead.
*/
@Deprecated // since 2.8
protected JavaType resolveType(DeserializationContext ctxt,
BeanDescription beanDesc, JavaType type, AnnotatedMember member)
throws JsonMappingException
{
return resolveMemberAndTypeAnnotations(ctxt, member, type);
}
/**
* @deprecated since 2.8 call <code>findJsonValueMethod</code> on {@link BeanDescription} instead
*/
@Deprecated // not used, possibly remove as early as 2.9
protected AnnotatedMethod _findJsonValueFor(DeserializationConfig config, JavaType enumType)
{
if (enumType == null) {
return null;
}
BeanDescription beanDesc = config.introspect(enumType);
return beanDesc.findJsonValueMethod();
}
/**
* Helper class to contain default mappings for abstract JDK {@link java.util.Collection}
* and {@link java.util.Map} types. Separated out here to defer cost of creating lookups
* until mappings are actually needed.
*
* @since 2.10
*/
@SuppressWarnings("rawtypes")
protected static class ContainerDefaultMappings {
// We do some defaulting for abstract Collection classes and
// interfaces, to avoid having to use exact types or annotations in
// cases where the most common concrete Collection will do.
final static HashMap<String, Class<? extends Collection>> _collectionFallbacks;
static {
HashMap<String, Class<? extends Collection>> fallbacks = new HashMap<>();
final Class<? extends Collection> DEFAULT_LIST = ArrayList.class;
final Class<? extends Collection> DEFAULT_SET = HashSet.class;
fallbacks.put(Collection.class.getName(), DEFAULT_LIST);
fallbacks.put(List.class.getName(), DEFAULT_LIST);
fallbacks.put(Set.class.getName(), DEFAULT_SET);
fallbacks.put(SortedSet.class.getName(), TreeSet.class);
fallbacks.put(Queue.class.getName(), LinkedList.class);
// 09-Feb-2019, tatu: How did we miss these? Related in [databind#2251] problem
fallbacks.put(AbstractList.class.getName(), DEFAULT_LIST);
fallbacks.put(AbstractSet.class.getName(), DEFAULT_SET);
// 09-Feb-2019, tatu: And more esoteric types added in JDK6
fallbacks.put(Deque.class.getName(), LinkedList.class);
fallbacks.put(NavigableSet.class.getName(), TreeSet.class);
_collectionFallbacks = fallbacks;
}
// We do some defaulting for abstract Map classes and
// interfaces, to avoid having to use exact types or annotations in
// cases where the most common concrete Maps will do.
final static HashMap<String, Class<? extends Map>> _mapFallbacks;
static {
HashMap<String, Class<? extends Map>> fallbacks = new HashMap<>();
final Class<? extends Map> DEFAULT_MAP = LinkedHashMap.class;
fallbacks.put(Map.class.getName(), DEFAULT_MAP);
fallbacks.put(AbstractMap.class.getName(), DEFAULT_MAP);
fallbacks.put(ConcurrentMap.class.getName(), ConcurrentHashMap.class);
fallbacks.put(SortedMap.class.getName(), TreeMap.class);
fallbacks.put(java.util.NavigableMap.class.getName(), TreeMap.class);
fallbacks.put(java.util.concurrent.ConcurrentNavigableMap.class.getName(),
java.util.concurrent.ConcurrentSkipListMap.class);
_mapFallbacks = fallbacks;
}
public static Class<?> findCollectionFallback(JavaType type) {
return _collectionFallbacks.get(type.getRawClass().getName());
}
public static Class<?> findMapFallback(JavaType type) {
return _mapFallbacks.get(type.getRawClass().getName());
}
}
/**
* Helper class to contain largish number of parameters that need to be passed
* during Creator introspection.
*
* @since 2.12
*/
protected static class CreatorCollectionState {
public final DeserializationContext context;
public final BeanDescription beanDesc;
public final VisibilityChecker<?> vchecker;
public final CreatorCollector creators;
public final Map<AnnotatedWithParams,BeanPropertyDefinition[]> creatorParams;
private List<CreatorCandidate> _implicitFactoryCandidates;
private int _explicitFactoryCount;
private List<CreatorCandidate> _implicitConstructorCandidates;
private int _explicitConstructorCount;
public CreatorCollectionState(DeserializationContext ctxt, BeanDescription bd,
VisibilityChecker<?> vc,
CreatorCollector cc,
Map<AnnotatedWithParams,BeanPropertyDefinition[]> cp)
{
context = ctxt;
beanDesc = bd;
vchecker = vc;
creators = cc;
creatorParams = cp;
}
public AnnotationIntrospector annotationIntrospector() {
return context.getAnnotationIntrospector();
}
// // // Factory creator candidate info
public void addImplicitFactoryCandidate(CreatorCandidate cc) {
if (_implicitFactoryCandidates == null) {
_implicitFactoryCandidates = new LinkedList<>();
}
_implicitFactoryCandidates.add(cc);
}
public void increaseExplicitFactoryCount() {
++_explicitFactoryCount;
}
public boolean hasExplicitFactories() {
return _explicitFactoryCount > 0;
}
public boolean hasImplicitFactoryCandidates() {
return _implicitFactoryCandidates != null;
}
public List<CreatorCandidate> implicitFactoryCandidates() {
return _implicitFactoryCandidates;
}
// // // Constructor creator candidate info
public void addImplicitConstructorCandidate(CreatorCandidate cc) {
if (_implicitConstructorCandidates == null) {
_implicitConstructorCandidates = new LinkedList<>();
}
_implicitConstructorCandidates.add(cc);
}
public void increaseExplicitConstructorCount() {
++_explicitConstructorCount;
}
public boolean hasExplicitConstructors() {
return _explicitConstructorCount > 0;
}
public boolean hasImplicitConstructorCandidates() {
return _implicitConstructorCandidates != null;
}
public List<CreatorCandidate> implicitConstructorCandidates() {
return _implicitConstructorCandidates;
}
}
}
|
9231bc799d6f35fd6f500d7b91fb3112701abeaf | 1,457 | java | Java | src/math/main/java/xilodyne/util/math/MathUtils.java | xilodyne/xilodyne.util | 2324ecea0abb9f4a40e178491a3ddd9baaac8587 | [
"MIT"
] | null | null | null | src/math/main/java/xilodyne/util/math/MathUtils.java | xilodyne/xilodyne.util | 2324ecea0abb9f4a40e178491a3ddd9baaac8587 | [
"MIT"
] | null | null | null | src/math/main/java/xilodyne/util/math/MathUtils.java | xilodyne/xilodyne.util | 2324ecea0abb9f4a40e178491a3ddd9baaac8587 | [
"MIT"
] | null | null | null | 23.190476 | 88 | 0.670089 | 995,950 | package xilodyne.util.math;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
/**
* @author Austin Davis Holiday (dycjh@example.com)
* @version 0.4 - 1/30/2018 - reflect xilodyne util changes
*
*/
public class MathUtils {
//private static Logger log = new Logger();
//https://en.wikipedia.org/wiki/Standard_deviation
public static double getStandardDeviation(double mean, double val) {
double result = 0;
result = (val - mean) * (val - mean);
//System.out.println("value: " + val+" mean: " + mean +" sqrt: " + Math.sqrt(result));
return Math.sqrt(result);
}
//assuming have entire population of data and not a sample of data
public static double getStandardScore(double mean, double val) {
double result = 0;
double stdDev = MathUtils.getStandardDeviation(mean, val);
result = (val - mean) / stdDev;
return result;
}
public static int getMeanRounded (ArrayList<Float> list) {
float sum = 0;
for (float f : list) {
sum += f;
}
sum = sum / list.size();
return Double.valueOf(sum).intValue();
}
public static float getMean (ArrayList<Float> list) {
float sum = 0;
for (float f : list) {
sum += f;
}
return sum = sum / list.size();
}
public static void sortList(ArrayList<Float> list) {
Collections.sort(list, new Comparator<Float>() {
@Override
public int compare(Float lbl1, Float lbl2) {
return lbl1.compareTo(lbl2);
}
});
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.