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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e0c1534297d45db0e7f81dcb87bcb4b98a6caf0 | 4,458 | java | Java | chunjun-core/src/main/java/com/dtstack/chunjun/util/FactoryHelper.java | wuchunfu/chunjun | a3fc935c49c09bd40b0d461443be2766418de0b9 | [
"ECL-2.0",
"Apache-2.0"
] | 114 | 2022-02-22T07:30:34.000Z | 2022-03-31T18:28:42.000Z | chunjun-core/src/main/java/com/dtstack/chunjun/util/FactoryHelper.java | wuchunfu/chunjun | a3fc935c49c09bd40b0d461443be2766418de0b9 | [
"ECL-2.0",
"Apache-2.0"
] | 53 | 2022-02-22T06:12:06.000Z | 2022-03-31T12:34:59.000Z | chunjun-core/src/main/java/com/dtstack/chunjun/util/FactoryHelper.java | wuchunfu/chunjun | a3fc935c49c09bd40b0d461443be2766418de0b9 | [
"ECL-2.0",
"Apache-2.0"
] | 53 | 2022-02-22T06:42:55.000Z | 2022-03-31T14:37:31.000Z | 35.380952 | 97 | 0.664648 | 5,124 | /*
* 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.dtstack.chunjun.util;
import com.dtstack.chunjun.constants.ConstantValue;
import org.apache.flink.configuration.ConfigOption;
import org.apache.flink.configuration.ConfigOptions;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.factories.TableFactoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* Date: 2021/08/05 Company: www.dtstack.com
*
* @author tudou
*/
public class FactoryHelper {
/** shipfile需要的jar的classPath name */
public static final ConfigOption<String> CLASS_FILE_NAME_FMT =
ConfigOptions.key("class_file_name_fmt")
.stringType()
.defaultValue("class_path_%d")
.withDescription("");
private static final Logger LOG = LoggerFactory.getLogger(TableFactoryService.class);
/** 插件路径 */
protected String localPluginPath = null;
/** 远端插件路径 */
protected String remotePluginPath = null;
/** 插件加载类型 */
protected String pluginLoadMode = ConstantValue.SHIP_FILE_PLUGIN_LOAD_MODE;
/** 上下文环境 */
protected StreamExecutionEnvironment env = null;
/** shipfile需要的jar */
protected List<URL> classPathSet = new ArrayList<>();
/** shipfile需要的jar的classPath index */
protected int classFileNameIndex = 0;
/** 任务执行模式 */
protected String executionMode;
public FactoryHelper() {}
/**
* register plugin jar file
*
* @param factoryIdentifier
* @param classLoader
* @param dirName
*/
public void registerCachedFile(
String factoryIdentifier, ClassLoader classLoader, String dirName) {
Set<URL> urlSet =
PluginUtil.getJarFileDirPath(
factoryIdentifier, this.localPluginPath, this.remotePluginPath, dirName);
try {
Method add = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
add.setAccessible(true);
List<String> urlList = new ArrayList<>(urlSet.size());
for (URL jarUrl : urlSet) {
add.invoke(classLoader, jarUrl);
if (!this.classPathSet.contains(jarUrl)) {
urlList.add(jarUrl.toString());
this.classPathSet.add(jarUrl);
String classFileName =
String.format(
CLASS_FILE_NAME_FMT.defaultValue(), this.classFileNameIndex);
this.env.registerCachedFile(jarUrl.getPath(), classFileName, true);
this.classFileNameIndex++;
}
}
PluginUtil.setPipelineOptionsToEnvConfig(this.env, urlList, executionMode);
} catch (Exception e) {
LOG.warn("can't add jar in {} to cachedFile, e = {}", urlSet, e.getMessage());
}
}
public void setLocalPluginPath(String localPluginPath) {
this.localPluginPath = localPluginPath;
}
public void setRemotePluginPath(String remotePluginPath) {
this.remotePluginPath = remotePluginPath;
}
public void setPluginLoadMode(String pluginLoadMode) {
this.pluginLoadMode = pluginLoadMode;
}
public void setEnv(StreamExecutionEnvironment env) {
this.env = env;
}
public String getExecutionMode() {
return executionMode;
}
public void setExecutionMode(String executionMode) {
this.executionMode = executionMode;
}
}
|
3e0c160058a3f390aabcf0ca3e2da13610997344 | 13,199 | java | Java | controller/src/main/java/com/athena/peacock/controller/web/ceph/osd/OsdController.java | OpenSourceConsulting/playce-peacock | 6bed20308c720634abe4fd3aff1c0c674d344f27 | [
"Apache-2.0"
] | 4 | 2015-10-07T06:26:57.000Z | 2018-01-01T23:01:43.000Z | controller/src/main/java/com/athena/peacock/controller/web/ceph/osd/OsdController.java | OpenSourceConsulting/playce-peacock | 6bed20308c720634abe4fd3aff1c0c674d344f27 | [
"Apache-2.0"
] | 1 | 2016-03-17T08:48:36.000Z | 2016-03-17T08:48:36.000Z | controller/src/main/java/com/athena/peacock/controller/web/ceph/osd/OsdController.java | OpenSourceConsulting/playce-peacock | 6bed20308c720634abe4fd3aff1c0c674d344f27 | [
"Apache-2.0"
] | 1 | 2016-03-09T22:13:22.000Z | 2016-03-09T22:13:22.000Z | 28.142857 | 168 | 0.649216 | 5,125 | /*
* Copyright (C) 2012-2014 Open Source Consulting, Inc. All rights reserved by Open Source Consulting, Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Revision History
* Author Date Description
* --------------- ---------------- ------------
* Sang-cheon Park 2015. 9. 24. First Draft.
*/
package com.athena.peacock.controller.web.ceph.osd;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.QueryParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
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 com.athena.peacock.controller.web.ceph.CephBaseController;
import com.athena.peacock.controller.web.common.model.SimpleJsonResponse;
/**
* <pre>
*
* </pre>
* @author Hojin kim
* @version 1.1
*/
@Controller
@RequestMapping("/ceph/osd")
public class OsdController extends CephBaseController {
private static final Logger LOGGER = LoggerFactory.getLogger(OsdController.class);
/**
* <pre>
*
* </pre>
* @param jsonRes
* @param dto
* @return
* @throws Exception
*/
@RequestMapping("/dump")
public @ResponseBody SimpleJsonResponse getDump(SimpleJsonResponse jsonRes) throws Exception {
try {
Object response = managementSubmit("/osd/dump", HttpMethod.GET);
jsonRes.setSuccess(true);
jsonRes.setData(response);
jsonRes.setMsg("OSD DUMP�??�상?�으�?조회?�었?�니??");
} catch (Exception e) {
jsonRes.setSuccess(false);
jsonRes.setMsg("OSD DUMP 조회 �??�러�?발생?��??�니??");
LOGGER.error("Unhandled Expeption has occurred. ", e);
}
return jsonRes;
}
/**
* <pre>
*
* </pre>
* @param jsonRes
* @param dto
* @return
* @throws Exception
*/
@RequestMapping("/tree")
public @ResponseBody SimpleJsonResponse getOSDTree(SimpleJsonResponse jsonRes) throws Exception {
try {
Object response = managementSubmit("/osd/tree", HttpMethod.GET);
jsonRes.setSuccess(true);
jsonRes.setData(response);
jsonRes.setMsg("OSD Tree�??�상?�으�?조회?�었?�니??");
} catch (Exception e) {
jsonRes.setSuccess(false);
jsonRes.setMsg("OSD Tree 조회 �??�러�?발생?��??�니??");
LOGGER.error("Unhandled Expeption has occurred. ", e);
}
return jsonRes;
}
/**
* <pre>
*
* </pre>
* @param jsonRes
* @param dto
* @return
* @throws Exception
*/
@RequestMapping("/blacklist/ls")
public @ResponseBody SimpleJsonResponse getOSDBlacklist(SimpleJsonResponse jsonRes) throws Exception {
try {
Object response = managementSubmit("/osd/blacklist/ls", HttpMethod.GET);
jsonRes.setSuccess(true);
jsonRes.setData(response);
jsonRes.setMsg("OSD Black List�??�상?�으�?조회?�었?�니??");
} catch (Exception e) {
jsonRes.setSuccess(false);
jsonRes.setMsg("OSD Black List 조회 �??�러�?발생?��??�니??");
LOGGER.error("Unhandled Expeption has occurred. ", e);
}
return jsonRes;
}
/**
* <pre>
*
* </pre>
* @param jsonRes
* @param dto
* @return
* @throws Exception
*/
@RequestMapping("/crush/dump")
public @ResponseBody SimpleJsonResponse getOSDCrushDump(SimpleJsonResponse jsonRes) throws Exception {
try {
Object response = managementSubmit("/osd/crush/dump", HttpMethod.GET);
jsonRes.setSuccess(true);
jsonRes.setData(response);
jsonRes.setMsg("OSD Crush dump�??�상?�으�?조회?�었?�니??");
} catch (Exception e) {
jsonRes.setSuccess(false);
jsonRes.setMsg("OSD Crush dump 조회 �??�러�?발생?��??�니??");
LOGGER.error("Unhandled Expeption has occurred. ", e);
}
return jsonRes;
}
/**
* <pre>
*
* </pre>
* @param jsonRes
* @param dto
* @return
* @throws Exception
*/
@RequestMapping("/crush/rule/dump")
public @ResponseBody SimpleJsonResponse getOSDCrushRuleDump(SimpleJsonResponse jsonRes) throws Exception {
try {
Object response = managementSubmit("/osd/crush/rule/dump", HttpMethod.GET);
jsonRes.setSuccess(true);
jsonRes.setData(response);
jsonRes.setMsg("OSD Crush Rule Dump�??�상?�으�?조회?�었?�니??");
} catch (Exception e) {
jsonRes.setSuccess(false);
jsonRes.setMsg("OSD Crush Rule Dump 조회 �??�러�?발생?��??�니??");
LOGGER.error("Unhandled Expeption has occurred. ", e);
}
return jsonRes;
}
/**
* <pre>
*
* </pre>
* @param jsonRes
* @param dto
* @return
* @throws Exception
*/
@RequestMapping("/crush/rule/list")
public @ResponseBody SimpleJsonResponse getOSDCrushRulelist(SimpleJsonResponse jsonRes) throws Exception {
try {
Object response = managementSubmit("/osd/crush/rule/list", HttpMethod.GET);
jsonRes.setSuccess(true);
jsonRes.setData(response);
jsonRes.setMsg("OSD Crush Rule List�??�상?�으�?조회?�었?�니??");
} catch (Exception e) {
jsonRes.setSuccess(false);
jsonRes.setMsg("OSD Crush Rule List�?조회 �??�러�?발생?��??�니??");
LOGGER.error("Unhandled Expeption has occurred. ", e);
}
return jsonRes;
}
/**
* <pre>
*
* </pre>
* @param jsonRes
* @param dto
* @return
* @throws Exception
*/
@RequestMapping("/map")
public @ResponseBody SimpleJsonResponse getOSDDumpepoch(SimpleJsonResponse jsonRes, @QueryParam("epoch") String epoch) throws Exception {
try {
Object response = managementSubmit("/osd/dump?epoch=" + epoch, HttpMethod.GET);
jsonRes.setSuccess(true);
jsonRes.setData(response);
jsonRes.setMsg("OSD Dump�??�상?�으�?조회?�었?�니??");
} catch (Exception e) {
jsonRes.setSuccess(false);
jsonRes.setMsg("OSD Dump 조회 �??�러�?발생?��??�니??");
LOGGER.error("Unhandled Expeption has occurred. ", e);
}
return jsonRes;
}
/**
* <pre>
*
* </pre>
* @param jsonRes
* @param dto
* @return
* @throws Exception
*/
@RequestMapping("/find")
public @ResponseBody SimpleJsonResponse getOSDCrushMapFind(SimpleJsonResponse jsonRes, @QueryParam("id") String id) throws Exception {
try {
Object response = managementSubmit("/osd/find?id=" + id, HttpMethod.GET);
jsonRes.setSuccess(true);
jsonRes.setData(response);
jsonRes.setMsg("OSD Find�??�상?�으�?조회?�었?�니??");
} catch (Exception e) {
jsonRes.setSuccess(false);
jsonRes.setMsg("OSD Find 조회 �??�러�?발생?��??�니??");
LOGGER.error("Unhandled Expeption has occurred. ", e);
}
return jsonRes;
}
/**
* <pre>
*
* </pre>
* @param jsonRes
* @param dto
* @return
* @throws Exception
*/
@RequestMapping("/getcrushmap")
public @ResponseBody SimpleJsonResponse getOSDCrushMap(SimpleJsonResponse jsonRes, @QueryParam("epoch") String epoch) throws Exception {
try {
Object response = managementSubmit("/osd/getcrushmap?epoch=" + epoch, HttpMethod.GET);
jsonRes.setSuccess(true);
jsonRes.setData(response);
jsonRes.setMsg("OSD Crush Map???�상?�으�?조회?�었?�니??");
} catch (Exception e) {
jsonRes.setSuccess(false);
jsonRes.setMsg("OSD Crush Map??조회 �??�러�?발생?��??�니??");
LOGGER.error("Unhandled Expeption has occurred. ", e);
}
return jsonRes;
}
/**
* <pre>
*
* </pre>
* @param jsonRes
* @param dto
* @return
* @throws Exception
*/
@RequestMapping("/getmap")
public @ResponseBody SimpleJsonResponse getOSDMap(SimpleJsonResponse jsonRes, @QueryParam("epoch") String epoch) throws Exception {
try {
Object response = managementSubmit("/osd/getmap?epoch=" + epoch, HttpMethod.GET);
jsonRes.setSuccess(true);
jsonRes.setData(response);
jsonRes.setMsg("OSD Map???�상?�으�?조회?�었?�니??");
} catch (Exception e) {
jsonRes.setSuccess(false);
jsonRes.setMsg("OSD Map??조회 �??�러�?발생?��??�니??");
LOGGER.error("Unhandled Expeption has occurred. ", e);
}
return jsonRes;
}
/**
* <pre>
*
* </pre>
* @param jsonRes
* @param dto
* @return
* @throws Exception
*/
@RequestMapping("/perf")
public @ResponseBody SimpleJsonResponse getOSDPerf(SimpleJsonResponse jsonRes) throws Exception {
try {
Object response = managementSubmit("/osd/perf", HttpMethod.GET);
jsonRes.setSuccess(true);
jsonRes.setData(response);
jsonRes.setMsg("OSD Perf�??�상?�으�?조회?�었?�니??");
} catch (Exception e) {
jsonRes.setSuccess(false);
jsonRes.setMsg("OSD Perf 조회 �??�러�?발생?��??�니??");
LOGGER.error("Unhandled Expeption has occurred. ", e);
}
return jsonRes;
}
/**
* <pre>
*
* </pre>
* @param jsonRes
* @param dto
* @return
* @throws Exception
*/
@RequestMapping("/stat")
public @ResponseBody SimpleJsonResponse getOSDstat(SimpleJsonResponse jsonRes) throws Exception {
try {
Object response = managementSubmit("/osd/stat", HttpMethod.GET);
jsonRes.setSuccess(true);
jsonRes.setData(response);
jsonRes.setMsg("stat�??�상?�으�?조회?�었?�니??");
} catch (Exception e) {
jsonRes.setSuccess(false);
jsonRes.setMsg("stat 조회 �??�러�?발생?��??�니??");
LOGGER.error("Unhandled Expeption has occurred. ", e);
}
return jsonRes;
}
/**
* <pre>
*
* </pre>
* @param jsonRes
* @param dto
* @return
* @throws Exception
*/
@RequestMapping("/cluster/{fsid}/{path}")
public @ResponseBody SimpleJsonResponse subCluster(SimpleJsonResponse jsonRes, @PathVariable("fsid") String fsid, @PathVariable("path") String path) throws Exception {
try {
Object response = null;
Map<String, Object> params = null;
if (path.equals("cli")) {
List<String> command = new ArrayList<String>();
command.add("osd");
command.add("dump");
params = new HashMap<String, Object>();
params.put("command", "osd list");
}
if (params != null) {
response = calamariSubmit("/cluster/" + fsid + "/" + path, params, HttpMethod.POST);
} else {
response = calamariSubmit("/cluster/" + fsid + "/" + path, HttpMethod.GET);
}
jsonRes.setSuccess(true);
jsonRes.setData(response);
jsonRes.setMsg("?�상?�으�?조회?�었?�니??");
} catch (Exception e) {
jsonRes.setSuccess(false);
jsonRes.setMsg("조회 �??�러�?발생?��??�니??");
LOGGER.error("Unhandled Expeption has occurred. ", e);
}
return jsonRes;
}
@RequestMapping("/create/test1")
public @ResponseBody SimpleJsonResponse createPool(SimpleJsonResponse jsonRes, @QueryParam("name") String name) throws Exception {
try {
Object response = managementSubmit("/osd/pool/stats?name=" + name, HttpMethod.GET);
jsonRes.setSuccess(true);
jsonRes.setData(response);
jsonRes.setMsg("Pool List�??�상?�으�?조회?�었?�니??");
} catch (Exception e) {
jsonRes.setSuccess(false);
jsonRes.setMsg("Pool List 조회 �??�러�?발생?��??�니??");
LOGGER.error("Unhandled Expeption has occurred. ", e);
}
return jsonRes;
}
@RequestMapping("/add")
public @ResponseBody SimpleJsonResponse add(SimpleJsonResponse jsonRes, @QueryParam("host") String host, @QueryParam("path") String path) throws Exception {
try {
Object response = execute("/usr/bin/ceph-deploy --overwrite-conf osd create " + host + ":" + path);
jsonRes.setSuccess(true);
jsonRes.setData(response);
jsonRes.setMsg("OSD 추�?�??�상?�으�??�었?�니??");
} catch (Exception e) {
jsonRes.setSuccess(false);
jsonRes.setMsg("OSD 추�?�? ?�러 발생?��??�니??");
LOGGER.error("Unhandled Expeption has occurred. ", e);
}
return jsonRes;
}
@RequestMapping("/delete")
public @ResponseBody SimpleJsonResponse delete(SimpleJsonResponse jsonRes, @QueryParam("host") String host, @QueryParam("id") String id) throws Exception {
try {
Object response = execute("/usr/bin/ceph osd crush remove osd." + id);
if (((String) response).indexOf("ERROR") > -1) {
throw new IllegalStateException("Crush remove failed."); // NOPMD
}
response = execute("rsh " + host + " \"/etc/init.d/ceph stop osd." + id + "\"");
if (((String) response).indexOf("ERROR") > -1) {
throw new IllegalStateException("OSD stop failed."); // NOPMD
}
response = execute("ceph osd rm " + id);
if (((String) response).indexOf("ERROR") > -1) {
throw new IllegalStateException("OSD rm failed."); // NOPMD
}
jsonRes.setSuccess(true);
jsonRes.setData(response);
jsonRes.setMsg("OSD�??�상?�으�???�� ?�었?�니??");
} catch (Exception e) {
jsonRes.setSuccess(false);
jsonRes.setMsg("OSD ??���??�패 ?��??�니??");
LOGGER.error("Unhandled Expeption has occurred. ", e);
}
return jsonRes;
}
}
// end of OsdController.java
|
3e0c16230b74c06e8b6cc861c4a28a986bdd29a6 | 3,284 | java | Java | pcgen/code/src/java/pcgen/core/chooser/ChoiceManagerList.java | odraccir/pcgen-deprecated | ab07cb4250e5d0419fd805197fb040a2ea425cc8 | [
"OML"
] | 1 | 2020-01-12T22:28:29.000Z | 2020-01-12T22:28:29.000Z | pcgen/code/src/java/pcgen/core/chooser/ChoiceManagerList.java | odraccir/pcgen-deprecated | ab07cb4250e5d0419fd805197fb040a2ea425cc8 | [
"OML"
] | null | null | null | pcgen/code/src/java/pcgen/core/chooser/ChoiceManagerList.java | odraccir/pcgen-deprecated | ab07cb4250e5d0419fd805197fb040a2ea425cc8 | [
"OML"
] | null | null | null | 27.181818 | 91 | 0.726665 | 5,126 | /**
* ChoiceManagerList.java
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Current Version: $Revision: 285 $
* Last Editor: $Author: nuance $
* Last Edited: $Date: 2006-03-17 15:19:49 +0000 (Fri, 17 Mar 2006) $
*
* Copyright 2006 Andrew Wilson <lyhxr@example.com>
*/
package pcgen.core.chooser;
import java.util.List;
import pcgen.cdom.base.ChooseDriver;
import pcgen.core.PlayerCharacter;
/**
* Choice Manager List interface
* @param <T>
*/
public interface ChoiceManagerList<T> {
/**
* return handled chooser
* @return handled chooser
*/
public abstract String typeHandled();
/**
* Get choices
* @param aPc
* @param availableList
* @param selectedList
*/
public abstract void getChoices(
final PlayerCharacter aPc,
final List<T> availableList,
final List<T> selectedList);
/**
* Do chooser
* @param aPc
* @param availableList
* @param selectedList
* @return the list of selected items
*/
public abstract List<T> doChooser(
PlayerCharacter aPc,
final List<T> availableList,
final List<T> selectedList,
final List<String> reservedList);
/**
* Do chooser for removing a choice
* @param aPc
* @param availableList
* @param selectedList
* @return
*/
public abstract List<T> doChooserRemove (
PlayerCharacter aPc,
final List<T> availableList,
final List<T> selectedList,
final List<String> reservedList);
/**
* Apply the choices to the Pc
*
* @param aPC
* @param selected
*/
public abstract boolean applyChoices(
final PlayerCharacter aPC,
final List<T> selected);
/**
* Calculate the number of effective choices the user can make.
*
* @param selectedList The list of already selected items.
* @param reservedList The list of options which cannot be offered.
* @param aPc The character the choice applies to.
* @return The number of choices that may be made
*/
public int getNumEffectiveChoices(final List<? extends T> selectedList,
final List<String> reservedList, PlayerCharacter aPc);
public abstract boolean conditionallyApply(PlayerCharacter pc, T item);
public abstract void restoreChoice(PlayerCharacter pc, ChooseDriver owner, String choice);
public void setController(ChooseController<T> cc);
public int getPreChooserChoices();
public int getChoicesPerUnitCost();
public void removeChoice(PlayerCharacter pc, ChooseDriver owner, T selection);
public void applyChoice(PlayerCharacter pc, ChooseDriver owner, T selection);
public abstract T decodeChoice(String choice);
public abstract String encodeChoice(T obj);
}
|
3e0c1668696e4d4181d4dfc1075e5ba410ba730b | 3,751 | java | Java | spring-aop/src/main/java/org/springframework/aop/MethodMatcher.java | FadeDemo/spring-framework | de95310ee86d70998a444e95d7ae980637871f47 | [
"Apache-2.0"
] | null | null | null | spring-aop/src/main/java/org/springframework/aop/MethodMatcher.java | FadeDemo/spring-framework | de95310ee86d70998a444e95d7ae980637871f47 | [
"Apache-2.0"
] | null | null | null | spring-aop/src/main/java/org/springframework/aop/MethodMatcher.java | FadeDemo/spring-framework | de95310ee86d70998a444e95d7ae980637871f47 | [
"Apache-2.0"
] | null | null | null | 43.616279 | 99 | 0.72674 | 5,127 | package org.springframework.aop;
import java.lang.reflect.Method;
/**
* Part of a {@link Pointcut}: Checks whether the target method is eligible for advice.
*
* <p>A MethodMatcher may be evaluated <b>statically</b> or at <b>runtime</b> (dynamically).
* Static matching involves method and (possibly) method attributes. Dynamic matching
* also makes arguments for a particular call available, and any effects of running
* previous advice applying to the joinpoint.
*
* <p>If an implementation returns {@code false} from its {@link #isRuntime()}
* method, evaluation can be performed statically, and the result will be the same
* for all invocations of this method, whatever their arguments. This means that
* if the {@link #isRuntime()} method returns {@code false}, the 3-arg
* {@link #matches(java.lang.reflect.Method, Class, Object[])} method will never be invoked.
*
* <p>If an implementation returns {@code true} from its 2-arg
* {@link #matches(java.lang.reflect.Method, Class)} method and its {@link #isRuntime()} method
* returns {@code true}, the 3-arg {@link #matches(java.lang.reflect.Method, Class, Object[])}
* method will be invoked <i>immediately before each potential execution of the related advice</i>,
* to decide whether the advice should run. All previous advice, such as earlier interceptors
* in an interceptor chain, will have run, so any state changes they have produced in
* parameters or ThreadLocal state will be available at the time of evaluation.
*
* <p>Concrete implementations of this interface typically should provide proper
* implementations of {@link Object#equals(Object)} and {@link Object#hashCode()}
* in order to allow the matcher to be used in caching scenarios — for
* example, in proxies generated by CGLIB.
*
* @author Rod Johnson
* @since 11.11.2003
* @see Pointcut
* @see ClassFilter
*/
public interface MethodMatcher {
/**
* Perform static checking whether the given method matches.
* <p>If this returns {@code false} or if the {@link #isRuntime()}
* method returns {@code false}, no runtime check (i.e. no
* {@link #matches(java.lang.reflect.Method, Class, Object[])} call)
* will be made.
* @param method the candidate method
* @param targetClass the target class
* @return whether or not this method matches statically
*/
boolean matches(Method method, Class<?> targetClass);
/**
* Is this MethodMatcher dynamic, that is, must a final call be made on the
* {@link #matches(java.lang.reflect.Method, Class, Object[])} method at
* runtime even if the 2-arg matches method returns {@code true}?
* <p>Can be invoked when an AOP proxy is created, and need not be invoked
* again before each method invocation,
* @return whether or not a runtime match via the 3-arg
* {@link #matches(java.lang.reflect.Method, Class, Object[])} method
* is required if static matching passed
*/
boolean isRuntime();
/**
* Check whether there a runtime (dynamic) match for this method,
* which must have matched statically.
* <p>This method is invoked only if the 2-arg matches method returns
* {@code true} for the given method and target class, and if the
* {@link #isRuntime()} method returns {@code true}. Invoked
* immediately before potential running of the advice, after any
* advice earlier in the advice chain has run.
* @param method the candidate method
* @param targetClass the target class
* @param args arguments to the method
* @return whether there's a runtime match
* @see MethodMatcher#matches(Method, Class)
*/
boolean matches(Method method, Class<?> targetClass, Object... args);
/**
* Canonical instance that matches all methods.
*/
MethodMatcher TRUE = TrueMethodMatcher.INSTANCE;
}
|
3e0c16e0a15566e353e7791ff32e95943a070534 | 560 | java | Java | business-center/user-center/src/main/java/com/open/capacity/user/model/UserExcelModel.java | wangsheng123/spring-cloud-basic | bbc0393bf074ceef646767addb0af85e11091e8c | [
"Apache-2.0"
] | null | null | null | business-center/user-center/src/main/java/com/open/capacity/user/model/UserExcelModel.java | wangsheng123/spring-cloud-basic | bbc0393bf074ceef646767addb0af85e11091e8c | [
"Apache-2.0"
] | null | null | null | business-center/user-center/src/main/java/com/open/capacity/user/model/UserExcelModel.java | wangsheng123/spring-cloud-basic | bbc0393bf074ceef646767addb0af85e11091e8c | [
"Apache-2.0"
] | null | null | null | 21.538462 | 50 | 0.716071 | 5,128 | package com.open.capacity.user.model;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
import lombok.Data;
import java.util.List;
@Data
public class UserExcelModel extends BaseRowModel {
@ExcelProperty(value = "ID",index = 1)
private int id;
@ExcelProperty(value = "姓名",index = 2)
private String name;
private List<RoleModel> roles;
@ExcelProperty(value = "角色名",index = 3)
private String roleName;
@ExcelProperty(value = "角色编码",index = 4)
private String roleCode;
}
|
3e0c177edbbfb2613fb03a4908d41812e90391dd | 7,711 | java | Java | src/edacc/EDACCSelectParentInstanceClassDialog.java | MalteSchledjewski/edacc_gui | f91fb0c06339b488cb1609d737e497905a419385 | [
"MIT"
] | 1 | 2019-07-18T15:19:29.000Z | 2019-07-18T15:19:29.000Z | src/edacc/EDACCSelectParentInstanceClassDialog.java | EDACC/edacc_gui | f91fb0c06339b488cb1609d737e497905a419385 | [
"MIT"
] | 1 | 2019-10-16T08:43:13.000Z | 2019-10-16T08:43:13.000Z | src/edacc/EDACCSelectParentInstanceClassDialog.java | MalteSchledjewski/edacc_gui | f91fb0c06339b488cb1609d737e497905a419385 | [
"MIT"
] | 2 | 2015-05-08T09:00:01.000Z | 2019-07-18T15:19:37.000Z | 41.456989 | 202 | 0.680586 | 5,129 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* EDACCSelectParentInstanceClassDialog.java
*
* Created on 19.11.2010, 13:08:26
*/
package edacc;
import edacc.model.InstanceClass;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeSelectionModel;
/**
*
* @author rretz
*/
public class EDACCSelectParentInstanceClassDialog extends javax.swing.JDialog {
private InstanceClass parent;
private DefaultTreeModel model;
/** Creates new form EDACCSelectParentInstanceClassDialog */
public EDACCSelectParentInstanceClassDialog(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
public EDACCSelectParentInstanceClassDialog(java.awt.Frame parent, boolean modal, DefaultTreeModel model) {
super(parent, modal);
initComponents();
this.model = model;
jTreeParents.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
jTreeParents.setRootVisible(false);
}
public InstanceClass getInstanceClassParent(){
return parent;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jTreeParents = new javax.swing.JTree();
jButtonSelect = new javax.swing.JButton();
jButtonDone = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(edacc.EDACCApp.class).getContext().getResourceMap(EDACCSelectParentInstanceClassDialog.class);
setTitle(resourceMap.getString("Form.title")); // NOI18N
setName("Form"); // NOI18N
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
jPanel1.setName("jPanel1"); // NOI18N
jScrollPane1.setName("jScrollPane1"); // NOI18N
jTreeParents.setName("jTreeParents"); // NOI18N
jScrollPane1.setViewportView(jTreeParents);
jButtonSelect.setText(resourceMap.getString("jButtonSelect.text")); // NOI18N
jButtonSelect.setName("jButtonSelect"); // NOI18N
jButtonSelect.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonSelectActionPerformed(evt);
}
});
jButtonDone.setText(resourceMap.getString("jButtonDone.text")); // NOI18N
jButtonDone.setName("jButtonDone"); // NOI18N
jButtonDone.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonDoneActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 286, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jButtonSelect)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 156, Short.MAX_VALUE)
.addComponent(jButtonDone))
);
jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jButtonDone, jButtonSelect});
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButtonSelect)
.addComponent(jButtonDone)))
);
jPanel1Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jButtonDone, jButtonSelect});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButtonSelectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSelectActionPerformed
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)jTreeParents.getLastSelectedPathComponent();
if(selectedNode == null){
JOptionPane.showMessageDialog(jPanel1,
"No node selected.",
"Warning",
JOptionPane.WARNING_MESSAGE);
}else{
parent = (InstanceClass) selectedNode.getUserObject();
this.dispose();
}
}//GEN-LAST:event_jButtonSelectActionPerformed
private void jButtonDoneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDoneActionPerformed
this.dispose();
parent = null;
}//GEN-LAST:event_jButtonDoneActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
EDACCSelectParentInstanceClassDialog dialog = new EDACCSelectParentInstanceClassDialog(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
void initialize() {
jTreeParents.setModel(this.model);
parent = null;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButtonDone;
private javax.swing.JButton jButtonSelect;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTree jTreeParents;
// End of variables declaration//GEN-END:variables
}
|
3e0c1797929e885e4d065ecb6b73323c281db1eb | 1,673 | java | Java | src/main/java/com/bbn/openmap/layer/terrain/LOSStateMachine.java | d2fn/passage | 2085183f1b085ac344198bd674024fe715bd4fca | [
"MIT"
] | 1 | 2020-04-10T09:43:49.000Z | 2020-04-10T09:43:49.000Z | src/main/java/com/bbn/openmap/layer/terrain/LOSStateMachine.java | d2fn/passage | 2085183f1b085ac344198bd674024fe715bd4fca | [
"MIT"
] | null | null | null | src/main/java/com/bbn/openmap/layer/terrain/LOSStateMachine.java | d2fn/passage | 2085183f1b085ac344198bd674024fe715bd4fca | [
"MIT"
] | 3 | 2015-05-01T20:36:49.000Z | 2022-03-09T22:47:04.000Z | 27.42623 | 89 | 0.57621 | 5,130 | // **********************************************************************
//
// <copyright>
//
// BBN Technologies
// 10 Moulton Street
// Cambridge, MA 02138
// (617) 873-8000
//
// Copyright (C) BBNT Solutions LLC. All rights reserved.
//
// </copyright>
// **********************************************************************
//
// $Source:
// /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/terrain/LOSStateMachine.java,v
// $
// $RCSfile: LOSStateMachine.java,v $
// $Revision: 1.3 $
// $Date: 2004/10/14 18:06:05 $
// $Author: dietrick $
//
// **********************************************************************
package com.bbn.openmap.layer.terrain;
import com.bbn.openmap.util.stateMachine.State;
import com.bbn.openmap.util.stateMachine.StateMachine;
class LOSStateMachine extends StateMachine {
public LOSGenerator losg;
public static final int TOOL_DO_NOTHING = 0;
public static final int TOOL_DRAW = 1;
public static final int TOOL_DEFINED = 2;
public static final int TOOL_VIEW = 3;
public LOSStateMachine(LOSGenerator generator) {
losg = generator;
State[] losStates = init();
setStates(losStates);
// set reset state
setResetState(TOOL_DO_NOTHING);
reset();
setMapMouseListenerResponses(true);
}
protected State[] init() {
State[] LOSStates = new State[4];
LOSStates[TOOL_DO_NOTHING] = new LOSDoNothingState(losg);
LOSStates[TOOL_DRAW] = new LOSDrawState(losg);
LOSStates[TOOL_DEFINED] = new LOSDefinedState(losg);
LOSStates[TOOL_VIEW] = new LOSViewState(losg);
return LOSStates;
}
}
|
3e0c17e0e0aadd672911c9b558506f751267b4f4 | 2,608 | java | Java | test/benchmark/ycsb/src/test/java/com/impetus/kundera/ycsb/CouchDBYCSBTest.java | sjvs/Kundera | 2d9644587a9ee0ab31fbba5a08c3481032d4db4e | [
"Apache-2.0"
] | 377 | 2015-01-02T07:59:37.000Z | 2018-01-27T12:13:16.000Z | test/benchmark/ycsb/src/test/java/com/impetus/kundera/ycsb/CouchDBYCSBTest.java | sjvs/Kundera | 2d9644587a9ee0ab31fbba5a08c3481032d4db4e | [
"Apache-2.0"
] | 332 | 2015-01-02T10:14:23.000Z | 2018-01-29T14:22:24.000Z | test/benchmark/ycsb/src/test/java/com/impetus/kundera/ycsb/CouchDBYCSBTest.java | sjvs/Kundera | 2d9644587a9ee0ab31fbba5a08c3481032d4db4e | [
"Apache-2.0"
] | 135 | 2015-01-02T07:59:42.000Z | 2018-01-25T19:22:13.000Z | 24.838095 | 86 | 0.667178 | 5,131 | /**
* Copyright 2012 Impetus Infotech.
*
* 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.impetus.kundera.ycsb;
import java.io.IOException;
import org.apache.commons.configuration.ConfigurationException;
import org.junit.After;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import com.impetus.kundera.ycsb.runner.CouchDBRunner;
/**
* Cassandra Kundera YCSB benchmarking.
*
* @author vivek.mishra
*
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class CouchDBYCSBTest extends YCSBBaseTest
{
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception
{
System.setProperty("fileName", "src/main/resources/db-couch.properties");
// in case property file name is not set as system property.
super.setUp();
}
@Test
public void onTest() throws Exception
{
testConcurrentWorkload();
testRead();
// testUpdate();
}
void testConcurrentWorkload() throws IOException, ConfigurationException
{
onChangeRunType("load");
Runtime runtime = Runtime.getRuntime();
runner.startServer(true, runtime);
process();
}
void testRead() throws Exception
{
onChangeRunType("t");
onRead();
}
void testUpdate() throws Exception
{
onChangeRunType(true);
onUpdate();
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception
{
onDestroy();
}
/**
* @param runType
* @throws ConfigurationException
*/
protected void onChangeRunType(final String runType) throws ConfigurationException
{
config.setProperty("run.type", runType);
config.setProperty("ycsbjar.location", ycsbJarLocation);
config.save();
runner = new CouchDBRunner(propsFileName, config);
// Runtime runtime = Runtime.getRuntime();
// runner.startServer(runType.equals("load"), runtime);
}
}
|
3e0c18033f41fb63eb09a4a18e5849859882ca43 | 1,585 | java | Java | src/main/java/com/akmal/springfoodieappbackend/controller/MenuItemController.java | akmal2409/spring-foodie-app-backend | a6404a5013d259b9504332d55a8e54a4d518130b | [
"Apache-2.0"
] | null | null | null | src/main/java/com/akmal/springfoodieappbackend/controller/MenuItemController.java | akmal2409/spring-foodie-app-backend | a6404a5013d259b9504332d55a8e54a4d518130b | [
"Apache-2.0"
] | null | null | null | src/main/java/com/akmal/springfoodieappbackend/controller/MenuItemController.java | akmal2409/spring-foodie-app-backend | a6404a5013d259b9504332d55a8e54a4d518130b | [
"Apache-2.0"
] | null | null | null | 30.480769 | 90 | 0.772871 | 5,132 | package com.akmal.springfoodieappbackend.controller;
import com.akmal.springfoodieappbackend.dto.MenuItemDto;
import com.akmal.springfoodieappbackend.service.MenuItemService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import static com.akmal.springfoodieappbackend.shared.http.ResponseEntityConverter.ok;
/**
* @author Akmal Alikhujaev
* @version 1.0
* @created 05/12/2021 - 8:05 PM
* @project Spring Foodie App Backend
* @since 1.0
*/
@RestController
@RequestMapping(MenuItemController.BASE_URL)
@RequiredArgsConstructor
public class MenuItemController {
public static final String BASE_URL = "/api";
private final MenuItemService menuItemService;
@GetMapping("/menu-items/{id}")
public ResponseEntity<MenuItemDto> findById(@PathVariable Long id) {
return ok(this.menuItemService.findById(id));
}
@GetMapping("/menus/{menuId}/menu-items")
public List<MenuItemDto> findByMenuId(@PathVariable Long menuId) {
return this.menuItemService.findByMenuId(menuId);
}
@PostMapping("/menu-items")
public MenuItemDto save(@RequestBody MenuItemDto menuItemDto) {
return this.menuItemService.save(menuItemDto);
}
@PutMapping("menu-items/{id}")
public MenuItemDto update(@RequestBody MenuItemDto menuItemDto, @PathVariable Long id) {
return this.menuItemService.update(menuItemDto, id);
}
@DeleteMapping("/menu-items/{id}")
public void deleteById(@PathVariable Long id) {
this.menuItemService.deleteById(id);
}
}
|
3e0c183a7fb598ec8422ebfabe5984fbdcec4e12 | 7,649 | java | Java | Core/EntityManager/src/main/java/eu/neclab/ngsildbroker/entityhandler/controller/EntityController.java | wagmarcel/ScorpioBroker | 813518465b8ca72086cdb20dcfa5ebf1d525de3c | [
"BSD-3-Clause"
] | null | null | null | Core/EntityManager/src/main/java/eu/neclab/ngsildbroker/entityhandler/controller/EntityController.java | wagmarcel/ScorpioBroker | 813518465b8ca72086cdb20dcfa5ebf1d525de3c | [
"BSD-3-Clause"
] | null | null | null | Core/EntityManager/src/main/java/eu/neclab/ngsildbroker/entityhandler/controller/EntityController.java | wagmarcel/ScorpioBroker | 813518465b8ca72086cdb20dcfa5ebf1d525de3c | [
"BSD-3-Clause"
] | null | null | null | 36.951691 | 117 | 0.767813 | 5,133 | package eu.neclab.ngsildbroker.entityhandler.controller;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
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.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.jsonldjava.core.Context;
import com.github.jsonldjava.core.JsonLdConsts;
import com.github.jsonldjava.core.JsonLdOptions;
import com.github.jsonldjava.core.JsonLdProcessor;
import com.github.jsonldjava.utils.JsonUtils;
import eu.neclab.ngsildbroker.commons.constants.AppConstants;
import eu.neclab.ngsildbroker.commons.controllers.EntryControllerFunctions;
import eu.neclab.ngsildbroker.commons.datatypes.results.UpdateResult;
import eu.neclab.ngsildbroker.commons.enums.ErrorType;
import eu.neclab.ngsildbroker.commons.exceptions.ResponseException;
import eu.neclab.ngsildbroker.commons.ngsiqueries.ParamsResolver;
import eu.neclab.ngsildbroker.commons.tools.HttpUtils;
import eu.neclab.ngsildbroker.entityhandler.services.EntityService;
/**
*
* @version 1.0
* @date 10-Jul-2018
*/
@RestController
@RequestMapping("/ngsi-ld/v1/entities")
public class EntityController {// implements EntityHandlerInterface {
private final static Logger logger = LoggerFactory.getLogger(EntityController.class);
@Autowired
EntityService entityService;
@Autowired
ObjectMapper objectMapper;
LocalDateTime startAt;
LocalDateTime endAt;
private JsonLdOptions opts = new JsonLdOptions(JsonLdOptions.JSON_LD_1_1);
@Value("${ngsild.corecontext:https://uri.etsi.org/ngsi-ld/v1/ngsi-ld-core-context.jsonld}")
String coreContext;
@PostConstruct
public void init() {
JsonLdProcessor.init(coreContext);
}
public EntityController() {
}
/**
* Method(POST) for "/ngsi-ld/v1/entities/" rest endpoint.
*
* @param payload jsonld message
* @return ResponseEntity object
*/
@PostMapping
public ResponseEntity<String> createEntity(HttpServletRequest request,
@RequestBody(required = false) String payload) {
return EntryControllerFunctions.createEntry(entityService, request, payload, AppConstants.ENTITY_CREATE_PAYLOAD,
AppConstants.ENTITES_URL, logger);
}
/**
* Method(PATCH) for "/ngsi-ld/v1/entities/{entityId}/attrs" rest endpoint.
*
* @param entityId
* @param payload json ld message
* @return ResponseEntity object
*/
@PatchMapping("/{entityId}/attrs")
public ResponseEntity<String> updateEntity(HttpServletRequest request, @PathVariable("entityId") String entityId,
@RequestBody String payload) {
return EntryControllerFunctions.updateEntry(entityService, request, entityId, payload,
AppConstants.ENTITY_UPDATE_PAYLOAD, logger);
}
/**
* Method(POST) for "/ngsi-ld/v1/entities/{entityId}/attrs" rest endpoint.
*
* @param entityId
* @param payload jsonld message
* @return ResponseEntity object
*/
@PostMapping("/{entityId}/attrs")
public ResponseEntity<String> appendEntity(HttpServletRequest request, @PathVariable("entityId") String entityId,
@RequestBody String payload, @RequestParam(required = false, name = "options") String options) {
return EntryControllerFunctions.appendToEntry(entityService, request, entityId, payload, options,
AppConstants.ENTITY_UPDATE_PAYLOAD, logger);
}
/**
* Method(PATCH) for "/ngsi-ld/v1/entities/{entityId}/attrs/{attrId}" rest
* endpoint.
*
* @param entityId
* @param attrId
* @param payload
* @return
*/
@SuppressWarnings("unchecked")
@PatchMapping("/{entityId}/attrs/{attrId}")
public ResponseEntity<String> partialUpdateEntity(HttpServletRequest request,
@PathVariable("entityId") String entityId, @PathVariable("attrId") String attrId,
@RequestBody String payload) {
try {
Object jsonPayload = JsonUtils.fromString(payload);
HttpUtils.validateUri(entityId);
List<Object> atContext = HttpUtils.getAtContext(request);
boolean atContextAllowed = HttpUtils.doPreflightCheck(request, atContext);
logger.trace("partial-update entity :: started");
Map<String, Object> expandedPayload = (Map<String, Object>) JsonLdProcessor
.expand(atContext, jsonPayload, opts, AppConstants.ENTITY_ATTRS_UPDATE_PAYLOAD, atContextAllowed)
.get(0);
Context context = JsonLdProcessor.getCoreContextClone();
context = context.parse(atContext, true);
if (jsonPayload instanceof Map) {
Object payloadContext = ((Map<String, Object>) jsonPayload).get(JsonLdConsts.CONTEXT);
if (payloadContext != null) {
context = context.parse(payloadContext, true);
}
}
String expandedAttrib = ParamsResolver.expandAttribute(attrId, context);
UpdateResult update = entityService.partialUpdateEntity(HttpUtils.getHeaders(request), entityId,
expandedAttrib, expandedPayload);
logger.trace("partial-update entity :: completed");
if (update.getNotUpdated().isEmpty()) {
return ResponseEntity.noContent().build();
} else {
return HttpUtils.handleControllerExceptions(new ResponseException(ErrorType.BadRequestData, JsonUtils
.toPrettyString(JsonLdProcessor.compact(update.getNotUpdated().get(0), context, opts))));
}
/*
* There is no 207 multi status response in the Partial Attribute Update
* operation. Section 6.7.3.1 else { return
* ResponseEntity.status(HttpStatus.MULTI_STATUS).body(update.
* getAppendedJsonFields()); }
*/
} catch (Exception exception) {
return HttpUtils.handleControllerExceptions(exception);
}
}
/**
* Method(DELETE) for "/ngsi-ld/v1/entities/{entityId}/attrs/{attrId}" rest
* endpoint.
*
* @param entityId
* @param attrId
* @return
*/
@DeleteMapping("/{entityId}/attrs/{attrId}")
public ResponseEntity<String> deleteAttribute(HttpServletRequest request, @PathVariable("entityId") String entityId,
@PathVariable("attrId") String attrId,
@RequestParam(value = "datasetId", required = false) String datasetId,
@RequestParam(value = "deleteAll", required = false) String deleteAll) {
try {
HttpUtils.validateUri(entityId);
logger.trace("delete attribute :: started");
Context context = JsonLdProcessor.getCoreContextClone();
context = context.parse(HttpUtils.getAtContext(request), true);
String expandedAttrib = ParamsResolver.expandAttribute(attrId, context);
entityService.deleteAttribute(HttpUtils.getHeaders(request), entityId, expandedAttrib, datasetId,
deleteAll);
logger.trace("delete attribute :: completed");
return ResponseEntity.noContent().build();
} catch (Exception exception) {
return HttpUtils.handleControllerExceptions(exception);
}
}
/**
* Method(DELETE) for "/ngsi-ld/v1/entities/{entityId}" rest endpoint.
*
* @param entityId
* @return
*/
@DeleteMapping("/{entityId}")
public ResponseEntity<String> deleteEntity(HttpServletRequest request, @PathVariable("entityId") String entityId) {
return EntryControllerFunctions.deleteEntry(entityService, request, entityId, logger);
}
}
|
3e0c189e7e1986d99610879ae0126473e053ee90 | 555 | java | Java | asciidoctorj-documentation/src/test/java/org/asciidoctor/integrationguide/extension/RobotsDocinfoProcessor.java | il-pazzo/asciidoctorj | 78429ff539fd7feffe41219a9e1dc6c230196928 | [
"Apache-2.0"
] | 516 | 2015-01-03T11:01:21.000Z | 2022-03-29T05:34:31.000Z | asciidoctorj-documentation/src/test/java/org/asciidoctor/integrationguide/extension/RobotsDocinfoProcessor.java | il-pazzo/asciidoctorj | 78429ff539fd7feffe41219a9e1dc6c230196928 | [
"Apache-2.0"
] | 695 | 2015-01-02T01:52:58.000Z | 2022-02-14T08:45:55.000Z | asciidoctorj-documentation/src/test/java/org/asciidoctor/integrationguide/extension/RobotsDocinfoProcessor.java | il-pazzo/asciidoctorj | 78429ff539fd7feffe41219a9e1dc6c230196928 | [
"Apache-2.0"
] | 167 | 2015-01-12T15:16:31.000Z | 2021-12-19T00:18:28.000Z | 30.833333 | 72 | 0.695495 | 5,134 | package org.asciidoctor.integrationguide.extension;
//tag::include[]
import org.asciidoctor.ast.Document;
import org.asciidoctor.extension.DocinfoProcessor;
import org.asciidoctor.extension.Location;
import org.asciidoctor.extension.LocationType;
@Location(LocationType.HEADER) // <1>
public class RobotsDocinfoProcessor extends DocinfoProcessor { // <2>
@Override
public String process(Document document) {
return "<meta name=\"robots\" content=\"index,follow\">"; // <3>
}
}
//end::include[]
|
3e0c18f8e5d71ce81ccbbf1de8265e9d800be864 | 113 | java | Java | test/cases/xbean/compile/scomp/schemacompiler/ext/H1.java | e-taka/xmlbeans | 0e8f6ac2fa44e68f53956a212acfd817c0ff54c5 | [
"Apache-2.0"
] | 5 | 2018-01-12T14:32:50.000Z | 2019-10-24T07:36:44.000Z | test/cases/xbean/compile/scomp/schemacompiler/ext/H1.java | e-taka/xmlbeans | 0e8f6ac2fa44e68f53956a212acfd817c0ff54c5 | [
"Apache-2.0"
] | 3 | 2017-06-29T23:19:45.000Z | 2018-10-15T18:14:55.000Z | test/cases/xbean/compile/scomp/schemacompiler/ext/H1.java | e-taka/xmlbeans | 0e8f6ac2fa44e68f53956a212acfd817c0ff54c5 | [
"Apache-2.0"
] | 4 | 2017-06-30T18:35:30.000Z | 2017-12-27T23:31:28.000Z | 14.125 | 61 | 0.619469 | 5,135 | package ext;
public class H1
{
public static void get(org.apache.xmlbeans.XmlObject xo)
{
}
} |
3e0c19734591af616e20719f40350906f44ab066 | 1,140 | java | Java | src/main/java/com/hongshen/boke/dao/object/TbfileDO.java | qhs1995/boke | 3b5c22171ed962927cb6442611a0a050de1fa9b5 | [
"Apache-2.0"
] | 1 | 2020-06-23T06:52:25.000Z | 2020-06-23T06:52:25.000Z | src/main/java/com/hongshen/boke/dao/object/TbfileDO.java | qhs1995/boke | 3b5c22171ed962927cb6442611a0a050de1fa9b5 | [
"Apache-2.0"
] | 2 | 2021-05-08T18:19:49.000Z | 2022-02-09T22:26:18.000Z | src/main/java/com/hongshen/boke/dao/object/TbfileDO.java | qhs1995/boke | 3b5c22171ed962927cb6442611a0a050de1fa9b5 | [
"Apache-2.0"
] | null | null | null | 20.727273 | 52 | 0.586842 | 5,136 | package com.hongshen.boke.dao.object;
import java.io.Serializable;
/**
* 该实体BEAN是由系统生成请勿修改
*
* Created by system on 2018/11/14
*/
public class TbfileDO implements Serializable {
private Integer id;
private String fname;
private byte[] fcontent;
private static final long serialVersionUID = 1L;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public byte[] getFcontent() {
return fcontent;
}
public void setFcontent(byte[] fcontent) {
this.fcontent = fcontent;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", fname=").append(fname);
sb.append(", fcontent=").append(fcontent);
sb.append("]");
return sb.toString();
}
} |
3e0c19972c3e3b8f8dbb86535249fa248ac951b1 | 1,408 | java | Java | src/main/java/net/kunmc/lab/lavaandwater/config/CentralPlayer.java | TeamKun/LavaAndWater | f8b5ca065d3561ca6510d7b2131948557ac56f66 | [
"MIT"
] | null | null | null | src/main/java/net/kunmc/lab/lavaandwater/config/CentralPlayer.java | TeamKun/LavaAndWater | f8b5ca065d3561ca6510d7b2131948557ac56f66 | [
"MIT"
] | null | null | null | src/main/java/net/kunmc/lab/lavaandwater/config/CentralPlayer.java | TeamKun/LavaAndWater | f8b5ca065d3561ca6510d7b2131948557ac56f66 | [
"MIT"
] | null | null | null | 26.566038 | 182 | 0.644886 | 5,137 | package net.kunmc.lab.lavaandwater.config;
import net.kunmc.lab.lavaandwater.world.waterLevelRise.BlockModel;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.util.BoundingBox;
import org.bukkit.util.Vector;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
public class CentralPlayer {
/** プレイヤー */
private Player player;
/** ワールド */
private World world;
CentralPlayer(Player player) {
this.player = player;
this.world = player.getWorld();
}
/**
* プレイヤー名を取得する
* */
public String playerName() {
return this.player.getName();
}
/**
* 水面上昇の処理範囲を取得する
* */
public List<BlockModel> effectiveBlocks(WaterLevel waterLevel) {
Location center = player.getLocation();
BoundingBox boundingBox = BoundingBox.of(center.getBlock()).expand(Config.effectiveRange().halfRange());
List<BlockModel> result = new ArrayList<>();
IntStream.range((int) boundingBox.getMinX(),(int) boundingBox.getMaxX()).forEach(i -> IntStream.range((int) boundingBox.getMinZ(), (int) boundingBox.getMaxZ()).forEach(j -> {
result.add(new BlockModel(
new Vector(i, waterLevel.currentLevel(), j)
.toLocation(this.world)));
}));
return result;
}
}
|
3e0c19dfcf99ca1481c070f5193bab6cea82b673 | 1,172 | java | Java | addressbook-web-tests/src/test/java/ru/stqa/pft/github/addressbook/tests/ContactDeletionTest.java | yutta13/java_36 | 696068cbb731b2a75e08397842a2827e660e8cd5 | [
"Apache-2.0"
] | null | null | null | addressbook-web-tests/src/test/java/ru/stqa/pft/github/addressbook/tests/ContactDeletionTest.java | yutta13/java_36 | 696068cbb731b2a75e08397842a2827e660e8cd5 | [
"Apache-2.0"
] | null | null | null | addressbook-web-tests/src/test/java/ru/stqa/pft/github/addressbook/tests/ContactDeletionTest.java | yutta13/java_36 | 696068cbb731b2a75e08397842a2827e660e8cd5 | [
"Apache-2.0"
] | null | null | null | 28.512195 | 145 | 0.707442 | 5,138 | package ru.stqa.pft.github.addressbook.tests;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ru.stqa.pft.github.addressbook.model.ContactData;
import ru.stqa.pft.github.addressbook.model.Contacts;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.*;
/**
* Created by uttabondarenko on 28.12.16.
*/
public class ContactDeletionTest extends TestBase {
@BeforeMethod
public void ensurePreconditions() {
if (app.db().contacts().size() == 0) {
app.goTo().HomePage();
app.contact().create(new ContactData()
.withFirstname("Yutta").withLastname("Bondarenko").withAddress("Moscow").withHomephone("89992223311").withEmail("nnheo@example.com"));
;
}
}
@Test
public void contactDeletionTests() {
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();
}
}
|
3e0c1a6af9fe5bd28df06044a655dd7bc464577e | 3,581 | java | Java | SPWebTest/test/com/gdevelop/gwt/syncrpc/spawebtest/client/GreetingServiceTest.java | nbartels/gwt-syncproxy | f18a43e62a3544c0e9a8dc3c092d953676838939 | [
"Apache-2.0"
] | 25 | 2015-03-30T14:52:55.000Z | 2021-04-30T05:13:08.000Z | SPWebTest/test/com/gdevelop/gwt/syncrpc/spawebtest/client/GreetingServiceTest.java | nbartels/gwt-syncproxy | f18a43e62a3544c0e9a8dc3c092d953676838939 | [
"Apache-2.0"
] | 12 | 2015-03-30T14:07:30.000Z | 2021-04-30T07:22:09.000Z | SPWebTest/test/com/gdevelop/gwt/syncrpc/spawebtest/client/GreetingServiceTest.java | nbartels/gwt-syncproxy | f18a43e62a3544c0e9a8dc3c092d953676838939 | [
"Apache-2.0"
] | 14 | 2015-04-03T02:53:38.000Z | 2021-05-04T14:04:08.000Z | 30.347458 | 77 | 0.685283 | 5,139 | package com.gdevelop.gwt.syncrpc.spawebtest.client;
import java.util.ArrayList;
import com.gdevelop.gwt.syncrpc.spawebtest.shared.T1;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.RpcTestBase;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
/**
* GWT JUnit tests must extend GWTTestCase.
*/
public class GreetingServiceTest extends RpcTestBase {
protected GreetingServiceAsync getAsyncService() {
GreetingServiceAsync greetingService = GWT
.create(GreetingService.class);
ServiceDefTarget target = (ServiceDefTarget) greetingService;
target.setServiceEntryPoint(GWT.getModuleBaseURL() + "spawebtest/greet");
return greetingService;
}
/**
* Must refer to a valid module that sources this class.
*/
@Override
public String getModuleName() {
return "com.gdevelop.gwt.syncrpc.spawebtest.SPAGWTTest";
}
/**
* This test will send a request to the server using the greetServer method
* in GreetingService and verify the response.
*/
public void testGreetingService() {
// Create the service that we will test.
GreetingServiceAsync greetingService = getAsyncService();
// Since RPC calls are asynchronous, we will need to wait for a response
// after this test method returns. This line tells the test runner to
// wait
// up to 10 seconds before timing out.
delayTestFinishForRpc();
// Send a request to the server.
greetingService.greetServer(GreetingService.NAME,
new AsyncCallback<String>() {
@Override
public void onFailure(Throwable caught) {
// The request resulted in an unexpected error.
fail("Request failure: " + caught.getMessage());
}
@Override
public void onSuccess(String result) {
// Verify that the response is correct.
assertTrue(result.contains(GreetingService.NAME));
// Now that we have received a response, we need to tell
// the
// test runner
// that the test is complete. You must call finishTest()
// after
// an
// asynchronous test finishes successfully, or the test
// will
// time out.
finishTest();
}
});
}
public void testGreetingService2() {
GreetingServiceAsync greetingService = getAsyncService();
delayTestFinishForRpc();
// Send a request to the server.
greetingService.greetServer2(GreetingService.NAME,
new AsyncCallback<T1>() {
@Override
public void onFailure(Throwable caught) {
// The request resulted in an unexpected error.
fail("Request failure: " + caught.getMessage());
}
@Override
public void onSuccess(T1 result) {
// Verify that the response is correct.
assertTrue(result.getText()
.equals(GreetingService.NAME));
finishTest();
}
});
}
public void testGreetingServiceArray() {
GreetingServiceAsync greetingService = getAsyncService();
delayTestFinishForRpc();
// Send a request to the server.
greetingService.greetServerArr(GreetingService.NAME,
new AsyncCallback<ArrayList<String>>() {
@Override
public void onFailure(Throwable caught) {
// The request resulted in an unexpected error.
fail("Request failure: " + caught.getMessage());
}
@Override
public void onSuccess(ArrayList<String> result) {
// Verify that the response is correct.
assertTrue(result.get(0).equals(GreetingService.NAME));
finishTest();
}
});
}
} |
3e0c1b15f73d354d8d3a3e8753eddda45856cf3b | 1,712 | java | Java | htb/fatty-10.10.10.174/fatty-client/org/springframework/web/context/request/SessionScope.java | benhunter/ctf | 3de1a222ea0034ef15eb6b75585b03a6ee37ec37 | [
"MIT"
] | null | null | null | htb/fatty-10.10.10.174/fatty-client/org/springframework/web/context/request/SessionScope.java | benhunter/ctf | 3de1a222ea0034ef15eb6b75585b03a6ee37ec37 | [
"MIT"
] | 1 | 2022-03-31T22:44:36.000Z | 2022-03-31T22:44:36.000Z | htb/fatty-10.10.10.174/fatty-client/org/springframework/web/context/request/SessionScope.java | benhunter/ctf | 3de1a222ea0034ef15eb6b75585b03a6ee37ec37 | [
"MIT"
] | null | null | null | 22.826667 | 144 | 0.454439 | 5,140 | /* */ package org.springframework.web.context.request;
/* */
/* */ import org.springframework.beans.factory.ObjectFactory;
/* */ import org.springframework.lang.Nullable;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public class SessionScope
/* */ extends AbstractRequestAttributesScope
/* */ {
/* */ protected int getScope() {
/* 45 */ return 1;
/* */ }
/* */
/* */
/* */ public String getConversationId() {
/* 50 */ return RequestContextHolder.currentRequestAttributes().getSessionId();
/* */ }
/* */
/* */
/* */ public Object get(String name, ObjectFactory<?> objectFactory) {
/* 55 */ Object mutex = RequestContextHolder.currentRequestAttributes().getSessionMutex();
/* 56 */ synchronized (mutex) {
/* 57 */ return super.get(name, objectFactory);
/* */ }
/* */ }
/* */
/* */
/* */ @Nullable
/* */ public Object remove(String name) {
/* 64 */ Object mutex = RequestContextHolder.currentRequestAttributes().getSessionMutex();
/* 65 */ synchronized (mutex) {
/* 66 */ return super.remove(name);
/* */ }
/* */ }
/* */ }
/* Location: /home/kali/ctf/htb/fatty-10.10.10.174/ftp/fatty-client.jar!/org/springframework/web/context/request/SessionScope.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ |
3e0c1b4ccb9d7628c256c1e10ce9a2ff4922aa44 | 172 | java | Java | examples/src/asp/i_Asp.java | JungleComputing/gmi | 2296d60b8170a0aab2a847894e3f3f9ce953f5c8 | [
"BSD-3-Clause"
] | null | null | null | examples/src/asp/i_Asp.java | JungleComputing/gmi | 2296d60b8170a0aab2a847894e3f3f9ce953f5c8 | [
"BSD-3-Clause"
] | null | null | null | examples/src/asp/i_Asp.java | JungleComputing/gmi | 2296d60b8170a0aab2a847894e3f3f9ce953f5c8 | [
"BSD-3-Clause"
] | null | null | null | 13.230769 | 43 | 0.674419 | 5,141 | /* $Id$ */
package asp;
import ibis.gmi.GroupInterface;
interface i_Asp extends GroupInterface {
public void transfer(int[] row, int k);
public void done();
}
|
3e0c1ba03e5ede66bc4443e10738f72978c72fd8 | 2,047 | java | Java | application/app/src/main/java/m_diary/assets/Weather.java | Su-Lemon/colorful_handbook | a964bca54e4e4a65ff61fcb919c88ef34fce59e2 | [
"MIT"
] | 7 | 2021-06-03T11:32:57.000Z | 2022-03-22T05:41:29.000Z | application/app/src/main/java/m_diary/assets/Weather.java | Su-Lemon/colorful_handbook | a964bca54e4e4a65ff61fcb919c88ef34fce59e2 | [
"MIT"
] | null | null | null | application/app/src/main/java/m_diary/assets/Weather.java | Su-Lemon/colorful_handbook | a964bca54e4e4a65ff61fcb919c88ef34fce59e2 | [
"MIT"
] | 1 | 2022-03-18T10:27:10.000Z | 2022-03-18T10:27:10.000Z | 28.041096 | 58 | 0.425012 | 5,142 | package m_diary.assets;
public class Weather {
public static int year = 2021;
public static int month = 1;
public static int day = 1;
public static String week = "星期五";
public static String weather = "晴";
public static String notice = "天气晴朗心情舒畅";
public static String temperature = "13.0f";
private static boolean leap_year;
public static String getDateStr(){
return year + "年" + month + "月" + day + "日";
}
public static void plusDAY(){
day++;
if(day>get_month_day(month)){
day = 1;
month++;
if (month>12){
month = 1;
year++;
leap_year = is_leap_year(year);
}
}
}
public static void minusDAY(){
day--;
if(day<1){
month--;
day = get_month_day(month);
if (month<1){
month = 12;
year--;
leap_year = is_leap_year(year);
}
}
}
public static int get_month_day(int month){
int days = 30;
switch (month){
case 1:{days = 31;}break;
case 2:{
if(leap_year){
days = 29;
}
else {
days = 28;
}
}break;
case 3:{days = 31;}break;
case 4:{days = 30;}break;
case 5:{days = 31;}break;
case 6:{days = 30;}break;
case 7:{days = 31;}break;
case 8:{days = 31;}break;
case 9:{days = 30;}break;
case 10:{days = 31;}break;
case 11:{days = 30;}break;
case 12:{days = 31;}break;
}
return days;
}
private static boolean is_leap_year(int year){
if((year%4 == 0&&year%100 != 0)||year%400 == 0) {
return true;
}
else{
return false;
}
}
}
|
3e0c1bdab9c8baba1a5aa2a108ac8a398e0b84f0 | 839 | java | Java | service/src/main/java/com/epam/rft/atsy/service/domain/ChannelDTO.java | epam-debrecen-rft-2015/atsy | 7874471b649dcd6bbfaf7b01e8afd1f5c8357eee | [
"Apache-2.0"
] | 10 | 2015-10-07T15:11:24.000Z | 2020-07-06T18:10:38.000Z | service/src/main/java/com/epam/rft/atsy/service/domain/ChannelDTO.java | epam-debrecen-rft-2015/atsy | 7874471b649dcd6bbfaf7b01e8afd1f5c8357eee | [
"Apache-2.0"
] | 47 | 2016-07-05T07:24:06.000Z | 2018-03-22T15:16:40.000Z | service/src/main/java/com/epam/rft/atsy/service/domain/ChannelDTO.java | epam-debrecen-rft-2015/atsy | 7874471b649dcd6bbfaf7b01e8afd1f5c8357eee | [
"Apache-2.0"
] | 4 | 2015-10-12T05:44:12.000Z | 2020-04-16T06:44:34.000Z | 24.676471 | 97 | 0.775924 | 5,143 | package com.epam.rft.atsy.service.domain;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;
/**
* Data transfer class that is used to transfer the data of a channel between the service and web
* layers. See {@link com.epam.rft.atsy.persistence.entities.ChannelEntity ChannelEntity}.
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class ChannelDTO extends LogicallyDeletableDTO {
@NotNull
@Size(min = 1)
private String name;
@Builder
public ChannelDTO(Long id, Boolean deleted, String name) {
super(id, deleted);
this.name = name;
}
}
|
3e0c1bdc2d7f32692d7ce212843437a50c79a44e | 2,918 | java | Java | src/ml/association/HashTree.java | shrtCKT/FCG-to-Vector | 782f0a1808af8e97c08d1f9384dd8a27b9e67686 | [
"Apache-2.0"
] | 7 | 2018-08-24T22:52:16.000Z | 2021-09-05T13:37:09.000Z | src/ml/association/HashTree.java | njucjc/FCG-to-Vector | 782f0a1808af8e97c08d1f9384dd8a27b9e67686 | [
"Apache-2.0"
] | 1 | 2020-03-02T12:22:21.000Z | 2020-03-02T12:22:21.000Z | src/ml/association/HashTree.java | njucjc/FCG-to-Vector | 782f0a1808af8e97c08d1f9384dd8a27b9e67686 | [
"Apache-2.0"
] | 6 | 2018-08-25T10:14:00.000Z | 2019-04-27T16:17:36.000Z | 23.532258 | 100 | 0.611378 | 5,144 | package ml.association;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class HashTree<E> {
static final int DEFAULT_NUM_BRANCHES = 3;
static class Node<E> {
List<ItemSet<E>> bucket;
HashMap<Integer, Node<E>> children;
public Node() {
children = new HashMap<Integer, Node<E>>();
}
public void addToBucket(ItemSet<E> elem) {
if (bucket == null) {
bucket = new ArrayList<ItemSet<E>>();
}
bucket.add(elem);
}
}
Node<E> root;
/**
* The number of branches for an internal node. Default is 3
*/
int numBranches;
/**
* The size of an itemset stored in this tree. This implies that all itemsets should contain equal
* number of items.
*/
int itemsetSize;
/**
* Number of elements in the tree.
*/
private int size;
public HashTree(int itemsetSize) {
initialize(itemsetSize, DEFAULT_NUM_BRANCHES);
}
public HashTree(int itemsetSize, int numBranches) {
initialize(itemsetSize, numBranches);
}
private void initialize(int itemsetSize, int numBranches) {
this.itemsetSize = itemsetSize;
this.numBranches = numBranches;
}
public void insert(ItemSet<E> itemset) {
root = insert(root, itemset, 0);
}
private Node<E> insert(Node<E> curr, ItemSet<E> itemset, int depth) {
if (depth == itemsetSize) { // case 1: Leaf node
// case 1.1: null curr then create node
if (curr == null) {
curr = new Node<E>();
}
// case 1.2: curr exists add to bucket
curr.addToBucket(itemset);
size++;
} else { // case 2: non leaf node
// case 1.1: null curr create node
if (curr == null) {
curr = new Node<E>();
}
// case 1.2: curr exists
int key = computeKey(itemset, depth);
Node<E> child = curr.children.get(key);
child = insert(child, itemset, depth+1);
curr.children.put(key, child);
}
return curr;
}
public int computeKey(ItemSet<E> itemset, int depth) {
return itemset.getItemAt(depth).hashCode() % HashTree.DEFAULT_NUM_BRANCHES;
}
public static <T> HashTree<T> makeTree(List<ItemSet<T>> collection, int itemsetSize) {
HashTree<T> tree = new HashTree<T>(itemsetSize);
for (ItemSet<T> itemset : collection) {
tree.insert(itemset);
}
return tree;
}
public int size() {
return size;
}
public ItemSet<E> get(ItemSet<E> itemset) {
return get(root, itemset, 0);
}
private ItemSet<E> get(Node<E> curr, ItemSet<E> itemset, int depth) {
if (curr == null) {
return null;
}
if (depth != itemsetSize) {
int key = computeKey(itemset, depth);
return get(curr.children.get(key), itemset, depth + 1);
}
int index = curr.bucket.indexOf(itemset);
if (index == -1) {
return null;
}
return curr.bucket.get(index);
}
}
|
3e0c1c87bb91bd1d7898f34e54aaa9511eacf993 | 4,030 | java | Java | sender-awssdk-sqs/src/test/java/zipkin2/reporter/awssdk/sqs/SQSAsyncSenderTest.java | Archium/zipkin-aws | 446bc679a9ce1391c0ff524861736768387e46e9 | [
"Apache-2.0"
] | null | null | null | sender-awssdk-sqs/src/test/java/zipkin2/reporter/awssdk/sqs/SQSAsyncSenderTest.java | Archium/zipkin-aws | 446bc679a9ce1391c0ff524861736768387e46e9 | [
"Apache-2.0"
] | null | null | null | sender-awssdk-sqs/src/test/java/zipkin2/reporter/awssdk/sqs/SQSAsyncSenderTest.java | Archium/zipkin-aws | 446bc679a9ce1391c0ff524861736768387e46e9 | [
"Apache-2.0"
] | null | null | null | 32.24 | 100 | 0.724069 | 5,145 | /*
* Copyright 2016-2019 The OpenZipkin Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package zipkin2.reporter.awssdk.sqs;
import java.net.URI;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sqs.SqsClient;
import zipkin2.Call;
import zipkin2.Callback;
import zipkin2.CheckResult;
import zipkin2.Span;
import zipkin2.codec.Encoding;
import zipkin2.codec.SpanBytesEncoder;
import zipkin2.junit.aws.AmazonSQSRule;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThat;
import static zipkin2.TestObjects.CLIENT_SPAN;
public class SQSAsyncSenderTest {
@Rule
public AmazonSQSRule sqsRule = new AmazonSQSRule().start(9324);
@Rule public ExpectedException thrown = ExpectedException.none();
SqsClient sqsClient = SqsClient.builder()
.httpClient(UrlConnectionHttpClient.create())
.region(Region.US_EAST_1)
.endpointOverride(URI.create(sqsRule.queueUrl()))
.credentialsProvider(
StaticCredentialsProvider.create(AwsBasicCredentials.create("x", "x")))
.build();
SQSSender sender =
SQSSender.newBuilder()
.queueUrl(sqsRule.queueUrl())
.sqsClient(sqsClient)
.build();
@Test
public void sendsSpans() throws Exception {
send(CLIENT_SPAN, CLIENT_SPAN).execute();
assertThat(readSpans()).containsExactly(CLIENT_SPAN, CLIENT_SPAN);
}
@Test
public void sendsSpans_json_unicode() throws Exception {
Span unicode = CLIENT_SPAN.toBuilder().putTag("error", "\uD83D\uDCA9").build();
send(unicode).execute();
assertThat(readSpans()).containsExactly(unicode);
}
@Test
public void sendsSpans_PROTO3() throws Exception {
sender.close();
sender = sender.toBuilder().encoding(Encoding.PROTO3).build();
send(CLIENT_SPAN, CLIENT_SPAN).execute();
assertThat(readSpans()).containsExactly(CLIENT_SPAN, CLIENT_SPAN);
}
@Test
public void outOfBandCancel() throws Exception {
SQSSender.SQSCall call = (SQSSender.SQSCall) send(CLIENT_SPAN, CLIENT_SPAN);
assertThat(call.isCanceled()).isFalse(); // sanity check
CountDownLatch latch = new CountDownLatch(1);
call.enqueue(
new Callback<Void>() {
@Override
public void onSuccess(Void aVoid) {
call.cancel();
latch.countDown();
}
@Override
public void onError(Throwable throwable) {
latch.countDown();
}
});
latch.await(5, TimeUnit.SECONDS);
assertThat(call.isCanceled()).isTrue();
}
@Test
public void checkOk() throws Exception {
assertThat(sender.check()).isEqualTo(CheckResult.OK);
}
Call<Void> send(Span... spans) {
SpanBytesEncoder bytesEncoder =
sender.encoding() == Encoding.JSON ? SpanBytesEncoder.JSON_V2 : SpanBytesEncoder.PROTO3;
return sender.sendSpans(Stream.of(spans).map(bytesEncoder::encode).collect(toList()));
}
List<Span> readSpans() {
assertThat(sqsRule.queueCount()).isEqualTo(1);
return sqsRule.getSpans();
}
}
|
3e0c1d7b5a2c28b50c7b7fb43cb98dc1d2ccbb0b | 1,363 | java | Java | ssl-socks-client/src/main/java/awesome/socks/client/bean/ClientOptions.java | demondevilhades/ssl-socks | aee63486f3ed9af1ed7b4f6b58b1e39d5e9df6d3 | [
"MIT"
] | 1 | 2021-10-09T09:14:03.000Z | 2021-10-09T09:14:03.000Z | ssl-socks-client/src/main/java/awesome/socks/client/bean/ClientOptions.java | demondevilhades/ssl-socks | aee63486f3ed9af1ed7b4f6b58b1e39d5e9df6d3 | [
"MIT"
] | null | null | null | ssl-socks-client/src/main/java/awesome/socks/client/bean/ClientOptions.java | demondevilhades/ssl-socks | aee63486f3ed9af1ed7b4f6b58b1e39d5e9df6d3 | [
"MIT"
] | null | null | null | 30.977273 | 102 | 0.738078 | 5,146 | package awesome.socks.client.bean;
import awesome.socks.common.bean.Options;
import awesome.socks.common.util.Config;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
/**
*
* @author awesome
*/
@Accessors(chain = true, fluent = true)
@Getter
@Setter
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ClientOptions extends Options {
protected static final String SSS_SERVER_HOST = "sss.server.host";
protected static final String SSS_LOCAL_PORT = "sss.local.port";
protected static final String SSS_LOCAL_FINGERPRINTSALGORITHM = "sss.local.fingerprintsAlgorithm";
protected static final String SSS_LOCAL_TESTURL = "sss.local.testUrl";
private static final ClientOptions INSTANCE = new ClientOptions()
.serverHost(Config.get(SSS_SERVER_HOST))
.localPort(Config.getInt(SSS_LOCAL_PORT))
.localFingerprintsAlgorithm(Config.get(SSS_LOCAL_FINGERPRINTSALGORITHM))
.localTestUrl(Config.get(SSS_LOCAL_TESTURL))
.optionsConfig();
public static ClientOptions getInstance() {
return INSTANCE;
}
protected String serverHost;
protected int localPort;
protected String localFingerprintsAlgorithm;
protected String localTestUrl;
}
|
3e0c1e8ddf5c3f4e7cc271ce52fddd3cd3422428 | 857 | java | Java | Dziennik/src/main/java/Converters/WarnsConverter.java | mjochab/PZ_2019_Lab2_Gr2 | 58c0a3111962924b272284b081124944413d342b | [
"MIT"
] | 1 | 2019-05-28T12:00:05.000Z | 2019-05-28T12:00:05.000Z | Dziennik/src/main/java/Converters/WarnsConverter.java | mjochab/PZ_2019_Lab2_Gr2 | 58c0a3111962924b272284b081124944413d342b | [
"MIT"
] | 1 | 2019-05-02T20:43:32.000Z | 2019-05-02T20:43:32.000Z | Dziennik/src/main/java/Converters/WarnsConverter.java | mjochab/PZ_2019_Lab2_Gr2 | 58c0a3111962924b272284b081124944413d342b | [
"MIT"
] | 1 | 2019-10-20T16:30:16.000Z | 2019-10-20T16:30:16.000Z | 32.961538 | 100 | 0.710618 | 5,147 | package Converters;
import Modele.Warns;
import modelFX.WarnsFx;
public class WarnsConverter {
public static WarnsFx convertToWarnsFx(Warns warns){
WarnsFx warnsFx = new WarnsFx();
warnsFx.setWarns_id(warns.getWarnId());
warnsFx.setContent(warns.getContent());
warnsFx.setDate_created(warns.getDateCreated());
warnsFx.setStudentFxObjectProperty(StudentConverter.convertToStudentFx(warns.getStudent()));
warnsFx.setTeacherFxObjectProperty(TeacherConverter.convertToTeacherFx(warns.getTeacher()));
return warnsFx;
}
public static Warns convertToWarns(WarnsFx warnsFx){
Warns warns = new Warns();
warns.setWarnId(warnsFx.getWarns_id());
warns.setContent(warnsFx.getContent());
warns.setDateCreated(warnsFx.getDate_created());
return warns;
}
}
|
3e0c1eed389c2f47fc6a48cf76ae469879e5d0f3 | 5,099 | java | Java | back-end/hub-api/src/main/java/io/apicurio/hub/api/rest/impl/ValidationProfilesResource.java | abhaykumarPS/apicurio-studio | d60cf39ca50555aa8b17167fae8828b258a9e2e0 | [
"Apache-2.0"
] | 746 | 2017-05-03T11:35:17.000Z | 2022-03-11T09:45:46.000Z | back-end/hub-api/src/main/java/io/apicurio/hub/api/rest/impl/ValidationProfilesResource.java | abhaykumarPS/apicurio-studio | d60cf39ca50555aa8b17167fae8828b258a9e2e0 | [
"Apache-2.0"
] | 1,179 | 2017-05-01T16:20:50.000Z | 2022-03-28T18:42:43.000Z | back-end/hub-api/src/main/java/io/apicurio/hub/api/rest/impl/ValidationProfilesResource.java | carlesarnal/apicurio-studio | 8bca071a28b804a80bf86229687ba2d5d153dab1 | [
"Apache-2.0"
] | 422 | 2017-05-03T13:01:05.000Z | 2022-03-31T12:26:04.000Z | 38.097015 | 158 | 0.686974 | 5,148 | /*
* Copyright 2019 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.apicurio.hub.api.rest.impl;
import java.util.Collection;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.apicurio.hub.api.metrics.IApiMetrics;
import io.apicurio.hub.api.rest.IValidationProfilesResource;
import io.apicurio.hub.api.security.ISecurityContext;
import io.apicurio.hub.core.beans.CreateValidationProfile;
import io.apicurio.hub.core.beans.UpdateValidationProfile;
import io.apicurio.hub.core.beans.ValidationProfile;
import io.apicurio.hub.core.exceptions.NotFoundException;
import io.apicurio.hub.core.exceptions.ServerError;
import io.apicurio.hub.core.storage.IStorage;
import io.apicurio.hub.core.storage.StorageException;
/**
* @author hzdkv@example.com
*/
@ApplicationScoped
public class ValidationProfilesResource implements IValidationProfilesResource {
private static Logger logger = LoggerFactory.getLogger(ValidationProfilesResource.class);
@Inject
private IStorage storage;
@Inject
private ISecurityContext security;
@Inject
private IApiMetrics metrics;
/**
* @see io.apicurio.hub.api.rest.IValidationProfilesResource#listValidationProfiles()
*/
@Override
public Collection<ValidationProfile> listValidationProfiles() throws ServerError {
metrics.apiCall("/validationProfiles", "GET");
try {
String user = this.security.getCurrentUser().getLogin();
logger.debug("Listing Validation Profiles for {}", user);
return this.storage.listValidationProfiles(user);
} catch (StorageException e) {
throw new ServerError(e);
}
}
/**
* @see io.apicurio.hub.api.rest.IValidationProfilesResource#createValidationProfile(io.apicurio.hub.core.beans.CreateValidationProfile)
*/
@Override
public ValidationProfile createValidationProfile(CreateValidationProfile info) throws ServerError {
metrics.apiCall("/validationProfiles", "POST");
try {
String user = this.security.getCurrentUser().getLogin();
logger.debug("Creating a new validaton profile for {} named: {}", user, info.getName());
ValidationProfile profile = new ValidationProfile();
profile.setName(info.getName());
profile.setDescription(info.getDescription());
if (info.getSeverities() != null) {
profile.setSeverities(info.getSeverities());
}
long pid = storage.createValidationProfile(user, profile);
profile.setId(pid);
return profile;
} catch (StorageException e) {
throw new ServerError(e);
}
}
/**
* @see io.apicurio.hub.api.rest.IValidationProfilesResource#updateValidationProfile(java.lang.String, io.apicurio.hub.core.beans.UpdateValidationProfile)
*/
@Override
public void updateValidationProfile(String profileId, UpdateValidationProfile update)
throws ServerError, NotFoundException {
metrics.apiCall("/validationProfiles/{profileId}", "PUT");
try {
String user = this.security.getCurrentUser().getLogin();
logger.debug("Updating an existing validaton profile for {} named: {}", user, update.getName());
ValidationProfile profile = new ValidationProfile();
profile.setId(Long.parseLong(profileId));
profile.setName(update.getName());
profile.setDescription(update.getDescription());
if (update.getSeverities() != null) {
profile.setSeverities(update.getSeverities());
}
storage.updateValidationProfile(user, profile);
} catch (StorageException e) {
throw new ServerError(e);
}
}
/**
* @see io.apicurio.hub.api.rest.IValidationProfilesResource#deleteValidationProfile(java.lang.String)
*/
@Override
public void deleteValidationProfile(String profileId) throws ServerError, NotFoundException {
metrics.apiCall("/validationProfiles/{profileId}", "DELETE");
try {
String user = this.security.getCurrentUser().getLogin();
logger.debug("Deleting validation profile for {} with ID: ", user, profileId);
this.storage.deleteValidationProfile(user, Long.parseLong(profileId));
} catch (StorageException e) {
throw new ServerError(e);
}
}
}
|
3e0c1f6d801f1cb9e4dfd203ee61fd64897850f6 | 120 | java | Java | Behavioural Design Patterns/Observer Pattern/WeatherStationImplementaton/Subject.java | AbhilashG97/WatermelonPudding | 41dd91ccfb1c8b09ab1ff919024b6fb8efb28030 | [
"MIT"
] | 1 | 2019-12-10T16:32:43.000Z | 2019-12-10T16:32:43.000Z | Behavioural Design Patterns/Observer Pattern/WeatherStationImplementaton/Subject.java | AbhilashG97/WatermelonPudding | 41dd91ccfb1c8b09ab1ff919024b6fb8efb28030 | [
"MIT"
] | null | null | null | Behavioural Design Patterns/Observer Pattern/WeatherStationImplementaton/Subject.java | AbhilashG97/WatermelonPudding | 41dd91ccfb1c8b09ab1ff919024b6fb8efb28030 | [
"MIT"
] | null | null | null | 13.333333 | 32 | 0.75 | 5,149 | public interface Subject {
void add(Observer observer);
void remove(Observer observer);
void notifyObservers();
} |
3e0c1f6e465b3bbbfbe7bde2602bfd6ad174ed82 | 555 | java | Java | src/org/appwork/swing/PropertyStateEventProviderInterface.java | friedlwo/AppWoksUtils | 35a2b21892432ecaa563f042305dfaeca732a856 | [
"Artistic-2.0"
] | 2 | 2015-08-30T13:01:19.000Z | 2020-06-07T19:54:25.000Z | src/org/appwork/swing/PropertyStateEventProviderInterface.java | friedlwo/AppWoksUtils | 35a2b21892432ecaa563f042305dfaeca732a856 | [
"Artistic-2.0"
] | null | null | null | src/org/appwork/swing/PropertyStateEventProviderInterface.java | friedlwo/AppWoksUtils | 35a2b21892432ecaa563f042305dfaeca732a856 | [
"Artistic-2.0"
] | null | null | null | 26.47619 | 87 | 0.719424 | 5,150 | /**
* Copyright (c) 2009 - 2013 AppWork UG(haftungsbeschränkt) <dycjh@example.com>
*
* This file is part of org.appwork.swing
*
* This software is licensed under the Artistic License 2.0,
* see the LICENSE file or http://www.opensource.org/licenses/artistic-license-2.0.php
* for details
*/
package org.appwork.swing;
import org.appwork.swing.event.PropertySetEventSender;
/**
* @author Thomas
*
*/
public interface PropertyStateEventProviderInterface {
public PropertySetEventSender getPropertySetEventSender();
}
|
3e0c2176032348ce34439ec2bb728046c75dc1eb | 118,089 | java | Java | OpenBeaconPackage/libraries/hibernate-release-4.2.7.SP1/project/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationBinder.java | HerrB92/obp | 31238554ec22a10e56892e987439ded36d671e1e | [
"MIT"
] | null | null | null | OpenBeaconPackage/libraries/hibernate-release-4.2.7.SP1/project/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationBinder.java | HerrB92/obp | 31238554ec22a10e56892e987439ded36d671e1e | [
"MIT"
] | null | null | null | OpenBeaconPackage/libraries/hibernate-release-4.2.7.SP1/project/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationBinder.java | HerrB92/obp | 31238554ec22a10e56892e987439ded36d671e1e | [
"MIT"
] | 1 | 2022-01-06T09:05:56.000Z | 2022-01-06T09:05:56.000Z | 38.044137 | 181 | 0.729382 | 5,151 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2010, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.cfg;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.persistence.Basic;
import javax.persistence.Cacheable;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.DiscriminatorType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.ElementCollection;
import javax.persistence.Embeddable;
import javax.persistence.Embedded;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.MapKey;
import javax.persistence.MapKeyColumn;
import javax.persistence.MapKeyJoinColumn;
import javax.persistence.MapKeyJoinColumns;
import javax.persistence.MappedSuperclass;
import javax.persistence.MapsId;
import javax.persistence.NamedNativeQueries;
import javax.persistence.NamedNativeQuery;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.OrderColumn;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.PrimaryKeyJoinColumns;
import javax.persistence.SequenceGenerator;
import javax.persistence.SharedCacheMode;
import javax.persistence.SqlResultSetMapping;
import javax.persistence.SqlResultSetMappings;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
import javax.persistence.UniqueConstraint;
import javax.persistence.Version;
import org.hibernate.AnnotationException;
import org.hibernate.AssertionFailure;
import org.hibernate.EntityMode;
import org.hibernate.FetchMode;
import org.hibernate.MappingException;
import org.hibernate.annotations.BatchSize;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.Check;
import org.hibernate.annotations.CollectionId;
import org.hibernate.annotations.Columns;
import org.hibernate.annotations.DiscriminatorOptions;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchProfile;
import org.hibernate.annotations.FetchProfiles;
import org.hibernate.annotations.Filter;
import org.hibernate.annotations.FilterDef;
import org.hibernate.annotations.FilterDefs;
import org.hibernate.annotations.Filters;
import org.hibernate.annotations.ForeignKey;
import org.hibernate.annotations.Formula;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.GenericGenerators;
import org.hibernate.annotations.Index;
import org.hibernate.annotations.LazyToOne;
import org.hibernate.annotations.LazyToOneOption;
import org.hibernate.annotations.ManyToAny;
import org.hibernate.annotations.MapKeyType;
import org.hibernate.annotations.NaturalId;
import org.hibernate.annotations.NaturalIdCache;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import org.hibernate.annotations.OrderBy;
import org.hibernate.annotations.ParamDef;
import org.hibernate.annotations.Parameter;
import org.hibernate.annotations.Parent;
import org.hibernate.annotations.Proxy;
import org.hibernate.annotations.Sort;
import org.hibernate.annotations.Source;
import org.hibernate.annotations.Tuplizer;
import org.hibernate.annotations.Tuplizers;
import org.hibernate.annotations.TypeDef;
import org.hibernate.annotations.TypeDefs;
import org.hibernate.annotations.Where;
import org.hibernate.annotations.common.reflection.ReflectionManager;
import org.hibernate.annotations.common.reflection.XAnnotatedElement;
import org.hibernate.annotations.common.reflection.XClass;
import org.hibernate.annotations.common.reflection.XMethod;
import org.hibernate.annotations.common.reflection.XPackage;
import org.hibernate.annotations.common.reflection.XProperty;
import org.hibernate.cache.spi.RegionFactory;
import org.hibernate.cfg.annotations.CollectionBinder;
import org.hibernate.cfg.annotations.EntityBinder;
import org.hibernate.cfg.annotations.MapKeyColumnDelegator;
import org.hibernate.cfg.annotations.MapKeyJoinColumnDelegator;
import org.hibernate.cfg.annotations.Nullability;
import org.hibernate.cfg.annotations.PropertyBinder;
import org.hibernate.cfg.annotations.QueryBinder;
import org.hibernate.cfg.annotations.SimpleValueBinder;
import org.hibernate.cfg.annotations.TableBinder;
import org.hibernate.engine.internal.Versioning;
import org.hibernate.engine.spi.FilterDefinition;
import org.hibernate.id.MultipleHiLoPerTableGenerator;
import org.hibernate.id.PersistentIdentifierGenerator;
import org.hibernate.id.SequenceHiLoGenerator;
import org.hibernate.id.TableHiLoGenerator;
import org.hibernate.id.enhanced.SequenceStyleGenerator;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.mapping.Any;
import org.hibernate.mapping.Component;
import org.hibernate.mapping.Constraint;
import org.hibernate.mapping.DependantValue;
import org.hibernate.mapping.IdGenerator;
import org.hibernate.mapping.Join;
import org.hibernate.mapping.JoinedSubclass;
import org.hibernate.mapping.KeyValue;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property;
import org.hibernate.mapping.RootClass;
import org.hibernate.mapping.SimpleValue;
import org.hibernate.mapping.SingleTableSubclass;
import org.hibernate.mapping.Subclass;
import org.hibernate.mapping.ToOne;
import org.hibernate.mapping.UnionSubclass;
import org.jboss.logging.Logger;
/**
* JSR 175 annotation binder which reads the annotations from classes, applies the
* principles of the EJB3 spec and produces the Hibernate configuration-time metamodel
* (the classes in the {@code org.hibernate.mapping} package)
*
* @author Emmanuel Bernard
* @author Hardy Ferentschik
*/
@SuppressWarnings("unchecked")
public final class AnnotationBinder {
private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, AnnotationBinder.class.getName() );
/*
* Some design description
* I tried to remove any link to annotation except from the 2 first level of
* method call.
* It'll enable to:
* - facilitate annotation overriding
* - mutualize one day xml and annotation binder (probably a dream though)
* - split this huge class in smaller mapping oriented classes
*
* bindSomething usually create the mapping container and is accessed by one of the 2 first level method
* makeSomething usually create the mapping container and is accessed by bindSomething[else]
* fillSomething take the container into parameter and fill it.
*/
private AnnotationBinder() {
}
public static void bindDefaults(Mappings mappings) {
Map defaults = mappings.getReflectionManager().getDefaults();
{
List<SequenceGenerator> anns = ( List<SequenceGenerator> ) defaults.get( SequenceGenerator.class );
if ( anns != null ) {
for ( SequenceGenerator ann : anns ) {
IdGenerator idGen = buildIdGenerator( ann, mappings );
if ( idGen != null ) {
mappings.addDefaultGenerator( idGen );
}
}
}
}
{
List<TableGenerator> anns = ( List<TableGenerator> ) defaults.get( TableGenerator.class );
if ( anns != null ) {
for ( TableGenerator ann : anns ) {
IdGenerator idGen = buildIdGenerator( ann, mappings );
if ( idGen != null ) {
mappings.addDefaultGenerator( idGen );
}
}
}
}
{
List<NamedQuery> anns = ( List<NamedQuery> ) defaults.get( NamedQuery.class );
if ( anns != null ) {
for ( NamedQuery ann : anns ) {
QueryBinder.bindQuery( ann, mappings, true );
}
}
}
{
List<NamedNativeQuery> anns = ( List<NamedNativeQuery> ) defaults.get( NamedNativeQuery.class );
if ( anns != null ) {
for ( NamedNativeQuery ann : anns ) {
QueryBinder.bindNativeQuery( ann, mappings, true );
}
}
}
{
List<SqlResultSetMapping> anns = ( List<SqlResultSetMapping> ) defaults.get( SqlResultSetMapping.class );
if ( anns != null ) {
for ( SqlResultSetMapping ann : anns ) {
QueryBinder.bindSqlResultsetMapping( ann, mappings, true );
}
}
}
}
public static void bindPackage(String packageName, Mappings mappings) {
XPackage pckg;
try {
pckg = mappings.getReflectionManager().packageForName( packageName );
}
catch ( ClassNotFoundException cnf ) {
LOG.packageNotFound( packageName );
return;
}
if ( pckg.isAnnotationPresent( SequenceGenerator.class ) ) {
SequenceGenerator ann = pckg.getAnnotation( SequenceGenerator.class );
IdGenerator idGen = buildIdGenerator( ann, mappings );
mappings.addGenerator( idGen );
if ( LOG.isTraceEnabled() ) {
LOG.tracev( "Add sequence generator with name: {0}", idGen.getName() );
}
}
if ( pckg.isAnnotationPresent( TableGenerator.class ) ) {
TableGenerator ann = pckg.getAnnotation( TableGenerator.class );
IdGenerator idGen = buildIdGenerator( ann, mappings );
mappings.addGenerator( idGen );
}
bindGenericGenerators( pckg, mappings );
bindQueries( pckg, mappings );
bindFilterDefs( pckg, mappings );
bindTypeDefs( pckg, mappings );
bindFetchProfiles( pckg, mappings );
BinderHelper.bindAnyMetaDefs( pckg, mappings );
}
private static void bindGenericGenerators(XAnnotatedElement annotatedElement, Mappings mappings) {
GenericGenerator defAnn = annotatedElement.getAnnotation( GenericGenerator.class );
GenericGenerators defsAnn = annotatedElement.getAnnotation( GenericGenerators.class );
if ( defAnn != null ) {
bindGenericGenerator( defAnn, mappings );
}
if ( defsAnn != null ) {
for ( GenericGenerator def : defsAnn.value() ) {
bindGenericGenerator( def, mappings );
}
}
}
private static void bindGenericGenerator(GenericGenerator def, Mappings mappings) {
IdGenerator idGen = buildIdGenerator( def, mappings );
mappings.addGenerator( idGen );
}
private static void bindQueries(XAnnotatedElement annotatedElement, Mappings mappings) {
{
SqlResultSetMapping ann = annotatedElement.getAnnotation( SqlResultSetMapping.class );
QueryBinder.bindSqlResultsetMapping( ann, mappings, false );
}
{
SqlResultSetMappings ann = annotatedElement.getAnnotation( SqlResultSetMappings.class );
if ( ann != null ) {
for ( SqlResultSetMapping current : ann.value() ) {
QueryBinder.bindSqlResultsetMapping( current, mappings, false );
}
}
}
{
NamedQuery ann = annotatedElement.getAnnotation( NamedQuery.class );
QueryBinder.bindQuery( ann, mappings, false );
}
{
org.hibernate.annotations.NamedQuery ann = annotatedElement.getAnnotation(
org.hibernate.annotations.NamedQuery.class
);
QueryBinder.bindQuery( ann, mappings );
}
{
NamedQueries ann = annotatedElement.getAnnotation( NamedQueries.class );
QueryBinder.bindQueries( ann, mappings, false );
}
{
org.hibernate.annotations.NamedQueries ann = annotatedElement.getAnnotation(
org.hibernate.annotations.NamedQueries.class
);
QueryBinder.bindQueries( ann, mappings );
}
{
NamedNativeQuery ann = annotatedElement.getAnnotation( NamedNativeQuery.class );
QueryBinder.bindNativeQuery( ann, mappings, false );
}
{
org.hibernate.annotations.NamedNativeQuery ann = annotatedElement.getAnnotation(
org.hibernate.annotations.NamedNativeQuery.class
);
QueryBinder.bindNativeQuery( ann, mappings );
}
{
NamedNativeQueries ann = annotatedElement.getAnnotation( NamedNativeQueries.class );
QueryBinder.bindNativeQueries( ann, mappings, false );
}
{
org.hibernate.annotations.NamedNativeQueries ann = annotatedElement.getAnnotation(
org.hibernate.annotations.NamedNativeQueries.class
);
QueryBinder.bindNativeQueries( ann, mappings );
}
}
private static IdGenerator buildIdGenerator(java.lang.annotation.Annotation ann, Mappings mappings) {
IdGenerator idGen = new IdGenerator();
if ( mappings.getSchemaName() != null ) {
idGen.addParam( PersistentIdentifierGenerator.SCHEMA, mappings.getSchemaName() );
}
if ( mappings.getCatalogName() != null ) {
idGen.addParam( PersistentIdentifierGenerator.CATALOG, mappings.getCatalogName() );
}
final boolean useNewGeneratorMappings = mappings.useNewGeneratorMappings();
if ( ann == null ) {
idGen = null;
}
else if ( ann instanceof TableGenerator ) {
TableGenerator tabGen = ( TableGenerator ) ann;
idGen.setName( tabGen.name() );
if ( useNewGeneratorMappings ) {
idGen.setIdentifierGeneratorStrategy( org.hibernate.id.enhanced.TableGenerator.class.getName() );
idGen.addParam( org.hibernate.id.enhanced.TableGenerator.CONFIG_PREFER_SEGMENT_PER_ENTITY, "true" );
if ( !BinderHelper.isEmptyAnnotationValue( tabGen.catalog() ) ) {
idGen.addParam( PersistentIdentifierGenerator.CATALOG, tabGen.catalog() );
}
if ( !BinderHelper.isEmptyAnnotationValue( tabGen.schema() ) ) {
idGen.addParam( PersistentIdentifierGenerator.SCHEMA, tabGen.schema() );
}
if ( !BinderHelper.isEmptyAnnotationValue( tabGen.table() ) ) {
idGen.addParam( org.hibernate.id.enhanced.TableGenerator.TABLE_PARAM, tabGen.table() );
}
if ( !BinderHelper.isEmptyAnnotationValue( tabGen.pkColumnName() ) ) {
idGen.addParam(
org.hibernate.id.enhanced.TableGenerator.SEGMENT_COLUMN_PARAM, tabGen.pkColumnName()
);
}
if ( !BinderHelper.isEmptyAnnotationValue( tabGen.pkColumnValue() ) ) {
idGen.addParam(
org.hibernate.id.enhanced.TableGenerator.SEGMENT_VALUE_PARAM, tabGen.pkColumnValue()
);
}
if ( !BinderHelper.isEmptyAnnotationValue( tabGen.valueColumnName() ) ) {
idGen.addParam(
org.hibernate.id.enhanced.TableGenerator.VALUE_COLUMN_PARAM, tabGen.valueColumnName()
);
}
idGen.addParam(
org.hibernate.id.enhanced.TableGenerator.INCREMENT_PARAM,
String.valueOf( tabGen.allocationSize() )
);
// See comment on HHH-4884 wrt initialValue. Basically initialValue is really the stated value + 1
idGen.addParam(
org.hibernate.id.enhanced.TableGenerator.INITIAL_PARAM,
String.valueOf( tabGen.initialValue() + 1 )
);
if (tabGen.uniqueConstraints() != null && tabGen.uniqueConstraints().length > 0) LOG.warn(tabGen.name());
}
else {
idGen.setIdentifierGeneratorStrategy( MultipleHiLoPerTableGenerator.class.getName() );
if ( !BinderHelper.isEmptyAnnotationValue( tabGen.table() ) ) {
idGen.addParam( MultipleHiLoPerTableGenerator.ID_TABLE, tabGen.table() );
}
if ( !BinderHelper.isEmptyAnnotationValue( tabGen.catalog() ) ) {
idGen.addParam( PersistentIdentifierGenerator.CATALOG, tabGen.catalog() );
}
if ( !BinderHelper.isEmptyAnnotationValue( tabGen.schema() ) ) {
idGen.addParam( PersistentIdentifierGenerator.SCHEMA, tabGen.schema() );
}
//FIXME implement uniqueconstrains
if (tabGen.uniqueConstraints() != null && tabGen.uniqueConstraints().length > 0) LOG.ignoringTableGeneratorConstraints(tabGen.name());
if ( !BinderHelper.isEmptyAnnotationValue( tabGen.pkColumnName() ) ) {
idGen.addParam( MultipleHiLoPerTableGenerator.PK_COLUMN_NAME, tabGen.pkColumnName() );
}
if ( !BinderHelper.isEmptyAnnotationValue( tabGen.valueColumnName() ) ) {
idGen.addParam( MultipleHiLoPerTableGenerator.VALUE_COLUMN_NAME, tabGen.valueColumnName() );
}
if ( !BinderHelper.isEmptyAnnotationValue( tabGen.pkColumnValue() ) ) {
idGen.addParam( MultipleHiLoPerTableGenerator.PK_VALUE_NAME, tabGen.pkColumnValue() );
}
idGen.addParam( TableHiLoGenerator.MAX_LO, String.valueOf( tabGen.allocationSize() - 1 ) );
}
if ( LOG.isTraceEnabled() ) {
LOG.tracev( "Add table generator with name: {0}", idGen.getName() );
}
}
else if ( ann instanceof SequenceGenerator ) {
SequenceGenerator seqGen = ( SequenceGenerator ) ann;
idGen.setName( seqGen.name() );
if ( useNewGeneratorMappings ) {
idGen.setIdentifierGeneratorStrategy( SequenceStyleGenerator.class.getName() );
if ( !BinderHelper.isEmptyAnnotationValue( seqGen.catalog() ) ) {
idGen.addParam( PersistentIdentifierGenerator.CATALOG, seqGen.catalog() );
}
if ( !BinderHelper.isEmptyAnnotationValue( seqGen.schema() ) ) {
idGen.addParam( PersistentIdentifierGenerator.SCHEMA, seqGen.schema() );
}
if ( !BinderHelper.isEmptyAnnotationValue( seqGen.sequenceName() ) ) {
idGen.addParam( SequenceStyleGenerator.SEQUENCE_PARAM, seqGen.sequenceName() );
}
idGen.addParam( SequenceStyleGenerator.INCREMENT_PARAM, String.valueOf( seqGen.allocationSize() ) );
idGen.addParam( SequenceStyleGenerator.INITIAL_PARAM, String.valueOf( seqGen.initialValue() ) );
}
else {
idGen.setIdentifierGeneratorStrategy( "seqhilo" );
if ( !BinderHelper.isEmptyAnnotationValue( seqGen.sequenceName() ) ) {
idGen.addParam( org.hibernate.id.SequenceGenerator.SEQUENCE, seqGen.sequenceName() );
}
//FIXME: work on initialValue() through SequenceGenerator.PARAMETERS
// steve : or just use o.h.id.enhanced.SequenceStyleGenerator
if ( seqGen.initialValue() != 1 ) {
LOG.unsupportedInitialValue( AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS );
}
idGen.addParam( SequenceHiLoGenerator.MAX_LO, String.valueOf( seqGen.allocationSize() - 1 ) );
if ( LOG.isTraceEnabled() ) {
LOG.tracev( "Add sequence generator with name: {0}", idGen.getName() );
}
}
}
else if ( ann instanceof GenericGenerator ) {
GenericGenerator genGen = ( GenericGenerator ) ann;
idGen.setName( genGen.name() );
idGen.setIdentifierGeneratorStrategy( genGen.strategy() );
Parameter[] params = genGen.parameters();
for ( Parameter parameter : params ) {
idGen.addParam( parameter.name(), parameter.value() );
}
if ( LOG.isTraceEnabled() ) {
LOG.tracev( "Add generic generator with name: {0}", idGen.getName() );
}
}
else {
throw new AssertionFailure( "Unknown Generator annotation: " + ann );
}
return idGen;
}
/**
* Bind a class having JSR175 annotations. Subclasses <b>have to</b> be bound after its parent class.
*
* @param clazzToProcess entity to bind as {@code XClass} instance
* @param inheritanceStatePerClass Meta data about the inheritance relationships for all mapped classes
* @param mappings Mapping meta data
*
* @throws MappingException in case there is an configuration error
*/
public static void bindClass(
XClass clazzToProcess,
Map<XClass, InheritanceState> inheritanceStatePerClass,
Mappings mappings) throws MappingException {
//@Entity and @MappedSuperclass on the same class leads to a NPE down the road
if ( clazzToProcess.isAnnotationPresent( Entity.class )
&& clazzToProcess.isAnnotationPresent( MappedSuperclass.class ) ) {
throw new AnnotationException( "An entity cannot be annotated with both @Entity and @MappedSuperclass: "
+ clazzToProcess.getName() );
}
//TODO: be more strict with secondarytable allowance (not for ids, not for secondary table join columns etc)
InheritanceState inheritanceState = inheritanceStatePerClass.get( clazzToProcess );
AnnotatedClassType classType = mappings.getClassType( clazzToProcess );
//Queries declared in MappedSuperclass should be usable in Subclasses
if ( AnnotatedClassType.EMBEDDABLE_SUPERCLASS.equals( classType ) ) {
bindQueries( clazzToProcess, mappings );
bindTypeDefs( clazzToProcess, mappings );
bindFilterDefs( clazzToProcess, mappings );
}
if ( !isEntityClassType( clazzToProcess, classType ) ) {
return;
}
if ( LOG.isDebugEnabled() ) {
LOG.debugf( "Binding entity from annotated class: %s", clazzToProcess.getName() );
}
PersistentClass superEntity = getSuperEntity(
clazzToProcess, inheritanceStatePerClass, mappings, inheritanceState
);
PersistentClass persistentClass = makePersistentClass( inheritanceState, superEntity );
Entity entityAnn = clazzToProcess.getAnnotation( Entity.class );
org.hibernate.annotations.Entity hibEntityAnn = clazzToProcess.getAnnotation(
org.hibernate.annotations.Entity.class
);
EntityBinder entityBinder = new EntityBinder(
entityAnn, hibEntityAnn, clazzToProcess, persistentClass, mappings
);
entityBinder.setInheritanceState( inheritanceState );
bindQueries( clazzToProcess, mappings );
bindFilterDefs( clazzToProcess, mappings );
bindTypeDefs( clazzToProcess, mappings );
bindFetchProfiles( clazzToProcess, mappings );
BinderHelper.bindAnyMetaDefs( clazzToProcess, mappings );
String schema = "";
String table = ""; //might be no @Table annotation on the annotated class
String catalog = "";
List<UniqueConstraintHolder> uniqueConstraints = new ArrayList<UniqueConstraintHolder>();
if ( clazzToProcess.isAnnotationPresent( javax.persistence.Table.class ) ) {
javax.persistence.Table tabAnn = clazzToProcess.getAnnotation( javax.persistence.Table.class );
table = tabAnn.name();
schema = tabAnn.schema();
catalog = tabAnn.catalog();
uniqueConstraints = TableBinder.buildUniqueConstraintHolders( tabAnn.uniqueConstraints() );
}
Ejb3JoinColumn[] inheritanceJoinedColumns = makeInheritanceJoinColumns(
clazzToProcess, mappings, inheritanceState, superEntity
);
Ejb3DiscriminatorColumn discriminatorColumn = null;
if ( InheritanceType.SINGLE_TABLE.equals( inheritanceState.getType() ) ) {
discriminatorColumn = processDiscriminatorProperties(
clazzToProcess, mappings, inheritanceState, entityBinder
);
}
entityBinder.setProxy( clazzToProcess.getAnnotation( Proxy.class ) );
entityBinder.setBatchSize( clazzToProcess.getAnnotation( BatchSize.class ) );
entityBinder.setWhere( clazzToProcess.getAnnotation( Where.class ) );
entityBinder.setCache( determineCacheSettings( clazzToProcess, mappings ) );
entityBinder.setNaturalIdCache( clazzToProcess, clazzToProcess.getAnnotation( NaturalIdCache.class ) );
bindFilters( clazzToProcess, entityBinder, mappings );
entityBinder.bindEntity();
if ( inheritanceState.hasTable() ) {
Check checkAnn = clazzToProcess.getAnnotation( Check.class );
String constraints = checkAnn == null ?
null :
checkAnn.constraints();
entityBinder.bindTable(
schema, catalog, table, uniqueConstraints,
constraints, inheritanceState.hasDenormalizedTable() ?
superEntity.getTable() :
null
);
}
else if ( clazzToProcess.isAnnotationPresent( Table.class ) ) {
LOG.invalidTableAnnotation( clazzToProcess.getName() );
}
PropertyHolder propertyHolder = PropertyHolderBuilder.buildPropertyHolder(
clazzToProcess,
persistentClass,
entityBinder, mappings, inheritanceStatePerClass
);
javax.persistence.SecondaryTable secTabAnn = clazzToProcess.getAnnotation(
javax.persistence.SecondaryTable.class
);
javax.persistence.SecondaryTables secTabsAnn = clazzToProcess.getAnnotation(
javax.persistence.SecondaryTables.class
);
entityBinder.firstLevelSecondaryTablesBinding( secTabAnn, secTabsAnn );
OnDelete onDeleteAnn = clazzToProcess.getAnnotation( OnDelete.class );
boolean onDeleteAppropriate = false;
if ( InheritanceType.JOINED.equals( inheritanceState.getType() ) && inheritanceState.hasParents() ) {
onDeleteAppropriate = true;
final JoinedSubclass jsc = ( JoinedSubclass ) persistentClass;
SimpleValue key = new DependantValue( mappings, jsc.getTable(), jsc.getIdentifier() );
jsc.setKey( key );
ForeignKey fk = clazzToProcess.getAnnotation( ForeignKey.class );
if ( fk != null && !BinderHelper.isEmptyAnnotationValue( fk.name() ) ) {
key.setForeignKeyName( fk.name() );
}
if ( onDeleteAnn != null ) {
key.setCascadeDeleteEnabled( OnDeleteAction.CASCADE.equals( onDeleteAnn.action() ) );
}
else {
key.setCascadeDeleteEnabled( false );
}
//we are never in a second pass at that stage, so queue it
SecondPass sp = new JoinedSubclassFkSecondPass( jsc, inheritanceJoinedColumns, key, mappings );
mappings.addSecondPass( sp );
mappings.addSecondPass( new CreateKeySecondPass( jsc ) );
}
else if ( InheritanceType.SINGLE_TABLE.equals( inheritanceState.getType() ) ) {
if ( ! inheritanceState.hasParents() ) {
if ( inheritanceState.hasSiblings() || !discriminatorColumn.isImplicit() ) {
//need a discriminator column
bindDiscriminatorToPersistentClass(
( RootClass ) persistentClass,
discriminatorColumn,
entityBinder.getSecondaryTables(),
propertyHolder,
mappings
);
entityBinder.bindDiscriminatorValue();//bind it again since the type might have changed
}
}
}
else if ( InheritanceType.TABLE_PER_CLASS.equals( inheritanceState.getType() ) ) {
//nothing to do
}
if (onDeleteAnn != null && !onDeleteAppropriate) LOG.invalidOnDeleteAnnotation(propertyHolder.getEntityName());
// try to find class level generators
HashMap<String, IdGenerator> classGenerators = buildLocalGenerators( clazzToProcess, mappings );
// check properties
final InheritanceState.ElementsToProcess elementsToProcess = inheritanceState.getElementsToProcess();
inheritanceState.postProcess( persistentClass, entityBinder );
final boolean subclassAndSingleTableStrategy = inheritanceState.getType() == InheritanceType.SINGLE_TABLE
&& inheritanceState.hasParents();
Set<String> idPropertiesIfIdClass = new HashSet<String>();
boolean isIdClass = mapAsIdClass(
inheritanceStatePerClass,
inheritanceState,
persistentClass,
entityBinder,
propertyHolder,
elementsToProcess,
idPropertiesIfIdClass,
mappings
);
if ( !isIdClass ) {
entityBinder.setWrapIdsInEmbeddedComponents( elementsToProcess.getIdPropertyCount() > 1 );
}
processIdPropertiesIfNotAlready(
inheritanceStatePerClass,
mappings,
persistentClass,
entityBinder,
propertyHolder,
classGenerators,
elementsToProcess,
subclassAndSingleTableStrategy,
idPropertiesIfIdClass
);
if ( !inheritanceState.hasParents() ) {
final RootClass rootClass = ( RootClass ) persistentClass;
mappings.addSecondPass( new CreateKeySecondPass( rootClass ) );
}
else {
superEntity.addSubclass( ( Subclass ) persistentClass );
}
mappings.addClass( persistentClass );
//Process secondary tables and complementary definitions (ie o.h.a.Table)
mappings.addSecondPass( new SecondaryTableSecondPass( entityBinder, propertyHolder, clazzToProcess ) );
//add process complementary Table definition (index & all)
entityBinder.processComplementaryTableDefinitions( clazzToProcess.getAnnotation( org.hibernate.annotations.Table.class ) );
entityBinder.processComplementaryTableDefinitions( clazzToProcess.getAnnotation( org.hibernate.annotations.Tables.class ) );
}
// parse everything discriminator column relevant in case of single table inheritance
private static Ejb3DiscriminatorColumn processDiscriminatorProperties(XClass clazzToProcess, Mappings mappings, InheritanceState inheritanceState, EntityBinder entityBinder) {
Ejb3DiscriminatorColumn discriminatorColumn = null;
javax.persistence.DiscriminatorColumn discAnn = clazzToProcess.getAnnotation(
javax.persistence.DiscriminatorColumn.class
);
DiscriminatorType discriminatorType = discAnn != null ?
discAnn.discriminatorType() :
DiscriminatorType.STRING;
org.hibernate.annotations.DiscriminatorFormula discFormulaAnn = clazzToProcess.getAnnotation(
org.hibernate.annotations.DiscriminatorFormula.class
);
if ( !inheritanceState.hasParents() ) {
discriminatorColumn = Ejb3DiscriminatorColumn.buildDiscriminatorColumn(
discriminatorType, discAnn, discFormulaAnn, mappings
);
}
if ( discAnn != null && inheritanceState.hasParents() ) {
LOG.invalidDiscriminatorAnnotation( clazzToProcess.getName() );
}
String discrimValue = clazzToProcess.isAnnotationPresent( DiscriminatorValue.class ) ?
clazzToProcess.getAnnotation( DiscriminatorValue.class ).value() :
null;
entityBinder.setDiscriminatorValue( discrimValue );
DiscriminatorOptions discriminatorOptions = clazzToProcess.getAnnotation( DiscriminatorOptions.class );
if ( discriminatorOptions != null) {
entityBinder.setForceDiscriminator( discriminatorOptions.force() );
entityBinder.setInsertableDiscriminator( discriminatorOptions.insert() );
}
return discriminatorColumn;
}
private static void processIdPropertiesIfNotAlready(
Map<XClass, InheritanceState> inheritanceStatePerClass,
Mappings mappings,
PersistentClass persistentClass,
EntityBinder entityBinder,
PropertyHolder propertyHolder,
HashMap<String, IdGenerator> classGenerators,
InheritanceState.ElementsToProcess elementsToProcess,
boolean subclassAndSingleTableStrategy,
Set<String> idPropertiesIfIdClass) {
Set<String> missingIdProperties = new HashSet<String>( idPropertiesIfIdClass );
for ( PropertyData propertyAnnotatedElement : elementsToProcess.getElements() ) {
String propertyName = propertyAnnotatedElement.getPropertyName();
if ( !idPropertiesIfIdClass.contains( propertyName ) ) {
processElementAnnotations(
propertyHolder,
subclassAndSingleTableStrategy ?
Nullability.FORCED_NULL :
Nullability.NO_CONSTRAINT,
propertyAnnotatedElement, classGenerators, entityBinder,
false, false, false, mappings, inheritanceStatePerClass
);
}
else {
missingIdProperties.remove( propertyName );
}
}
if ( missingIdProperties.size() != 0 ) {
StringBuilder missings = new StringBuilder();
for ( String property : missingIdProperties ) {
missings.append( property ).append( ", " );
}
throw new AnnotationException(
"Unable to find properties ("
+ missings.substring( 0, missings.length() - 2 )
+ ") in entity annotated with @IdClass:" + persistentClass.getEntityName()
);
}
}
private static boolean mapAsIdClass(
Map<XClass, InheritanceState> inheritanceStatePerClass,
InheritanceState inheritanceState,
PersistentClass persistentClass,
EntityBinder entityBinder,
PropertyHolder propertyHolder,
InheritanceState.ElementsToProcess elementsToProcess,
Set<String> idPropertiesIfIdClass,
Mappings mappings) {
/*
* We are looking for @IdClass
* In general we map the id class as identifier using the mapping metadata of the main entity's properties
* and we create an identifier mapper containing the id properties of the main entity
*
* In JPA 2, there is a shortcut if the id class is the Pk of the associated class pointed to by the id
* it ought to be treated as an embedded and not a real IdClass (at least in the Hibernate's internal way
*/
XClass classWithIdClass = inheritanceState.getClassWithIdClass( false );
if ( classWithIdClass != null ) {
IdClass idClass = classWithIdClass.getAnnotation( IdClass.class );
XClass compositeClass = mappings.getReflectionManager().toXClass( idClass.value() );
PropertyData inferredData = new PropertyPreloadedData(
entityBinder.getPropertyAccessType(), "id", compositeClass
);
PropertyData baseInferredData = new PropertyPreloadedData(
entityBinder.getPropertyAccessType(), "id", classWithIdClass
);
AccessType propertyAccessor = entityBinder.getPropertyAccessor( compositeClass );
//In JPA 2, there is a shortcut if the IdClass is the Pk of the associated class pointed to by the id
//it ought to be treated as an embedded and not a real IdClass (at least in the Hibernate's internal way
final boolean isFakeIdClass = isIdClassPkOfTheAssociatedEntity(
elementsToProcess,
compositeClass,
inferredData,
baseInferredData,
propertyAccessor,
inheritanceStatePerClass,
mappings
);
if ( isFakeIdClass ) {
return false;
}
boolean isComponent = true;
String generatorType = "assigned";
String generator = BinderHelper.ANNOTATION_STRING_DEFAULT;
boolean ignoreIdAnnotations = entityBinder.isIgnoreIdAnnotations();
entityBinder.setIgnoreIdAnnotations( true );
propertyHolder.setInIdClass( true );
bindIdClass(
generatorType,
generator,
inferredData,
baseInferredData,
null,
propertyHolder,
isComponent,
propertyAccessor,
entityBinder,
true,
false,
mappings,
inheritanceStatePerClass
);
propertyHolder.setInIdClass( null );
inferredData = new PropertyPreloadedData(
propertyAccessor, "_identifierMapper", compositeClass
);
Component mapper = fillComponent(
propertyHolder,
inferredData,
baseInferredData,
propertyAccessor,
false,
entityBinder,
true,
true,
false,
mappings,
inheritanceStatePerClass
);
entityBinder.setIgnoreIdAnnotations( ignoreIdAnnotations );
persistentClass.setIdentifierMapper( mapper );
//If id definition is on a mapped superclass, update the mapping
final org.hibernate.mapping.MappedSuperclass superclass =
BinderHelper.getMappedSuperclassOrNull(
inferredData.getDeclaringClass(),
inheritanceStatePerClass,
mappings
);
if ( superclass != null ) {
superclass.setDeclaredIdentifierMapper( mapper );
}
else {
//we are for sure on the entity
persistentClass.setDeclaredIdentifierMapper( mapper );
}
Property property = new Property();
property.setName( "_identifierMapper" );
property.setNodeName( "id" );
property.setUpdateable( false );
property.setInsertable( false );
property.setValue( mapper );
property.setPropertyAccessorName( "embedded" );
persistentClass.addProperty( property );
entityBinder.setIgnoreIdAnnotations( true );
Iterator properties = mapper.getPropertyIterator();
while ( properties.hasNext() ) {
idPropertiesIfIdClass.add( ( ( Property ) properties.next() ).getName() );
}
return true;
}
else {
return false;
}
}
private static boolean isIdClassPkOfTheAssociatedEntity(
InheritanceState.ElementsToProcess elementsToProcess,
XClass compositeClass,
PropertyData inferredData,
PropertyData baseInferredData,
AccessType propertyAccessor,
Map<XClass, InheritanceState> inheritanceStatePerClass,
Mappings mappings) {
if ( elementsToProcess.getIdPropertyCount() == 1 ) {
final PropertyData idPropertyOnBaseClass = getUniqueIdPropertyFromBaseClass(
inferredData, baseInferredData, propertyAccessor, mappings
);
final InheritanceState state = inheritanceStatePerClass.get( idPropertyOnBaseClass.getClassOrElement() );
if ( state == null ) {
return false; //while it is likely a user error, let's consider it is something that might happen
}
final XClass associatedClassWithIdClass = state.getClassWithIdClass( true );
if ( associatedClassWithIdClass == null ) {
//we cannot know for sure here unless we try and find the @EmbeddedId
//Let's not do this thorough checking but do some extra validation
final XProperty property = idPropertyOnBaseClass.getProperty();
return property.isAnnotationPresent( ManyToOne.class )
|| property.isAnnotationPresent( OneToOne.class );
}
else {
final XClass idClass = mappings.getReflectionManager().toXClass(
associatedClassWithIdClass.getAnnotation( IdClass.class ).value()
);
return idClass.equals( compositeClass );
}
}
else {
return false;
}
}
private static Cache determineCacheSettings(XClass clazzToProcess, Mappings mappings) {
Cache cacheAnn = clazzToProcess.getAnnotation( Cache.class );
if ( cacheAnn != null ) {
return cacheAnn;
}
Cacheable cacheableAnn = clazzToProcess.getAnnotation( Cacheable.class );
SharedCacheMode mode = determineSharedCacheMode( mappings );
switch ( mode ) {
case ALL: {
cacheAnn = buildCacheMock( clazzToProcess.getName(), mappings );
break;
}
case ENABLE_SELECTIVE: {
if ( cacheableAnn != null && cacheableAnn.value() ) {
cacheAnn = buildCacheMock( clazzToProcess.getName(), mappings );
}
break;
}
case DISABLE_SELECTIVE: {
if ( cacheableAnn == null || cacheableAnn.value() ) {
cacheAnn = buildCacheMock( clazzToProcess.getName(), mappings );
}
break;
}
default: {
// treat both NONE and UNSPECIFIED the same
break;
}
}
return cacheAnn;
}
private static SharedCacheMode determineSharedCacheMode(Mappings mappings) {
SharedCacheMode mode;
final Object value = mappings.getConfigurationProperties().get( "javax.persistence.sharedCache.mode" );
if ( value == null ) {
LOG.debug( "No value specified for 'javax.persistence.sharedCache.mode'; using UNSPECIFIED" );
mode = SharedCacheMode.UNSPECIFIED;
}
else {
if ( SharedCacheMode.class.isInstance( value ) ) {
mode = ( SharedCacheMode ) value;
}
else {
try {
mode = SharedCacheMode.valueOf( value.toString() );
}
catch ( Exception e ) {
LOG.debugf( "Unable to resolve given mode name [%s]; using UNSPECIFIED : %s", value, e );
mode = SharedCacheMode.UNSPECIFIED;
}
}
}
return mode;
}
private static Cache buildCacheMock(String region, Mappings mappings) {
return new LocalCacheAnnotationImpl( region, determineCacheConcurrencyStrategy( mappings ) );
}
private static CacheConcurrencyStrategy DEFAULT_CACHE_CONCURRENCY_STRATEGY;
static void prepareDefaultCacheConcurrencyStrategy(Properties properties) {
if ( DEFAULT_CACHE_CONCURRENCY_STRATEGY != null ) {
LOG.trace( "Default cache concurrency strategy already defined" );
return;
}
if ( !properties.containsKey( AvailableSettings.DEFAULT_CACHE_CONCURRENCY_STRATEGY ) ) {
LOG.trace( "Given properties did not contain any default cache concurrency strategy setting" );
return;
}
final String strategyName = properties.getProperty( AvailableSettings.DEFAULT_CACHE_CONCURRENCY_STRATEGY );
LOG.tracev( "Discovered default cache concurrency strategy via config [{0}]", strategyName );
CacheConcurrencyStrategy strategy = CacheConcurrencyStrategy.parse( strategyName );
if ( strategy == null ) {
LOG.trace( "Discovered default cache concurrency strategy specified nothing" );
return;
}
LOG.debugf( "Setting default cache concurrency strategy via config [%s]", strategy.name() );
DEFAULT_CACHE_CONCURRENCY_STRATEGY = strategy;
}
private static CacheConcurrencyStrategy determineCacheConcurrencyStrategy(Mappings mappings) {
if ( DEFAULT_CACHE_CONCURRENCY_STRATEGY == null ) {
final RegionFactory cacheRegionFactory = SettingsFactory.createRegionFactory(
mappings.getConfigurationProperties(), true
);
DEFAULT_CACHE_CONCURRENCY_STRATEGY = CacheConcurrencyStrategy.fromAccessType( cacheRegionFactory.getDefaultAccessType() );
}
return DEFAULT_CACHE_CONCURRENCY_STRATEGY;
}
@SuppressWarnings({ "ClassExplicitlyAnnotation" })
private static class LocalCacheAnnotationImpl implements Cache {
private final String region;
private final CacheConcurrencyStrategy usage;
private LocalCacheAnnotationImpl(String region, CacheConcurrencyStrategy usage) {
this.region = region;
this.usage = usage;
}
public CacheConcurrencyStrategy usage() {
return usage;
}
public String region() {
return region;
}
public String include() {
return "all";
}
public Class<? extends Annotation> annotationType() {
return Cache.class;
}
}
private static PersistentClass makePersistentClass(InheritanceState inheritanceState, PersistentClass superEntity) {
//we now know what kind of persistent entity it is
PersistentClass persistentClass;
//create persistent class
if ( !inheritanceState.hasParents() ) {
persistentClass = new RootClass();
}
else if ( InheritanceType.SINGLE_TABLE.equals( inheritanceState.getType() ) ) {
persistentClass = new SingleTableSubclass( superEntity );
}
else if ( InheritanceType.JOINED.equals( inheritanceState.getType() ) ) {
persistentClass = new JoinedSubclass( superEntity );
}
else if ( InheritanceType.TABLE_PER_CLASS.equals( inheritanceState.getType() ) ) {
persistentClass = new UnionSubclass( superEntity );
}
else {
throw new AssertionFailure( "Unknown inheritance type: " + inheritanceState.getType() );
}
return persistentClass;
}
private static Ejb3JoinColumn[] makeInheritanceJoinColumns(
XClass clazzToProcess,
Mappings mappings,
InheritanceState inheritanceState,
PersistentClass superEntity) {
Ejb3JoinColumn[] inheritanceJoinedColumns = null;
final boolean hasJoinedColumns = inheritanceState.hasParents()
&& InheritanceType.JOINED.equals( inheritanceState.getType() );
if ( hasJoinedColumns ) {
//@Inheritance(JOINED) subclass need to link back to the super entity
PrimaryKeyJoinColumns jcsAnn = clazzToProcess.getAnnotation( PrimaryKeyJoinColumns.class );
boolean explicitInheritanceJoinedColumns = jcsAnn != null && jcsAnn.value().length != 0;
if ( explicitInheritanceJoinedColumns ) {
int nbrOfInhJoinedColumns = jcsAnn.value().length;
PrimaryKeyJoinColumn jcAnn;
inheritanceJoinedColumns = new Ejb3JoinColumn[nbrOfInhJoinedColumns];
for ( int colIndex = 0; colIndex < nbrOfInhJoinedColumns; colIndex++ ) {
jcAnn = jcsAnn.value()[colIndex];
inheritanceJoinedColumns[colIndex] = Ejb3JoinColumn.buildJoinColumn(
jcAnn, null, superEntity.getIdentifier(),
( Map<String, Join> ) null, ( PropertyHolder ) null, mappings
);
}
}
else {
PrimaryKeyJoinColumn jcAnn = clazzToProcess.getAnnotation( PrimaryKeyJoinColumn.class );
inheritanceJoinedColumns = new Ejb3JoinColumn[1];
inheritanceJoinedColumns[0] = Ejb3JoinColumn.buildJoinColumn(
jcAnn, null, superEntity.getIdentifier(),
( Map<String, Join> ) null, ( PropertyHolder ) null, mappings
);
}
LOG.trace( "Subclass joined column(s) created" );
}
else {
if ( clazzToProcess.isAnnotationPresent( PrimaryKeyJoinColumns.class )
|| clazzToProcess.isAnnotationPresent( PrimaryKeyJoinColumn.class ) ) {
LOG.invalidPrimaryKeyJoinColumnAnnotation();
}
}
return inheritanceJoinedColumns;
}
private static PersistentClass getSuperEntity(XClass clazzToProcess, Map<XClass, InheritanceState> inheritanceStatePerClass, Mappings mappings, InheritanceState inheritanceState) {
InheritanceState superEntityState = InheritanceState.getInheritanceStateOfSuperEntity(
clazzToProcess, inheritanceStatePerClass
);
PersistentClass superEntity = superEntityState != null ?
mappings.getClass(
superEntityState.getClazz().getName()
) :
null;
if ( superEntity == null ) {
//check if superclass is not a potential persistent class
if ( inheritanceState.hasParents() ) {
throw new AssertionFailure(
"Subclass has to be binded after it's mother class: "
+ superEntityState.getClazz().getName()
);
}
}
return superEntity;
}
private static boolean isEntityClassType(XClass clazzToProcess, AnnotatedClassType classType) {
if ( AnnotatedClassType.EMBEDDABLE_SUPERCLASS.equals( classType ) //will be processed by their subentities
|| AnnotatedClassType.NONE.equals( classType ) //to be ignored
|| AnnotatedClassType.EMBEDDABLE.equals( classType ) //allow embeddable element declaration
) {
if ( AnnotatedClassType.NONE.equals( classType )
&& clazzToProcess.isAnnotationPresent( org.hibernate.annotations.Entity.class ) ) {
LOG.missingEntityAnnotation( clazzToProcess.getName() );
}
return false;
}
if ( !classType.equals( AnnotatedClassType.ENTITY ) ) {
throw new AnnotationException(
"Annotated class should have a @javax.persistence.Entity, @javax.persistence.Embeddable or @javax.persistence.EmbeddedSuperclass annotation: " + clazzToProcess
.getName()
);
}
return true;
}
/*
* Process the filters defined on the given class, as well as all filters defined
* on the MappedSuperclass(s) in the inheritance hierarchy
*/
private static void bindFilters(XClass annotatedClass, EntityBinder entityBinder,
Mappings mappings) {
bindFilters( annotatedClass, entityBinder );
XClass classToProcess = annotatedClass.getSuperclass();
while ( classToProcess != null ) {
AnnotatedClassType classType = mappings.getClassType( classToProcess );
if ( AnnotatedClassType.EMBEDDABLE_SUPERCLASS.equals( classType ) ) {
bindFilters( classToProcess, entityBinder );
}
classToProcess = classToProcess.getSuperclass();
}
}
private static void bindFilters(XAnnotatedElement annotatedElement, EntityBinder entityBinder) {
Filters filtersAnn = annotatedElement.getAnnotation( Filters.class );
if ( filtersAnn != null ) {
for ( Filter filter : filtersAnn.value() ) {
entityBinder.addFilter(filter);
}
}
Filter filterAnn = annotatedElement.getAnnotation( Filter.class );
if ( filterAnn != null ) {
entityBinder.addFilter(filterAnn);
}
}
private static void bindFilterDefs(XAnnotatedElement annotatedElement, Mappings mappings) {
FilterDef defAnn = annotatedElement.getAnnotation( FilterDef.class );
FilterDefs defsAnn = annotatedElement.getAnnotation( FilterDefs.class );
if ( defAnn != null ) {
bindFilterDef( defAnn, mappings );
}
if ( defsAnn != null ) {
for ( FilterDef def : defsAnn.value() ) {
bindFilterDef( def, mappings );
}
}
}
private static void bindFilterDef(FilterDef defAnn, Mappings mappings) {
Map<String, org.hibernate.type.Type> params = new HashMap<String, org.hibernate.type.Type>();
for ( ParamDef param : defAnn.parameters() ) {
params.put( param.name(), mappings.getTypeResolver().heuristicType( param.type() ) );
}
FilterDefinition def = new FilterDefinition( defAnn.name(), defAnn.defaultCondition(), params );
LOG.debugf( "Binding filter definition: %s", def.getFilterName() );
mappings.addFilterDefinition( def );
}
private static void bindTypeDefs(XAnnotatedElement annotatedElement, Mappings mappings) {
TypeDef defAnn = annotatedElement.getAnnotation( TypeDef.class );
TypeDefs defsAnn = annotatedElement.getAnnotation( TypeDefs.class );
if ( defAnn != null ) {
bindTypeDef( defAnn, mappings );
}
if ( defsAnn != null ) {
for ( TypeDef def : defsAnn.value() ) {
bindTypeDef( def, mappings );
}
}
}
private static void bindFetchProfiles(XAnnotatedElement annotatedElement, Mappings mappings) {
FetchProfile fetchProfileAnnotation = annotatedElement.getAnnotation( FetchProfile.class );
FetchProfiles fetchProfileAnnotations = annotatedElement.getAnnotation( FetchProfiles.class );
if ( fetchProfileAnnotation != null ) {
bindFetchProfile( fetchProfileAnnotation, mappings );
}
if ( fetchProfileAnnotations != null ) {
for ( FetchProfile profile : fetchProfileAnnotations.value() ) {
bindFetchProfile( profile, mappings );
}
}
}
private static void bindFetchProfile(FetchProfile fetchProfileAnnotation, Mappings mappings) {
for ( FetchProfile.FetchOverride fetch : fetchProfileAnnotation.fetchOverrides() ) {
org.hibernate.annotations.FetchMode mode = fetch.mode();
if ( !mode.equals( org.hibernate.annotations.FetchMode.JOIN ) ) {
throw new MappingException( "Only FetchMode.JOIN is currently supported" );
}
SecondPass sp = new VerifyFetchProfileReferenceSecondPass( fetchProfileAnnotation.name(), fetch, mappings );
mappings.addSecondPass( sp );
}
}
private static void bindTypeDef(TypeDef defAnn, Mappings mappings) {
Properties params = new Properties();
for ( Parameter param : defAnn.parameters() ) {
params.setProperty( param.name(), param.value() );
}
if ( BinderHelper.isEmptyAnnotationValue( defAnn.name() ) && defAnn.defaultForType().equals( void.class ) ) {
throw new AnnotationException(
"Either name or defaultForType (or both) attribute should be set in TypeDef having typeClass " +
defAnn.typeClass().getName()
);
}
final String typeBindMessageF = "Binding type definition: %s";
if ( !BinderHelper.isEmptyAnnotationValue( defAnn.name() ) ) {
if ( LOG.isDebugEnabled() ) {
LOG.debugf( typeBindMessageF, defAnn.name() );
}
mappings.addTypeDef( defAnn.name(), defAnn.typeClass().getName(), params );
}
if ( !defAnn.defaultForType().equals( void.class ) ) {
if ( LOG.isDebugEnabled() ) {
LOG.debugf( typeBindMessageF, defAnn.defaultForType().getName() );
}
mappings.addTypeDef( defAnn.defaultForType().getName(), defAnn.typeClass().getName(), params );
}
}
private static void bindDiscriminatorToPersistentClass(
RootClass rootClass,
Ejb3DiscriminatorColumn discriminatorColumn,
Map<String, Join> secondaryTables,
PropertyHolder propertyHolder,
Mappings mappings) {
if ( rootClass.getDiscriminator() == null ) {
if ( discriminatorColumn == null ) {
throw new AssertionFailure( "discriminator column should have been built" );
}
discriminatorColumn.setJoins( secondaryTables );
discriminatorColumn.setPropertyHolder( propertyHolder );
SimpleValue discrim = new SimpleValue( mappings, rootClass.getTable() );
rootClass.setDiscriminator( discrim );
discriminatorColumn.linkWithValue( discrim );
discrim.setTypeName( discriminatorColumn.getDiscriminatorTypeName() );
rootClass.setPolymorphic( true );
if ( LOG.isTraceEnabled() ) {
LOG.tracev( "Setting discriminator for entity {0}", rootClass.getEntityName() );
}
}
}
/**
* @param elements List of {@code ProperyData} instances
* @param defaultAccessType The default value access strategy which has to be used in case no explicit local access
* strategy is used
* @param propertyContainer Metadata about a class and its properties
* @param mappings Mapping meta data
*
* @return the number of id properties found while iterating the elements of {@code annotatedClass} using
* the determined access strategy, {@code false} otherwise.
*/
static int addElementsOfClass(
List<PropertyData> elements,
AccessType defaultAccessType,
PropertyContainer propertyContainer,
Mappings mappings) {
int idPropertyCounter = 0;
AccessType accessType = defaultAccessType;
if ( propertyContainer.hasExplicitAccessStrategy() ) {
accessType = propertyContainer.getExplicitAccessStrategy();
}
Collection<XProperty> properties = propertyContainer.getProperties( accessType );
for ( XProperty p : properties ) {
final int currentIdPropertyCounter = addProperty(
propertyContainer, p, elements, accessType.getType(), mappings
);
idPropertyCounter += currentIdPropertyCounter;
}
return idPropertyCounter;
}
private static int addProperty(
PropertyContainer propertyContainer,
XProperty property,
List<PropertyData> annElts,
String propertyAccessor,
Mappings mappings) {
final XClass declaringClass = propertyContainer.getDeclaringClass();
final XClass entity = propertyContainer.getEntityAtStake();
int idPropertyCounter = 0;
PropertyData propertyAnnotatedElement = new PropertyInferredData(
declaringClass, property, propertyAccessor,
mappings.getReflectionManager()
);
/*
* put element annotated by @Id in front
* since it has to be parsed before any association by Hibernate
*/
final XAnnotatedElement element = propertyAnnotatedElement.getProperty();
if ( element.isAnnotationPresent( Id.class ) || element.isAnnotationPresent( EmbeddedId.class ) ) {
annElts.add( 0, propertyAnnotatedElement );
/**
* The property must be put in hibernate.properties as it's a system wide property. Fixable?
* TODO support true/false/default on the property instead of present / not present
* TODO is @Column mandatory?
* TODO add method support
*/
if ( mappings.isSpecjProprietarySyntaxEnabled() ) {
if ( element.isAnnotationPresent( Id.class ) && element.isAnnotationPresent( Column.class ) ) {
String columnName = element.getAnnotation( Column.class ).name();
for ( XProperty prop : declaringClass.getDeclaredProperties( AccessType.FIELD.getType() ) ) {
if ( !prop.isAnnotationPresent( MapsId.class ) ) {
/**
* The detection of a configured individual JoinColumn differs between Annotation
* and XML configuration processing.
*/
boolean isRequiredAnnotationPresent = false;
JoinColumns groupAnnotation = prop.getAnnotation( JoinColumns.class );
if ( (prop.isAnnotationPresent( JoinColumn.class )
&& prop.getAnnotation( JoinColumn.class ).name().equals( columnName )) ) {
isRequiredAnnotationPresent = true;
}
else if ( prop.isAnnotationPresent( JoinColumns.class ) ) {
for ( JoinColumn columnAnnotation : groupAnnotation.value() ) {
if ( columnName.equals( columnAnnotation.name() ) ) {
isRequiredAnnotationPresent = true;
break;
}
}
}
if ( isRequiredAnnotationPresent ) {
//create a PropertyData fpr the specJ property holding the mapping
PropertyData specJPropertyData = new PropertyInferredData(
declaringClass,
//same dec
prop,
// the actual @XToOne property
propertyAccessor,
//TODO we should get the right accessor but the same as id would do
mappings.getReflectionManager()
);
mappings.addPropertyAnnotatedWithMapsIdSpecj(
entity,
specJPropertyData,
element.toString()
);
}
}
}
}
}
if ( element.isAnnotationPresent( ManyToOne.class ) || element.isAnnotationPresent( OneToOne.class ) ) {
mappings.addToOneAndIdProperty( entity, propertyAnnotatedElement );
}
idPropertyCounter++;
}
else {
annElts.add( propertyAnnotatedElement );
}
if ( element.isAnnotationPresent( MapsId.class ) ) {
mappings.addPropertyAnnotatedWithMapsId( entity, propertyAnnotatedElement );
}
return idPropertyCounter;
}
/*
* Process annotation of a particular property
*/
private static void processElementAnnotations(
PropertyHolder propertyHolder,
Nullability nullability,
PropertyData inferredData,
HashMap<String, IdGenerator> classGenerators,
EntityBinder entityBinder,
boolean isIdentifierMapper,
boolean isComponentEmbedded,
boolean inSecondPass,
Mappings mappings,
Map<XClass, InheritanceState> inheritanceStatePerClass) throws MappingException {
/**
* inSecondPass can only be used to apply right away the second pass of a composite-element
* Because it's a value type, there is no bidirectional association, hence second pass
* ordering does not matter
*/
final boolean traceEnabled = LOG.isTraceEnabled();
if ( traceEnabled ) {
LOG.tracev( "Processing annotations of {0}.{1}" , propertyHolder.getEntityName(), inferredData.getPropertyName() );
}
final XProperty property = inferredData.getProperty();
if ( property.isAnnotationPresent( Parent.class ) ) {
if ( propertyHolder.isComponent() ) {
propertyHolder.setParentProperty( property.getName() );
}
else {
throw new AnnotationException(
"@Parent cannot be applied outside an embeddable object: "
+ BinderHelper.getPath( propertyHolder, inferredData )
);
}
return;
}
ColumnsBuilder columnsBuilder = new ColumnsBuilder(
propertyHolder, nullability, property, inferredData, entityBinder, mappings
).extractMetadata();
Ejb3Column[] columns = columnsBuilder.getColumns();
Ejb3JoinColumn[] joinColumns = columnsBuilder.getJoinColumns();
final XClass returnedClass = inferredData.getClassOrElement();
//prepare PropertyBinder
PropertyBinder propertyBinder = new PropertyBinder();
propertyBinder.setName( inferredData.getPropertyName() );
propertyBinder.setReturnedClassName( inferredData.getTypeName() );
propertyBinder.setAccessType( inferredData.getDefaultAccess() );
propertyBinder.setHolder( propertyHolder );
propertyBinder.setProperty( property );
propertyBinder.setReturnedClass( inferredData.getPropertyClass() );
propertyBinder.setMappings( mappings );
if ( isIdentifierMapper ) {
propertyBinder.setInsertable( false );
propertyBinder.setUpdatable( false );
}
propertyBinder.setDeclaringClass( inferredData.getDeclaringClass() );
propertyBinder.setEntityBinder( entityBinder );
propertyBinder.setInheritanceStatePerClass( inheritanceStatePerClass );
boolean isId = !entityBinder.isIgnoreIdAnnotations() &&
( property.isAnnotationPresent( Id.class )
|| property.isAnnotationPresent( EmbeddedId.class ) );
propertyBinder.setId( isId );
if ( property.isAnnotationPresent( Version.class ) ) {
if ( isIdentifierMapper ) {
throw new AnnotationException(
"@IdClass class should not have @Version property"
);
}
if ( !( propertyHolder.getPersistentClass() instanceof RootClass ) ) {
throw new AnnotationException(
"Unable to define/override @Version on a subclass: "
+ propertyHolder.getEntityName()
);
}
if ( !propertyHolder.isEntity() ) {
throw new AnnotationException(
"Unable to define @Version on an embedded class: "
+ propertyHolder.getEntityName()
);
}
if ( traceEnabled ) {
LOG.tracev( "{0} is a version property", inferredData.getPropertyName() );
}
RootClass rootClass = ( RootClass ) propertyHolder.getPersistentClass();
propertyBinder.setColumns( columns );
Property prop = propertyBinder.makePropertyValueAndBind();
setVersionInformation( property, propertyBinder );
rootClass.setVersion( prop );
//If version is on a mapped superclass, update the mapping
final org.hibernate.mapping.MappedSuperclass superclass = BinderHelper.getMappedSuperclassOrNull(
inferredData.getDeclaringClass(),
inheritanceStatePerClass,
mappings
);
if ( superclass != null ) {
superclass.setDeclaredVersion( prop );
}
else {
//we know the property is on the actual entity
rootClass.setDeclaredVersion( prop );
}
SimpleValue simpleValue = ( SimpleValue ) prop.getValue();
simpleValue.setNullValue( "undefined" );
rootClass.setOptimisticLockMode( Versioning.OPTIMISTIC_LOCK_VERSION );
if ( traceEnabled ) {
LOG.tracev( "Version name: {0}, unsavedValue: {1}", rootClass.getVersion().getName(),
( (SimpleValue) rootClass.getVersion().getValue() ).getNullValue() );
}
}
else {
final boolean forcePersist = property.isAnnotationPresent( MapsId.class )
|| property.isAnnotationPresent( Id.class );
if ( property.isAnnotationPresent( ManyToOne.class ) ) {
ManyToOne ann = property.getAnnotation( ManyToOne.class );
//check validity
if ( property.isAnnotationPresent( Column.class )
|| property.isAnnotationPresent( Columns.class ) ) {
throw new AnnotationException(
"@Column(s) not allowed on a @ManyToOne property: "
+ BinderHelper.getPath( propertyHolder, inferredData )
);
}
Cascade hibernateCascade = property.getAnnotation( Cascade.class );
NotFound notFound = property.getAnnotation( NotFound.class );
boolean ignoreNotFound = notFound != null && notFound.action().equals( NotFoundAction.IGNORE );
OnDelete onDeleteAnn = property.getAnnotation( OnDelete.class );
boolean onDeleteCascade = onDeleteAnn != null && OnDeleteAction.CASCADE.equals( onDeleteAnn.action() );
JoinTable assocTable = propertyHolder.getJoinTable( property );
if ( assocTable != null ) {
Join join = propertyHolder.addJoin( assocTable, false );
for ( Ejb3JoinColumn joinColumn : joinColumns ) {
joinColumn.setSecondaryTableName( join.getTable().getName() );
}
}
final boolean mandatory = !ann.optional() || forcePersist;
bindManyToOne(
getCascadeStrategy( ann.cascade(), hibernateCascade, false, forcePersist ),
joinColumns,
!mandatory,
ignoreNotFound, onDeleteCascade,
ToOneBinder.getTargetEntity( inferredData, mappings ),
propertyHolder,
inferredData, false, isIdentifierMapper,
inSecondPass, propertyBinder, mappings
);
}
else if ( property.isAnnotationPresent( OneToOne.class ) ) {
OneToOne ann = property.getAnnotation( OneToOne.class );
//check validity
if ( property.isAnnotationPresent( Column.class )
|| property.isAnnotationPresent( Columns.class ) ) {
throw new AnnotationException(
"@Column(s) not allowed on a @OneToOne property: "
+ BinderHelper.getPath( propertyHolder, inferredData )
);
}
//FIXME support a proper PKJCs
boolean trueOneToOne = property.isAnnotationPresent( PrimaryKeyJoinColumn.class )
|| property.isAnnotationPresent( PrimaryKeyJoinColumns.class );
Cascade hibernateCascade = property.getAnnotation( Cascade.class );
NotFound notFound = property.getAnnotation( NotFound.class );
boolean ignoreNotFound = notFound != null && notFound.action().equals( NotFoundAction.IGNORE );
OnDelete onDeleteAnn = property.getAnnotation( OnDelete.class );
boolean onDeleteCascade = onDeleteAnn != null && OnDeleteAction.CASCADE.equals( onDeleteAnn.action() );
JoinTable assocTable = propertyHolder.getJoinTable( property );
if ( assocTable != null ) {
Join join = propertyHolder.addJoin( assocTable, false );
for ( Ejb3JoinColumn joinColumn : joinColumns ) {
joinColumn.setSecondaryTableName( join.getTable().getName() );
}
}
//MapsId means the columns belong to the pk => not null
//@OneToOne with @PKJC can still be optional
final boolean mandatory = !ann.optional() || forcePersist;
bindOneToOne(
getCascadeStrategy( ann.cascade(), hibernateCascade, ann.orphanRemoval(), forcePersist ),
joinColumns,
!mandatory,
getFetchMode( ann.fetch() ),
ignoreNotFound, onDeleteCascade,
ToOneBinder.getTargetEntity( inferredData, mappings ),
propertyHolder,
inferredData,
ann.mappedBy(),
trueOneToOne,
isIdentifierMapper,
inSecondPass,
propertyBinder,
mappings
);
}
else if ( property.isAnnotationPresent( org.hibernate.annotations.Any.class ) ) {
//check validity
if ( property.isAnnotationPresent( Column.class )
|| property.isAnnotationPresent( Columns.class ) ) {
throw new AnnotationException(
"@Column(s) not allowed on a @Any property: "
+ BinderHelper.getPath( propertyHolder, inferredData )
);
}
Cascade hibernateCascade = property.getAnnotation( Cascade.class );
OnDelete onDeleteAnn = property.getAnnotation( OnDelete.class );
boolean onDeleteCascade = onDeleteAnn != null && OnDeleteAction.CASCADE.equals( onDeleteAnn.action() );
JoinTable assocTable = propertyHolder.getJoinTable( property );
if ( assocTable != null ) {
Join join = propertyHolder.addJoin( assocTable, false );
for ( Ejb3JoinColumn joinColumn : joinColumns ) {
joinColumn.setSecondaryTableName( join.getTable().getName() );
}
}
bindAny(
getCascadeStrategy( null, hibernateCascade, false, forcePersist ),
//@Any has not cascade attribute
joinColumns,
onDeleteCascade,
nullability,
propertyHolder,
inferredData,
entityBinder,
isIdentifierMapper,
mappings
);
}
else if ( property.isAnnotationPresent( OneToMany.class )
|| property.isAnnotationPresent( ManyToMany.class )
|| property.isAnnotationPresent( ElementCollection.class )
|| property.isAnnotationPresent( ManyToAny.class ) ) {
OneToMany oneToManyAnn = property.getAnnotation( OneToMany.class );
ManyToMany manyToManyAnn = property.getAnnotation( ManyToMany.class );
ElementCollection elementCollectionAnn = property.getAnnotation( ElementCollection.class );
final IndexColumn indexColumn;
if ( property.isAnnotationPresent( OrderColumn.class ) ) {
indexColumn = IndexColumn.buildColumnFromAnnotation(
property.getAnnotation( OrderColumn.class ),
propertyHolder,
inferredData,
entityBinder.getSecondaryTables(),
mappings
);
}
else {
//if @IndexColumn is not there, the generated IndexColumn is an implicit column and not used.
//so we can leave the legacy processing as the default
indexColumn = IndexColumn.buildColumnFromAnnotation(
property.getAnnotation( org.hibernate.annotations.IndexColumn.class ),
propertyHolder,
inferredData,
mappings
);
}
CollectionBinder collectionBinder = CollectionBinder.getCollectionBinder(
propertyHolder.getEntityName(),
property,
!indexColumn.isImplicit(),
property.isAnnotationPresent( MapKeyType.class ),
mappings
);
collectionBinder.setIndexColumn( indexColumn );
collectionBinder.setMapKey( property.getAnnotation( MapKey.class ) );
collectionBinder.setPropertyName( inferredData.getPropertyName() );
BatchSize batchAnn = property.getAnnotation( BatchSize.class );
collectionBinder.setBatchSize( batchAnn );
javax.persistence.OrderBy ejb3OrderByAnn = property.getAnnotation( javax.persistence.OrderBy.class );
OrderBy orderByAnn = property.getAnnotation( OrderBy.class );
collectionBinder.setEjb3OrderBy( ejb3OrderByAnn );
collectionBinder.setSqlOrderBy( orderByAnn );
Sort sortAnn = property.getAnnotation( Sort.class );
collectionBinder.setSort( sortAnn );
Cache cachAnn = property.getAnnotation( Cache.class );
collectionBinder.setCache( cachAnn );
collectionBinder.setPropertyHolder( propertyHolder );
Cascade hibernateCascade = property.getAnnotation( Cascade.class );
NotFound notFound = property.getAnnotation( NotFound.class );
boolean ignoreNotFound = notFound != null && notFound.action().equals( NotFoundAction.IGNORE );
collectionBinder.setIgnoreNotFound( ignoreNotFound );
collectionBinder.setCollectionType( inferredData.getProperty().getElementClass() );
collectionBinder.setMappings( mappings );
collectionBinder.setAccessType( inferredData.getDefaultAccess() );
Ejb3Column[] elementColumns;
//do not use "element" if you are a JPA 2 @ElementCollection only for legacy Hibernate mappings
boolean isJPA2ForValueMapping = property.isAnnotationPresent( ElementCollection.class );
PropertyData virtualProperty = isJPA2ForValueMapping ? inferredData : new WrappedInferredData(
inferredData, "element"
);
if ( property.isAnnotationPresent( Column.class ) || property.isAnnotationPresent(
Formula.class
) ) {
Column ann = property.getAnnotation( Column.class );
Formula formulaAnn = property.getAnnotation( Formula.class );
elementColumns = Ejb3Column.buildColumnFromAnnotation(
new Column[] { ann },
formulaAnn,
nullability,
propertyHolder,
virtualProperty,
entityBinder.getSecondaryTables(),
mappings
);
}
else if ( property.isAnnotationPresent( Columns.class ) ) {
Columns anns = property.getAnnotation( Columns.class );
elementColumns = Ejb3Column.buildColumnFromAnnotation(
anns.columns(), null, nullability, propertyHolder, virtualProperty,
entityBinder.getSecondaryTables(), mappings
);
}
else {
elementColumns = Ejb3Column.buildColumnFromAnnotation(
null,
null,
nullability,
propertyHolder,
virtualProperty,
entityBinder.getSecondaryTables(),
mappings
);
}
{
Column[] keyColumns = null;
//JPA 2 has priority and has different default column values, differenciate legacy from JPA 2
Boolean isJPA2 = null;
if ( property.isAnnotationPresent( MapKeyColumn.class ) ) {
isJPA2 = Boolean.TRUE;
keyColumns = new Column[] { new MapKeyColumnDelegator( property.getAnnotation( MapKeyColumn.class ) ) };
}
//not explicitly legacy
if ( isJPA2 == null ) {
isJPA2 = Boolean.TRUE;
}
//nullify empty array
keyColumns = keyColumns != null && keyColumns.length > 0 ? keyColumns : null;
//"mapkey" is the legacy column name of the key column pre JPA 2
PropertyData mapKeyVirtualProperty = new WrappedInferredData( inferredData, "mapkey" );
Ejb3Column[] mapColumns = Ejb3Column.buildColumnFromAnnotation(
keyColumns,
null,
Nullability.FORCED_NOT_NULL,
propertyHolder,
isJPA2 ? inferredData : mapKeyVirtualProperty,
isJPA2 ? "_KEY" : null,
entityBinder.getSecondaryTables(),
mappings
);
collectionBinder.setMapKeyColumns( mapColumns );
}
{
JoinColumn[] joinKeyColumns = null;
//JPA 2 has priority and has different default column values, differenciate legacy from JPA 2
Boolean isJPA2 = null;
if ( property.isAnnotationPresent( MapKeyJoinColumns.class ) ) {
isJPA2 = Boolean.TRUE;
final MapKeyJoinColumn[] mapKeyJoinColumns = property.getAnnotation( MapKeyJoinColumns.class )
.value();
joinKeyColumns = new JoinColumn[mapKeyJoinColumns.length];
int index = 0;
for ( MapKeyJoinColumn joinColumn : mapKeyJoinColumns ) {
joinKeyColumns[index] = new MapKeyJoinColumnDelegator( joinColumn );
index++;
}
if ( property.isAnnotationPresent( MapKeyJoinColumn.class ) ) {
throw new AnnotationException(
"@MapKeyJoinColumn and @MapKeyJoinColumns used on the same property: "
+ BinderHelper.getPath( propertyHolder, inferredData )
);
}
}
else if ( property.isAnnotationPresent( MapKeyJoinColumn.class ) ) {
isJPA2 = Boolean.TRUE;
joinKeyColumns = new JoinColumn[] {
new MapKeyJoinColumnDelegator(
property.getAnnotation(
MapKeyJoinColumn.class
)
)
};
}
//not explicitly legacy
if ( isJPA2 == null ) {
isJPA2 = Boolean.TRUE;
}
PropertyData mapKeyVirtualProperty = new WrappedInferredData( inferredData, "mapkey" );
Ejb3JoinColumn[] mapJoinColumns = Ejb3JoinColumn.buildJoinColumnsWithDefaultColumnSuffix(
joinKeyColumns,
null,
entityBinder.getSecondaryTables(),
propertyHolder,
isJPA2 ? inferredData.getPropertyName() : mapKeyVirtualProperty.getPropertyName(),
isJPA2 ? "_KEY" : null,
mappings
);
collectionBinder.setMapKeyManyToManyColumns( mapJoinColumns );
}
//potential element
collectionBinder.setEmbedded( property.isAnnotationPresent( Embedded.class ) );
collectionBinder.setElementColumns( elementColumns );
collectionBinder.setProperty( property );
//TODO enhance exception with @ManyToAny and @CollectionOfElements
if ( oneToManyAnn != null && manyToManyAnn != null ) {
throw new AnnotationException(
"@OneToMany and @ManyToMany on the same property is not allowed: "
+ propertyHolder.getEntityName() + "." + inferredData.getPropertyName()
);
}
String mappedBy = null;
if ( oneToManyAnn != null ) {
for ( Ejb3JoinColumn column : joinColumns ) {
if ( column.isSecondary() ) {
throw new NotYetImplementedException( "Collections having FK in secondary table" );
}
}
collectionBinder.setFkJoinColumns( joinColumns );
mappedBy = oneToManyAnn.mappedBy();
collectionBinder.setTargetEntity(
mappings.getReflectionManager().toXClass( oneToManyAnn.targetEntity() )
);
collectionBinder.setCascadeStrategy(
getCascadeStrategy(
oneToManyAnn.cascade(), hibernateCascade, oneToManyAnn.orphanRemoval(), false
)
);
collectionBinder.setOneToMany( true );
}
else if ( elementCollectionAnn != null ) {
for ( Ejb3JoinColumn column : joinColumns ) {
if ( column.isSecondary() ) {
throw new NotYetImplementedException( "Collections having FK in secondary table" );
}
}
collectionBinder.setFkJoinColumns( joinColumns );
mappedBy = "";
final Class<?> targetElement = elementCollectionAnn.targetClass();
collectionBinder.setTargetEntity(
mappings.getReflectionManager().toXClass( targetElement )
);
//collectionBinder.setCascadeStrategy( getCascadeStrategy( embeddedCollectionAnn.cascade(), hibernateCascade ) );
collectionBinder.setOneToMany( true );
}
else if ( manyToManyAnn != null ) {
mappedBy = manyToManyAnn.mappedBy();
collectionBinder.setTargetEntity(
mappings.getReflectionManager().toXClass( manyToManyAnn.targetEntity() )
);
collectionBinder.setCascadeStrategy(
getCascadeStrategy(
manyToManyAnn.cascade(), hibernateCascade, false, false
)
);
collectionBinder.setOneToMany( false );
}
else if ( property.isAnnotationPresent( ManyToAny.class ) ) {
mappedBy = "";
collectionBinder.setTargetEntity(
mappings.getReflectionManager().toXClass( void.class )
);
collectionBinder.setCascadeStrategy( getCascadeStrategy( null, hibernateCascade, false, false ) );
collectionBinder.setOneToMany( false );
}
collectionBinder.setMappedBy( mappedBy );
bindJoinedTableAssociation(
property, mappings, entityBinder, collectionBinder, propertyHolder, inferredData, mappedBy
);
OnDelete onDeleteAnn = property.getAnnotation( OnDelete.class );
boolean onDeleteCascade = onDeleteAnn != null && OnDeleteAction.CASCADE.equals( onDeleteAnn.action() );
collectionBinder.setCascadeDeleteEnabled( onDeleteCascade );
if ( isIdentifierMapper ) {
collectionBinder.setInsertable( false );
collectionBinder.setUpdatable( false );
}
if ( property.isAnnotationPresent( CollectionId.class ) ) { //do not compute the generators unless necessary
HashMap<String, IdGenerator> localGenerators = ( HashMap<String, IdGenerator> ) classGenerators.clone();
localGenerators.putAll( buildLocalGenerators( property, mappings ) );
collectionBinder.setLocalGenerators( localGenerators );
}
collectionBinder.setInheritanceStatePerClass( inheritanceStatePerClass );
collectionBinder.setDeclaringClass( inferredData.getDeclaringClass() );
collectionBinder.bind();
}
//Either a regular property or a basic @Id or @EmbeddedId while not ignoring id annotations
else if ( !isId || !entityBinder.isIgnoreIdAnnotations() ) {
//define whether the type is a component or not
boolean isComponent = false;
//Overrides from @MapsId if needed
boolean isOverridden = false;
if ( isId || propertyHolder.isOrWithinEmbeddedId() || propertyHolder.isInIdClass() ) {
//the associated entity could be using an @IdClass making the overridden property a component
final PropertyData overridingProperty = BinderHelper.getPropertyOverriddenByMapperOrMapsId(
isId, propertyHolder, property.getName(), mappings
);
if ( overridingProperty != null ) {
isOverridden = true;
final InheritanceState state = inheritanceStatePerClass.get( overridingProperty.getClassOrElement() );
if ( state != null ) {
isComponent = isComponent || state.hasIdClassOrEmbeddedId();
}
//Get the new column
columns = columnsBuilder.overrideColumnFromMapperOrMapsIdProperty( isId );
}
}
isComponent = isComponent
|| property.isAnnotationPresent( Embedded.class )
|| property.isAnnotationPresent( EmbeddedId.class )
|| returnedClass.isAnnotationPresent( Embeddable.class );
if ( isComponent ) {
String referencedEntityName = null;
if ( isOverridden ) {
final PropertyData mapsIdProperty = BinderHelper.getPropertyOverriddenByMapperOrMapsId(
isId, propertyHolder, property.getName(), mappings
);
referencedEntityName = mapsIdProperty.getClassOrElementName();
}
AccessType propertyAccessor = entityBinder.getPropertyAccessor( property );
propertyBinder = bindComponent(
inferredData,
propertyHolder,
propertyAccessor,
entityBinder,
isIdentifierMapper,
mappings,
isComponentEmbedded,
isId,
inheritanceStatePerClass,
referencedEntityName,
isOverridden ? ( Ejb3JoinColumn[] ) columns : null
);
}
else {
//provide the basic property mapping
boolean optional = true;
boolean lazy = false;
if ( property.isAnnotationPresent( Basic.class ) ) {
Basic ann = property.getAnnotation( Basic.class );
optional = ann.optional();
lazy = ann.fetch() == FetchType.LAZY;
}
//implicit type will check basic types and Serializable classes
if ( isId || ( !optional && nullability != Nullability.FORCED_NULL ) ) {
//force columns to not null
for ( Ejb3Column col : columns ) {
col.forceNotNull();
}
}
propertyBinder.setLazy( lazy );
propertyBinder.setColumns( columns );
if ( isOverridden ) {
final PropertyData mapsIdProperty = BinderHelper.getPropertyOverriddenByMapperOrMapsId(
isId, propertyHolder, property.getName(), mappings
);
propertyBinder.setReferencedEntityName( mapsIdProperty.getClassOrElementName() );
}
propertyBinder.makePropertyValueAndBind();
}
if ( isOverridden ) {
final PropertyData mapsIdProperty = BinderHelper.getPropertyOverriddenByMapperOrMapsId(
isId, propertyHolder, property.getName(), mappings
);
Map<String, IdGenerator> localGenerators = ( HashMap<String, IdGenerator> ) classGenerators.clone();
final IdGenerator foreignGenerator = new IdGenerator();
foreignGenerator.setIdentifierGeneratorStrategy( "assigned" );
foreignGenerator.setName( "Hibernate-local--foreign generator" );
foreignGenerator.setIdentifierGeneratorStrategy( "foreign" );
foreignGenerator.addParam( "property", mapsIdProperty.getPropertyName() );
localGenerators.put( foreignGenerator.getName(), foreignGenerator );
BinderHelper.makeIdGenerator(
( SimpleValue ) propertyBinder.getValue(),
foreignGenerator.getIdentifierGeneratorStrategy(),
foreignGenerator.getName(),
mappings,
localGenerators
);
}
if ( isId ) {
//components and regular basic types create SimpleValue objects
final SimpleValue value = ( SimpleValue ) propertyBinder.getValue();
if ( !isOverridden ) {
processId(
propertyHolder,
inferredData,
value,
classGenerators,
isIdentifierMapper,
mappings
);
}
}
}
}
//init index
//process indexes after everything: in second pass, many to one has to be done before indexes
Index index = property.getAnnotation( Index.class );
if ( index != null ) {
if ( joinColumns != null ) {
for ( Ejb3Column column : joinColumns ) {
column.addIndex( index, inSecondPass );
}
}
else {
if ( columns != null ) {
for ( Ejb3Column column : columns ) {
column.addIndex( index, inSecondPass );
}
}
}
}
// Natural ID columns must reside in one single UniqueKey within the Table.
// For now, simply ensure consistent naming.
// TODO: AFAIK, there really isn't a reason for these UKs to be created
// on the secondPass. This whole area should go away...
NaturalId naturalIdAnn = property.getAnnotation( NaturalId.class );
if ( naturalIdAnn != null ) {
if ( joinColumns != null ) {
for ( Ejb3Column column : joinColumns ) {
String keyName = "UK_" + Constraint.hashedName( column.getTable().getName() + "_NaturalID" );
column.addUniqueKey( keyName, inSecondPass );
}
}
else {
for ( Ejb3Column column : columns ) {
String keyName = "UK_" + Constraint.hashedName( column.getTable().getName() + "_NaturalID" );
column.addUniqueKey( keyName, inSecondPass );
}
}
}
}
private static void setVersionInformation(XProperty property, PropertyBinder propertyBinder) {
propertyBinder.getSimpleValueBinder().setVersion( true );
if(property.isAnnotationPresent( Source.class )) {
Source source = property.getAnnotation( Source.class );
propertyBinder.getSimpleValueBinder().setTimestampVersionType( source.value().typeName() );
}
}
private static void processId(
PropertyHolder propertyHolder,
PropertyData inferredData,
SimpleValue idValue,
HashMap<String, IdGenerator> classGenerators,
boolean isIdentifierMapper,
Mappings mappings) {
if ( isIdentifierMapper ) {
throw new AnnotationException(
"@IdClass class should not have @Id nor @EmbeddedId properties: "
+ BinderHelper.getPath( propertyHolder, inferredData )
);
}
XClass returnedClass = inferredData.getClassOrElement();
XProperty property = inferredData.getProperty();
//clone classGenerator and override with local values
HashMap<String, IdGenerator> localGenerators = ( HashMap<String, IdGenerator> ) classGenerators.clone();
localGenerators.putAll( buildLocalGenerators( property, mappings ) );
//manage composite related metadata
//guess if its a component and find id data access (property, field etc)
final boolean isComponent = returnedClass.isAnnotationPresent( Embeddable.class )
|| property.isAnnotationPresent( EmbeddedId.class );
GeneratedValue generatedValue = property.getAnnotation( GeneratedValue.class );
String generatorType = generatedValue != null ?
generatorType( generatedValue.strategy(), mappings ) :
"assigned";
String generatorName = generatedValue != null ?
generatedValue.generator() :
BinderHelper.ANNOTATION_STRING_DEFAULT;
if ( isComponent ) {
generatorType = "assigned";
} //a component must not have any generator
BinderHelper.makeIdGenerator( idValue, generatorType, generatorName, mappings, localGenerators );
if ( LOG.isTraceEnabled() ) {
LOG.tracev( "Bind {0} on {1}", ( isComponent ? "@EmbeddedId" : "@Id" ), inferredData.getPropertyName() );
}
}
//TODO move that to collection binder?
private static void bindJoinedTableAssociation(
XProperty property,
Mappings mappings,
EntityBinder entityBinder,
CollectionBinder collectionBinder,
PropertyHolder propertyHolder,
PropertyData inferredData,
String mappedBy) {
TableBinder associationTableBinder = new TableBinder();
JoinColumn[] annJoins;
JoinColumn[] annInverseJoins;
JoinTable assocTable = propertyHolder.getJoinTable( property );
CollectionTable collectionTable = property.getAnnotation( CollectionTable.class );
if ( assocTable != null || collectionTable != null ) {
final String catalog;
final String schema;
final String tableName;
final UniqueConstraint[] uniqueConstraints;
final JoinColumn[] joins;
final JoinColumn[] inverseJoins;
//JPA 2 has priority
if ( collectionTable != null ) {
catalog = collectionTable.catalog();
schema = collectionTable.schema();
tableName = collectionTable.name();
uniqueConstraints = collectionTable.uniqueConstraints();
joins = collectionTable.joinColumns();
inverseJoins = null;
}
else {
catalog = assocTable.catalog();
schema = assocTable.schema();
tableName = assocTable.name();
uniqueConstraints = assocTable.uniqueConstraints();
joins = assocTable.joinColumns();
inverseJoins = assocTable.inverseJoinColumns();
}
collectionBinder.setExplicitAssociationTable( true );
if ( !BinderHelper.isEmptyAnnotationValue( schema ) ) {
associationTableBinder.setSchema( schema );
}
if ( !BinderHelper.isEmptyAnnotationValue( catalog ) ) {
associationTableBinder.setCatalog( catalog );
}
if ( !BinderHelper.isEmptyAnnotationValue( tableName ) ) {
associationTableBinder.setName( tableName );
}
associationTableBinder.setUniqueConstraints( uniqueConstraints );
//set check constaint in the second pass
annJoins = joins.length == 0 ? null : joins;
annInverseJoins = inverseJoins == null || inverseJoins.length == 0 ? null : inverseJoins;
}
else {
annJoins = null;
annInverseJoins = null;
}
Ejb3JoinColumn[] joinColumns = Ejb3JoinColumn.buildJoinTableJoinColumns(
annJoins, entityBinder.getSecondaryTables(), propertyHolder, inferredData.getPropertyName(), mappedBy,
mappings
);
Ejb3JoinColumn[] inverseJoinColumns = Ejb3JoinColumn.buildJoinTableJoinColumns(
annInverseJoins, entityBinder.getSecondaryTables(), propertyHolder, inferredData.getPropertyName(),
mappedBy, mappings
);
associationTableBinder.setMappings( mappings );
collectionBinder.setTableBinder( associationTableBinder );
collectionBinder.setJoinColumns( joinColumns );
collectionBinder.setInverseJoinColumns( inverseJoinColumns );
}
private static PropertyBinder bindComponent(
PropertyData inferredData,
PropertyHolder propertyHolder,
AccessType propertyAccessor,
EntityBinder entityBinder,
boolean isIdentifierMapper,
Mappings mappings,
boolean isComponentEmbedded,
boolean isId, //is a identifier
Map<XClass, InheritanceState> inheritanceStatePerClass,
String referencedEntityName, //is a component who is overridden by a @MapsId
Ejb3JoinColumn[] columns) {
Component comp;
if ( referencedEntityName != null ) {
comp = createComponent( propertyHolder, inferredData, isComponentEmbedded, isIdentifierMapper, mappings );
SecondPass sp = new CopyIdentifierComponentSecondPass(
comp,
referencedEntityName,
columns,
mappings
);
mappings.addSecondPass( sp );
}
else {
comp = fillComponent(
propertyHolder, inferredData, propertyAccessor, !isId, entityBinder,
isComponentEmbedded, isIdentifierMapper,
false, mappings, inheritanceStatePerClass
);
}
if ( isId ) {
comp.setKey( true );
if ( propertyHolder.getPersistentClass().getIdentifier() != null ) {
throw new AnnotationException(
comp.getComponentClassName()
+ " must not have @Id properties when used as an @EmbeddedId: "
+ BinderHelper.getPath( propertyHolder, inferredData )
);
}
if ( referencedEntityName == null && comp.getPropertySpan() == 0 ) {
throw new AnnotationException(
comp.getComponentClassName()
+ " has no persistent id property: "
+ BinderHelper.getPath( propertyHolder, inferredData )
);
}
}
XProperty property = inferredData.getProperty();
setupComponentTuplizer( property, comp );
PropertyBinder binder = new PropertyBinder();
binder.setName( inferredData.getPropertyName() );
binder.setValue( comp );
binder.setProperty( inferredData.getProperty() );
binder.setAccessType( inferredData.getDefaultAccess() );
binder.setEmbedded( isComponentEmbedded );
binder.setHolder( propertyHolder );
binder.setId( isId );
binder.setEntityBinder( entityBinder );
binder.setInheritanceStatePerClass( inheritanceStatePerClass );
binder.setMappings( mappings );
binder.makePropertyAndBind();
return binder;
}
public static Component fillComponent(
PropertyHolder propertyHolder,
PropertyData inferredData,
AccessType propertyAccessor,
boolean isNullable,
EntityBinder entityBinder,
boolean isComponentEmbedded,
boolean isIdentifierMapper,
boolean inSecondPass,
Mappings mappings,
Map<XClass, InheritanceState> inheritanceStatePerClass) {
return fillComponent(
propertyHolder, inferredData, null, propertyAccessor,
isNullable, entityBinder, isComponentEmbedded, isIdentifierMapper, inSecondPass, mappings,
inheritanceStatePerClass
);
}
public static Component fillComponent(
PropertyHolder propertyHolder,
PropertyData inferredData,
PropertyData baseInferredData, //base inferred data correspond to the entity reproducing inferredData's properties (ie IdClass)
AccessType propertyAccessor,
boolean isNullable,
EntityBinder entityBinder,
boolean isComponentEmbedded,
boolean isIdentifierMapper,
boolean inSecondPass,
Mappings mappings,
Map<XClass, InheritanceState> inheritanceStatePerClass) {
/**
* inSecondPass can only be used to apply right away the second pass of a composite-element
* Because it's a value type, there is no bidirectional association, hence second pass
* ordering does not matter
*/
Component comp = createComponent( propertyHolder, inferredData, isComponentEmbedded, isIdentifierMapper, mappings );
String subpath = BinderHelper.getPath( propertyHolder, inferredData );
LOG.tracev( "Binding component with path: {0}", subpath );
PropertyHolder subHolder = PropertyHolderBuilder.buildPropertyHolder(
comp, subpath,
inferredData, propertyHolder, mappings
);
final XClass xClassProcessed = inferredData.getPropertyClass();
List<PropertyData> classElements = new ArrayList<PropertyData>();
XClass returnedClassOrElement = inferredData.getClassOrElement();
List<PropertyData> baseClassElements = null;
Map<String, PropertyData> orderedBaseClassElements = new HashMap<String, PropertyData>();
XClass baseReturnedClassOrElement;
if ( baseInferredData != null ) {
baseClassElements = new ArrayList<PropertyData>();
baseReturnedClassOrElement = baseInferredData.getClassOrElement();
bindTypeDefs( baseReturnedClassOrElement, mappings );
PropertyContainer propContainer = new PropertyContainer( baseReturnedClassOrElement, xClassProcessed );
addElementsOfClass( baseClassElements, propertyAccessor, propContainer, mappings );
for ( PropertyData element : baseClassElements ) {
orderedBaseClassElements.put( element.getPropertyName(), element );
}
}
//embeddable elements can have type defs
bindTypeDefs( returnedClassOrElement, mappings );
PropertyContainer propContainer = new PropertyContainer( returnedClassOrElement, xClassProcessed );
addElementsOfClass( classElements, propertyAccessor, propContainer, mappings );
//add elements of the embeddable superclass
XClass superClass = xClassProcessed.getSuperclass();
while ( superClass != null && superClass.isAnnotationPresent( MappedSuperclass.class ) ) {
//FIXME: proper support of typevariables incl var resolved at upper levels
propContainer = new PropertyContainer( superClass, xClassProcessed );
addElementsOfClass( classElements, propertyAccessor, propContainer, mappings );
superClass = superClass.getSuperclass();
}
if ( baseClassElements != null ) {
//useful to avoid breaking pre JPA 2 mappings
if ( !hasAnnotationsOnIdClass( xClassProcessed ) ) {
for ( int i = 0; i < classElements.size(); i++ ) {
final PropertyData idClassPropertyData = classElements.get( i );
final PropertyData entityPropertyData = orderedBaseClassElements.get( idClassPropertyData.getPropertyName() );
if ( propertyHolder.isInIdClass() ) {
if ( entityPropertyData == null ) {
throw new AnnotationException(
"Property of @IdClass not found in entity "
+ baseInferredData.getPropertyClass().getName() + ": "
+ idClassPropertyData.getPropertyName()
);
}
final boolean hasXToOneAnnotation = entityPropertyData.getProperty()
.isAnnotationPresent( ManyToOne.class )
|| entityPropertyData.getProperty().isAnnotationPresent( OneToOne.class );
final boolean isOfDifferentType = !entityPropertyData.getClassOrElement()
.equals( idClassPropertyData.getClassOrElement() );
if ( hasXToOneAnnotation && isOfDifferentType ) {
//don't replace here as we need to use the actual original return type
//the annotation overriding will be dealt with by a mechanism similar to @MapsId
}
else {
classElements.set( i, entityPropertyData ); //this works since they are in the same order
}
}
else {
classElements.set( i, entityPropertyData ); //this works since they are in the same order
}
}
}
}
for ( PropertyData propertyAnnotatedElement : classElements ) {
processElementAnnotations(
subHolder, isNullable ?
Nullability.NO_CONSTRAINT :
Nullability.FORCED_NOT_NULL,
propertyAnnotatedElement,
new HashMap<String, IdGenerator>(), entityBinder, isIdentifierMapper, isComponentEmbedded,
inSecondPass, mappings, inheritanceStatePerClass
);
XProperty property = propertyAnnotatedElement.getProperty();
if ( property.isAnnotationPresent( GeneratedValue.class ) &&
property.isAnnotationPresent( Id.class ) ) {
//clone classGenerator and override with local values
Map<String, IdGenerator> localGenerators = new HashMap<String, IdGenerator>();
localGenerators.putAll( buildLocalGenerators( property, mappings ) );
GeneratedValue generatedValue = property.getAnnotation( GeneratedValue.class );
String generatorType = generatedValue != null ? generatorType(
generatedValue.strategy(), mappings
) : "assigned";
String generator = generatedValue != null ? generatedValue.generator() : BinderHelper.ANNOTATION_STRING_DEFAULT;
BinderHelper.makeIdGenerator(
( SimpleValue ) comp.getProperty( property.getName() ).getValue(),
generatorType,
generator,
mappings,
localGenerators
);
}
}
return comp;
}
public static Component createComponent(
PropertyHolder propertyHolder,
PropertyData inferredData,
boolean isComponentEmbedded,
boolean isIdentifierMapper,
Mappings mappings) {
Component comp = new Component( mappings, propertyHolder.getPersistentClass() );
comp.setEmbedded( isComponentEmbedded );
//yuk
comp.setTable( propertyHolder.getTable() );
//FIXME shouldn't identifier mapper use getClassOrElementName? Need to be checked.
if ( isIdentifierMapper || ( isComponentEmbedded && inferredData.getPropertyName() == null ) ) {
comp.setComponentClassName( comp.getOwner().getClassName() );
}
else {
comp.setComponentClassName( inferredData.getClassOrElementName() );
}
comp.setNodeName( inferredData.getPropertyName() );
return comp;
}
private static void bindIdClass(
String generatorType,
String generatorName,
PropertyData inferredData,
PropertyData baseInferredData,
Ejb3Column[] columns,
PropertyHolder propertyHolder,
boolean isComposite,
AccessType propertyAccessor,
EntityBinder entityBinder,
boolean isEmbedded,
boolean isIdentifierMapper,
Mappings mappings,
Map<XClass, InheritanceState> inheritanceStatePerClass) {
/*
* Fill simple value and property since and Id is a property
*/
PersistentClass persistentClass = propertyHolder.getPersistentClass();
if ( !( persistentClass instanceof RootClass ) ) {
throw new AnnotationException(
"Unable to define/override @Id(s) on a subclass: "
+ propertyHolder.getEntityName()
);
}
RootClass rootClass = ( RootClass ) persistentClass;
String persistentClassName = rootClass.getClassName();
SimpleValue id;
final String propertyName = inferredData.getPropertyName();
HashMap<String, IdGenerator> localGenerators = new HashMap<String, IdGenerator>();
if ( isComposite ) {
id = fillComponent(
propertyHolder, inferredData, baseInferredData, propertyAccessor,
false, entityBinder, isEmbedded, isIdentifierMapper, false, mappings, inheritanceStatePerClass
);
Component componentId = ( Component ) id;
componentId.setKey( true );
if ( rootClass.getIdentifier() != null ) {
throw new AnnotationException( componentId.getComponentClassName() + " must not have @Id properties when used as an @EmbeddedId" );
}
if ( componentId.getPropertySpan() == 0 ) {
throw new AnnotationException( componentId.getComponentClassName() + " has no persistent id property" );
}
//tuplizers
XProperty property = inferredData.getProperty();
setupComponentTuplizer( property, componentId );
}
else {
//TODO I think this branch is never used. Remove.
for ( Ejb3Column column : columns ) {
column.forceNotNull(); //this is an id
}
SimpleValueBinder value = new SimpleValueBinder();
value.setPropertyName( propertyName );
value.setReturnedClassName( inferredData.getTypeName() );
value.setColumns( columns );
value.setPersistentClassName( persistentClassName );
value.setMappings( mappings );
value.setType( inferredData.getProperty(), inferredData.getClassOrElement(), persistentClassName );
value.setAccessType( propertyAccessor );
id = value.make();
}
rootClass.setIdentifier( id );
BinderHelper.makeIdGenerator( id, generatorType, generatorName, mappings, localGenerators );
if ( isEmbedded ) {
rootClass.setEmbeddedIdentifier( inferredData.getPropertyClass() == null );
}
else {
PropertyBinder binder = new PropertyBinder();
binder.setName( propertyName );
binder.setValue( id );
binder.setAccessType( inferredData.getDefaultAccess() );
binder.setProperty( inferredData.getProperty() );
Property prop = binder.makeProperty();
rootClass.setIdentifierProperty( prop );
//if the id property is on a superclass, update the metamodel
final org.hibernate.mapping.MappedSuperclass superclass = BinderHelper.getMappedSuperclassOrNull(
inferredData.getDeclaringClass(),
inheritanceStatePerClass,
mappings
);
if ( superclass != null ) {
superclass.setDeclaredIdentifierProperty( prop );
}
else {
//we know the property is on the actual entity
rootClass.setDeclaredIdentifierProperty( prop );
}
}
}
private static PropertyData getUniqueIdPropertyFromBaseClass(
PropertyData inferredData,
PropertyData baseInferredData,
AccessType propertyAccessor,
Mappings mappings) {
List<PropertyData> baseClassElements = new ArrayList<PropertyData>();
XClass baseReturnedClassOrElement = baseInferredData.getClassOrElement();
PropertyContainer propContainer = new PropertyContainer(
baseReturnedClassOrElement, inferredData.getPropertyClass()
);
addElementsOfClass( baseClassElements, propertyAccessor, propContainer, mappings );
//Id properties are on top and there is only one
return baseClassElements.get( 0 );
}
private static void setupComponentTuplizer(XProperty property, Component component) {
if ( property == null ) {
return;
}
if ( property.isAnnotationPresent( Tuplizers.class ) ) {
for ( Tuplizer tuplizer : property.getAnnotation( Tuplizers.class ).value() ) {
EntityMode mode = EntityMode.parse( tuplizer.entityMode() );
//todo tuplizer.entityModeType
component.addTuplizer( mode, tuplizer.impl().getName() );
}
}
if ( property.isAnnotationPresent( Tuplizer.class ) ) {
Tuplizer tuplizer = property.getAnnotation( Tuplizer.class );
EntityMode mode = EntityMode.parse( tuplizer.entityMode() );
//todo tuplizer.entityModeType
component.addTuplizer( mode, tuplizer.impl().getName() );
}
}
private static void bindManyToOne(
String cascadeStrategy,
Ejb3JoinColumn[] columns,
boolean optional,
boolean ignoreNotFound,
boolean cascadeOnDelete,
XClass targetEntity,
PropertyHolder propertyHolder,
PropertyData inferredData,
boolean unique,
boolean isIdentifierMapper,
boolean inSecondPass,
PropertyBinder propertyBinder,
Mappings mappings) {
//All FK columns should be in the same table
org.hibernate.mapping.ManyToOne value = new org.hibernate.mapping.ManyToOne( mappings, columns[0].getTable() );
// This is a @OneToOne mapped to a physical o.h.mapping.ManyToOne
if ( unique ) {
value.markAsLogicalOneToOne();
}
value.setReferencedEntityName( ToOneBinder.getReferenceEntityName( inferredData, targetEntity, mappings ) );
final XProperty property = inferredData.getProperty();
defineFetchingStrategy( value, property );
//value.setFetchMode( fetchMode );
value.setIgnoreNotFound( ignoreNotFound );
value.setCascadeDeleteEnabled( cascadeOnDelete );
//value.setLazy( fetchMode != FetchMode.JOIN );
if ( !optional ) {
for ( Ejb3JoinColumn column : columns ) {
column.setNullable( false );
}
}
if ( property.isAnnotationPresent( MapsId.class ) ) {
//read only
for ( Ejb3JoinColumn column : columns ) {
column.setInsertable( false );
column.setUpdatable( false );
}
}
//Make sure that JPA1 key-many-to-one columns are read only tooj
boolean hasSpecjManyToOne=false;
if ( mappings.isSpecjProprietarySyntaxEnabled() ) {
String columnName = "";
for ( XProperty prop : inferredData.getDeclaringClass()
.getDeclaredProperties( AccessType.FIELD.getType() ) ) {
if ( prop.isAnnotationPresent( Id.class ) && prop.isAnnotationPresent( Column.class ) ) {
columnName = prop.getAnnotation( Column.class ).name();
}
final JoinColumn joinColumn = property.getAnnotation( JoinColumn.class );
if ( property.isAnnotationPresent( ManyToOne.class ) && joinColumn != null
&& ! BinderHelper.isEmptyAnnotationValue( joinColumn.name() )
&& joinColumn.name().equals( columnName )
&& !property.isAnnotationPresent( MapsId.class ) ) {
hasSpecjManyToOne = true;
for ( Ejb3JoinColumn column : columns ) {
column.setInsertable( false );
column.setUpdatable( false );
}
}
}
}
value.setTypeName( inferredData.getClassOrElementName() );
final String propertyName = inferredData.getPropertyName();
value.setTypeUsingReflection( propertyHolder.getClassName(), propertyName );
ForeignKey fk = property.getAnnotation( ForeignKey.class );
String fkName = fk != null ?
fk.name() :
"";
if ( !BinderHelper.isEmptyAnnotationValue( fkName ) ) {
value.setForeignKeyName( fkName );
}
String path = propertyHolder.getPath() + "." + propertyName;
FkSecondPass secondPass = new ToOneFkSecondPass(
value, columns,
!optional && unique, //cannot have nullable and unique on certain DBs like Derby
propertyHolder.getEntityOwnerClassName(),
path, mappings
);
if ( inSecondPass ) {
secondPass.doSecondPass( mappings.getClasses() );
}
else {
mappings.addSecondPass(
secondPass
);
}
Ejb3Column.checkPropertyConsistency( columns, propertyHolder.getEntityName() + propertyName );
//PropertyBinder binder = new PropertyBinder();
propertyBinder.setName( propertyName );
propertyBinder.setValue( value );
//binder.setCascade(cascadeStrategy);
if ( isIdentifierMapper ) {
propertyBinder.setInsertable( false );
propertyBinder.setUpdatable( false );
}
else if (hasSpecjManyToOne) {
propertyBinder.setInsertable( false );
propertyBinder.setUpdatable( false );
}
else {
propertyBinder.setInsertable( columns[0].isInsertable() );
propertyBinder.setUpdatable( columns[0].isUpdatable() );
}
propertyBinder.setColumns( columns );
propertyBinder.setAccessType( inferredData.getDefaultAccess() );
propertyBinder.setCascade( cascadeStrategy );
propertyBinder.setProperty( property );
propertyBinder.setXToMany( true );
propertyBinder.makePropertyAndBind();
}
protected static void defineFetchingStrategy(ToOne toOne, XProperty property) {
LazyToOne lazy = property.getAnnotation( LazyToOne.class );
Fetch fetch = property.getAnnotation( Fetch.class );
ManyToOne manyToOne = property.getAnnotation( ManyToOne.class );
OneToOne oneToOne = property.getAnnotation( OneToOne.class );
FetchType fetchType;
if ( manyToOne != null ) {
fetchType = manyToOne.fetch();
}
else if ( oneToOne != null ) {
fetchType = oneToOne.fetch();
}
else {
throw new AssertionFailure(
"Define fetch strategy on a property not annotated with @OneToMany nor @OneToOne"
);
}
if ( lazy != null ) {
toOne.setLazy( !( lazy.value() == LazyToOneOption.FALSE ) );
toOne.setUnwrapProxy( ( lazy.value() == LazyToOneOption.NO_PROXY ) );
}
else {
toOne.setLazy( fetchType == FetchType.LAZY );
toOne.setUnwrapProxy( false );
}
if ( fetch != null ) {
if ( fetch.value() == org.hibernate.annotations.FetchMode.JOIN ) {
toOne.setFetchMode( FetchMode.JOIN );
toOne.setLazy( false );
toOne.setUnwrapProxy( false );
}
else if ( fetch.value() == org.hibernate.annotations.FetchMode.SELECT ) {
toOne.setFetchMode( FetchMode.SELECT );
}
else if ( fetch.value() == org.hibernate.annotations.FetchMode.SUBSELECT ) {
throw new AnnotationException( "Use of FetchMode.SUBSELECT not allowed on ToOne associations" );
}
else {
throw new AssertionFailure( "Unknown FetchMode: " + fetch.value() );
}
}
else {
toOne.setFetchMode( getFetchMode( fetchType ) );
}
}
private static void bindOneToOne(
String cascadeStrategy,
Ejb3JoinColumn[] joinColumns,
boolean optional,
FetchMode fetchMode,
boolean ignoreNotFound,
boolean cascadeOnDelete,
XClass targetEntity,
PropertyHolder propertyHolder,
PropertyData inferredData,
String mappedBy,
boolean trueOneToOne,
boolean isIdentifierMapper,
boolean inSecondPass,
PropertyBinder propertyBinder,
Mappings mappings) {
//column.getTable() => persistentClass.getTable()
final String propertyName = inferredData.getPropertyName();
LOG.tracev( "Fetching {0} with {1}", propertyName, fetchMode );
boolean mapToPK = true;
if ( !trueOneToOne ) {
//try to find a hidden true one to one (FK == PK columns)
KeyValue identifier = propertyHolder.getIdentifier();
if ( identifier == null ) {
//this is a @OneToOne in a @EmbeddedId (the persistentClass.identifier is not set yet, it's being built)
//by definition the PK cannot refers to itself so it cannot map to itself
mapToPK = false;
}
else {
Iterator idColumns = identifier.getColumnIterator();
List<String> idColumnNames = new ArrayList<String>();
org.hibernate.mapping.Column currentColumn;
if ( identifier.getColumnSpan() != joinColumns.length ) {
mapToPK = false;
}
else {
while ( idColumns.hasNext() ) {
currentColumn = ( org.hibernate.mapping.Column ) idColumns.next();
idColumnNames.add( currentColumn.getName() );
}
for ( Ejb3JoinColumn col : joinColumns ) {
if ( !idColumnNames.contains( col.getMappingColumn().getName() ) ) {
mapToPK = false;
break;
}
}
}
}
}
if ( trueOneToOne || mapToPK || !BinderHelper.isEmptyAnnotationValue( mappedBy ) ) {
//is a true one-to-one
//FIXME referencedColumnName ignored => ordering may fail.
OneToOneSecondPass secondPass = new OneToOneSecondPass(
mappedBy,
propertyHolder.getEntityName(),
propertyName,
propertyHolder, inferredData, targetEntity, ignoreNotFound, cascadeOnDelete,
optional, cascadeStrategy, joinColumns, mappings
);
if ( inSecondPass ) {
secondPass.doSecondPass( mappings.getClasses() );
}
else {
mappings.addSecondPass(
secondPass, BinderHelper.isEmptyAnnotationValue( mappedBy )
);
}
}
else {
//has a FK on the table
bindManyToOne(
cascadeStrategy, joinColumns, optional, ignoreNotFound, cascadeOnDelete,
targetEntity,
propertyHolder, inferredData, true, isIdentifierMapper, inSecondPass,
propertyBinder, mappings
);
}
}
private static void bindAny(
String cascadeStrategy,
Ejb3JoinColumn[] columns,
boolean cascadeOnDelete,
Nullability nullability,
PropertyHolder propertyHolder,
PropertyData inferredData,
EntityBinder entityBinder,
boolean isIdentifierMapper,
Mappings mappings) {
org.hibernate.annotations.Any anyAnn = inferredData.getProperty()
.getAnnotation( org.hibernate.annotations.Any.class );
if ( anyAnn == null ) {
throw new AssertionFailure(
"Missing @Any annotation: "
+ BinderHelper.getPath( propertyHolder, inferredData )
);
}
Any value = BinderHelper.buildAnyValue(
anyAnn.metaDef(), columns, anyAnn.metaColumn(), inferredData,
cascadeOnDelete, nullability, propertyHolder, entityBinder, anyAnn.optional(), mappings
);
PropertyBinder binder = new PropertyBinder();
binder.setName( inferredData.getPropertyName() );
binder.setValue( value );
binder.setLazy( anyAnn.fetch() == FetchType.LAZY );
//binder.setCascade(cascadeStrategy);
if ( isIdentifierMapper ) {
binder.setInsertable( false );
binder.setUpdatable( false );
}
else {
binder.setInsertable( columns[0].isInsertable() );
binder.setUpdatable( columns[0].isUpdatable() );
}
binder.setAccessType( inferredData.getDefaultAccess() );
binder.setCascade( cascadeStrategy );
Property prop = binder.makeProperty();
//composite FK columns are in the same table so its OK
propertyHolder.addProperty( prop, columns, inferredData.getDeclaringClass() );
}
private static String generatorType(GenerationType generatorEnum, Mappings mappings) {
boolean useNewGeneratorMappings = mappings.useNewGeneratorMappings();
switch ( generatorEnum ) {
case IDENTITY:
return "identity";
case AUTO:
return useNewGeneratorMappings
? org.hibernate.id.enhanced.SequenceStyleGenerator.class.getName()
: "native";
case TABLE:
return useNewGeneratorMappings
? org.hibernate.id.enhanced.TableGenerator.class.getName()
: MultipleHiLoPerTableGenerator.class.getName();
case SEQUENCE:
return useNewGeneratorMappings
? org.hibernate.id.enhanced.SequenceStyleGenerator.class.getName()
: "seqhilo";
}
throw new AssertionFailure( "Unknown GeneratorType: " + generatorEnum );
}
private static EnumSet<CascadeType> convertToHibernateCascadeType(javax.persistence.CascadeType[] ejbCascades) {
EnumSet<CascadeType> hibernateCascadeSet = EnumSet.noneOf( CascadeType.class );
if ( ejbCascades != null && ejbCascades.length > 0 ) {
for ( javax.persistence.CascadeType cascade : ejbCascades ) {
switch ( cascade ) {
case ALL:
hibernateCascadeSet.add( CascadeType.ALL );
break;
case PERSIST:
hibernateCascadeSet.add( CascadeType.PERSIST );
break;
case MERGE:
hibernateCascadeSet.add( CascadeType.MERGE );
break;
case REMOVE:
hibernateCascadeSet.add( CascadeType.REMOVE );
break;
case REFRESH:
hibernateCascadeSet.add( CascadeType.REFRESH );
break;
case DETACH:
hibernateCascadeSet.add( CascadeType.DETACH );
break;
}
}
}
return hibernateCascadeSet;
}
private static String getCascadeStrategy(
javax.persistence.CascadeType[] ejbCascades,
Cascade hibernateCascadeAnnotation,
boolean orphanRemoval,
boolean forcePersist) {
EnumSet<CascadeType> hibernateCascadeSet = convertToHibernateCascadeType( ejbCascades );
CascadeType[] hibernateCascades = hibernateCascadeAnnotation == null ?
null :
hibernateCascadeAnnotation.value();
if ( hibernateCascades != null && hibernateCascades.length > 0 ) {
hibernateCascadeSet.addAll( Arrays.asList( hibernateCascades ) );
}
if ( orphanRemoval ) {
hibernateCascadeSet.add( CascadeType.DELETE_ORPHAN );
hibernateCascadeSet.add( CascadeType.REMOVE );
}
if ( forcePersist ) {
hibernateCascadeSet.add( CascadeType.PERSIST );
}
StringBuilder cascade = new StringBuilder();
for ( CascadeType aHibernateCascadeSet : hibernateCascadeSet ) {
switch ( aHibernateCascadeSet ) {
case ALL:
cascade.append( "," ).append( "all" );
break;
case SAVE_UPDATE:
cascade.append( "," ).append( "save-update" );
break;
case PERSIST:
cascade.append( "," ).append( "persist" );
break;
case MERGE:
cascade.append( "," ).append( "merge" );
break;
case LOCK:
cascade.append( "," ).append( "lock" );
break;
case REFRESH:
cascade.append( "," ).append( "refresh" );
break;
case REPLICATE:
cascade.append( "," ).append( "replicate" );
break;
case EVICT:
case DETACH:
cascade.append( "," ).append( "evict" );
break;
case DELETE:
cascade.append( "," ).append( "delete" );
break;
case DELETE_ORPHAN:
cascade.append( "," ).append( "delete-orphan" );
break;
case REMOVE:
cascade.append( "," ).append( "delete" );
break;
}
}
return cascade.length() > 0 ?
cascade.substring( 1 ) :
"none";
}
public static FetchMode getFetchMode(FetchType fetch) {
if ( fetch == FetchType.EAGER ) {
return FetchMode.JOIN;
}
else {
return FetchMode.SELECT;
}
}
private static HashMap<String, IdGenerator> buildLocalGenerators(XAnnotatedElement annElt, Mappings mappings) {
HashMap<String, IdGenerator> generators = new HashMap<String, IdGenerator>();
TableGenerator tabGen = annElt.getAnnotation( TableGenerator.class );
SequenceGenerator seqGen = annElt.getAnnotation( SequenceGenerator.class );
GenericGenerator genGen = annElt.getAnnotation( GenericGenerator.class );
if ( tabGen != null ) {
IdGenerator idGen = buildIdGenerator( tabGen, mappings );
generators.put( idGen.getName(), idGen );
}
if ( seqGen != null ) {
IdGenerator idGen = buildIdGenerator( seqGen, mappings );
generators.put( idGen.getName(), idGen );
}
if ( genGen != null ) {
IdGenerator idGen = buildIdGenerator( genGen, mappings );
generators.put( idGen.getName(), idGen );
}
return generators;
}
public static boolean isDefault(XClass clazz, Mappings mappings) {
return mappings.getReflectionManager().equals( clazz, void.class );
}
/**
* For the mapped entities build some temporary data-structure containing information about the
* inheritance status of a class.
*
* @param orderedClasses Order list of all annotated entities and their mapped superclasses
*
* @return A map of {@code InheritanceState}s keyed against their {@code XClass}.
*/
public static Map<XClass, InheritanceState> buildInheritanceStates(
List<XClass> orderedClasses,
Mappings mappings) {
ReflectionManager reflectionManager = mappings.getReflectionManager();
Map<XClass, InheritanceState> inheritanceStatePerClass = new HashMap<XClass, InheritanceState>(
orderedClasses.size()
);
for ( XClass clazz : orderedClasses ) {
InheritanceState superclassState = InheritanceState.getSuperclassInheritanceState(
clazz, inheritanceStatePerClass
);
InheritanceState state = new InheritanceState( clazz, inheritanceStatePerClass, mappings );
if ( superclassState != null ) {
//the classes are ordered thus preventing an NPE
//FIXME if an entity has subclasses annotated @MappedSperclass wo sub @Entity this is wrong
superclassState.setHasSiblings( true );
InheritanceState superEntityState = InheritanceState.getInheritanceStateOfSuperEntity(
clazz, inheritanceStatePerClass
);
state.setHasParents( superEntityState != null );
final boolean nonDefault = state.getType() != null && !InheritanceType.SINGLE_TABLE
.equals( state.getType() );
if ( superclassState.getType() != null ) {
final boolean mixingStrategy = state.getType() != null && !state.getType()
.equals( superclassState.getType() );
if ( nonDefault && mixingStrategy ) {
LOG.invalidSubStrategy( clazz.getName() );
}
state.setType( superclassState.getType() );
}
}
inheritanceStatePerClass.put( clazz, state );
}
return inheritanceStatePerClass;
}
private static boolean hasAnnotationsOnIdClass(XClass idClass) {
// if(idClass.getAnnotation(Embeddable.class) != null)
// return true;
List<XProperty> properties = idClass.getDeclaredProperties( XClass.ACCESS_FIELD );
for ( XProperty property : properties ) {
if ( property.isAnnotationPresent( Column.class ) || property.isAnnotationPresent( OneToMany.class ) ||
property.isAnnotationPresent( ManyToOne.class ) || property.isAnnotationPresent( Id.class ) ||
property.isAnnotationPresent( GeneratedValue.class ) || property.isAnnotationPresent( OneToOne.class ) ||
property.isAnnotationPresent( ManyToMany.class )
) {
return true;
}
}
List<XMethod> methods = idClass.getDeclaredMethods();
for ( XMethod method : methods ) {
if ( method.isAnnotationPresent( Column.class ) || method.isAnnotationPresent( OneToMany.class ) ||
method.isAnnotationPresent( ManyToOne.class ) || method.isAnnotationPresent( Id.class ) ||
method.isAnnotationPresent( GeneratedValue.class ) || method.isAnnotationPresent( OneToOne.class ) ||
method.isAnnotationPresent( ManyToMany.class )
) {
return true;
}
}
return false;
}
}
|
3e0c23155674c2deeabcb1700a08a2180d71a299 | 4,380 | java | Java | raptor-api/raptor-common/src/main/java/org/createnet/raptor/common/query/AppQueryBuilder.java | raptorbox/raptor | 268fca7c7feb9ca483f49dbc5fd210a78ab6a332 | [
"Apache-2.0"
] | 15 | 2016-11-25T10:16:34.000Z | 2021-11-04T17:29:02.000Z | raptor-api/raptor-common/src/main/java/org/createnet/raptor/common/query/AppQueryBuilder.java | muka/raptor | 268fca7c7feb9ca483f49dbc5fd210a78ab6a332 | [
"Apache-2.0"
] | 38 | 2016-06-08T08:56:51.000Z | 2016-11-02T13:42:15.000Z | raptor-api/raptor-common/src/main/java/org/createnet/raptor/common/query/AppQueryBuilder.java | muka/raptor | 268fca7c7feb9ca483f49dbc5fd210a78ab6a332 | [
"Apache-2.0"
] | 7 | 2016-11-04T08:00:51.000Z | 2019-11-19T16:24:07.000Z | 27.872611 | 102 | 0.61426 | 5,152 | /*
* Copyright 2017 FBK/CREATE-NET
*
* 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.createnet.raptor.common.query;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.ListPath;
import com.querydsl.core.types.dsl.StringPath;
import org.createnet.raptor.models.app.AppUser;
import org.createnet.raptor.models.app.QApp;
import org.createnet.raptor.models.app.QAppUser;
import org.createnet.raptor.models.query.AppQuery;
import org.createnet.raptor.models.query.StringListQuery;
import org.createnet.raptor.models.query.TextQuery;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
/**
*
* @author Luca Capra <ychag@example.com>
*/
public class AppQueryBuilder {
private final AppQuery query;
public AppQueryBuilder(AppQuery query) {
this.query = query;
}
public Pageable getPaging() {
if (query.sortBy.getFields().isEmpty()) {
return new PageRequest(query.getOffset(), query.getLimit());
}
return new PageRequest(
query.getOffset(), query.getLimit(),
new Sort(
Sort.Direction.valueOf(query.sortBy.getDirection()),
query.sortBy.getFields()
));
}
public Predicate getPredicate() {
QApp app = new QApp("app");
BooleanBuilder predicate = new BooleanBuilder();
if (query.getUserId() != null) {
predicate.and(app.userId.eq(query.getUserId()));
}
// id
Predicate pid = buildTextQuery(query.id, app.id);
if (pid != null) {
predicate.and(pid);
}
// name
Predicate pname = buildTextQuery(query.name, app.name);
if (pname != null) {
predicate.and(pname);
}
// description
Predicate pdesc = buildTextQuery(query.description, app.description);
if (pdesc != null) {
predicate.and(pdesc);
}
//users (id)
Predicate users = buildAppUserListQuery(query.users, app.users);
if (users != null) {
predicate.and(users);
}
return predicate;
}
private Predicate buildTextQuery(TextQuery txt, StringPath txtfield) {
if (txt.isEmpty()) {
return null;
}
BooleanBuilder predicate = new BooleanBuilder();
if (txt.getContains() != null) {
predicate.and(txtfield.contains(txt.getContains()));
}
if (txt.getStartWith() != null) {
predicate.and(txtfield.startsWith(txt.getStartWith()));
}
if (txt.getEndWith() != null) {
predicate.and(txtfield.endsWith(txt.getEndWith()));
}
if (txt.getEquals() != null) {
predicate.and(txtfield.endsWith(txt.getEquals()));
}
if (!txt.getIn().isEmpty()) {
predicate.and(txtfield.in(txt.getIn()));
}
return predicate;
}
private Predicate buildListQuery(StringListQuery query, ListPath<String, StringPath> list) {
if (query.isEmpty()) {
return null;
}
BooleanBuilder predicate = new BooleanBuilder();
if (query.getIn() != null && query.getIn().isEmpty()) {
predicate.and(list.any().in(query.getIn()));
}
return predicate;
}
private Predicate buildAppUserListQuery(StringListQuery query, ListPath<AppUser, QAppUser> list) {
if (query.isEmpty()) {
return null;
}
BooleanBuilder predicate = new BooleanBuilder();
if (query.getIn() != null) {
predicate.and(list.any().id.in(query.getIn()));
}
return predicate;
}
}
|
3e0c2328aa899d7624fcb26cdbcf135032e1ee87 | 6,227 | java | Java | client-runtime/src/main/java/com/microsoft/rest/serializer/FlatteningSerializer.java | jianghaolu/autorest-clientruntime-for-java | 8fb9d515e2a26675052728c69597259ff9ca7115 | [
"MIT"
] | null | null | null | client-runtime/src/main/java/com/microsoft/rest/serializer/FlatteningSerializer.java | jianghaolu/autorest-clientruntime-for-java | 8fb9d515e2a26675052728c69597259ff9ca7115 | [
"MIT"
] | null | null | null | client-runtime/src/main/java/com/microsoft/rest/serializer/FlatteningSerializer.java | jianghaolu/autorest-clientruntime-for-java | 8fb9d515e2a26675052728c69597259ff9ca7115 | [
"MIT"
] | 1 | 2017-08-01T21:48:05.000Z | 2017-08-01T21:48:05.000Z | 42.360544 | 139 | 0.611691 | 5,153 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*/
package com.microsoft.rest.serializer;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
import com.fasterxml.jackson.databind.ser.ResolvableSerializer;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* Custom serializer for serializing types with wrapped properties.
* For example, a property with annotation @JsonProperty(value = "properties.name")
* will be mapped from a top level "name" property in the POJO model to
* {'properties' : { 'name' : 'my_name' }} in the serialized payload.
*/
public class FlatteningSerializer extends StdSerializer<Object> implements ResolvableSerializer {
/**
* The default mapperAdapter for the current type.
*/
private final JsonSerializer<?> defaultSerializer;
/**
* The object mapper for default serializations.
*/
private final ObjectMapper mapper;
/**
* Creates an instance of FlatteningSerializer.
* @param vc handled type
* @param defaultSerializer the default JSON serializer
* @param mapper the object mapper for default serializations
*/
protected FlatteningSerializer(Class<?> vc, JsonSerializer<?> defaultSerializer, ObjectMapper mapper) {
super(vc, false);
this.defaultSerializer = defaultSerializer;
this.mapper = mapper;
}
/**
* Gets a module wrapping this serializer as an adapter for the Jackson
* ObjectMapper.
*
* @param mapper the object mapper for default serializations
* @return a simple module to be plugged onto Jackson ObjectMapper.
*/
public static SimpleModule getModule(final ObjectMapper mapper) {
SimpleModule module = new SimpleModule();
module.setSerializerModifier(new BeanSerializerModifier() {
@Override
public JsonSerializer<?> modifySerializer(SerializationConfig config, BeanDescription beanDesc, JsonSerializer<?> serializer) {
if (beanDesc.getBeanClass().getAnnotation(JsonFlatten.class) != null) {
return new FlatteningSerializer(beanDesc.getBeanClass(), serializer, mapper);
}
return serializer;
}
});
return module;
}
@Override
public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
if (value == null) {
jgen.writeNull();
return;
}
// BFS for all collapsed properties
ObjectNode root = mapper.valueToTree(value);
ObjectNode res = root.deepCopy();
Queue<ObjectNode> source = new LinkedBlockingQueue<ObjectNode>();
Queue<ObjectNode> target = new LinkedBlockingQueue<ObjectNode>();
source.add(root);
target.add(res);
while (!source.isEmpty()) {
ObjectNode current = source.poll();
ObjectNode resCurrent = target.poll();
Iterator<Map.Entry<String, JsonNode>> fields = current.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> field = fields.next();
ObjectNode node = resCurrent;
String key = field.getKey();
JsonNode outNode = resCurrent.get(key);
if (field.getKey().matches(".+[^\\\\]\\..+")) {
String[] values = field.getKey().split("((?<!\\\\))\\.");
for (int i = 0; i < values.length; ++i) {
values[i] = values[i].replace("\\.", ".");
if (i == values.length - 1) {
break;
}
String val = values[i];
if (node.has(val)) {
node = (ObjectNode) node.get(val);
} else {
ObjectNode child = new ObjectNode(JsonNodeFactory.instance);
node.put(val, child);
node = child;
}
}
node.set(values[values.length - 1], resCurrent.get(field.getKey()));
resCurrent.remove(field.getKey());
outNode = node.get(values[values.length - 1]);
}
if (field.getValue() instanceof ObjectNode) {
source.add((ObjectNode) field.getValue());
target.add((ObjectNode) outNode);
} else if (field.getValue() instanceof ArrayNode
&& (field.getValue()).size() > 0
&& (field.getValue()).get(0) instanceof ObjectNode) {
Iterator<JsonNode> sourceIt = field.getValue().elements();
Iterator<JsonNode> targetIt = outNode.elements();
while (sourceIt.hasNext()) {
source.add((ObjectNode) sourceIt.next());
target.add((ObjectNode) targetIt.next());
}
}
}
}
jgen.writeTree(res);
}
@Override
public void resolve(SerializerProvider provider) throws JsonMappingException {
((ResolvableSerializer) defaultSerializer).resolve(provider);
}
}
|
3e0c247dbde1f0ce03dd65f27982542bf13dce61 | 404 | java | Java | AppService/src/main/java/com/service/base/ServiceApp.java | zhangsuixu/SynthesisTool | 8126f9864850729963ae327d60f5e63a4b490d94 | [
"Apache-2.0"
] | 8 | 2019-10-30T07:31:11.000Z | 2019-11-30T03:25:42.000Z | AppService/src/main/java/com/service/base/ServiceApp.java | zhangsuixu/SynthesisTool | 8126f9864850729963ae327d60f5e63a4b490d94 | [
"Apache-2.0"
] | null | null | null | AppService/src/main/java/com/service/base/ServiceApp.java | zhangsuixu/SynthesisTool | 8126f9864850729963ae327d60f5e63a4b490d94 | [
"Apache-2.0"
] | null | null | null | 18.363636 | 59 | 0.74505 | 5,154 | package com.service.base;
import android.app.Application;
import com.common.base.ComponentApplication;
import com.common.tools.LogUtil;
public class ServiceApp extends ComponentApplication {
@Override
protected void init(Application application) {
LogUtil.initLogger(DebugConfig.isDebug);//初始化日志打印工具
}
@Override
public void lazyInit(Application application) {
}
}
|
3e0c248f5c51b5a72b22b969799ce20cf0aea216 | 709 | java | Java | src/gscrot/uploader/imgbi/ImgbiUploader.java | redpois0n/gscrot-imgbi | f2947be6ae389383731d3337ce6a7b5bcea4c2d8 | [
"MIT"
] | 3 | 2015-05-10T17:22:53.000Z | 2015-06-23T22:33:10.000Z | src/gscrot/uploader/imgbi/ImgbiUploader.java | gscrot/gscrot-imgbi | f2947be6ae389383731d3337ce6a7b5bcea4c2d8 | [
"MIT"
] | null | null | null | src/gscrot/uploader/imgbi/ImgbiUploader.java | gscrot/gscrot-imgbi | f2947be6ae389383731d3337ce6a7b5bcea4c2d8 | [
"MIT"
] | null | null | null | 22.870968 | 66 | 0.729196 | 5,155 | package gscrot.uploader.imgbi;
import iconlib.IconUtils;
import com.redpois0n.gscrot.Capture;
import com.redpois0n.gscrot.CaptureUploader;
import com.redpois0n.gscrot.UploadResponse;
public class ImgbiUploader extends CaptureUploader {
public ImgbiUploader() {
super("Imgbi", IconUtils.getIcon("imgbi", ImgbiUploader.class));
}
@Override
public UploadResponse process(Capture capture) throws Exception {
String response = Imgbi.upload(capture.getBinary());
if (response.startsWith("ERROR: ")) {
throw new Exception(response);
} else {
String[] split = response.split("\n");
String url = split[0];
String rmurl = split[1];
return new UploadResponse(url, rmurl);
}
}
}
|
3e0c2493a13baf270a2434fdeb860762ebe5ca52 | 1,295 | java | Java | openapi-generator-for-spring-test/src/test/java/de/qaware/openapigeneratorforspring/test/app29/App29Test.java | MueChr/openapi-generator-for-spring | a3e9399fbb3c9ad80eee9a530c99524aea7fc15e | [
"Apache-2.0"
] | 56 | 2020-12-01T10:50:22.000Z | 2022-03-23T10:46:31.000Z | openapi-generator-for-spring-test/src/test/java/de/qaware/openapigeneratorforspring/test/app29/App29Test.java | MueChr/openapi-generator-for-spring | a3e9399fbb3c9ad80eee9a530c99524aea7fc15e | [
"Apache-2.0"
] | 74 | 2020-11-30T08:55:14.000Z | 2022-03-24T04:14:30.000Z | openapi-generator-for-spring-test/src/test/java/de/qaware/openapigeneratorforspring/test/app29/App29Test.java | MueChr/openapi-generator-for-spring | a3e9399fbb3c9ad80eee9a530c99524aea7fc15e | [
"Apache-2.0"
] | 4 | 2020-12-04T09:55:09.000Z | 2021-12-21T13:07:41.000Z | 41.774194 | 105 | 0.796139 | 5,156 | package de.qaware.openapigeneratorforspring.test.app29;
import de.qaware.openapigeneratorforspring.test.AbstractOpenApiGeneratorWebIntTest;
import de.qaware.openapigeneratorforspring.ui.swagger.SwaggerUiIndexHtmlWebJarResourceTransformerFactory;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.mock.mockito.SpyBean;
import org.springframework.test.context.TestPropertySource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@TestPropertySource(properties = {
"openapi-generator-for-spring.ui.cache-ui-resources=true",
"spring.main.web-application-type = REACTIVE"
})
class App29Test extends AbstractOpenApiGeneratorWebIntTest {
@SpyBean
private SwaggerUiIndexHtmlWebJarResourceTransformerFactory transformerFactory;
@Test
void testSwaggerUiIndexHtmlResourceIsCached() throws Exception {
assertThat(getResponseBody("/swagger-ui/index.html")).isNotBlank();
assertThat(getResponseBody("/swagger-ui/index.html")).contains(CSRF_TOKEN_HEADER_NAME);
// with caching, resource is only transformed once
verify(transformerFactory, times(1)).create(any(), any());
}
}
|
3e0c25e45df46873bb595dc92a741ca78af66336 | 3,172 | java | Java | src/main/java/com/fishercoder/solutions/_269.java | codingwhite/Leetcode-4 | 10dc650675a535ffef3e08154e2c091032145d5a | [
"Apache-2.0"
] | 4 | 2018-05-18T13:06:43.000Z | 2019-07-09T23:33:14.000Z | src/main/java/com/fishercoder/solutions/_269.java | codingwhite/Leetcode-4 | 10dc650675a535ffef3e08154e2c091032145d5a | [
"Apache-2.0"
] | null | null | null | src/main/java/com/fishercoder/solutions/_269.java | codingwhite/Leetcode-4 | 10dc650675a535ffef3e08154e2c091032145d5a | [
"Apache-2.0"
] | 7 | 2017-11-04T19:39:10.000Z | 2019-03-19T09:08:05.000Z | 32.040404 | 287 | 0.500315 | 5,157 | package com.fishercoder.solutions;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
/**
* There is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you. You receive a list of words from the dictionary, where words are sorted lexicographically by the rules of this new language. Derive the order of letters in this language.
For example,
Given the following words in dictionary,
[
"wrt",
"wrf",
"er",
"ett",
"rftt"
]
The correct order is: "wertf".
Note:
You may assume all letters are in lowercase.
If the order is invalid, return an empty string.
There may be multiple valid order of letters, return any one of them is fine.
*/
public class _269 {
/**reference: https://discuss.leetcode.com/topic/28308/java-ac-solution-using-bfs*/
public static String alienOrder(String[] words) {
Map<Character, Set<Character>> map = new HashMap();
Map<Character, Integer> degree = new HashMap<>();
String result = "";
if (words == null || words.length == 0) {
return result;
}
for (String s : words) {
for (char c : s.toCharArray()) {
degree.put(c, 0);//keeps overwriting it, the purpose is to create one entry
//for each letter in the degree map
}
}
for (int i = 0; i < words.length - 1; i++) {
String cur = words[i];
String next = words[i + 1];
int length = Math.min(cur.length(), next.length());
for (int j = 0; j < length; j++) {
char c1 = cur.charAt(j);
char c2 = next.charAt(j);
if (c1 != c2) {
Set<Character> set = new HashSet<>();
if (map.containsKey(c1)) {
set = map.get(c1);
}
if (!set.contains(c2)) {
set.add(c2);
map.put(c1, set);
degree.put(c2, degree.get(c2) + 1);
}
break;
}
}
}
Queue<Character> queue = new LinkedList<>();
for (char c : degree.keySet()) {
if (degree.get(c) == 0) {
queue.add(c);
}
}
while (!queue.isEmpty()) {
char c = queue.remove();
result += c;
if (map.containsKey(c)) {
for (char c2 : map.get(c)) {
degree.put(c2, degree.get(c2) - 1);
if (degree.get(c2) == 0) {
queue.add(c2);
}
}
}
}
if (result.length() != degree.size()) {
return "";
}
return result;
}
public static void main(String... args) {
System.out.println("Hello world.");
String[] words = new String[]{"wrt", "wrf", "er", "ett", "rftt"};
String order = alienOrder(words);
System.out.print(order);
}
}
|
3e0c26076d0cf9ec860153cd14c8a174e664ee47 | 196 | java | Java | model/src/main/java/de/thwiese/weather/model/supplier/ISupplier.java | thwiese/weather | 7400cf2c561c3988cee3a1dc56c5e77183161ac4 | [
"MIT"
] | null | null | null | model/src/main/java/de/thwiese/weather/model/supplier/ISupplier.java | thwiese/weather | 7400cf2c561c3988cee3a1dc56c5e77183161ac4 | [
"MIT"
] | null | null | null | model/src/main/java/de/thwiese/weather/model/supplier/ISupplier.java | thwiese/weather | 7400cf2c561c3988cee3a1dc56c5e77183161ac4 | [
"MIT"
] | null | null | null | 17.818182 | 47 | 0.755102 | 5,158 | package de.thwiese.weather.model.supplier;
import de.thwiese.weather.model.value.ValueSet;
public interface ISupplier {
String getVersion();
ValueSet grabValueSet(Object... params);
}
|
3e0c2636f87582cdfe9c0d5623ecaf51af9ca47a | 742 | java | Java | day07/src/com/company/Auto.java | lbfjoin/JavaSEcode | 89bd7e772c3616f193f5ce130610498b40e995ec | [
"Apache-2.0"
] | null | null | null | day07/src/com/company/Auto.java | lbfjoin/JavaSEcode | 89bd7e772c3616f193f5ce130610498b40e995ec | [
"Apache-2.0"
] | null | null | null | day07/src/com/company/Auto.java | lbfjoin/JavaSEcode | 89bd7e772c3616f193f5ce130610498b40e995ec | [
"Apache-2.0"
] | null | null | null | 16.488889 | 54 | 0.556604 | 5,159 | package com.company;
/**
* @author lbf
* @date 2020/5/31 19:20
*/
public class Auto {
private String brand;
private int length;
private int price;
public Auto() {
}
public Auto(String brand, int length, int price) {
this.brand = brand;
this.length = length;
this.price = price;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
|
3e0c2651fbf36189d8caa9afe73b0a62759075da | 541 | java | Java | app/src/main/java/com/antiless/template/receiver/DevicePolicyReceiver.java | auv1107/keep-alive-android | aab97abcbb5f93ed322fd472c5de3c26465ceab9 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/antiless/template/receiver/DevicePolicyReceiver.java | auv1107/keep-alive-android | aab97abcbb5f93ed322fd472c5de3c26465ceab9 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/antiless/template/receiver/DevicePolicyReceiver.java | auv1107/keep-alive-android | aab97abcbb5f93ed322fd472c5de3c26465ceab9 | [
"Apache-2.0"
] | null | null | null | 30.055556 | 66 | 0.744917 | 5,160 | package com.antiless.template.receiver;
import android.app.admin.DeviceAdminReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class DevicePolicyReceiver extends DeviceAdminReceiver {
@Override
public void onEnabled(Context context, Intent intent) {
Toast.makeText(context, "已开启", Toast.LENGTH_SHORT).show();
}
@Override
public void onDisabled(Context context, Intent intent) {
Toast.makeText(context, "已关闭", Toast.LENGTH_SHORT).show();
}
} |
3e0c289087757c1492425ae439c72b0fcf32b56e | 411 | java | Java | mclib/src/main/java/com/eliotlash/mclib/math/functions/classic/Exp.java | SimplyCmd/Terrariamod | d0629a589a38cf8eed380a2a2da73152ce815ae9 | [
"CC0-1.0"
] | 6 | 2020-05-13T00:03:50.000Z | 2021-12-04T16:09:50.000Z | mclib/src/main/java/com/eliotlash/mclib/math/functions/classic/Exp.java | SimplyCmd/Terrariamod | d0629a589a38cf8eed380a2a2da73152ce815ae9 | [
"CC0-1.0"
] | 6 | 2020-08-14T14:02:44.000Z | 2021-08-15T05:11:12.000Z | mclib/src/main/java/com/eliotlash/mclib/math/functions/classic/Exp.java | SimplyCmd/Terrariamod | d0629a589a38cf8eed380a2a2da73152ce815ae9 | [
"CC0-1.0"
] | 3 | 2020-10-19T20:03:53.000Z | 2021-09-09T02:38:38.000Z | 16.44 | 58 | 0.734793 | 5,161 | package com.eliotlash.mclib.math.functions.classic;
import com.eliotlash.mclib.math.IValue;
import com.eliotlash.mclib.math.functions.Function;
public class Exp extends Function
{
public Exp(IValue[] values, String name) throws Exception
{
super(values, name);
}
@Override
public int getRequiredArguments()
{
return 1;
}
@Override
public double get()
{
return Math.exp(this.getArg(0));
}
}
|
3e0c29ae92c807497f29e8195383688241cb125c | 1,514 | java | Java | uics-ippower-consumer/src/test/java/com/uics/ippower/consumer/RestClient.java | firefly-uics/uics-ippower | 373fb66e9e559183036cb326ced3cdbc7756c1f2 | [
"Apache-2.0"
] | null | null | null | uics-ippower-consumer/src/test/java/com/uics/ippower/consumer/RestClient.java | firefly-uics/uics-ippower | 373fb66e9e559183036cb326ced3cdbc7756c1f2 | [
"Apache-2.0"
] | null | null | null | uics-ippower-consumer/src/test/java/com/uics/ippower/consumer/RestClient.java | firefly-uics/uics-ippower | 373fb66e9e559183036cb326ced3cdbc7756c1f2 | [
"Apache-2.0"
] | null | null | null | 28.566038 | 103 | 0.642668 | 5,162 |
package com.uics.ippower.consumer;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* @author baiqw
*/
public class RestClient {
public static void main(String[] args) {
final String port = "8828";
signIn("http://localhost:" + port + "/api/v2/accounts/sign-in", MediaType.APPLICATION_JSON_TYPE);
}
private static void signIn(String url, MediaType mediaType) {
System.out.println("signIn account via " + url);
SignInVO account = new SignInVO();
account.setName("白群伟");
account.setPassword("123456");
From from = new From();
from.setAgentId("test");
from.setAgentName("R03025");
from.setAgentType("MacOS");
from.setClientVersion("1.0");
from.setLocation("1,2,3");
from.setOsVersion("10.10.5");
account.setFrom(from);
Client client = ClientBuilder.newClient();
WebTarget target = client.target(url);
Response response = target.request().post(Entity.entity(account, mediaType));
try {
if (response.getStatus() != 200) {
throw new RuntimeException("Failed with HTTP error code : " + response.getStatus());
}
System.out.println("Successfully got result: " + response.readEntity(String.class));
} finally {
response.close();
client.close();
}
}
}
|
3e0c2a73741e5108611b0ac43d7530f6d8518d57 | 5,000 | java | Java | starter/critter/src/main/java/com/udacity/jdnd/course3/critter/schedule/ScheduleService.java | welshimeat/nd035-c3-data-stores-and-persistence-project-starter | 624a966a82a0ec4f0ea98d5dd3cdf4df2eb98550 | [
"MIT"
] | null | null | null | starter/critter/src/main/java/com/udacity/jdnd/course3/critter/schedule/ScheduleService.java | welshimeat/nd035-c3-data-stores-and-persistence-project-starter | 624a966a82a0ec4f0ea98d5dd3cdf4df2eb98550 | [
"MIT"
] | null | null | null | starter/critter/src/main/java/com/udacity/jdnd/course3/critter/schedule/ScheduleService.java | welshimeat/nd035-c3-data-stores-and-persistence-project-starter | 624a966a82a0ec4f0ea98d5dd3cdf4df2eb98550 | [
"MIT"
] | null | null | null | 39.370079 | 125 | 0.6762 | 5,163 | package com.udacity.jdnd.course3.critter.schedule;
import com.udacity.jdnd.course3.critter.pet.Pet;
import com.udacity.jdnd.course3.critter.pet.PetDTO;
import com.udacity.jdnd.course3.critter.pet.PetRepository;
import com.udacity.jdnd.course3.critter.user.Customer;
import com.udacity.jdnd.course3.critter.user.CustomerRepository;
import com.udacity.jdnd.course3.critter.user.Employee;
import com.udacity.jdnd.course3.critter.user.EmployeeRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
@Transactional
@Service
public class ScheduleService {
@Autowired
private ScheduleRepository scheduleRepository;
@Autowired
private PetRepository petRepository;
@Autowired
private EmployeeRepository employeeRepository;
@Autowired
private CustomerRepository customerRepository;
public ScheduleDTO save(ScheduleDTO scheduleDTO){
System.out.println(scheduleDTO.getEmployeeIds());
Schedule schedule = convertScheduleDTOToEntity(scheduleDTO);
System.out.println(schedule.getEmployees());
schedule = scheduleRepository.save(schedule);
System.out.println(schedule.getEmployees());
return convertEntityToScheduleDTO(schedule);
}
public List<ScheduleDTO> getSchedules(){
List<Schedule> schedules = scheduleRepository.findAll();
List<ScheduleDTO> scheduleDTOs = new ArrayList<>();
for(Schedule schedule : schedules){
scheduleDTOs.add(convertEntityToScheduleDTO(schedule));
}
return scheduleDTOs;
}
public List<ScheduleDTO> getSchedulesByPet(Long petId){
Optional<Pet> optionalPet = petRepository.findById(petId);
if(optionalPet.isPresent()){
List<Schedule> schedules = scheduleRepository.findAllByPetsContaining(optionalPet.get());
List<ScheduleDTO> scheduleDTOs = new ArrayList<>();
for(Schedule schedule : schedules) {
scheduleDTOs.add(convertEntityToScheduleDTO(schedule));
}
return scheduleDTOs;
}
else {
throw new NullPointerException();
}
}
public List<ScheduleDTO> getSchedulesByEmployee(Long employeeId){
Optional<Employee> optionalEmployee = employeeRepository.findById(employeeId);
if(optionalEmployee.isPresent()){
List<Schedule> schedules = scheduleRepository.findAllByEmployeesContaining(optionalEmployee.get());
List<ScheduleDTO> scheduleDTOs = new ArrayList<>();
for(Schedule schedule : schedules) {
scheduleDTOs.add(convertEntityToScheduleDTO(schedule));
}
return scheduleDTOs;
}
else {
throw new NullPointerException();
}
}
public List<ScheduleDTO> getSchedulesByCustomer(Long customerId){
Optional<Customer> optionalCustomer = customerRepository.findById(customerId);
if(optionalCustomer.isPresent()){
List<Pet> pets = optionalCustomer.get().getPets();
List<Schedule> schedules = scheduleRepository.findAllByPetsIn(pets);
List<ScheduleDTO> scheduleDTOs = new ArrayList<>();
for(Schedule schedule : schedules) {
scheduleDTOs.add(convertEntityToScheduleDTO(schedule));
}
return scheduleDTOs;
}
else throw new NullPointerException();
}
private ScheduleDTO convertEntityToScheduleDTO(Schedule schedule){
ScheduleDTO scheduleDTO = new ScheduleDTO();
BeanUtils.copyProperties(schedule, scheduleDTO);
if(schedule.getPets() != null){
List<Long> pets = new ArrayList<>();
schedule.getPets().forEach(pet -> pets.add(pet.getId()));
scheduleDTO.setPetIds(pets);
}
if(schedule.getEmployees() != null){
List<Long> employees = new ArrayList<>();
schedule.getEmployees().forEach(employee -> employees.add(employee.getId()));
scheduleDTO.setEmployeeIds(employees);
}
return scheduleDTO;
}
private Schedule convertScheduleDTOToEntity(ScheduleDTO scheduleDTO){
Schedule schedule = new Schedule();
BeanUtils.copyProperties(scheduleDTO, schedule);
if(scheduleDTO.getPetIds() != null){
Set<Pet> pets = new HashSet<>();
scheduleDTO.getPetIds().forEach(petId -> pets.add(petRepository.findById(petId).get()));
schedule.setPets(pets);
}
if(scheduleDTO.getEmployeeIds() != null){
Set<Employee> employees = new HashSet<>();
scheduleDTO.getEmployeeIds().forEach(employeeId -> employees.add(employeeRepository.findById(employeeId).get()));
schedule.setEmployees(employees);
}
return schedule;
}
}
|
3e0c2ae965a743459fb31d6932de43f1f8a5dfaa | 37,748 | java | Java | src/fredy/share/JdbcTable.java | hulmen/SQLAdmin | ffda855149fce17001a3b1e43280dd9c7515018a | [
"MIT"
] | null | null | null | src/fredy/share/JdbcTable.java | hulmen/SQLAdmin | ffda855149fce17001a3b1e43280dd9c7515018a | [
"MIT"
] | null | null | null | src/fredy/share/JdbcTable.java | hulmen/SQLAdmin | ffda855149fce17001a3b1e43280dd9c7515018a | [
"MIT"
] | null | null | null | 37.22288 | 177 | 0.436016 | 5,164 | /*
Copyright (c) 2017 Fredy Fischer, envkt@example.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/*
this is a dynamic JTable created out of a SQL-Query
it can by called by different constructors:
- by a javax.sql.Connection
- by a sql.fredy.share.t_connect
- by hostname, username, userpassword and db so it will create a connecitn based of sql.fredy.share.t_connect
- by a JDBC-Driver and the connection URL
once instatiated without any error, you call the methode excuteQuery(String sqlquery) it will create the JTable and fill it with
the result of the query
to display this query add the JTable to a JPanel like
JFrame frame = new JFrame("My Query Result");
frame.getContentPane.setLayout(new BorderLayout());
JdbcTable table = new JdbcTable(connection);
table.executeQuery("select * from employee");
frame.getContentPane().add(BorderLayout.CENTER,new JScrollPane(table));
frame.pack();
frame.setVisible(true);
*/
package sql.fredy.share;
import java.math.BigDecimal;
import java.sql.Array;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
/**
*
* @author fredy
*/
public class JdbcTable extends AbstractTableModel {
private Connection con = null;
private Statement stmt = null;
private ResultSet rs = null;
private Logger logger = Logger.getLogger("sql.fredy.share");
private boolean connectionEstablished;
private String[] columnNames;
private String[] fieldNames;
private int[] columnTypes;
private ResultSetMetaData rsmd;
private Vector rows;
private int counter;
private boolean standalone = false;
private String SQLError;
private SimpleDateFormat sdf;
private SimpleDateFormat sdt;
private int maxRows = 10000;
private String nullTxt;
private boolean useNullTxt = true;
/*
instantiate JdbcTable with a java.sql.Connection
*/
public JdbcTable(Connection con) {
setNullTxt("NULL");
setCon(con);
setCounter(0);
try {
setStmt(con.createStatement());
} catch (SQLException sqlex) {
logSqlException("JdbcTable(Connection con)", Level.WARNING, sqlex);
setConnectionEstablished(false);
}
}
/*
instantiate JdbcTable with a sql.fredy.share.t_connext Object
*/
public JdbcTable(t_connect tcon) {
setNullTxt("NULL");
setCounter(0);
setCon(tcon.getCon());
setStmt(tcon.getStmt());
setConnectionEstablished(true);
}
/*
instantiate JdbcTable via t_connect but instantiate t_connect with host, user, password and the db name
*/
public JdbcTable(String host, String user, String password, String db) {
setNullTxt("NULL");
setCounter(0);
t_connect tcon = new t_connect(host, user, password, db);
setCon(tcon.getCon());
setStmt(tcon.getStmt());
setConnectionEstablished(true);
}
/*
instantiate JdbcTable by a JDBC-Driver and an URL
*/
public JdbcTable(String jdbcDriver, String jdbcUrl) {
setNullTxt("NULL");
setCounter(0);
try {
Class.forName(jdbcDriver);
setCon(DriverManager.getConnection(jdbcUrl));
setConnectionEstablished(true);
} catch (ClassNotFoundException ex) {
logException("JdbcTable(String jdbcDriver, String jdbcUrl)", Level.SEVERE, "can not load drvier class " + ex.getMessage());
setConnectionEstablished(false);
} catch (SQLException sqlex) {
logSqlException("JdbcTable(Connection con)", Level.WARNING, sqlex);
setConnectionEstablished(false);
}
}
public int getColumnType(int col) {
return columnTypes[col];
}
/*
close the Statement and the connection, use with care not to close your connection by fault
*/
public void close() {
logger.log(Level.INFO, "Closing connection");
try {
if (stmt != null) {
stmt.close();
}
if (con != null) {
con.close();
}
} catch (SQLException sqlex) {
logSqlException("close() ", Level.WARNING, sqlex);
}
}
public TableRowSorter<TableModel> getRowSorter() {
TableRowSorter<TableModel> rowSorter = new TableRowSorter<TableModel>(this);
for (int i = 0; i < getColumnCount(); i++) {
int type = columnTypes[i];
switch (type) {
case Types.ARRAY:
//newRow.add(rs.getArray(i));
break;
case Types.BIGINT:
//newRow.add((Long) rs.getLong(i));
try {
rowSorter.setComparator(i, new Comparator<Long>() {
@Override
public int compare(Long o1, Long o2) {
return o1.compareTo(o2);
}
});
} catch (Exception e) {
rowSorter = new TableRowSorter<TableModel>(this);
}
break;
case Types.BINARY:
//newRow.add((String) "BINARY not supported");
break;
case Types.BIT:
//newRow.add(rs.getBoolean(i));
break;
case Types.BLOB:
//newRow.add((String) "BLOB not supported");
break;
case Types.BOOLEAN:
//newRow.add(rs.getBoolean(i));
break;
case Types.CHAR:
//newRow.add((String) rs.getString(i));
break;
case Types.CLOB:
//newRow.add((String) "CLOB not supported");
break;
case Types.DATALINK:
//newRow.add((String) "DATALINK not supported");
break;
case Types.DATE:
//newRow.add((java.sql.Date) rs.getDate(i));
try {
rowSorter.setComparator(i, new Comparator<Date>() {
@Override
public int compare(Date o1, Date o2) {
if (o1.before(o2)) {
return -1;
}
if (o1.equals(o2)) {
return 0;
}
if (o1.after(o2)) {
return 1;
}
return 0;
}
});
} catch (Exception e) {
rowSorter = new TableRowSorter<TableModel>(this);
}
break;
case Types.DECIMAL:
//newRow.add((java.math.BigDecimal) rs.getBigDecimal(i));
try {
rowSorter.setComparator(i, new Comparator<BigDecimal>() {
@Override
public int compare(BigDecimal o1, BigDecimal o2) {
return o1.compareTo(o2);
}
});
} catch (Exception e) {
rowSorter = new TableRowSorter<TableModel>(this);
}
break;
case Types.DISTINCT:
//newRow.add((String) "DISTINCT not supported");
break;
case Types.DOUBLE:
//newRow.add((Double) rs.getDouble(i));
try {
rowSorter.setComparator(i, new Comparator<Double>() {
@Override
public int compare(Double o1, Double o2) {
return o1.compareTo(o2);
}
});
} catch (Exception e) {
rowSorter = new TableRowSorter<TableModel>(this);
}
break;
case Types.FLOAT:
//newRow.add((Float) rs.getFloat(i));
try {
rowSorter.setComparator(i, new Comparator<Float>() {
@Override
public int compare(Float o1, Float o2) {
return o1.compareTo(o2);
}
});
} catch (Exception e) {
rowSorter = new TableRowSorter<TableModel>(this);
}
break;
case Types.INTEGER:
//newRow.add((Integer) rs.getInt(i));
try {
rowSorter.setComparator(i, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
});
} catch (Exception e) {
rowSorter = new TableRowSorter<TableModel>(this);
}
break;
case Types.JAVA_OBJECT:
//newRow.add((String) "JAVA_OBJECT not supported");
break;
case Types.LONGNVARCHAR:
//newRow.add((String) rs.getString(i));
break;
case Types.LONGVARBINARY:
//newRow.add((String) "LONGVARBINARY not supported");
break;
case Types.LONGVARCHAR:
//newRow.add((String) rs.getString(i));
break;
case Types.NCHAR:
//newRow.add((String) rs.getString(i));
break;
case Types.NCLOB:
//newRow.add((String) "NCLOB not supported");
break;
case Types.NULL:
//newRow.add((String) "NULL Type not supported");
break;
case Types.NUMERIC:
//newRow.add((java.math.BigDecimal) rs.getBigDecimal(i));
break;
case Types.NVARCHAR:
//newRow.add((String) rs.getString(i));
break;
case Types.OTHER:
//newRow.add((String) "OTHER Type not supported");
break;
case Types.REAL:
//newRow.add((Float) rs.getFloat(i));
break;
case Types.REF:
//newRow.add((String) "REF Type not supported");
break;
case Types.REF_CURSOR:
//newRow.add((String) "REF_CURSOR Type not supported");
break;
case Types.ROWID:
//newRow.add((String) "ROWID Type not supported");
break;
case Types.SMALLINT:
//newRow.add((Integer) rs.getInt(i));
break;
case Types.SQLXML:
//newRow.add((String) rs.getString(i));
break;
case Types.STRUCT:
//newRow.add((String) "STRUCT Type not supported");
break;
case Types.TIME:
//newRow.add((java.sql.Time) rs.getTime(i));
try {
rowSorter.setComparator(i, new Comparator<java.sql.Time>() {
@Override
public int compare(java.sql.Time o1, java.sql.Time o2) {
if (o1.before(o2)) {
return -1;
}
if (o1.equals(o2)) {
return 0;
}
if (o1.after(o2)) {
return 1;
}
return 0;
}
});
} catch (Exception e) {
rowSorter = new TableRowSorter<TableModel>(this);
}
break;
case Types.TIMESTAMP:
//newRow.add((java.sql.Timestamp) rs.getTimestamp(i));
try {
rowSorter.setComparator(i, new Comparator<Timestamp>() {
@Override
public int compare(Timestamp o1, Timestamp o2) {
if (o1.before(o2)) {
return -1;
}
if (o1.equals(o2)) {
return 0;
}
if (o1.after(o2)) {
return 1;
}
return 0;
}
});
} catch (Exception e) {
// might come from a possible null value within a result
}
break;
case Types.TIMESTAMP_WITH_TIMEZONE:
//newRow.add((java.sql.Timestamp) rs.getTimestamp(i));
try {
rowSorter.setComparator(i, new Comparator<Timestamp>() {
@Override
public int compare(Timestamp o1, Timestamp o2) {
if (o1.before(o2)) {
return -1;
}
if (o1.equals(o2)) {
return 0;
}
if (o1.after(o2)) {
return 1;
}
return 0;
}
});
} catch (Exception e) {
rowSorter = new TableRowSorter<TableModel>(this);
}
break;
case Types.TIME_WITH_TIMEZONE:
//newRow.add((java.sql.Time) rs.getTime(i));
try {
rowSorter.setComparator(i, new Comparator<Time>() {
@Override
public int compare(Time o1, Time o2) {
if (o1.before(o2)) {
return -1;
}
if (o1.equals(o2)) {
return 0;
}
if (o1.after(o2)) {
return 1;
}
return 0;
}
});
} catch (Exception e) {
rowSorter = new TableRowSorter<TableModel>(this);
}
break;
case Types.TINYINT:
//newRow.add((Integer) rs.getInt(i));
break;
case Types.VARBINARY:
//newRow.add((String) "VARBINARY Type not supported");
break;
case Types.VARCHAR:
//newRow.add((String) rs.getString(i));
break;
default:
//newRow.add((String) rs.getString(i));
break;
}
}
return rowSorter;
}
/*
execute the query if a connection exists
@param query the SQL statement to be run
*/
public boolean executeQuery(String query) {
if (!isConnectionEstablished()) {
return false;
}
// max Row Count
TConnectProperties props = new TConnectProperties();
setMaxRows(Integer.parseInt(props.getDefaultMaxRowCount()));
//sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
//sdt = new SimpleDateFormat("HH:mm:ss.SSS");
sdf = (SimpleDateFormat) DateFormat.getDateTimeInstance();
sdt = (SimpleDateFormat) DateFormat.getTimeInstance();
Timestamp timestamp = null;
Time time = null;
java.sql.Date date = null;
try {
// we send the query to the DB
rs = getStmt().executeQuery(query);
// then we need the ResultSetMetaData
setRsmd(rs.getMetaData());
// we loop the result and add each row to the Vector
rows = new Vector();
setCounter(0);
while (rs.next()) {
// this is just one Line
Vector newRow = new Vector();
// thanks to the ResultSetMetaData, we now the number of columns
for (int i = 1; i <= getColumnCount(); i++) {
// Depending on the Type, we add every single value
int type = columnTypes[i - 1];
switch (type) {
case Types.ARRAY:
newRow.add(rs.getArray(i));
break;
case Types.BIGINT:
newRow.add((Long) rs.getLong(i));
break;
case Types.BINARY:
newRow.add((String) "BINARY not supported");
break;
case Types.BIT:
newRow.add(rs.getBoolean(i));
break;
case Types.BLOB:
newRow.add((String) "BLOB not supported");
break;
case Types.BOOLEAN:
newRow.add(rs.getBoolean(i));
break;
case Types.CHAR:
newRow.add((String) rs.getString(i));
break;
case Types.CLOB:
newRow.add((String) "CLOB not supported");
break;
case Types.DATALINK:
newRow.add((String) "DATALINK not supported");
break;
case Types.DATE:
newRow.add((java.sql.Date) rs.getDate(i));
break;
case Types.DECIMAL:
newRow.add((java.math.BigDecimal) rs.getBigDecimal(i));
break;
case Types.DISTINCT:
newRow.add((String) "DISTINCT not supported");
break;
case Types.DOUBLE:
newRow.add((Double) rs.getDouble(i));
break;
case Types.FLOAT:
newRow.add((Float) rs.getFloat(i));
break;
case Types.INTEGER:
newRow.add((Integer) rs.getInt(i));
break;
case Types.JAVA_OBJECT:
newRow.add((String) "JAVA_OBJECT not supported");
break;
case Types.LONGNVARCHAR:
newRow.add((String) rs.getString(i));
break;
case Types.LONGVARBINARY:
newRow.add((String) "LONGVARBINARY not supported");
break;
case Types.LONGVARCHAR:
newRow.add((String) rs.getString(i));
break;
case Types.NCHAR:
newRow.add((String) rs.getString(i));
break;
case Types.NCLOB:
newRow.add((String) "NCLOB not supported");
break;
case Types.NULL:
newRow.add((String) "NULL Type not supported");
break;
case Types.NUMERIC:
newRow.add((java.math.BigDecimal) rs.getBigDecimal(i));
break;
case Types.NVARCHAR:
newRow.add((String) rs.getString(i));
break;
case Types.OTHER:
newRow.add((String) "OTHER Type not supported");
break;
case Types.REAL:
newRow.add((Float) rs.getFloat(i));
break;
case Types.REF:
newRow.add((String) "REF Type not supported");
break;
case Types.REF_CURSOR:
newRow.add((String) "REF_CURSOR Type not supported");
break;
case Types.ROWID:
newRow.add((String) "ROWID Type not supported");
break;
case Types.SMALLINT:
newRow.add((Integer) rs.getInt(i));
break;
case Types.SQLXML:
newRow.add((String) rs.getString(i));
break;
case Types.STRUCT:
newRow.add((String) "STRUCT Type not supported");
break;
case Types.TIME:
//newRow.add((java.sql.Time) rs.getTime(i));
time = rs.getTime(i);
if (time != null) {
newRow.add(time);
//newRow.add((String) sdt.format(time.getTime()));
} else {
newRow.add((String) getNullTxt());
}
break;
case Types.TIMESTAMP:
newRow.add((java.sql.Timestamp) rs.getTimestamp(i));
// because JTable does format Timestmap as Date
/*
timestamp = rs.getTimestamp(i);
if (timestamp != null) {
newRow.add((String) sdf.format(timestamp.getTime()));
} else {
newRow.add((String) getNullTxt());
}
*/
break;
case Types.TIMESTAMP_WITH_TIMEZONE:
//newRow.add((java.sql.Timestamp) rs.getTimestamp(i));
timestamp = rs.getTimestamp(i);
if (timestamp != null) {
newRow.add((String) sdf.format(timestamp.getTime()));
} else {
newRow.add((String) getNullTxt());
}
break;
case Types.TIME_WITH_TIMEZONE:
//newRow.add((java.sql.Time) rs.getTime(i));
time = rs.getTime(i);
if (time != null) {
newRow.add(time);
//newRow.add((String) sdt.format(time.getTime()));
} else {
newRow.add((String) getNullTxt());
}
break;
case Types.TINYINT:
newRow.add((Integer) rs.getInt(i));
break;
case Types.VARBINARY:
newRow.add((String) "VARBINARY Type not supported");
break;
case Types.VARCHAR:
newRow.add((String) rs.getString(i));
break;
default:
newRow.add((String) rs.getString(i));
break;
}
if (rs.wasNull()) {
newRow.remove(newRow.size() - 1);
if ((getColumnClass(newRow.size() - 1) != String.class) || (!isUseNullTxt())) {
newRow.add(null);
} else {
newRow.add(getNullTxt());
}
}
}
rows.add(newRow);
/*
We limit the numbers of rows read to the value of maxRows.
This value is by default set to 10'000 if you set it to 0,
there will be no limit.
*/
counter++;
if ((getMaxRows() > 0) && (counter == getMaxRows())) {
break;
}
}
} catch (SQLException sqlex) {
logSqlException("executeQuery()", Level.WARNING, sqlex);
return false;
}
return true;
}
/*
log a SQLexception by providing the methode and the Exception
*/
private void logSqlException(String methode, Level level, SQLException sqlex) {
logger.log(level, "SQL Exception in {0} : {1} SQLState: {2} SQL Error Code: {3}", new Object[]{methode, sqlex.getMessage(), sqlex.getSQLState(), sqlex.getErrorCode()});
setSQLError("\tSQL Exception: " + sqlex.getMessage() + "\n\tSQL State: " + sqlex.getSQLState() + "\n\tError-Code: " + sqlex.getErrorCode() + "\n");
//sqlex.printStackTrace();
}
/*
log an exception by providing the methode and the Exception
*/
private void logException(String methode, Level level, String message) {
logger.log(level, "Exception in {0} : Message: {1} ", new Object[]{methode, message});
}
@Override
public int getRowCount() {
return rows.size();
}
public int getNumRows() {
return getRowCount();
}
@Override
public int getColumnCount() {
return columnNames.length;
}
public String getColumnName(int column) {
if (columnNames[column] != null) {
return columnNames[column];
} else {
return "";
}
}
public Class getColumnClass(int column) {
int type;
try {
type = getColumnType(column);
} catch (Exception e) {
if (column >= 0) {
logException("getColumnClass(" + column + ")", Level.WARNING, "Error fetching column class type, using default String.class. Exception: " + e.getMessage());
}
//e.printStackTrace();
return String.class;
}
switch (type) {
case Types.ARRAY:
return Array.class;
case Types.BIGINT:
return long.class;
case Types.BINARY:
return byte.class;
case Types.BIT:
return boolean.class;
case Types.BLOB:
return byte.class;
case Types.BOOLEAN:
return boolean.class;
case Types.CHAR:
return String.class;
case Types.CLOB:
return String.class;
case Types.DATALINK:
return Object.class;
case Types.DATE:
return java.sql.Date.class;
case Types.DECIMAL:
return java.math.BigDecimal.class;
case Types.DISTINCT:
return Object.class;
case Types.DOUBLE:
return double.class;
case Types.FLOAT:
return float.class;
case Types.INTEGER:
return int.class;
case Types.JAVA_OBJECT:
return Object.class;
case Types.LONGNVARCHAR:
return String.class;
case Types.LONGVARBINARY:
return Object.class;
case Types.LONGVARCHAR:
return String.class;
case Types.NCHAR:
return String.class;
case Types.NCLOB:
return Object.class;
case Types.NULL:
return Object.class;
case Types.NUMERIC:
return java.math.BigDecimal.class;
case Types.NVARCHAR:
return String.class;
case Types.OTHER:
return String.class;
case Types.REAL:
return float.class;
case Types.REF:
return Object.class;
case Types.REF_CURSOR:
return Object.class;
case Types.ROWID:
return Object.class;
case Types.SMALLINT:
return int.class;
case Types.SQLXML:
return String.class;
case Types.STRUCT:
return Object.class;
case Types.TIME:
// TIME is not correctly rendered
//return java.sql.Time.class;
return String.class;
case Types.TIMESTAMP:
// Timestamp is not correctly rendered
//return java.sql.Timestamp.class;
return String.class;
case Types.TIMESTAMP_WITH_TIMEZONE:
// Timestamp is not correctly rendered
//return java.sql.Timestamp.class;
return String.class;
case Types.TIME_WITH_TIMEZONE:
// TIME is not correctly rendered
//return java.sql.Time.class;
return String.class;
case Types.TINYINT:
return int.class;
case Types.VARBINARY:
return String.class;
case Types.VARCHAR:
return String.class;
default:
return Object.class;
}
}
public boolean isCellEditable(int row, int column) {
return false;
/*
is always false, in this case I do not want to write.. try {
*/
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Vector v = (Vector) rows.elementAt(rowIndex);
return (Object) v.elementAt(columnIndex);
}
/**
* @return the con
*/
public Connection getCon() {
return con;
}
/**
* @param con the con to set
*/
public void setCon(Connection con) {
this.con = con;
}
/**
* @return the stmt
*/
public Statement getStmt() {
return stmt;
}
/**
* @param stmt the stmt to set
*/
public void setStmt(Statement stmt) {
this.stmt = stmt;
}
/**
* @return the connectionEstablished
*/
public boolean isConnectionEstablished() {
return connectionEstablished;
}
/**
* @param connectionEstablished the connectionEstablished to set
*/
public void setConnectionEstablished(boolean connectionEstablished) {
this.connectionEstablished = connectionEstablished;
}
/**
* @return the rsmd
*/
public ResultSetMetaData getRsmd() {
return rsmd;
}
public ResultSetMetaData getMetaData() {
return rsmd;
}
/**
* @param rsmd the rsmd to set
*/
public void setRsmd(ResultSetMetaData rsmd) {
this.rsmd = rsmd;
try {
// we also set the Values for the JTable Headers
int noCols = rsmd.getColumnCount();
// and now we set the Column Headers and the fieldNames
columnNames = new String[noCols];
fieldNames = new String[noCols];
columnTypes = new int[noCols];
for (int i = 0; i < noCols; i++) {
columnNames[i] = rsmd.getColumnLabel(i + 1);
fieldNames[i] = rsmd.getColumnName(i + 1);
columnTypes[i] = rsmd.getColumnType(i + 1);
}
} catch (SQLException sqlex) {
logSqlException("setRsmd(ResultSetMetaData rsmd", Level.WARNING, sqlex);
}
}
/**
* @return the counter
*/
public int getCounter() {
return counter;
}
/**
* @param counter the counter to set
*/
public void setCounter(int counter) {
this.counter = counter;
}
/**
* @return the standalone
*/
public boolean isStandalone() {
return standalone;
}
/**
* @param standalone the standalone to set
*/
public void setStandalone(boolean standalone) {
this.standalone = standalone;
}
/**
* @return the SQLError
*/
public String getSQLError() {
return SQLError;
}
/**
* @param SQLError the SQLError to set
*/
public void setSQLError(String SQLError) {
this.SQLError = SQLError;
}
/**
* @return the maxRows
*/
public int getMaxRows() {
return maxRows;
}
public int getMaxRowCount() {
return maxRows;
}
/**
* @param maxRows the maxRows to set
*/
public void setMaxRows(int maxRows) {
this.maxRows = maxRows;
}
public void setMaxRowCount(int v) {
this.maxRows = v;
}
/**
* @return the nullTxt
*/
public String getNullTxt() {
return nullTxt;
}
/**
* @param nullTxt the nullTxt to set
*/
public void setNullTxt(String nullTxt) {
this.nullTxt = nullTxt;
}
/**
* @return the useNullTxt
*/
public boolean isUseNullTxt() {
return useNullTxt;
}
/**
* @param useNullTxt the useNullTxt to set
*/
public void setUseNullTxt(boolean useNullTxt) {
this.useNullTxt = useNullTxt;
}
}
|
3e0c2b139c9ada2bfe875998510fdec356c213dd | 531 | java | Java | jgiven-mockito-spring/src/main/java/de/ahus1/bdd/calculator/domain/Calculator.java | naimsaid/testing | 6543c64816883a957cc88ba50d6332cbcd05c456 | [
"Apache-2.0"
] | 12 | 2015-03-08T02:51:50.000Z | 2021-02-18T04:31:48.000Z | jgiven-mockito-spring/src/main/java/de/ahus1/bdd/calculator/domain/Calculator.java | naimsaid/testing | 6543c64816883a957cc88ba50d6332cbcd05c456 | [
"Apache-2.0"
] | null | null | null | jgiven-mockito-spring/src/main/java/de/ahus1/bdd/calculator/domain/Calculator.java | naimsaid/testing | 6543c64816883a957cc88ba50d6332cbcd05c456 | [
"Apache-2.0"
] | 10 | 2015-03-23T15:40:00.000Z | 2020-10-25T14:56:47.000Z | 16.59375 | 61 | 0.555556 | 5,165 | package de.ahus1.bdd.calculator.domain;
public class Calculator {
private long state = 0;
private long version;
public void reset() {
state = 0;
}
public void add(long val) {
state += val;
}
public long getState() {
return state;
}
public void setState(long val) {
state = val;
}
public void multiplyBy(long val) {
state *= val;
}
public void power(long val) {
state = new Double(Math.pow(state, val)).longValue();
}
}
|
3e0c2b8d7a2576763c428b6646c4b9b5e6df2bf5 | 1,774 | java | Java | src/main/java/com/simiacryptus/mindseye/pyramid/ValueSampler.java | SimiaCryptus/mindseye-vggart | b3513519a85c0f147a36298a392ca7f44595eccb | [
"Apache-2.0"
] | null | null | null | src/main/java/com/simiacryptus/mindseye/pyramid/ValueSampler.java | SimiaCryptus/mindseye-vggart | b3513519a85c0f147a36298a392ca7f44595eccb | [
"Apache-2.0"
] | null | null | null | src/main/java/com/simiacryptus/mindseye/pyramid/ValueSampler.java | SimiaCryptus/mindseye-vggart | b3513519a85c0f147a36298a392ca7f44595eccb | [
"Apache-2.0"
] | null | null | null | 31.122807 | 88 | 0.646561 | 5,166 | /*
* Copyright (c) 2019 by Andrew Charneski.
*
* The author 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.simiacryptus.mindseye.pyramid;
import java.io.Serializable;
public interface ValueSampler extends Serializable {
double getValue(final double xf, final double yf, final int band);
default ValueSampler wrapped() {
return (xf, yf, band) -> {
while (xf < 0) xf += 1;
xf %= 1;
while (yf < 0) yf += 1;
yf %= 1;
return ValueSampler.this.getValue(xf, yf, band);
};
}
default ValueSampler zoom(double x, double y, double width, double height) {
return zoom(width, height).offset(x, y);
}
default ValueSampler zoom(double width, double height) {
return (xf, yf, band) -> ValueSampler.this.getValue(xf * width, yf * height, band);
}
default ValueSampler offset(double x, double y) {
return (xf, yf, band) -> ValueSampler.this.getValue(x + xf, y + yf, band);
}
default ValueSampler rotate(double angle) {
return (xf, yf, band) -> ValueSampler.this.getValue(
Math.cos(angle) * xf + Math.sin(angle) * yf,
Math.cos(angle) * yf - Math.sin(angle) * xf,
band
);
}
}
|
3e0c2bf11a9dc38723ce8e99bb31545d881b52b7 | 729 | java | Java | anychart/src/main/java/com/anychart/core/stock/indicators/Base.java | gitdevstar/FinanicalApp | b9d8af5c6fd17a8f3f5ae178f31b9c9325fca012 | [
"Apache-2.0"
] | null | null | null | anychart/src/main/java/com/anychart/core/stock/indicators/Base.java | gitdevstar/FinanicalApp | b9d8af5c6fd17a8f3f5ae178f31b9c9325fca012 | [
"Apache-2.0"
] | null | null | null | anychart/src/main/java/com/anychart/core/stock/indicators/Base.java | gitdevstar/FinanicalApp | b9d8af5c6fd17a8f3f5ae178f31b9c9325fca012 | [
"Apache-2.0"
] | null | null | null | 17.780488 | 71 | 0.655693 | 5,167 | package com.anychart.core.stock.indicators;
import com.anychart.APIlib;
import com.anychart.chart.common.dataentry.DataEntry;
import com.anychart.JsObject;
import java.util.Locale;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import android.text.TextUtils;
// class
/**
*
*/
public class Base extends JsObject {
protected Base() {
}
public static Base instantiate() {
return new Base("new anychart.core.stock.indicators.base()");
}
public Base(String jsChart) {
jsBase = "base" + ++variableIndex;
APIlib.getInstance().addJSLine(jsBase + " = " + jsChart + ";");
}
public String getJsBase() {
return jsBase;
}
} |
3e0c2e1d89693280734163250a7aee6cabac83a4 | 642 | java | Java | java/debugger/impl/src/com/intellij/debugger/ui/tree/render/ValueIconRenderer.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/tree/render/ValueIconRenderer.java | nvartolomei/intellij-community | 1aac326dadacf65d45decc25cef21f94f7b80d69 | [
"Apache-2.0"
] | 1 | 2020-07-30T19:04:47.000Z | 2020-07-30T19:04:47.000Z | java/debugger/impl/src/com/intellij/debugger/ui/tree/render/ValueIconRenderer.java | nvartolomei/intellij-community | 1aac326dadacf65d45decc25cef21f94f7b80d69 | [
"Apache-2.0"
] | 1 | 2020-10-15T05:56:42.000Z | 2020-10-15T05:56:42.000Z | 40.125 | 140 | 0.827103 | 5,168 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.debugger.ui.tree.render;
import com.intellij.debugger.engine.evaluation.EvaluateException;
import com.intellij.debugger.engine.evaluation.EvaluationContext;
import com.intellij.debugger.ui.tree.ValueDescriptor;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
public interface ValueIconRenderer {
@Nullable
Icon calcValueIcon(ValueDescriptor descriptor, EvaluationContext evaluationContext, DescriptorLabelListener listener)
throws EvaluateException;
}
|
3e0c2e95b2800396c106cd674605cc8c079ef1b0 | 112,677 | java | Java | SimianArmy/345ad9513aafff397050d613fa87ad06ddffe99d/evosuite_2/evosuite-tests/com/netflix/simianarmy/basic/janitor/BasicJanitorMonkeyContext_ESTest_scaffolding.java | leusonmario/2022PhDThesis | 22969dccdafbc02f022633e9b4c4346821da1402 | [
"MIT"
] | null | null | null | SimianArmy/345ad9513aafff397050d613fa87ad06ddffe99d/evosuite_2/evosuite-tests/com/netflix/simianarmy/basic/janitor/BasicJanitorMonkeyContext_ESTest_scaffolding.java | leusonmario/2022PhDThesis | 22969dccdafbc02f022633e9b4c4346821da1402 | [
"MIT"
] | null | null | null | SimianArmy/345ad9513aafff397050d613fa87ad06ddffe99d/evosuite_2/evosuite-tests/com/netflix/simianarmy/basic/janitor/BasicJanitorMonkeyContext_ESTest_scaffolding.java | leusonmario/2022PhDThesis | 22969dccdafbc02f022633e9b4c4346821da1402 | [
"MIT"
] | null | null | null | 62.012658 | 184 | 0.765986 | 5,169 | /**
* Scaffolding file used to store all the setups needed to run
* tests automatically generated by EvoSuite
* Wed Nov 03 01:49:17 GMT 2021
*/
package com.netflix.simianarmy.basic.janitor;
import org.evosuite.runtime.annotation.EvoSuiteClassExclude;
import org.junit.BeforeClass;
import org.junit.Before;
import org.junit.After;
import org.junit.AfterClass;
import org.evosuite.runtime.sandbox.Sandbox;
import org.evosuite.runtime.sandbox.Sandbox.SandboxMode;
@EvoSuiteClassExclude
public class BasicJanitorMonkeyContext_ESTest_scaffolding {
@org.junit.Rule
public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule();
private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone();
private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 10000);
@BeforeClass
public static void initEvoSuiteFramework() {
org.evosuite.runtime.RuntimeSettings.className = "com.netflix.simianarmy.basic.janitor.BasicJanitorMonkeyContext";
org.evosuite.runtime.GuiSupport.initialize();
org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100;
org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000;
org.evosuite.runtime.RuntimeSettings.mockSystemIn = true;
org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED;
org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT();
org.evosuite.runtime.classhandling.JDKClassResetter.init();
setSystemProperties();
initializeClasses();
org.evosuite.runtime.Runtime.getInstance().resetRuntime();
}
@AfterClass
public static void clearEvoSuiteFramework(){
Sandbox.resetDefaultSecurityManager();
java.lang.System.setProperties((java.util.Properties) defaultProperties.clone());
}
@Before
public void initTestCase(){
threadStopper.storeCurrentThreads();
threadStopper.startRecordingTime();
org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler();
org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode();
setSystemProperties();
org.evosuite.runtime.GuiSupport.setHeadless();
org.evosuite.runtime.Runtime.getInstance().resetRuntime();
org.evosuite.runtime.agent.InstrumentingAgent.activate();
}
@After
public void doneWithTestCase(){
threadStopper.killAndJoinClientThreads();
org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks();
org.evosuite.runtime.classhandling.JDKClassResetter.reset();
resetClasses();
org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode();
org.evosuite.runtime.agent.InstrumentingAgent.deactivate();
org.evosuite.runtime.GuiSupport.restoreHeadlessMode();
}
public static void setSystemProperties() {
java.lang.System.setProperties((java.util.Properties) defaultProperties.clone());
java.lang.System.setProperty("file.encoding", "UTF-8");
java.lang.System.setProperty("java.awt.headless", "true");
java.lang.System.setProperty("java.io.tmpdir", "/tmp");
java.lang.System.setProperty("user.country", "US");
java.lang.System.setProperty("user.dir", "/home/CIN/lmps2/semantic-conflict-study/SMAT/output-test-dest/SimianArmy/345ad9513aafff397050d613fa87ad06ddffe99d/evosuite_2");
java.lang.System.setProperty("user.home", "/home/CIN/lmps2");
java.lang.System.setProperty("user.language", "en");
java.lang.System.setProperty("user.name", "lmps2");
java.lang.System.setProperty("user.timezone", "America/Recife");
java.lang.System.setProperty("sun.management.compiler", "HotSpot 64-Bit Tiered Compilers");
}
private static void initializeClasses() {
org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(BasicJanitorMonkeyContext_ESTest_scaffolding.class.getClassLoader() ,
"org.apache.commons.lang.StringUtils",
"com.netflix.simianarmy.janitor.AbstractJanitor$Context",
"com.amazonaws.auth.DefaultAWSCredentialsProviderChain",
"com.fasterxml.jackson.databind.deser.BeanDeserializerModifier",
"com.amazonaws.event.ProgressListener$1",
"com.google.common.collect.Collections2",
"com.netflix.simianarmy.conformity.ConformityMonkey$Type",
"com.fasterxml.jackson.databind.deser.std.EnumDeserializer",
"com.fasterxml.jackson.annotation.ObjectIdGenerators$Base",
"com.amazonaws.services.simpleemail.model.SetIdentityNotificationTopicRequest",
"org.apache.http.impl.conn.SystemDefaultDnsResolver",
"com.fasterxml.jackson.databind.cfg.MapperConfigBase",
"com.fasterxml.jackson.databind.deser.std.DateDeserializers$CalendarDeserializer",
"com.fasterxml.jackson.databind.deser.std.StdKeyDeserializers",
"com.amazonaws.auth.AWSCredentials",
"com.fasterxml.jackson.databind.type.MapLikeType",
"com.fasterxml.jackson.databind.type.MapType",
"com.amazonaws.handlers.RequestHandler2",
"com.amazonaws.internal.config.SignerConfig",
"com.amazonaws.services.simpleemail.model.SendEmailRequest",
"com.fasterxml.jackson.databind.type.TypeBase",
"com.fasterxml.jackson.databind.deser.impl.ManagedReferenceProperty",
"org.apache.http.pool.AbstractConnPool$1",
"org.apache.http.conn.ssl.AllowAllHostnameVerifier",
"com.fasterxml.jackson.databind.ser.std.DateTimeSerializerBase",
"com.fasterxml.jackson.databind.deser.BeanDeserializerBuilder",
"com.amazonaws.http.ConnectionManagerFactory",
"com.fasterxml.jackson.databind.deser.std.JacksonDeserializers",
"org.apache.http.client.CredentialsProvider",
"com.netflix.simianarmy.janitor.AbstractJanitor",
"com.amazonaws.AmazonClientException",
"com.fasterxml.jackson.annotation.JsonIgnoreProperties",
"com.google.common.base.Joiner",
"org.apache.http.params.HttpConnectionParams",
"com.fasterxml.jackson.databind.node.DecimalNode",
"com.netflix.simianarmy.basic.janitor.BasicJanitorMonkeyContext$BasicJanitorContext",
"com.amazonaws.transform.Unmarshaller",
"com.fasterxml.jackson.databind.deser.Deserializers",
"org.apache.http.conn.ssl.AbstractVerifier",
"com.google.common.collect.Lists$Partition",
"com.fasterxml.jackson.databind.deser.KeyDeserializers",
"com.fasterxml.jackson.databind.type.CollectionLikeType",
"org.apache.http.HttpClientConnection",
"org.apache.http.conn.ssl.SSLContexts",
"com.fasterxml.jackson.databind.deser.ValueInstantiator",
"com.amazonaws.services.simpledb.model.transform.InvalidQueryExpressionExceptionUnmarshaller",
"org.apache.http.protocol.HttpProcessor",
"com.netflix.simianarmy.MonkeyEmailNotifier",
"com.netflix.simianarmy.NotFoundException",
"com.amazonaws.internal.SdkFilterInputStream",
"com.netflix.simianarmy.aws.janitor.rule.asg.OldEmptyASGRule",
"com.netflix.simianarmy.NamedType",
"com.fasterxml.jackson.databind.introspect.BasicClassIntrospector",
"com.fasterxml.jackson.core.base.ParserMinimalBase",
"com.amazonaws.services.simpledb.model.TooManyRequestedAttributesException",
"com.fasterxml.jackson.databind.deser.BeanDeserializerBase",
"com.fasterxml.jackson.annotation.JsonSetter",
"com.netflix.simianarmy.basic.janitor.BasicJanitorEmailBuilder",
"com.google.common.base.Joiner$1",
"com.google.common.base.Joiner$2",
"com.fasterxml.jackson.core.SerializableString",
"com.fasterxml.jackson.core.Versioned",
"com.google.common.collect.ImmutableEnumMap",
"com.netflix.simianarmy.chaos.ChaosCrawler$InstanceGroup",
"com.netflix.simianarmy.basic.janitor.BasicVolumeTaggingMonkeyContext",
"com.amazonaws.internal.config.SignerConfigJsonHelper",
"org.apache.http.conn.scheme.SchemeLayeredSocketFactory",
"org.apache.http.params.CoreConnectionPNames",
"com.amazonaws.jmx.spi.SdkMBeanRegistry",
"com.netflix.simianarmy.basic.BasicChaosMonkeyContext",
"com.fasterxml.jackson.databind.deser.std.EnumSetDeserializer",
"org.apache.http.cookie.CookieSpecFactory",
"com.fasterxml.jackson.databind.introspect.AnnotatedMember",
"org.apache.http.impl.client.DefaultRedirectStrategy",
"com.fasterxml.jackson.databind.BeanDescription",
"com.amazonaws.services.simpledb.model.transform.NumberSubmittedAttributesExceededExceptionUnmarshaller",
"com.netflix.simianarmy.conformity.ClusterCrawler",
"com.google.common.collect.Lists$AbstractListWrapper",
"com.amazonaws.http.impl.client.HttpRequestNoRetryHandler",
"com.netflix.simianarmy.conformity.ConformityClusterTracker",
"org.apache.http.pool.PoolEntryCallback",
"com.amazonaws.services.simpleemail.AmazonSimpleEmailService",
"com.fasterxml.jackson.databind.introspect.AnnotatedWithParams",
"org.apache.http.pool.ConnFactory",
"com.netflix.simianarmy.basic.BasicSimianArmyContext",
"com.fasterxml.jackson.databind.deser.std.NumberDeserializers$IntegerDeserializer",
"com.google.common.collect.Lists$2",
"com.fasterxml.jackson.databind.annotation.JsonNaming",
"com.google.common.collect.Lists$1",
"org.joda.time.format.DateTimeFormatterBuilder$PaddedNumber",
"com.amazonaws.services.simpleemail.model.VerifyDomainDkimRequest",
"com.fasterxml.jackson.annotation.JsonPropertyOrder",
"com.netflix.simianarmy.janitor.Rule",
"com.fasterxml.jackson.databind.type.SimpleType",
"com.fasterxml.jackson.databind.deser.std.JdkDeserializers$CurrencyDeserializer",
"com.fasterxml.jackson.databind.ser.ContextualSerializer",
"com.netflix.simianarmy.basic.chaos.BasicChaosEmailNotifier",
"com.fasterxml.jackson.databind.DeserializationConfig",
"com.fasterxml.jackson.databind.MapperFeature",
"com.fasterxml.jackson.core.util.InternCache",
"com.netflix.simianarmy.aws.janitor.crawler.LaunchConfigJanitorCrawler",
"com.amazonaws.retry.PredefinedRetryPolicies$DynamoDBDefaultBackoffStrategy",
"com.fasterxml.jackson.databind.node.ContainerNode",
"com.fasterxml.jackson.databind.ser.std.NumberSerializers$LongSerializer",
"com.fasterxml.jackson.databind.deser.BeanDeserializerFactory",
"com.amazonaws.util.UnreliableFilterInputStream",
"org.joda.time.format.DateTimeFormatterBuilder$NumberFormatter",
"com.fasterxml.jackson.databind.AbstractTypeResolver",
"org.apache.http.client.UserTokenHandler",
"com.fasterxml.jackson.databind.ser.std.NumberSerializers$DoubleSerializer",
"com.netflix.simianarmy.janitor.JanitorMonkey",
"com.fasterxml.jackson.core.Base64Variants",
"com.fasterxml.jackson.databind.ser.std.StdJdkSerializers$AtomicIntegerSerializer",
"com.google.common.collect.Maps$EntryTransformer",
"com.netflix.simianarmy.MonkeyRecorder",
"com.amazonaws.RequestClientOptions$Marker",
"com.fasterxml.jackson.core.io.IOContext",
"org.apache.http.conn.ConnectionReleaseTrigger",
"com.amazonaws.auth.AWS3Signer",
"com.fasterxml.jackson.databind.deser.impl.BeanPropertyMap$IteratorImpl",
"org.apache.http.client.methods.HttpPost",
"com.amazonaws.jmx.SdkMBeanRegistrySupport",
"com.fasterxml.jackson.databind.ser.BeanSerializer",
"org.joda.time.format.DateTimeFormatterBuilder$StringLiteral",
"com.netflix.simianarmy.basic.conformity.BasicConformityEmailBuilder",
"com.fasterxml.jackson.databind.node.NullNode",
"com.netflix.simianarmy.MonkeyConfiguration",
"com.amazonaws.transform.StandardErrorUnmarshaller",
"com.fasterxml.jackson.databind.ser.BeanSerializerModifier",
"org.apache.http.HttpMessage",
"com.fasterxml.jackson.databind.ser.std.EnumMapSerializer",
"com.amazonaws.retry.RetryPolicy$BackoffStrategy",
"com.fasterxml.jackson.annotation.ObjectIdGenerators$PropertyGenerator",
"com.fasterxml.jackson.core.io.UTF8Writer",
"org.apache.http.conn.scheme.SchemeSocketFactory",
"com.fasterxml.jackson.databind.deser.impl.BeanPropertyMap$Bucket",
"com.fasterxml.jackson.databind.introspect.POJOPropertiesCollector",
"com.google.common.collect.SortedMapDifference",
"com.amazonaws.services.simpleemail.model.DeleteVerifiedEmailAddressRequest",
"com.netflix.simianarmy.MonkeyRecorder$Event",
"org.apache.http.impl.conn.HttpPoolEntry",
"com.amazonaws.services.simpleemail.model.GetIdentityNotificationAttributesRequest",
"com.fasterxml.jackson.databind.deser.std.PrimitiveArrayDeserializers$ShortDeser",
"com.fasterxml.jackson.core.JsonGenerator",
"com.fasterxml.jackson.databind.deser.DefaultDeserializationContext",
"org.apache.http.protocol.HttpRequestExecutor",
"com.amazonaws.services.simpleemail.model.DeleteIdentityRequest",
"com.fasterxml.jackson.databind.ext.OptionalHandlerFactory",
"org.apache.http.conn.ConnectTimeoutException",
"com.fasterxml.jackson.core.JsonGenerationException",
"com.netflix.simianarmy.conformity.ConformityEmailNotifier$Context",
"com.amazonaws.Protocol",
"com.netflix.simianarmy.chaos.ChaosMonkey",
"com.fasterxml.jackson.databind.ser.std.JsonValueSerializer",
"com.fasterxml.jackson.core.json.UTF8JsonGenerator",
"com.fasterxml.jackson.databind.ser.std.SerializableSerializer",
"org.apache.http.ProtocolVersion",
"com.fasterxml.jackson.databind.deser.std.StdValueInstantiator",
"com.fasterxml.jackson.databind.util.TokenBuffer",
"com.amazonaws.jmx.MBeans",
"com.fasterxml.jackson.core.util.DefaultPrettyPrinter$NopIndenter",
"com.fasterxml.jackson.core.json.WriterBasedJsonGenerator",
"com.amazonaws.services.simpledb.model.transform.DuplicateItemNameExceptionUnmarshaller",
"com.fasterxml.jackson.databind.node.LongNode",
"com.fasterxml.jackson.databind.util.Provider",
"com.google.common.collect.ImmutableEnumSet",
"com.fasterxml.jackson.databind.deser.CreatorProperty",
"com.netflix.simianarmy.aws.janitor.VolumeTaggingMonkey$Context",
"com.netflix.simianarmy.chaos.ChaosMonkey$Context",
"com.fasterxml.jackson.core.JsonParseException",
"com.google.common.base.Converter",
"com.fasterxml.jackson.databind.ser.std.TokenBufferSerializer",
"org.joda.time.format.DateTimeFormat",
"org.apache.http.conn.ssl.SSLInitializationException",
"org.apache.commons.lang.text.StrTokenizer",
"com.fasterxml.jackson.databind.deser.std.PrimitiveArrayDeserializers$FloatDeser",
"com.fasterxml.jackson.databind.ser.std.MapSerializer",
"org.apache.http.HttpResponseInterceptor",
"com.fasterxml.jackson.databind.util.RootNameLookup",
"com.amazonaws.transform.AbstractErrorUnmarshaller",
"com.fasterxml.jackson.databind.ser.impl.FailingSerializer",
"com.amazonaws.services.simpledb.model.transform.NumberDomainAttributesExceededExceptionUnmarshaller",
"com.fasterxml.jackson.databind.JsonMappingException",
"com.fasterxml.jackson.databind.deser.std.DateDeserializers$SqlDateDeserializer",
"com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer",
"com.fasterxml.jackson.databind.ser.std.SqlTimeSerializer",
"org.apache.http.conn.ClientConnectionRequest",
"com.amazonaws.auth.Presigner",
"com.fasterxml.jackson.databind.util.BeanUtil",
"com.fasterxml.jackson.databind.deser.std.DateDeserializers$DateDeserializer",
"com.netflix.simianarmy.janitor.JanitorEmailBuilder",
"com.amazonaws.services.simpleemail.model.GetIdentityDkimAttributesRequest",
"com.fasterxml.jackson.core.io.SerializedString",
"com.fasterxml.jackson.core.util.DefaultPrettyPrinter$FixedSpaceIndenter",
"com.fasterxml.jackson.annotation.JsonFormat$Shape",
"com.netflix.simianarmy.aws.janitor.rule.snapshot.NoGeneratedAMIRule",
"com.amazonaws.services.ec2.model.Instance",
"com.amazonaws.AmazonWebServiceRequest$1",
"org.apache.http.conn.scheme.SchemeRegistry",
"com.fasterxml.jackson.databind.deser.ContextualDeserializer",
"com.amazonaws.retry.PredefinedRetryPolicies",
"com.netflix.simianarmy.aws.conformity.SimpleDBConformityClusterTracker",
"com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$BoolKD",
"com.fasterxml.jackson.annotation.ObjectIdGenerator",
"com.netflix.simianarmy.aws.janitor.VolumeTaggingMonkey$EventTypes",
"com.fasterxml.jackson.databind.ser.std.CalendarSerializer",
"org.joda.time.UTCDateTimeZone",
"com.fasterxml.jackson.databind.deser.std.NumberDeserializers$BigIntegerDeserializer",
"com.netflix.simianarmy.client.MonkeyRestClient",
"com.amazonaws.internal.config.InternalConfig",
"com.fasterxml.jackson.databind.deser.std.JacksonDeserializers$JsonLocationInstantiator",
"com.fasterxml.jackson.databind.deser.std.ClassDeserializer",
"com.fasterxml.jackson.databind.ser.std.BooleanSerializer",
"com.amazonaws.services.simpledb.model.transform.MissingParameterExceptionUnmarshaller",
"org.apache.http.HttpConnection",
"com.netflix.simianarmy.janitor.Janitor",
"com.fasterxml.jackson.annotation.JsonProperty",
"com.amazonaws.auth.QueryStringSigner",
"com.fasterxml.jackson.databind.deser.std.JdkDeserializers$URIDeserializer",
"com.google.common.collect.Lists$RandomAccessPartition",
"com.amazonaws.RequestClientOptions",
"com.fasterxml.jackson.databind.deser.std.JdkDeserializers$URLDeserializer",
"com.amazonaws.services.simpledb.model.transform.NoSuchDomainExceptionUnmarshaller",
"com.fasterxml.jackson.databind.deser.std.CollectionDeserializer",
"com.fasterxml.jackson.databind.deser.std.DateDeserializers$DateBasedDeserializer",
"com.fasterxml.jackson.databind.type.TypeFactory",
"com.fasterxml.jackson.databind.type.ArrayType",
"com.amazonaws.services.simpleemail.model.VerifyEmailAddressRequest",
"com.netflix.simianarmy.aws.conformity.rule.InstanceInSecurityGroup",
"com.amazonaws.services.simpledb.model.ListDomainsRequest",
"com.amazonaws.internal.CRC32MismatchException",
"com.netflix.simianarmy.aws.janitor.rule.asg.DummyASGInstanceValidator",
"com.amazonaws.auth.profile.ProfileCredentialsProvider",
"com.fasterxml.jackson.databind.util.Named",
"org.apache.http.impl.conn.SchemeRegistryFactory",
"com.fasterxml.jackson.databind.deser.std.StringCollectionDeserializer",
"com.fasterxml.jackson.databind.ser.std.StdScalarSerializer",
"com.fasterxml.jackson.annotation.JsonAutoDetect",
"com.amazonaws.services.simpledb.model.BatchPutAttributesRequest",
"com.netflix.simianarmy.conformity.ConformityRule",
"com.fasterxml.jackson.databind.deser.std.EnumMapDeserializer",
"com.amazonaws.services.simpledb.model.NumberSubmittedAttributesExceededException",
"com.fasterxml.jackson.databind.deser.SettableBeanProperty",
"com.amazonaws.metrics.RequestMetricType",
"org.apache.commons.lang.Validate",
"com.netflix.simianarmy.aws.janitor.EBSSnapshotJanitor",
"org.apache.http.conn.scheme.PlainSocketFactory",
"org.apache.http.client.ClientProtocolException",
"com.netflix.simianarmy.conformity.ConformityEmailNotifier",
"com.amazonaws.internal.config.Builder",
"com.fasterxml.jackson.core.json.ByteSourceJsonBootstrapper",
"org.apache.http.client.methods.HttpHead",
"org.apache.http.params.AbstractHttpParams",
"org.apache.http.impl.conn.HttpConnPool$InternalConnFactory",
"com.fasterxml.jackson.databind.type.TypeParser",
"com.fasterxml.jackson.databind.jsontype.SubtypeResolver",
"com.fasterxml.jackson.databind.deser.std.NumberDeserializers",
"com.amazonaws.auth.EnvironmentVariableCredentialsProvider",
"com.amazonaws.util.AwsHostNameUtils",
"com.amazonaws.util.TimingInfoFullSupport",
"com.amazonaws.http.protocol.SdkHttpRequestExecutor",
"com.google.common.collect.Lists",
"org.apache.http.client.methods.AbstractExecutionAwareRequest",
"org.apache.http.pool.PoolStats",
"com.netflix.simianarmy.conformity.ConformityMonkey",
"com.fasterxml.jackson.databind.deser.std.PrimitiveArrayDeserializers$CharDeser",
"com.netflix.simianarmy.basic.BasicConfiguration",
"com.fasterxml.jackson.databind.deser.std.JdkDeserializers$CharsetDeserializer",
"org.apache.http.conn.ConnectionPoolTimeoutException",
"com.google.common.collect.Maps$BiMapConverter",
"com.amazonaws.http.IdleConnectionReaper",
"org.apache.http.client.RedirectStrategy",
"com.fasterxml.jackson.databind.deser.std.JacksonDeserializers$TokenBufferDeserializer",
"com.amazonaws.ClientConfiguration",
"com.amazonaws.http.conn.ClientConnectionManagerFactory",
"com.amazonaws.metrics.AwsSdkMetrics",
"com.fasterxml.jackson.core.util.ByteArrayBuilder",
"org.apache.http.protocol.HttpContext",
"org.apache.http.HttpResponse",
"com.google.common.base.Preconditions",
"com.fasterxml.jackson.core.util.BufferRecycler$ByteBufferType",
"com.fasterxml.jackson.databind.ser.ContainerSerializer",
"com.fasterxml.jackson.databind.ser.std.DateSerializer",
"com.fasterxml.jackson.core.util.BufferRecycler$CharBufferType",
"org.joda.time.format.DateTimeFormatterBuilder$CharacterLiteral",
"com.netflix.simianarmy.janitor.JanitorMonkey$EventTypes",
"com.fasterxml.jackson.annotation.JacksonAnnotation",
"com.fasterxml.jackson.databind.introspect.POJOPropertyBuilder",
"com.amazonaws.services.simpledb.model.transform.ListDomainsResultStaxUnmarshaller",
"com.amazonaws.services.simpledb.model.NumberDomainBytesExceededException",
"com.google.common.collect.ImmutableSet",
"com.fasterxml.jackson.databind.util.SimpleBeanPropertyDefinition",
"com.netflix.simianarmy.aws.janitor.ASGJanitor",
"com.fasterxml.jackson.annotation.JsonAutoDetect$Visibility",
"com.amazonaws.auth.profile.internal.ProfilesConfigFileLoader",
"com.amazonaws.services.simpleemail.model.ListVerifiedEmailAddressesRequest",
"org.apache.http.conn.scheme.SocketFactory",
"com.google.common.collect.Lists$StringAsImmutableList",
"com.amazonaws.services.simpleemail.model.SetIdentityDkimEnabledRequest",
"org.apache.http.client.CircularRedirectException",
"org.apache.commons.logging.impl.Jdk14Logger",
"org.apache.http.HttpVersion",
"com.fasterxml.jackson.databind.deser.std.MapDeserializer",
"com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$CharKD",
"com.amazonaws.services.simpleemail.model.GetSendStatisticsRequest",
"com.netflix.simianarmy.ResourceType",
"com.fasterxml.jackson.databind.annotation.JsonSerialize",
"org.apache.http.conn.ClientConnectionOperator",
"org.jclouds.domain.LoginCredentials",
"org.apache.commons.lang.text.StrBuilder$StrBuilderTokenizer",
"com.fasterxml.jackson.core.JsonParser",
"org.joda.time.format.DateTimeFormatter",
"com.amazonaws.auth.AbstractAWSSigner",
"com.netflix.simianarmy.AbstractEmailBuilder",
"com.amazonaws.services.simpledb.model.AttributeDoesNotExistException",
"com.fasterxml.jackson.core.JsonProcessingException",
"com.amazonaws.services.simpledb.model.CreateDomainRequest",
"org.apache.http.client.methods.HttpPut",
"com.amazonaws.util.CountingInputStream",
"com.fasterxml.jackson.annotation.JsonCreator",
"org.apache.http.impl.conn.DefaultClientConnectionOperator",
"com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException",
"com.fasterxml.jackson.core.io.CharTypes",
"com.fasterxml.jackson.databind.ser.std.StdJdkSerializers$AtomicBooleanSerializer",
"com.fasterxml.jackson.databind.ser.std.StdJdkSerializers$AtomicLongSerializer",
"com.fasterxml.jackson.databind.ser.std.InetAddressSerializer",
"com.fasterxml.jackson.databind.jsontype.impl.StdSubtypeResolver",
"com.fasterxml.jackson.core.sym.Name",
"com.amazonaws.services.simpledb.model.transform.InvalidNumberPredicatesExceptionUnmarshaller",
"com.fasterxml.jackson.databind.deser.std.StdDeserializer",
"com.amazonaws.util.ResponseMetadataCache$InternalCache",
"com.amazonaws.handlers.HandlerChainFactory",
"com.fasterxml.jackson.databind.JsonSerializer",
"org.apache.commons.lang.text.StrBuilder$StrBuilderReader",
"com.fasterxml.jackson.databind.JsonNode",
"com.amazonaws.transform.LegacyErrorUnmarshaller",
"com.amazonaws.auth.profile.ProfilesConfigFile",
"com.fasterxml.jackson.databind.ser.ResolvableSerializer",
"org.apache.http.conn.ClientConnectionManager",
"com.fasterxml.jackson.databind.deser.std.JdkDeserializers$InetAddressDeserializer",
"com.fasterxml.jackson.databind.deser.std.PrimitiveArrayDeserializers",
"org.apache.http.HttpRequest",
"org.apache.http.pool.ConnPoolControl",
"com.fasterxml.jackson.databind.deser.std.JdkDeserializers$AtomicReferenceDeserializer",
"com.amazonaws.services.simpledb.model.MissingParameterException",
"org.apache.http.client.AuthenticationStrategy",
"com.amazonaws.services.simpledb.model.InvalidNumberValueTestsException",
"com.fasterxml.jackson.databind.node.JsonNodeFactory",
"com.fasterxml.jackson.databind.cfg.MapperConfig",
"com.fasterxml.jackson.databind.deser.std.JdkDeserializers$LocaleDeserializer",
"com.fasterxml.jackson.databind.deser.std.PrimitiveArrayDeserializers$ByteDeser",
"com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$StringFactoryKeyDeserializer",
"com.amazonaws.services.simpledb.model.transform.InvalidParameterValueExceptionUnmarshaller",
"com.fasterxml.jackson.databind.deser.impl.InnerClassProperty",
"com.fasterxml.jackson.databind.annotation.JsonDeserialize",
"com.fasterxml.jackson.databind.util.ObjectBuffer",
"com.netflix.simianarmy.aws.conformity.rule.InstanceTooOld",
"com.netflix.simianarmy.GroupType",
"org.joda.time.format.DateTimeFormatterBuilder",
"com.fasterxml.jackson.databind.introspect.AnnotationIntrospectorPair",
"com.amazonaws.util.json.Jackson",
"org.joda.time.format.InternalPrinter",
"org.jclouds.compute.ComputeService",
"com.fasterxml.jackson.databind.deser.BeanDeserializer",
"com.amazonaws.services.elasticloadbalancing.model.LoadBalancerAttributes",
"org.apache.http.impl.conn.PoolingClientConnectionManager",
"com.google.common.collect.Lists$TransformingSequentialList",
"com.amazonaws.auth.ServiceAwareSigner",
"com.amazonaws.services.simpledb.model.NumberDomainsExceededException",
"com.fasterxml.jackson.databind.deser.BuilderBasedDeserializer",
"com.fasterxml.jackson.core.util.TextBuffer",
"com.fasterxml.jackson.core.JsonFactory",
"com.fasterxml.jackson.databind.deser.impl.BeanPropertyMap",
"com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$EnumKD",
"com.fasterxml.jackson.databind.deser.std.JdkDeserializers$StackTraceElementDeserializer",
"com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$DateKD",
"com.netflix.simianarmy.EventType",
"com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$ShortKD",
"org.apache.http.ProtocolException",
"com.netflix.simianarmy.basic.conformity.BasicConformityMonkeyContext$1",
"com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$CalendarKD",
"com.amazonaws.services.simpledb.model.GetAttributesRequest",
"com.amazonaws.auth.NoOpSigner",
"com.fasterxml.jackson.databind.SerializationConfig",
"com.fasterxml.jackson.databind.deser.std.PrimitiveArrayDeserializers$StringDeser",
"com.netflix.simianarmy.aws.janitor.rule.launchconfig.OldUnusedLaunchConfigRule",
"com.fasterxml.jackson.databind.ser.std.StdJdkSerializers$AtomicReferenceSerializer",
"com.fasterxml.jackson.databind.ser.std.BeanSerializerBase",
"com.google.common.collect.Lists$RandomAccessListWrapper",
"org.apache.http.conn.ssl.StrictHostnameVerifier",
"com.amazonaws.util.Classes",
"org.apache.http.conn.routing.HttpRoutePlanner",
"org.apache.http.params.HttpParamsNames",
"com.google.common.collect.Maps$1",
"com.google.common.collect.CollectPreconditions",
"com.fasterxml.jackson.annotation.JsonFormat",
"org.apache.http.conn.OperatedClientConnection",
"org.apache.http.conn.ssl.BrowserCompatHostnameVerifier",
"com.amazonaws.services.simpleemail.model.transform.MessageRejectedExceptionUnmarshaller",
"com.fasterxml.jackson.annotation.JsonTypeInfo",
"com.fasterxml.jackson.annotation.JsonUnwrapped",
"com.amazonaws.services.simpledb.model.transform.NumberDomainsExceededExceptionUnmarshaller",
"org.apache.commons.lang.text.StrBuilder",
"com.amazonaws.retry.PredefinedRetryPolicies$SDKDefaultBackoffStrategy",
"org.apache.http.conn.routing.HttpRoute",
"com.fasterxml.jackson.core.JsonFactory$Feature",
"com.amazonaws.internal.config.JsonIndex",
"com.fasterxml.jackson.databind.ser.SerializerCache",
"com.fasterxml.jackson.databind.ser.std.NumberSerializers$IntegerSerializer",
"org.apache.http.client.CookieStore",
"com.fasterxml.jackson.databind.type.TypeBindings",
"com.amazonaws.services.simpledb.model.DeleteAttributesRequest",
"com.amazonaws.metrics.AwsSdkMetrics$MetricRegistry",
"com.fasterxml.jackson.databind.SerializerProvider",
"org.apache.http.client.HttpRequestRetryHandler",
"com.netflix.simianarmy.aws.janitor.rule.asg.SuspendedASGRule",
"com.netflix.simianarmy.basic.janitor.BasicJanitorRuleEngine",
"com.fasterxml.jackson.databind.ser.DefaultSerializerProvider$Impl",
"com.fasterxml.jackson.databind.deser.DeserializerCache",
"com.fasterxml.jackson.core.json.UTF8StreamJsonParser",
"com.fasterxml.jackson.databind.deser.std.NumberDeserializers$BooleanDeserializer",
"com.fasterxml.jackson.databind.SerializationFeature",
"org.apache.http.conn.routing.RouteInfo",
"com.amazonaws.services.simpledb.model.InvalidNumberPredicatesException",
"org.apache.http.conn.scheme.LayeredSocketFactory",
"org.joda.time.DateTimeZone",
"org.apache.http.client.methods.HttpPatch",
"com.fasterxml.jackson.databind.introspect.POJOPropertyBuilder$WithMember",
"com.fasterxml.jackson.databind.util.ArrayBuilders$ArrayIterator",
"com.amazonaws.auth.SystemPropertiesCredentialsProvider",
"com.netflix.simianarmy.EmailBuilder",
"com.fasterxml.jackson.databind.deser.impl.FieldProperty",
"com.amazonaws.http.impl.client.SdkHttpClient",
"com.amazonaws.services.simpledb.model.transform.InvalidNextTokenExceptionUnmarshaller",
"com.netflix.simianarmy.aws.janitor.crawler.EBSSnapshotJanitorCrawler",
"com.fasterxml.jackson.databind.introspect.AnnotatedConstructor",
"com.fasterxml.jackson.databind.ser.impl.UnknownSerializer",
"com.amazonaws.ResetException",
"com.amazonaws.services.simpleemail.model.ListIdentitiesRequest",
"com.fasterxml.jackson.databind.ser.std.StdJdkSerializers$FileSerializer",
"org.joda.time.DateTimeFieldType$StandardDateTimeFieldType",
"com.fasterxml.jackson.databind.annotation.JsonTypeResolver",
"com.amazonaws.metrics.RequestMetricCollector$1",
"com.fasterxml.jackson.databind.deser.std.FromStringDeserializer",
"com.fasterxml.jackson.databind.ObjectWriter",
"com.amazonaws.internal.config.HttpClientConfigJsonHelper",
"com.fasterxml.jackson.core.util.Instantiatable",
"com.fasterxml.jackson.databind.deser.std.DateDeserializers$TimestampDeserializer",
"org.apache.http.HttpException",
"com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$ByteKD",
"com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$LongKD",
"com.amazonaws.services.simpledb.model.transform.AttributeDoesNotExistExceptionUnmarshaller",
"org.apache.http.pool.RouteSpecificPool",
"com.fasterxml.jackson.databind.deser.std.PrimitiveArrayDeserializers$LongDeser",
"org.apache.http.client.methods.Configurable",
"com.amazonaws.retry.RetryPolicy$RetryCondition",
"com.fasterxml.jackson.core.util.DefaultPrettyPrinter$Indenter",
"com.amazonaws.services.simpleemail.model.GetSendQuotaRequest",
"com.amazonaws.services.simpledb.AmazonSimpleDBClient",
"com.fasterxml.jackson.databind.util.Annotations",
"com.netflix.simianarmy.aws.SimpleDBRecorder",
"com.amazonaws.internal.Releasable",
"org.apache.http.auth.Credentials",
"com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitable",
"com.fasterxml.jackson.databind.deser.std.NumberDeserializers$FloatDeserializer",
"com.fasterxml.jackson.databind.introspect.VisibilityChecker$Std",
"com.fasterxml.jackson.core.TreeNode",
"com.fasterxml.jackson.databind.node.NumericNode",
"com.netflix.simianarmy.chaos.ChaosCrawler",
"com.fasterxml.jackson.databind.deser.std.DateDeserializers$TimeZoneDeserializer",
"com.fasterxml.jackson.databind.ser.std.StaticListSerializerBase",
"org.apache.http.pool.ConnPool",
"com.amazonaws.services.simpledb.model.InvalidNextTokenException",
"com.amazonaws.ServiceNameFactory",
"com.netflix.simianarmy.Monkey$Context",
"com.amazonaws.http.conn.Wrapped",
"com.fasterxml.jackson.core.util.DefaultPrettyPrinter$Lf2SpacesIndenter",
"com.fasterxml.jackson.databind.BeanProperty$Std",
"com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition",
"org.apache.http.client.RedirectHandler",
"org.apache.http.impl.client.DefaultHttpClient",
"com.netflix.simianarmy.conformity.ConformityRuleEngine",
"com.fasterxml.jackson.databind.deser.ValueInstantiators",
"com.google.common.collect.ImmutableCollection",
"org.apache.http.conn.scheme.LayeredSchemeSocketFactory",
"com.fasterxml.jackson.databind.deser.std.JdkDeserializers$UUIDDeserializer",
"com.amazonaws.services.simpledb.model.NumberItemAttributesExceededException",
"com.amazonaws.services.simpleemail.model.SendRawEmailRequest",
"com.fasterxml.jackson.databind.introspect.BasicBeanDescription",
"com.amazonaws.auth.SignerFactory",
"com.amazonaws.metrics.MetricType",
"org.apache.http.conn.ConnectionKeepAliveStrategy",
"com.netflix.simianarmy.basic.chaos.BasicChaosInstanceSelector",
"com.fasterxml.jackson.databind.JsonSerializable",
"org.joda.time.DateTimeField",
"com.fasterxml.jackson.databind.deser.impl.TypeWrappedDeserializer",
"com.netflix.simianarmy.aws.janitor.crawler.EBSVolumeJanitorCrawler",
"com.fasterxml.jackson.databind.deser.std.PrimitiveArrayDeserializers$BooleanDeser",
"com.fasterxml.jackson.databind.deser.std.NumberDeserializers$DoubleDeserializer",
"com.netflix.simianarmy.aws.AWSEmailNotifier",
"com.netflix.simianarmy.janitor.JanitorCrawler",
"com.fasterxml.jackson.databind.deser.std.JacksonDeserializers$JavaTypeDeserializer",
"org.apache.http.HttpEntity",
"org.apache.http.client.methods.HttpRequestBase",
"com.amazonaws.metrics.ServiceMetricType",
"com.fasterxml.jackson.databind.introspect.AnnotatedMethodMap",
"org.joda.time.format.DateTimeFormatterBuilder$Composite",
"com.fasterxml.jackson.core.Base64Variant",
"com.fasterxml.jackson.core.io.MergedStream",
"com.netflix.simianarmy.aws.conformity.crawler.AWSClusterCrawler",
"com.fasterxml.jackson.core.sym.BytesToNameCanonicalizer$Bucket",
"com.fasterxml.jackson.databind.ser.SerializerFactory",
"com.google.common.collect.Multiset",
"org.apache.http.conn.DnsResolver",
"com.netflix.simianarmy.aws.conformity.rule.ConformityEurekaClient",
"com.netflix.simianarmy.janitor.JanitorRuleEngine",
"com.google.common.collect.ImmutableList",
"com.fasterxml.jackson.databind.Module$SetupContext",
"com.netflix.simianarmy.janitor.JanitorMonkey$Context",
"com.netflix.simianarmy.janitor.JanitorMonkey$Type",
"com.fasterxml.jackson.databind.util.ClassUtil",
"org.apache.http.impl.client.AbstractHttpClient",
"com.fasterxml.jackson.databind.ser.std.StdSerializer",
"org.apache.http.HttpEntityEnclosingRequest",
"com.fasterxml.jackson.databind.ser.BeanSerializerFactory",
"com.netflix.simianarmy.Monkey",
"com.fasterxml.jackson.databind.jsonschema.SchemaAware",
"com.fasterxml.jackson.annotation.JacksonAnnotationsInside",
"com.netflix.simianarmy.Resource",
"org.apache.http.conn.HttpRoutedConnection",
"com.amazonaws.util.AWSRequestMetrics$Field",
"com.fasterxml.jackson.databind.util.ArrayBuilders",
"com.amazonaws.transform.Marshaller",
"com.netflix.simianarmy.MonkeyScheduler",
"org.apache.http.ConnectionReuseStrategy",
"com.fasterxml.jackson.core.PrettyPrinter",
"org.joda.time.DurationFieldType$StandardDurationFieldType",
"org.apache.http.conn.ManagedHttpClientConnection",
"com.fasterxml.jackson.core.base.GeneratorBase",
"com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector",
"com.fasterxml.jackson.core.io.BaseReader",
"org.apache.http.impl.conn.HttpConnPool",
"com.netflix.simianarmy.aws.janitor.EBSVolumeJanitor",
"com.netflix.simianarmy.aws.janitor.crawler.InstanceJanitorCrawler",
"com.fasterxml.jackson.databind.ser.DefaultSerializerProvider",
"com.amazonaws.services.simpledb.model.InvalidParameterValueException",
"org.apache.http.conn.ssl.SSLSocketFactory",
"org.joda.time.DateTimeFieldType",
"com.fasterxml.jackson.databind.jsontype.TypeResolverBuilder",
"com.amazonaws.internal.ReleasableInputStream",
"org.apache.http.HttpRequestInterceptor",
"com.netflix.simianarmy.aws.janitor.crawler.AbstractAWSJanitorCrawler",
"com.fasterxml.jackson.databind.introspect.NopAnnotationIntrospector",
"com.fasterxml.jackson.databind.deser.std.PrimitiveArrayDeserializers$Base",
"org.apache.http.pool.AbstractConnPool",
"com.fasterxml.jackson.annotation.JacksonInject",
"com.fasterxml.jackson.databind.BeanProperty",
"org.apache.http.HttpInetConnection",
"com.netflix.simianarmy.aws.janitor.rule.generic.UntaggedRule",
"org.apache.http.client.AuthenticationHandler",
"com.amazonaws.services.simpledb.model.NumberDomainAttributesExceededException",
"com.amazonaws.util.ResponseMetadataCache",
"com.netflix.simianarmy.janitor.JanitorResourceTracker",
"com.fasterxml.jackson.databind.deser.std.PrimitiveArrayDeserializers$DoubleDeser",
"com.amazonaws.metrics.MetricAdmin",
"com.fasterxml.jackson.core.base.ParserBase",
"com.fasterxml.jackson.databind.ser.std.NumberSerializers$IntLikeSerializer",
"com.amazonaws.auth.InstanceProfileCredentialsProvider",
"com.fasterxml.jackson.databind.introspect.AnnotationMap",
"com.fasterxml.jackson.databind.ser.std.ToStringSerializer",
"com.fasterxml.jackson.databind.ser.Serializers",
"org.apache.http.client.RedirectException",
"org.apache.http.client.methods.HttpUriRequest",
"com.fasterxml.jackson.databind.deser.std.NumberDeserializers$CharacterDeserializer",
"com.netflix.simianarmy.aws.conformity.rule.SameZonesInElbAndAsg",
"com.fasterxml.jackson.databind.type.ClassKey",
"com.fasterxml.jackson.databind.deser.std.DateDeserializers",
"com.fasterxml.jackson.core.JsonEncoding",
"org.apache.http.client.HttpClient",
"com.amazonaws.http.ExecutionContext",
"com.fasterxml.jackson.databind.deser.impl.SetterlessProperty",
"com.netflix.simianarmy.aws.janitor.InstanceJanitor",
"com.netflix.simianarmy.MonkeyCalendar",
"com.amazonaws.services.simpleemail.model.VerifyDomainIdentityRequest",
"com.fasterxml.jackson.databind.introspect.Annotated",
"com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$DelegatingKD",
"com.amazonaws.util.AWSServiceMetrics",
"com.amazonaws.metrics.MetricAdminMBean",
"com.google.common.collect.UnmodifiableIterator",
"com.amazonaws.internal.SdkBufferedInputStream",
"com.amazonaws.services.simpledb.model.transform.RequestTimeoutExceptionUnmarshaller",
"org.apache.http.HttpHost",
"com.amazonaws.services.simpledb.model.DomainMetadataRequest",
"com.amazonaws.http.AmazonHttpClient",
"com.fasterxml.jackson.core.sym.Name1",
"com.fasterxml.jackson.databind.deser.std.JdkDeserializers$AtomicBooleanDeserializer",
"com.fasterxml.jackson.core.sym.Name2",
"com.fasterxml.jackson.core.sym.Name3",
"com.fasterxml.jackson.databind.deser.std.JdkDeserializers",
"com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$DoubleKD",
"com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$StringCtorKeyDeserializer",
"com.fasterxml.jackson.annotation.JsonAnyGetter",
"com.amazonaws.services.simpledb.model.RequestTimeoutException",
"com.netflix.simianarmy.aws.janitor.crawler.ASGJanitorCrawler",
"com.fasterxml.jackson.annotation.JsonBackReference",
"com.google.common.base.Function",
"com.amazonaws.util.FakeIOException",
"com.google.common.collect.ImmutableMap",
"com.fasterxml.jackson.databind.deser.std.NumberDeserializers$BigDecimalDeserializer",
"com.amazonaws.services.simpledb.model.SelectRequest",
"com.amazonaws.http.HttpMethodName",
"com.fasterxml.jackson.databind.cfg.SerializerFactoryConfig",
"org.apache.http.conn.socket.LayeredConnectionSocketFactory",
"org.joda.time.tz.Provider",
"com.fasterxml.jackson.databind.ser.std.SqlDateSerializer",
"com.fasterxml.jackson.databind.introspect.AnnotatedClass",
"org.joda.time.DurationFieldType",
"com.netflix.simianarmy.aws.AWSResourceType",
"com.amazonaws.services.simpleemail.model.GetIdentityVerificationAttributesRequest",
"com.netflix.simianarmy.aws.janitor.rule.volume.OldDetachedVolumeRule",
"com.fasterxml.jackson.databind.deser.std.NumberDeserializers$ShortDeserializer",
"org.apache.http.client.RequestDirector",
"com.amazonaws.Request",
"com.fasterxml.jackson.databind.ser.impl.TypeWrappedSerializer",
"com.fasterxml.jackson.databind.node.ObjectNode",
"com.amazonaws.http.HttpClientFactory",
"com.fasterxml.jackson.core.JsonParser$Feature",
"com.amazonaws.services.simpledb.model.DeleteDomainRequest",
"com.amazonaws.services.ec2.AmazonEC2",
"com.fasterxml.jackson.databind.introspect.AnnotatedField",
"com.fasterxml.jackson.databind.deser.std.ContainerDeserializerBase",
"com.amazonaws.AmazonWebServiceRequest",
"org.apache.http.impl.client.CloseableHttpClient",
"com.fasterxml.jackson.databind.ser.std.ArraySerializerBase",
"com.fasterxml.jackson.core.sym.NameN",
"com.fasterxml.jackson.databind.introspect.POJOPropertyBuilder$Linked",
"com.fasterxml.jackson.databind.ser.std.NumberSerializers$NumberSerializer",
"com.google.common.collect.Maps",
"com.google.common.primitives.Ints",
"com.fasterxml.jackson.databind.annotation.JsonValueInstantiator",
"com.netflix.simianarmy.aws.janitor.LaunchConfigJanitor",
"com.amazonaws.util.StringUtils",
"com.amazonaws.services.simpledb.model.DuplicateItemNameException",
"com.fasterxml.jackson.annotation.JsonAutoDetect$1",
"com.amazonaws.jmx.spi.SdkMBeanRegistry$Factory",
"com.netflix.simianarmy.client.aws.chaos.ASGChaosCrawler",
"com.fasterxml.jackson.databind.introspect.ClassIntrospector",
"com.amazonaws.AmazonWebServiceClient",
"com.fasterxml.jackson.core.sym.CharsToNameCanonicalizer",
"com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$UuidKD",
"com.amazonaws.metrics.RequestMetricCollector",
"com.fasterxml.jackson.databind.node.TreeTraversingParser",
"com.amazonaws.internal.MetricAware",
"com.amazonaws.http.HttpClientFactory$LocationHeaderNotRequiredRedirectStrategy",
"com.netflix.simianarmy.chaos.ChaosMonkey$EventTypes",
"com.google.common.collect.Sets$2",
"com.google.common.collect.Sets$3",
"com.google.common.collect.Sets$1",
"com.fasterxml.jackson.core.sym.BytesToNameCanonicalizer$TableInfo",
"com.netflix.simianarmy.basic.BasicScheduler",
"com.netflix.simianarmy.aws.janitor.rule.instance.OrphanedInstanceRule",
"com.fasterxml.jackson.databind.type.CollectionType",
"com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClient",
"com.fasterxml.jackson.databind.node.ValueNode",
"com.fasterxml.jackson.databind.ser.BasicSerializerFactory",
"com.netflix.simianarmy.Resource$CleanupState",
"org.jclouds.domain.Credentials",
"com.amazonaws.services.simpledb.AmazonSimpleDB",
"com.amazonaws.http.conn.ClientConnectionManagerFactory$Handler",
"com.netflix.simianarmy.conformity.ConformityMonkey$Context",
"com.fasterxml.jackson.core.json.ReaderBasedJsonParser",
"com.fasterxml.jackson.core.JsonLocation",
"com.amazonaws.services.simpledb.model.transform.NumberDomainBytesExceededExceptionUnmarshaller",
"com.fasterxml.jackson.databind.node.IntNode",
"com.fasterxml.jackson.core.ObjectCodec",
"com.netflix.simianarmy.aws.conformity.rule.InstanceHasStatusUrl",
"com.fasterxml.jackson.databind.deser.std.NumberDeserializers$PrimitiveOrWrapperDeserializer",
"com.fasterxml.jackson.core.json.JsonReadContext",
"com.netflix.simianarmy.conformity.ConformityEmailBuilder",
"com.fasterxml.jackson.databind.ser.std.EnumSerializer",
"com.fasterxml.jackson.core.util.DefaultPrettyPrinter",
"com.fasterxml.jackson.databind.KeyDeserializer",
"com.amazonaws.util.TimingInfoUnmodifiable",
"com.fasterxml.jackson.core.util.BufferRecycler",
"com.fasterxml.jackson.databind.deser.impl.PropertyBasedObjectIdGenerator",
"com.fasterxml.jackson.databind.ser.impl.StringCollectionSerializer",
"com.amazonaws.services.simpleemail.model.MessageRejectedException",
"com.fasterxml.jackson.databind.DeserializationContext",
"com.amazonaws.internal.SdkDigestInputStream",
"com.fasterxml.jackson.databind.ser.std.StdJdkSerializers$ClassSerializer",
"com.netflix.simianarmy.janitor.JanitorEmailNotifier",
"com.google.common.base.Joiner$MapJoiner",
"com.fasterxml.jackson.databind.ser.std.ObjectArraySerializer",
"org.joda.time.tz.FixedDateTimeZone",
"com.amazonaws.util.AWSRequestMetricsFullSupport",
"com.netflix.simianarmy.CloudClient",
"com.fasterxml.jackson.databind.deser.std.NumberDeserializers$ByteDeserializer",
"com.fasterxml.jackson.databind.node.DoubleNode",
"com.amazonaws.services.simpledb.model.BatchDeleteAttributesRequest",
"com.fasterxml.jackson.databind.ser.impl.IndexedStringListSerializer",
"org.apache.http.params.HttpParams",
"com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$FloatKD",
"com.amazonaws.util.ClassLoaderHelper",
"com.amazonaws.internal.config.HttpClientConfig",
"com.amazonaws.retry.RetryPolicy",
"com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$LocaleKD",
"com.fasterxml.jackson.annotation.JsonView",
"com.fasterxml.jackson.databind.AnnotationIntrospector",
"com.netflix.simianarmy.basic.janitor.BasicJanitorMonkey",
"com.fasterxml.jackson.databind.ser.std.NullSerializer",
"com.fasterxml.jackson.databind.deser.std.PrimitiveArrayDeserializers$IntDeser",
"com.fasterxml.jackson.databind.deser.std.StringDeserializer",
"com.fasterxml.jackson.annotation.JsonGetter",
"com.fasterxml.jackson.databind.DeserializationFeature",
"com.fasterxml.jackson.databind.deser.impl.BeanAsArrayDeserializer",
"org.apache.http.conn.ssl.X509HostnameVerifier",
"com.fasterxml.jackson.databind.node.BaseJsonNode",
"com.fasterxml.jackson.databind.node.BigIntegerNode",
"org.apache.http.impl.client.DefaultHttpRequestRetryHandler",
"com.fasterxml.jackson.databind.util.LRUMap",
"com.fasterxml.jackson.databind.JsonDeserializer",
"com.netflix.simianarmy.client.edda.EddaClient",
"com.google.common.collect.BiMap",
"com.netflix.simianarmy.MonkeyType",
"com.fasterxml.jackson.databind.deser.impl.MethodProperty",
"org.joda.time.IllegalInstantException",
"com.fasterxml.jackson.databind.introspect.MemberKey",
"com.netflix.simianarmy.chaos.ChaosInstanceSelector",
"com.amazonaws.services.simpledb.model.NoSuchDomainException",
"org.apache.http.client.methods.HttpGet",
"com.amazonaws.services.simpledb.model.transform.NumberItemAttributesExceededExceptionUnmarshaller",
"com.fasterxml.jackson.databind.exc.InvalidFormatException",
"com.netflix.simianarmy.aws.janitor.ImageJanitor",
"com.fasterxml.jackson.core.sym.BytesToNameCanonicalizer",
"com.fasterxml.jackson.databind.ser.std.NonTypedScalarSerializerBase",
"com.amazonaws.auth.AWSCredentialsProviderChain",
"com.amazonaws.internal.EC2MetadataClient",
"com.fasterxml.jackson.databind.deser.std.NumberDeserializers$NumberDeserializer",
"com.amazonaws.SDKGlobalConfiguration",
"com.fasterxml.jackson.core.type.ResolvedType",
"com.fasterxml.jackson.databind.deser.impl.CreatorCollector",
"com.fasterxml.jackson.databind.ser.std.NumberSerializers",
"com.amazonaws.services.simpledb.model.transform.NumberSubmittedItemsExceededExceptionUnmarshaller",
"com.fasterxml.jackson.databind.deser.std.NumberDeserializers$LongDeserializer",
"com.fasterxml.jackson.annotation.JsonIgnore",
"com.fasterxml.jackson.databind.ser.impl.PropertyBasedObjectIdGenerator",
"org.apache.http.message.AbstractHttpMessage",
"com.amazonaws.auth.AWS4Signer",
"com.fasterxml.jackson.databind.introspect.AnnotatedMethod",
"com.netflix.simianarmy.basic.janitor.BasicJanitorMonkeyContext$1",
"com.amazonaws.util.TimingInfo",
"com.netflix.simianarmy.basic.conformity.BasicConformityMonkeyContext",
"com.fasterxml.jackson.databind.introspect.VisibilityChecker",
"com.fasterxml.jackson.databind.introspect.AnnotatedParameter",
"com.amazonaws.retry.PredefinedRetryPolicies$SDKDefaultRetryCondition",
"com.fasterxml.jackson.databind.ser.std.NumberSerializers$FloatSerializer",
"com.fasterxml.jackson.core.JsonStreamContext",
"com.netflix.simianarmy.chaos.ChaosEmailNotifier",
"com.fasterxml.jackson.core.sym.CharsToNameCanonicalizer$Bucket",
"com.fasterxml.jackson.core.io.UTF32Reader",
"com.amazonaws.internal.config.InternalConfig$Factory",
"com.netflix.simianarmy.basic.janitor.BasicJanitorMonkeyContext",
"com.fasterxml.jackson.databind.deser.std.ObjectArrayDeserializer",
"org.apache.commons.lang.ArrayUtils",
"com.netflix.simianarmy.basic.LocalDbRecorder",
"com.fasterxml.jackson.databind.deser.DefaultDeserializationContext$Impl",
"com.amazonaws.DefaultRequest",
"com.fasterxml.jackson.databind.util.ObjectBuffer$Node",
"org.apache.http.client.config.RequestConfig",
"com.amazonaws.event.ProgressListener",
"org.joda.time.JodaTimePermission",
"com.google.common.collect.Lists$TransformingRandomAccessList",
"com.fasterxml.jackson.databind.cfg.DeserializerFactoryConfig",
"com.netflix.simianarmy.janitor.JanitorEmailNotifier$Context",
"com.fasterxml.jackson.databind.deser.impl.ObjectIdValueProperty",
"org.apache.http.conn.HttpInetSocketAddress",
"com.amazonaws.AmazonServiceException",
"com.amazonaws.services.simpledb.model.transform.ListDomainsRequestMarshaller",
"com.fasterxml.jackson.databind.deser.BasicDeserializerFactory",
"org.apache.http.conn.socket.ConnectionSocketFactory",
"com.amazonaws.http.HttpResponseHandler",
"com.fasterxml.jackson.databind.ser.impl.StringArraySerializer",
"com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$StringKD",
"com.fasterxml.jackson.annotation.JsonManagedReference",
"com.fasterxml.jackson.databind.MappingJsonFactory",
"org.apache.http.pool.PoolEntry",
"com.fasterxml.jackson.databind.deser.std.JdkDeserializers$PatternDeserializer",
"com.google.common.collect.Sets$SetView",
"com.fasterxml.jackson.databind.deser.std.ThrowableDeserializer",
"com.fasterxml.jackson.databind.ser.std.TimeZoneSerializer",
"com.fasterxml.jackson.databind.introspect.POJOPropertyBuilder$2",
"com.amazonaws.internal.ResettableInputStream",
"com.fasterxml.jackson.databind.introspect.POJOPropertyBuilder$1",
"org.apache.http.client.methods.AbortableHttpRequest",
"org.joda.time.format.DateTimeFormatterBuilder$TextField",
"com.amazonaws.auth.AWSCredentialsProvider",
"org.apache.http.auth.AuthSchemeFactory",
"com.fasterxml.jackson.databind.ser.std.StringSerializer",
"com.netflix.simianarmy.aws.janitor.VolumeTaggingMonkey$Type",
"com.fasterxml.jackson.databind.JavaType",
"com.netflix.simianarmy.aws.janitor.VolumeTaggingMonkey",
"com.amazonaws.services.simpleemail.model.VerifyEmailIdentityRequest",
"com.google.common.collect.MapDifference",
"com.fasterxml.jackson.databind.util.StdDateFormat",
"com.amazonaws.services.simpledb.model.NumberSubmittedItemsExceededException",
"org.apache.http.client.methods.HttpEntityEnclosingRequestBase",
"com.fasterxml.jackson.core.util.MinimalPrettyPrinter",
"org.apache.http.params.BasicHttpParams",
"com.fasterxml.jackson.annotation.JsonValue",
"com.amazonaws.services.simpledb.model.PutAttributesRequest",
"com.fasterxml.jackson.databind.deser.ResolvableDeserializer",
"com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer",
"com.amazonaws.auth.RegionAwareSigner",
"com.amazonaws.services.simpledb.model.InvalidQueryExpressionException",
"com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$IntKD",
"com.amazonaws.handlers.RequestHandler",
"com.amazonaws.http.HttpRequestFactory",
"org.apache.http.util.Args",
"org.joda.time.ReadableInstant",
"com.fasterxml.jackson.databind.ser.std.StdJdkSerializers",
"com.fasterxml.jackson.databind.deser.std.UntypedObjectDeserializer",
"org.apache.commons.lang.text.StrBuilder$StrBuilderWriter",
"com.fasterxml.jackson.databind.deser.DeserializerFactory",
"com.google.common.primitives.Ints$IntConverter",
"com.google.common.collect.Sets",
"org.apache.http.conn.scheme.Scheme",
"org.joda.time.tz.NameProvider",
"com.fasterxml.jackson.databind.introspect.ClassIntrospector$MixInResolver",
"com.fasterxml.jackson.core.json.JsonGeneratorImpl",
"com.amazonaws.internal.config.InternalConfigJsonHelper",
"com.amazonaws.util.AWSRequestMetrics",
"com.fasterxml.jackson.databind.deser.AbstractDeserializer",
"com.amazonaws.util.VersionInfoUtils",
"com.amazonaws.services.simpledb.model.transform.InvalidNumberValueTestsExceptionUnmarshaller",
"com.netflix.simianarmy.aws.janitor.SimpleDBJanitorResourceTracker",
"org.apache.http.client.methods.HttpDelete",
"com.netflix.simianarmy.basic.BasicCalendar",
"com.fasterxml.jackson.core.io.SegmentedStringWriter",
"com.amazonaws.auth.Signer",
"com.fasterxml.jackson.core.JsonToken",
"com.amazonaws.services.simpleemail.model.SetIdentityFeedbackForwardingEnabledRequest",
"com.netflix.simianarmy.client.aws.AWSClient",
"com.fasterxml.jackson.annotation.JsonIdentityInfo",
"com.fasterxml.jackson.core.JsonGenerator$Feature",
"com.amazonaws.services.simpledb.model.transform.TooManyRequestedAttributesExceptionUnmarshaller",
"com.fasterxml.jackson.databind.cfg.BaseSettings",
"com.fasterxml.jackson.databind.ObjectMapper",
"org.apache.http.client.methods.HttpExecutionAware",
"org.apache.http.conn.ManagedClientConnection",
"org.jclouds.ssh.SshClient",
"com.fasterxml.jackson.databind.cfg.ConfigFeature",
"org.joda.time.format.InternalParser",
"com.fasterxml.jackson.annotation.JsonIgnoreType",
"com.netflix.simianarmy.aws.janitor.rule.asg.ASGInstanceValidator",
"com.netflix.simianarmy.chaos.ChaosMonkey$Type"
);
}
private static void resetClasses() {
org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(BasicJanitorMonkeyContext_ESTest_scaffolding.class.getClassLoader());
org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses(
"com.netflix.simianarmy.basic.BasicSimianArmyContext",
"com.netflix.simianarmy.basic.janitor.BasicJanitorMonkeyContext",
"com.netflix.simianarmy.basic.janitor.BasicJanitorMonkeyContext$1",
"com.netflix.simianarmy.basic.janitor.BasicJanitorMonkeyContext$BasicJanitorContext",
"org.apache.commons.lang.ArrayUtils",
"com.netflix.discovery.DiscoveryManager",
"org.apache.commons.logging.impl.Jdk14Logger",
"com.amazonaws.auth.AWSCredentialsProviderChain",
"com.amazonaws.auth.DefaultAWSCredentialsProviderChain",
"com.amazonaws.auth.EnvironmentVariableCredentialsProvider",
"com.amazonaws.auth.SystemPropertiesCredentialsProvider",
"com.amazonaws.auth.profile.ProfileCredentialsProvider",
"com.amazonaws.util.StringUtils",
"com.amazonaws.auth.InstanceProfileCredentialsProvider",
"com.netflix.simianarmy.basic.BasicConfiguration",
"com.netflix.simianarmy.basic.BasicCalendar",
"org.apache.commons.lang.StringUtils",
"com.netflix.simianarmy.client.aws.AWSClient",
"com.netflix.simianarmy.basic.BasicScheduler",
"com.netflix.simianarmy.aws.SimpleDBRecorder",
"org.apache.commons.lang.Validate",
"com.amazonaws.AmazonWebServiceClient",
"com.amazonaws.services.simpledb.AmazonSimpleDBClient",
"com.amazonaws.util.VersionInfoUtils",
"com.amazonaws.internal.config.InternalConfig",
"com.amazonaws.util.ClassLoaderHelper",
"com.fasterxml.jackson.core.ObjectCodec",
"com.fasterxml.jackson.core.type.ResolvedType",
"com.fasterxml.jackson.databind.JavaType",
"com.fasterxml.jackson.databind.type.TypeBase",
"com.fasterxml.jackson.databind.type.SimpleType",
"com.fasterxml.jackson.databind.introspect.ClassIntrospector",
"com.fasterxml.jackson.databind.introspect.Annotated",
"com.fasterxml.jackson.databind.introspect.AnnotatedClass",
"com.fasterxml.jackson.databind.BeanDescription",
"com.fasterxml.jackson.databind.introspect.BasicBeanDescription",
"com.fasterxml.jackson.databind.introspect.BasicClassIntrospector",
"com.fasterxml.jackson.databind.AnnotationIntrospector",
"com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector",
"com.fasterxml.jackson.annotation.JsonAutoDetect$Visibility",
"com.fasterxml.jackson.databind.introspect.VisibilityChecker$Std",
"com.fasterxml.jackson.core.io.SerializedString",
"com.fasterxml.jackson.core.util.DefaultPrettyPrinter",
"com.fasterxml.jackson.core.util.DefaultPrettyPrinter$FixedSpaceIndenter",
"com.fasterxml.jackson.core.util.DefaultPrettyPrinter$Lf2SpacesIndenter",
"com.fasterxml.jackson.databind.cfg.BaseSettings",
"com.fasterxml.jackson.databind.util.LRUMap",
"com.fasterxml.jackson.databind.type.TypeParser",
"com.fasterxml.jackson.databind.type.TypeFactory",
"com.fasterxml.jackson.databind.util.StdDateFormat",
"com.fasterxml.jackson.core.Base64Variant",
"com.fasterxml.jackson.core.Base64Variants",
"com.fasterxml.jackson.databind.ObjectMapper",
"com.fasterxml.jackson.core.JsonFactory$Feature",
"com.fasterxml.jackson.core.JsonParser$Feature",
"com.fasterxml.jackson.core.JsonGenerator$Feature",
"com.fasterxml.jackson.core.JsonFactory",
"com.fasterxml.jackson.databind.MappingJsonFactory",
"com.fasterxml.jackson.core.sym.CharsToNameCanonicalizer",
"com.fasterxml.jackson.core.sym.BytesToNameCanonicalizer",
"com.fasterxml.jackson.core.sym.BytesToNameCanonicalizer$TableInfo",
"com.fasterxml.jackson.databind.jsontype.SubtypeResolver",
"com.fasterxml.jackson.databind.jsontype.impl.StdSubtypeResolver",
"com.fasterxml.jackson.databind.util.RootNameLookup",
"com.fasterxml.jackson.databind.cfg.MapperConfig",
"com.fasterxml.jackson.databind.MapperFeature",
"com.fasterxml.jackson.databind.cfg.MapperConfigBase",
"com.fasterxml.jackson.databind.SerializationConfig",
"com.fasterxml.jackson.databind.SerializationFeature",
"com.fasterxml.jackson.databind.DeserializationConfig",
"com.fasterxml.jackson.databind.DeserializationFeature",
"com.fasterxml.jackson.databind.node.JsonNodeFactory",
"com.fasterxml.jackson.databind.JsonSerializer",
"com.fasterxml.jackson.databind.ser.std.StdSerializer",
"com.fasterxml.jackson.databind.ser.impl.FailingSerializer",
"com.fasterxml.jackson.databind.ser.impl.UnknownSerializer",
"com.fasterxml.jackson.databind.SerializerProvider",
"com.fasterxml.jackson.databind.ser.DefaultSerializerProvider",
"com.fasterxml.jackson.databind.ser.DefaultSerializerProvider$Impl",
"com.fasterxml.jackson.databind.ser.std.NullSerializer",
"com.fasterxml.jackson.databind.ser.SerializerCache",
"com.fasterxml.jackson.databind.DeserializationContext",
"com.fasterxml.jackson.databind.deser.DefaultDeserializationContext",
"com.fasterxml.jackson.databind.deser.DefaultDeserializationContext$Impl",
"com.fasterxml.jackson.databind.deser.DeserializerFactory",
"com.fasterxml.jackson.databind.JsonDeserializer",
"com.fasterxml.jackson.databind.deser.std.StdDeserializer",
"com.fasterxml.jackson.databind.deser.std.PrimitiveArrayDeserializers$Base",
"com.fasterxml.jackson.databind.deser.std.PrimitiveArrayDeserializers$BooleanDeser",
"com.fasterxml.jackson.databind.deser.std.PrimitiveArrayDeserializers$ByteDeser",
"com.fasterxml.jackson.databind.type.ClassKey",
"com.fasterxml.jackson.databind.deser.std.PrimitiveArrayDeserializers$ShortDeser",
"com.fasterxml.jackson.databind.deser.std.PrimitiveArrayDeserializers$IntDeser",
"com.fasterxml.jackson.databind.deser.std.PrimitiveArrayDeserializers$LongDeser",
"com.fasterxml.jackson.databind.deser.std.PrimitiveArrayDeserializers$FloatDeser",
"com.fasterxml.jackson.databind.deser.std.PrimitiveArrayDeserializers$DoubleDeser",
"com.fasterxml.jackson.databind.deser.std.PrimitiveArrayDeserializers$StringDeser",
"com.fasterxml.jackson.databind.deser.std.PrimitiveArrayDeserializers$CharDeser",
"com.fasterxml.jackson.databind.deser.std.PrimitiveArrayDeserializers",
"com.fasterxml.jackson.databind.deser.std.StdKeyDeserializers",
"com.fasterxml.jackson.databind.KeyDeserializer",
"com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer",
"com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$BoolKD",
"com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$ByteKD",
"com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$CharKD",
"com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$ShortKD",
"com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$IntKD",
"com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$LongKD",
"com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$FloatKD",
"com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$DoubleKD",
"com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$DateKD",
"com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$CalendarKD",
"com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$UuidKD",
"com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer$LocaleKD",
"com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer",
"com.fasterxml.jackson.databind.deser.std.FromStringDeserializer",
"com.fasterxml.jackson.databind.deser.std.JdkDeserializers$LocaleDeserializer",
"com.fasterxml.jackson.databind.deser.std.UntypedObjectDeserializer",
"com.fasterxml.jackson.databind.deser.std.StringDeserializer",
"com.fasterxml.jackson.databind.deser.std.NumberDeserializers",
"com.fasterxml.jackson.databind.deser.std.NumberDeserializers$PrimitiveOrWrapperDeserializer",
"com.fasterxml.jackson.databind.deser.std.NumberDeserializers$BooleanDeserializer",
"com.fasterxml.jackson.databind.deser.std.NumberDeserializers$ByteDeserializer",
"com.fasterxml.jackson.databind.deser.std.NumberDeserializers$ShortDeserializer",
"com.fasterxml.jackson.databind.deser.std.NumberDeserializers$CharacterDeserializer",
"com.fasterxml.jackson.databind.deser.std.NumberDeserializers$IntegerDeserializer",
"com.fasterxml.jackson.databind.deser.std.NumberDeserializers$LongDeserializer",
"com.fasterxml.jackson.databind.deser.std.NumberDeserializers$FloatDeserializer",
"com.fasterxml.jackson.databind.deser.std.NumberDeserializers$DoubleDeserializer",
"com.fasterxml.jackson.databind.deser.std.NumberDeserializers$NumberDeserializer",
"com.fasterxml.jackson.databind.deser.std.NumberDeserializers$BigDecimalDeserializer",
"com.fasterxml.jackson.databind.deser.std.NumberDeserializers$BigIntegerDeserializer",
"com.fasterxml.jackson.databind.deser.std.DateDeserializers",
"com.fasterxml.jackson.databind.deser.std.DateDeserializers$DateBasedDeserializer",
"com.fasterxml.jackson.databind.deser.std.DateDeserializers$CalendarDeserializer",
"com.fasterxml.jackson.databind.deser.std.DateDeserializers$DateDeserializer",
"com.fasterxml.jackson.databind.deser.std.DateDeserializers$SqlDateDeserializer",
"com.fasterxml.jackson.databind.deser.std.DateDeserializers$TimestampDeserializer",
"com.fasterxml.jackson.databind.deser.std.DateDeserializers$TimeZoneDeserializer",
"com.fasterxml.jackson.databind.deser.std.JdkDeserializers",
"com.fasterxml.jackson.databind.deser.std.JdkDeserializers$UUIDDeserializer",
"com.fasterxml.jackson.databind.deser.std.JdkDeserializers$URLDeserializer",
"com.fasterxml.jackson.databind.deser.std.JdkDeserializers$URIDeserializer",
"com.fasterxml.jackson.databind.deser.std.JdkDeserializers$CurrencyDeserializer",
"com.fasterxml.jackson.databind.deser.std.JdkDeserializers$PatternDeserializer",
"com.fasterxml.jackson.databind.deser.std.JdkDeserializers$InetAddressDeserializer",
"com.fasterxml.jackson.databind.deser.std.JdkDeserializers$CharsetDeserializer",
"com.fasterxml.jackson.databind.deser.std.JdkDeserializers$AtomicBooleanDeserializer",
"com.fasterxml.jackson.databind.deser.std.ClassDeserializer",
"com.fasterxml.jackson.databind.deser.std.JdkDeserializers$StackTraceElementDeserializer",
"com.fasterxml.jackson.databind.deser.std.JacksonDeserializers",
"com.fasterxml.jackson.databind.deser.std.JacksonDeserializers$JavaTypeDeserializer",
"com.fasterxml.jackson.databind.deser.std.JacksonDeserializers$TokenBufferDeserializer",
"com.fasterxml.jackson.databind.deser.BasicDeserializerFactory",
"com.fasterxml.jackson.databind.cfg.DeserializerFactoryConfig",
"com.fasterxml.jackson.databind.ext.OptionalHandlerFactory",
"com.fasterxml.jackson.databind.deser.BeanDeserializerFactory",
"com.fasterxml.jackson.databind.deser.DeserializerCache",
"com.fasterxml.jackson.databind.ser.SerializerFactory",
"com.fasterxml.jackson.databind.ser.std.StdScalarSerializer",
"com.fasterxml.jackson.databind.ser.std.NonTypedScalarSerializerBase",
"com.fasterxml.jackson.databind.ser.std.StringSerializer",
"com.fasterxml.jackson.databind.ser.std.ToStringSerializer",
"com.fasterxml.jackson.databind.ser.std.NumberSerializers",
"com.fasterxml.jackson.databind.ser.std.NumberSerializers$IntegerSerializer",
"com.fasterxml.jackson.databind.ser.std.NumberSerializers$LongSerializer",
"com.fasterxml.jackson.databind.ser.std.NumberSerializers$IntLikeSerializer",
"com.fasterxml.jackson.databind.ser.std.NumberSerializers$FloatSerializer",
"com.fasterxml.jackson.databind.ser.std.NumberSerializers$DoubleSerializer",
"com.fasterxml.jackson.databind.ser.std.BooleanSerializer",
"com.fasterxml.jackson.databind.ser.std.NumberSerializers$NumberSerializer",
"com.fasterxml.jackson.databind.ser.std.DateTimeSerializerBase",
"com.fasterxml.jackson.databind.ser.std.CalendarSerializer",
"com.fasterxml.jackson.databind.ser.std.DateSerializer",
"com.fasterxml.jackson.databind.ser.std.SqlDateSerializer",
"com.fasterxml.jackson.databind.ser.std.SqlTimeSerializer",
"com.fasterxml.jackson.databind.ser.std.StdJdkSerializers",
"com.fasterxml.jackson.databind.ser.BasicSerializerFactory",
"com.fasterxml.jackson.databind.cfg.SerializerFactoryConfig",
"com.fasterxml.jackson.databind.ser.BeanSerializerFactory",
"com.fasterxml.jackson.core.util.MinimalPrettyPrinter",
"com.fasterxml.jackson.databind.ObjectWriter",
"com.amazonaws.util.json.Jackson",
"com.fasterxml.jackson.core.io.IOContext",
"com.fasterxml.jackson.core.util.BufferRecycler",
"com.fasterxml.jackson.core.util.BufferRecycler$ByteBufferType",
"com.fasterxml.jackson.core.util.BufferRecycler$CharBufferType",
"com.fasterxml.jackson.core.json.ByteSourceJsonBootstrapper",
"com.fasterxml.jackson.core.JsonEncoding",
"com.fasterxml.jackson.core.JsonParser",
"com.fasterxml.jackson.core.base.ParserMinimalBase",
"com.fasterxml.jackson.core.base.ParserBase",
"com.fasterxml.jackson.core.io.CharTypes",
"com.fasterxml.jackson.core.json.UTF8StreamJsonParser",
"com.fasterxml.jackson.core.util.TextBuffer",
"com.fasterxml.jackson.core.JsonStreamContext",
"com.fasterxml.jackson.core.json.JsonReadContext",
"com.fasterxml.jackson.core.JsonToken",
"com.fasterxml.jackson.databind.util.ClassUtil",
"com.fasterxml.jackson.databind.introspect.POJOPropertiesCollector",
"com.fasterxml.jackson.databind.introspect.AnnotationMap",
"com.fasterxml.jackson.databind.introspect.AnnotatedMember",
"com.fasterxml.jackson.databind.introspect.AnnotatedField",
"com.fasterxml.jackson.annotation.JsonAutoDetect$1",
"com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition",
"com.fasterxml.jackson.databind.introspect.POJOPropertyBuilder",
"com.fasterxml.jackson.databind.introspect.POJOPropertyBuilder$Linked",
"com.fasterxml.jackson.databind.introspect.AnnotatedMethodMap",
"com.fasterxml.jackson.databind.introspect.AnnotatedWithParams",
"com.fasterxml.jackson.databind.introspect.AnnotatedMethod",
"com.fasterxml.jackson.databind.introspect.MemberKey",
"com.fasterxml.jackson.databind.util.BeanUtil",
"com.fasterxml.jackson.databind.introspect.AnnotatedConstructor",
"com.fasterxml.jackson.databind.util.ArrayBuilders",
"com.fasterxml.jackson.databind.util.ArrayBuilders$ArrayIterator",
"com.fasterxml.jackson.databind.deser.impl.CreatorCollector",
"com.fasterxml.jackson.databind.deser.ValueInstantiator",
"com.fasterxml.jackson.databind.deser.std.StdValueInstantiator",
"com.fasterxml.jackson.databind.deser.BeanDeserializerBuilder",
"com.fasterxml.jackson.databind.type.ArrayType",
"com.fasterxml.jackson.databind.type.TypeBindings",
"com.fasterxml.jackson.databind.BeanProperty$Std",
"com.fasterxml.jackson.databind.deser.SettableBeanProperty",
"com.fasterxml.jackson.databind.deser.impl.MethodProperty",
"com.fasterxml.jackson.core.util.InternCache",
"com.fasterxml.jackson.databind.introspect.POJOPropertyBuilder$2",
"com.fasterxml.jackson.databind.introspect.POJOPropertyBuilder$1",
"com.fasterxml.jackson.databind.deser.impl.BeanPropertyMap",
"com.fasterxml.jackson.databind.deser.impl.BeanPropertyMap$Bucket",
"com.fasterxml.jackson.databind.deser.BeanDeserializerBase",
"com.fasterxml.jackson.databind.deser.BeanDeserializer",
"com.fasterxml.jackson.databind.deser.impl.BeanPropertyMap$IteratorImpl",
"com.fasterxml.jackson.databind.deser.std.ContainerDeserializerBase",
"com.fasterxml.jackson.databind.deser.std.ObjectArrayDeserializer",
"com.fasterxml.jackson.databind.introspect.AnnotatedParameter",
"com.fasterxml.jackson.databind.deser.impl.FieldProperty",
"com.fasterxml.jackson.annotation.JsonFormat$Shape",
"com.fasterxml.jackson.core.sym.Name",
"com.fasterxml.jackson.core.sym.NameN",
"com.amazonaws.internal.config.InternalConfigJsonHelper",
"com.fasterxml.jackson.core.sym.Name3",
"com.amazonaws.internal.config.SignerConfigJsonHelper",
"com.fasterxml.jackson.databind.util.ObjectBuffer",
"com.fasterxml.jackson.core.sym.Name1",
"com.amazonaws.internal.config.JsonIndex",
"com.fasterxml.jackson.core.sym.Name2",
"com.fasterxml.jackson.databind.util.ObjectBuffer$Node",
"com.fasterxml.jackson.core.sym.BytesToNameCanonicalizer$Bucket",
"com.amazonaws.internal.config.HttpClientConfigJsonHelper",
"com.amazonaws.internal.config.SignerConfig",
"com.amazonaws.internal.config.HttpClientConfig",
"com.amazonaws.internal.config.InternalConfig$Factory",
"com.amazonaws.retry.PredefinedRetryPolicies$SDKDefaultRetryCondition",
"com.amazonaws.retry.PredefinedRetryPolicies$SDKDefaultBackoffStrategy",
"com.amazonaws.retry.PredefinedRetryPolicies$DynamoDBDefaultBackoffStrategy",
"com.amazonaws.retry.RetryPolicy",
"com.amazonaws.retry.PredefinedRetryPolicies",
"com.amazonaws.ClientConfiguration",
"com.amazonaws.Protocol",
"com.amazonaws.http.HttpRequestFactory",
"com.amazonaws.http.HttpClientFactory",
"com.amazonaws.http.AmazonHttpClient",
"org.apache.http.params.AbstractHttpParams",
"org.apache.http.params.BasicHttpParams",
"org.apache.http.params.HttpConnectionParams",
"org.apache.http.util.Args",
"com.amazonaws.http.ConnectionManagerFactory",
"org.apache.http.impl.conn.PoolingClientConnectionManager",
"org.apache.http.impl.conn.SchemeRegistryFactory",
"org.apache.http.conn.scheme.SchemeRegistry",
"org.apache.http.conn.scheme.Scheme",
"org.apache.http.conn.scheme.PlainSocketFactory",
"org.apache.http.conn.ssl.AbstractVerifier",
"org.apache.http.conn.ssl.AllowAllHostnameVerifier",
"org.apache.http.conn.ssl.BrowserCompatHostnameVerifier",
"org.apache.http.conn.ssl.StrictHostnameVerifier",
"org.apache.http.conn.ssl.SSLSocketFactory",
"org.apache.http.conn.ssl.SSLContexts",
"org.apache.http.impl.conn.SystemDefaultDnsResolver",
"org.apache.http.impl.conn.DefaultClientConnectionOperator",
"org.apache.http.pool.AbstractConnPool",
"org.apache.http.impl.conn.HttpConnPool",
"org.apache.http.impl.conn.HttpConnPool$InternalConnFactory",
"com.amazonaws.http.IdleConnectionReaper",
"org.apache.http.impl.client.CloseableHttpClient",
"org.apache.http.impl.client.AbstractHttpClient",
"org.apache.http.impl.client.DefaultHttpClient",
"com.amazonaws.http.impl.client.SdkHttpClient",
"com.amazonaws.http.conn.ClientConnectionManagerFactory",
"com.amazonaws.http.conn.ClientConnectionManagerFactory$Handler",
"org.apache.http.conn.routing.HttpRoute",
"org.apache.http.impl.client.DefaultHttpRequestRetryHandler",
"com.amazonaws.http.impl.client.HttpRequestNoRetryHandler",
"org.apache.http.impl.client.DefaultRedirectStrategy",
"com.amazonaws.http.HttpClientFactory$LocationHeaderNotRequiredRedirectStrategy",
"com.amazonaws.util.ResponseMetadataCache",
"com.amazonaws.util.ResponseMetadataCache$InternalCache",
"com.amazonaws.SDKGlobalConfiguration",
"com.amazonaws.transform.LegacyErrorUnmarshaller",
"com.amazonaws.services.simpledb.model.transform.InvalidParameterValueExceptionUnmarshaller",
"com.amazonaws.services.simpledb.model.transform.NumberDomainBytesExceededExceptionUnmarshaller",
"com.amazonaws.services.simpledb.model.transform.NoSuchDomainExceptionUnmarshaller",
"com.amazonaws.services.simpledb.model.transform.NumberDomainsExceededExceptionUnmarshaller",
"com.amazonaws.services.simpledb.model.transform.NumberSubmittedItemsExceededExceptionUnmarshaller",
"com.amazonaws.services.simpledb.model.transform.RequestTimeoutExceptionUnmarshaller",
"com.amazonaws.services.simpledb.model.transform.InvalidQueryExpressionExceptionUnmarshaller",
"com.amazonaws.services.simpledb.model.transform.NumberSubmittedAttributesExceededExceptionUnmarshaller",
"com.amazonaws.services.simpledb.model.transform.DuplicateItemNameExceptionUnmarshaller",
"com.amazonaws.services.simpledb.model.transform.NumberDomainAttributesExceededExceptionUnmarshaller",
"com.amazonaws.services.simpledb.model.transform.InvalidNumberPredicatesExceptionUnmarshaller",
"com.amazonaws.services.simpledb.model.transform.TooManyRequestedAttributesExceptionUnmarshaller",
"com.amazonaws.services.simpledb.model.transform.InvalidNextTokenExceptionUnmarshaller",
"com.amazonaws.services.simpledb.model.transform.NumberItemAttributesExceededExceptionUnmarshaller",
"com.amazonaws.services.simpledb.model.transform.AttributeDoesNotExistExceptionUnmarshaller",
"com.amazonaws.services.simpledb.model.transform.MissingParameterExceptionUnmarshaller",
"com.amazonaws.services.simpledb.model.transform.InvalidNumberValueTestsExceptionUnmarshaller",
"com.amazonaws.util.Classes",
"com.amazonaws.ServiceNameFactory",
"com.amazonaws.util.AwsHostNameUtils",
"com.amazonaws.auth.SignerFactory",
"com.amazonaws.auth.AbstractAWSSigner",
"com.amazonaws.auth.QueryStringSigner",
"com.amazonaws.handlers.HandlerChainFactory",
"com.amazonaws.AmazonWebServiceRequest$1",
"com.amazonaws.event.ProgressListener$1",
"com.amazonaws.event.ProgressListener",
"com.amazonaws.RequestClientOptions",
"com.amazonaws.RequestClientOptions$Marker",
"com.amazonaws.AmazonWebServiceRequest",
"com.amazonaws.services.simpledb.model.ListDomainsRequest",
"com.amazonaws.metrics.AwsSdkMetrics$MetricRegistry",
"com.amazonaws.util.AWSRequestMetrics$Field",
"com.amazonaws.util.AWSServiceMetrics",
"com.amazonaws.jmx.SdkMBeanRegistrySupport",
"com.amazonaws.jmx.spi.SdkMBeanRegistry$Factory",
"com.amazonaws.metrics.MetricAdmin",
"com.amazonaws.jmx.MBeans",
"com.amazonaws.metrics.AwsSdkMetrics",
"com.amazonaws.metrics.RequestMetricCollector$1",
"com.amazonaws.metrics.RequestMetricCollector",
"com.amazonaws.http.ExecutionContext",
"com.amazonaws.util.AWSRequestMetrics",
"com.amazonaws.util.TimingInfo",
"com.amazonaws.services.simpledb.model.transform.ListDomainsRequestMarshaller",
"com.amazonaws.DefaultRequest",
"com.amazonaws.http.HttpMethodName",
"com.amazonaws.services.simpledb.model.transform.ListDomainsResultStaxUnmarshaller",
"com.amazonaws.AmazonClientException",
"com.amazonaws.auth.profile.ProfilesConfigFile",
"com.amazonaws.auth.profile.internal.ProfilesConfigFileLoader",
"com.amazonaws.internal.EC2MetadataClient",
"com.netflix.simianarmy.aws.janitor.SimpleDBJanitorResourceTracker",
"com.netflix.simianarmy.AbstractEmailBuilder",
"com.netflix.simianarmy.janitor.JanitorEmailBuilder",
"org.joda.time.format.DateTimeFormat",
"org.joda.time.format.DateTimeFormatterBuilder",
"org.joda.time.DateTimeFieldType$StandardDateTimeFieldType",
"org.joda.time.DurationFieldType$StandardDurationFieldType",
"org.joda.time.DurationFieldType",
"org.joda.time.DateTimeFieldType",
"org.joda.time.format.DateTimeFormatterBuilder$TextField",
"org.joda.time.format.DateTimeFormatterBuilder$StringLiteral",
"org.joda.time.format.DateTimeFormatterBuilder$CharacterLiteral",
"org.joda.time.format.DateTimeFormatterBuilder$NumberFormatter",
"org.joda.time.format.DateTimeFormatterBuilder$PaddedNumber",
"org.joda.time.format.DateTimeFormatterBuilder$Composite",
"org.joda.time.format.DateTimeFormatter",
"com.netflix.simianarmy.basic.janitor.BasicJanitorEmailBuilder",
"com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClient",
"com.amazonaws.transform.AbstractErrorUnmarshaller",
"com.amazonaws.transform.StandardErrorUnmarshaller",
"com.amazonaws.services.simpleemail.model.transform.MessageRejectedExceptionUnmarshaller",
"org.joda.time.UTCDateTimeZone",
"org.joda.time.DateTimeZone",
"com.amazonaws.auth.AWS4Signer",
"com.netflix.simianarmy.aws.AWSEmailNotifier",
"com.netflix.simianarmy.janitor.JanitorEmailNotifier",
"com.netflix.simianarmy.basic.janitor.BasicJanitorRuleEngine",
"com.netflix.simianarmy.aws.janitor.rule.asg.DummyASGInstanceValidator",
"com.netflix.simianarmy.aws.janitor.rule.asg.OldEmptyASGRule",
"com.netflix.simianarmy.aws.janitor.rule.asg.SuspendedASGRule",
"com.netflix.simianarmy.aws.janitor.rule.generic.UntaggedRule",
"com.netflix.simianarmy.aws.janitor.crawler.AbstractAWSJanitorCrawler",
"com.netflix.simianarmy.aws.janitor.crawler.ASGJanitorCrawler",
"com.netflix.simianarmy.janitor.AbstractJanitor",
"com.netflix.simianarmy.aws.janitor.ASGJanitor",
"com.netflix.simianarmy.aws.AWSResourceType",
"com.netflix.simianarmy.aws.janitor.rule.instance.OrphanedInstanceRule",
"com.netflix.simianarmy.aws.janitor.crawler.InstanceJanitorCrawler",
"com.netflix.simianarmy.aws.janitor.InstanceJanitor",
"com.netflix.simianarmy.aws.janitor.rule.volume.OldDetachedVolumeRule",
"com.netflix.simianarmy.aws.janitor.crawler.EBSVolumeJanitorCrawler",
"com.netflix.simianarmy.aws.janitor.EBSVolumeJanitor",
"com.netflix.simianarmy.aws.janitor.rule.snapshot.NoGeneratedAMIRule",
"com.netflix.simianarmy.aws.janitor.crawler.EBSSnapshotJanitorCrawler",
"com.netflix.simianarmy.aws.janitor.EBSSnapshotJanitor",
"com.netflix.simianarmy.aws.janitor.rule.launchconfig.OldUnusedLaunchConfigRule",
"com.netflix.simianarmy.aws.janitor.crawler.LaunchConfigJanitorCrawler",
"com.netflix.simianarmy.aws.janitor.LaunchConfigJanitor",
"com.netflix.simianarmy.janitor.JanitorMonkey$Type",
"com.netflix.simianarmy.chaos.ChaosMonkey$EventTypes",
"com.netflix.simianarmy.basic.BasicRecorderEvent",
"com.netflix.simianarmy.client.vsphere.VSphereClient",
"com.vmware.vim25.DynamicData",
"com.vmware.vim25.EventFilterSpec",
"com.netflix.config.DynamicPropertyFactory",
"com.netflix.config.SimpleDeploymentContext",
"com.netflix.config.ConfigurationBasedDeploymentContext",
"com.netflix.config.ConfigurationManager",
"org.apache.commons.configuration.event.EventSource",
"org.apache.commons.configuration.AbstractConfiguration",
"com.netflix.config.ConcurrentMapConfiguration",
"com.netflix.config.ConcurrentCompositeConfiguration",
"org.apache.commons.logging.impl.NoOpLog",
"com.netflix.config.ConcurrentCompositeConfiguration$1",
"org.apache.commons.configuration.MapConfiguration",
"org.apache.commons.configuration.SystemConfiguration",
"com.netflix.config.DynamicConfiguration",
"com.netflix.config.DynamicURLConfiguration",
"com.netflix.config.sources.URLConfigurationSource",
"com.netflix.config.ConfigurationBackedDynamicPropertySupportImpl",
"com.netflix.config.DynamicProperty",
"com.netflix.config.DynamicProperty$DynamicPropertyListener",
"com.netflix.config.ExpandedConfigurationListenerAdapter",
"com.netflix.discovery.DiscoveryClient",
"com.netflix.simianarmy.aws.janitor.rule.asg.DiscoveryASGInstanceValidator",
"com.netflix.simianarmy.basic.BasicChaosMonkeyContext",
"com.amazonaws.auth.BasicAWSCredentials",
"com.amazonaws.http.StaxResponseHandler",
"com.amazonaws.services.simpledb.internal.SimpleDBStaxResponseHandler",
"com.amazonaws.http.DefaultErrorResponseHandler",
"com.amazonaws.event.ProgressEventType",
"com.amazonaws.event.SDKProgressPublisher",
"com.amazonaws.http.AmazonHttpClient$ExecOneRequestParams",
"com.amazonaws.auth.SignatureVersion",
"com.amazonaws.auth.SigningAlgorithm",
"com.amazonaws.util.HttpUtils",
"com.amazonaws.util.Base64Codec",
"com.amazonaws.util.CodecUtils",
"com.amazonaws.util.Base64",
"org.apache.http.message.BasicNameValuePair",
"org.apache.http.client.utils.URLEncodedUtils",
"org.apache.http.message.AbstractHttpMessage",
"org.apache.http.client.methods.AbstractExecutionAwareRequest",
"org.apache.http.client.methods.HttpRequestBase",
"org.apache.http.client.methods.HttpEntityEnclosingRequestBase",
"org.apache.http.client.methods.HttpPost",
"org.apache.http.message.HeaderGroup",
"org.apache.http.entity.AbstractHttpEntity",
"org.apache.http.entity.StringEntity",
"org.apache.http.Consts",
"org.apache.http.util.TextUtils",
"org.apache.http.entity.ContentType",
"org.apache.http.util.CharArrayBuffer",
"org.apache.http.message.BasicHeader",
"org.apache.http.protocol.BasicHttpContext",
"org.apache.http.client.utils.URIUtils",
"org.apache.http.HttpHost",
"org.apache.http.auth.AuthSchemeRegistry",
"org.apache.http.impl.auth.BasicSchemeFactory",
"org.apache.http.impl.auth.DigestSchemeFactory",
"org.apache.http.impl.auth.NTLMSchemeFactory",
"org.apache.http.impl.auth.SPNegoSchemeFactory",
"org.apache.http.impl.auth.KerberosSchemeFactory",
"org.apache.http.cookie.CookieSpecRegistry",
"org.apache.http.impl.cookie.BestMatchSpecFactory",
"org.apache.http.impl.cookie.BrowserCompatSpecFactory",
"org.apache.http.impl.cookie.BrowserCompatSpecFactory$SecurityLevel",
"org.apache.http.impl.cookie.NetscapeDraftSpecFactory",
"org.apache.http.impl.cookie.RFC2109SpecFactory",
"org.apache.http.impl.cookie.RFC2965SpecFactory",
"org.apache.http.impl.cookie.IgnoreSpecFactory",
"org.apache.http.impl.client.BasicCookieStore",
"org.apache.http.cookie.CookieIdentityComparator",
"org.apache.http.impl.client.BasicCredentialsProvider",
"org.apache.http.protocol.DefaultedHttpContext",
"org.apache.http.impl.client.ClientParamsStack",
"org.apache.http.client.params.HttpClientParamConfig",
"org.apache.http.client.config.RequestConfig$Builder",
"org.apache.http.client.config.RequestConfig",
"org.apache.http.protocol.HttpRequestExecutor",
"com.amazonaws.http.protocol.SdkHttpRequestExecutor",
"org.apache.http.impl.DefaultConnectionReuseStrategy",
"org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy",
"org.apache.http.impl.conn.DefaultHttpRoutePlanner",
"org.apache.http.protocol.BasicHttpProcessor",
"org.apache.http.client.protocol.RequestDefaultHeaders",
"org.apache.http.protocol.RequestContent",
"org.apache.http.protocol.RequestTargetHost",
"org.apache.http.client.protocol.RequestClientConnControl",
"org.apache.http.protocol.RequestUserAgent",
"org.apache.http.protocol.RequestExpectContinue",
"org.apache.http.client.protocol.RequestAddCookies",
"org.apache.http.client.protocol.ResponseProcessCookies",
"org.apache.http.client.protocol.RequestAuthCache",
"org.apache.http.client.protocol.RequestAuthenticationBase",
"org.apache.http.client.protocol.RequestTargetAuthentication",
"org.apache.http.client.protocol.RequestProxyAuthentication",
"org.apache.http.protocol.ImmutableHttpProcessor",
"org.apache.http.impl.client.AuthenticationStrategyImpl",
"org.apache.http.impl.client.TargetAuthenticationStrategy",
"org.apache.http.impl.client.ProxyAuthenticationStrategy",
"org.apache.http.impl.client.DefaultUserTokenHandler",
"org.apache.http.impl.client.DefaultRequestDirector",
"org.apache.http.impl.auth.HttpAuthenticator",
"org.apache.http.impl.client.HttpAuthenticator",
"org.apache.http.auth.AuthState",
"org.apache.http.auth.AuthProtocolState",
"org.apache.http.impl.client.RequestWrapper",
"org.apache.http.impl.client.EntityEnclosingRequestWrapper",
"org.apache.http.entity.HttpEntityWrapper",
"org.apache.http.impl.client.EntityEnclosingRequestWrapper$EntityWrapper",
"org.apache.http.conn.routing.RouteInfo$TunnelType",
"org.apache.http.conn.routing.RouteInfo$LayerType",
"org.apache.http.conn.params.ConnRouteParams",
"org.apache.http.util.Asserts",
"org.apache.http.impl.client.RoutedRequest",
"org.apache.http.pool.PoolEntryFuture",
"org.apache.http.pool.AbstractConnPool$2",
"org.apache.http.impl.conn.PoolingClientConnectionManager$1",
"com.amazonaws.http.conn.ClientConnectionRequestFactory",
"com.amazonaws.http.conn.ClientConnectionRequestFactory$Handler",
"org.apache.http.client.methods.AbstractExecutionAwareRequest$1",
"org.apache.http.client.params.HttpClientParams",
"com.amazonaws.metrics.ServiceLatencyProvider",
"org.apache.http.util.LangUtils",
"org.apache.http.pool.RouteSpecificPool",
"org.apache.http.pool.AbstractConnPool$1",
"org.apache.http.impl.AbstractHttpClientConnection",
"org.apache.http.impl.SocketHttpClientConnection",
"org.apache.http.impl.conn.DefaultClientConnection",
"org.apache.http.impl.entity.EntitySerializer",
"org.apache.http.impl.entity.StrictContentLengthStrategy",
"org.apache.http.impl.entity.EntityDeserializer",
"org.apache.http.impl.entity.LaxContentLengthStrategy",
"org.apache.http.pool.PoolEntry",
"org.apache.http.impl.conn.HttpPoolEntry",
"org.apache.http.conn.routing.RouteTracker",
"org.apache.http.impl.conn.ManagedClientConnectionImpl",
"com.amazonaws.metrics.ServiceMetricCollector$1",
"com.amazonaws.metrics.ServiceMetricCollector",
"org.apache.http.client.methods.AbstractExecutionAwareRequest$2",
"org.apache.http.conn.HttpInetSocketAddress",
"com.amazonaws.util.IOUtils",
"com.netflix.simianarmy.basic.conformity.BasicConformityMonkeyContext",
"com.google.common.base.Joiner",
"com.google.common.base.Preconditions",
"com.google.common.base.Joiner$1",
"com.google.common.collect.Collections2",
"com.google.common.base.Joiner$MapJoiner",
"com.google.common.collect.Maps",
"com.google.common.collect.Lists",
"com.google.common.collect.CollectPreconditions",
"com.google.common.primitives.Ints",
"com.netflix.simianarmy.aws.conformity.SimpleDBConformityClusterTracker",
"com.netflix.simianarmy.conformity.ConformityRuleEngine",
"com.netflix.simianarmy.aws.conformity.rule.InstanceInSecurityGroup",
"com.google.common.collect.Sets",
"org.apache.commons.lang.text.StrBuilder",
"com.netflix.simianarmy.aws.conformity.rule.InstanceTooOld",
"com.netflix.simianarmy.aws.conformity.rule.SameZonesInElbAndAsg",
"com.netflix.simianarmy.aws.conformity.crawler.AWSClusterCrawler",
"com.netflix.simianarmy.conformity.ConformityEmailBuilder",
"com.netflix.simianarmy.basic.conformity.BasicConformityEmailBuilder",
"com.netflix.simianarmy.conformity.ConformityEmailNotifier",
"com.netflix.simianarmy.basic.conformity.BasicConformityMonkeyContext$1",
"com.netflix.simianarmy.client.aws.chaos.ASGChaosCrawler",
"com.netflix.simianarmy.basic.chaos.BasicChaosInstanceSelector",
"com.netflix.simianarmy.chaos.ChaosEmailNotifier",
"com.netflix.simianarmy.basic.chaos.BasicChaosEmailNotifier",
"com.netflix.simianarmy.Monkey",
"com.netflix.simianarmy.chaos.ChaosMonkey",
"com.netflix.simianarmy.basic.chaos.BasicChaosMonkey",
"com.netflix.simianarmy.basic.chaos.CloudFormationChaosMonkey",
"com.netflix.simianarmy.chaos.ChaosType",
"com.netflix.simianarmy.chaos.ShutdownInstanceChaosType",
"com.netflix.simianarmy.chaos.BlockAllNetworkTrafficChaosType",
"com.netflix.simianarmy.chaos.DetachVolumesChaosType",
"com.netflix.simianarmy.chaos.ScriptChaosType",
"com.netflix.simianarmy.chaos.BurnCpuChaosType",
"com.netflix.simianarmy.chaos.BurnIoChaosType",
"com.netflix.simianarmy.chaos.KillProcessesChaosType",
"com.netflix.simianarmy.chaos.NullRouteChaosType",
"com.netflix.simianarmy.chaos.FailEc2ChaosType",
"com.netflix.simianarmy.chaos.FailDnsChaosType",
"com.netflix.simianarmy.chaos.FailDynamoDbChaosType",
"com.netflix.simianarmy.chaos.FailS3ChaosType",
"com.netflix.simianarmy.chaos.FillDiskChaosType",
"com.netflix.simianarmy.chaos.NetworkCorruptionChaosType",
"com.netflix.simianarmy.chaos.NetworkLatencyChaosType",
"com.netflix.simianarmy.chaos.NetworkLossChaosType",
"com.netflix.simianarmy.FeatureNotEnabledException",
"com.netflix.simianarmy.janitor.JanitorMonkey",
"com.netflix.simianarmy.basic.janitor.BasicJanitorMonkey",
"com.amazonaws.services.simpledb.model.SelectRequest",
"com.amazonaws.services.simpledb.model.transform.SelectRequestMarshaller",
"com.amazonaws.services.simpledb.model.transform.SelectResultStaxUnmarshaller",
"com.netflix.simianarmy.basic.LocalDbRecorder",
"com.netflix.simianarmy.aws.AWSResource",
"com.amazonaws.services.simpledb.model.ReplaceableAttribute",
"com.amazonaws.services.simpledb.model.PutAttributesRequest",
"com.amazonaws.services.ec2.AmazonEC2Client",
"com.amazonaws.handlers.AbstractRequestHandler",
"com.amazonaws.services.ec2.model.transform.EC2RequestHandler",
"com.amazonaws.handlers.RequestHandler2",
"com.amazonaws.handlers.RequestHandler2Adaptor",
"com.amazonaws.handlers.CredentialsRequestHandler",
"com.amazonaws.services.ec2.model.transform.GeneratePreSignUrlRequestHandler",
"com.amazonaws.services.ec2.model.DescribeSecurityGroupsRequest",
"com.amazonaws.services.ec2.model.transform.DescribeSecurityGroupsRequestMarshaller",
"com.amazonaws.internal.ListWithAutoConstructFlag",
"com.amazonaws.services.ec2.model.transform.DescribeSecurityGroupsResultStaxUnmarshaller",
"com.netflix.simianarmy.aws.janitor.rule.ami.UnusedImageRule",
"com.amazonaws.services.ec2.model.TerminateInstancesRequest",
"com.amazonaws.services.ec2.model.transform.TerminateInstancesRequestMarshaller",
"com.amazonaws.services.ec2.model.transform.TerminateInstancesResultStaxUnmarshaller",
"com.amazonaws.services.opsworks.model.WeeklyAutoScalingSchedule",
"com.netflix.simianarmy.chaos.ChaosMonkey$Type",
"com.netflix.simianarmy.janitor.JanitorMonkey$EventTypes",
"com.amazonaws.auth.ClasspathPropertiesFileCredentialsProvider",
"com.netflix.simianarmy.basic.janitor.BasicVolumeTaggingMonkeyContext",
"com.netflix.simianarmy.client.vsphere.PropertyBasedTerminationStrategy",
"com.netflix.simianarmy.client.vsphere.VSphereServiceConnection",
"com.amazonaws.services.autoscaling.AmazonAutoScalingClient",
"com.amazonaws.services.autoscaling.model.transform.InvalidNextTokenExceptionUnmarshaller",
"com.amazonaws.services.autoscaling.model.transform.ScalingActivityInProgressExceptionUnmarshaller",
"com.amazonaws.services.autoscaling.model.transform.LimitExceededExceptionUnmarshaller",
"com.amazonaws.services.autoscaling.model.transform.AlreadyExistsExceptionUnmarshaller",
"com.amazonaws.services.autoscaling.model.transform.ResourceInUseExceptionUnmarshaller",
"com.amazonaws.services.securitytoken.model.AssumeRoleRequest",
"com.vmware.vim25.HostPatchManagerPatchManagerOperationSpec",
"com.amazonaws.auth.WebIdentityFederationSessionCredentialsProvider",
"com.amazonaws.services.elasticloadbalancing.AmazonElasticLoadBalancingClient",
"com.amazonaws.services.elasticloadbalancing.model.transform.ListenerNotFoundExceptionUnmarshaller",
"com.amazonaws.services.elasticloadbalancing.model.transform.SubnetNotFoundExceptionUnmarshaller",
"com.amazonaws.services.elasticloadbalancing.model.transform.InvalidConfigurationRequestExceptionUnmarshaller",
"com.amazonaws.services.elasticloadbalancing.model.transform.LoadBalancerAttributeNotFoundExceptionUnmarshaller",
"com.amazonaws.services.elasticloadbalancing.model.transform.CertificateNotFoundExceptionUnmarshaller",
"com.amazonaws.services.elasticloadbalancing.model.transform.TooManyPoliciesExceptionUnmarshaller",
"com.amazonaws.services.elasticloadbalancing.model.transform.InvalidSubnetExceptionUnmarshaller",
"com.amazonaws.services.elasticloadbalancing.model.transform.TooManyTagsExceptionUnmarshaller",
"com.amazonaws.services.elasticloadbalancing.model.transform.DuplicateTagKeysExceptionUnmarshaller",
"com.amazonaws.services.elasticloadbalancing.model.transform.InvalidSecurityGroupExceptionUnmarshaller",
"com.amazonaws.services.elasticloadbalancing.model.transform.LoadBalancerNotFoundExceptionUnmarshaller",
"com.amazonaws.services.elasticloadbalancing.model.transform.PolicyNotFoundExceptionUnmarshaller",
"com.amazonaws.services.elasticloadbalancing.model.transform.DuplicateListenerExceptionUnmarshaller",
"com.amazonaws.services.elasticloadbalancing.model.transform.TooManyLoadBalancersExceptionUnmarshaller",
"com.amazonaws.services.elasticloadbalancing.model.transform.PolicyTypeNotFoundExceptionUnmarshaller",
"com.amazonaws.services.elasticloadbalancing.model.transform.InvalidSchemeExceptionUnmarshaller",
"com.amazonaws.services.elasticloadbalancing.model.transform.InvalidInstanceExceptionUnmarshaller",
"com.amazonaws.services.elasticloadbalancing.model.transform.DuplicatePolicyNameExceptionUnmarshaller",
"com.amazonaws.services.elasticloadbalancing.model.transform.DuplicateLoadBalancerNameExceptionUnmarshaller",
"com.amazonaws.services.elasticloadbalancing.model.DescribeLoadBalancersRequest",
"com.amazonaws.services.s3.model.GetObjectRequest",
"com.amazonaws.services.s3.model.EncryptedGetObjectRequest",
"com.amazonaws.services.s3.model.S3ObjectIdBuilder",
"com.amazonaws.services.s3.model.ExtraMaterialsDescription$ConflictResolution",
"com.amazonaws.services.s3.model.ExtraMaterialsDescription",
"com.netflix.simianarmy.client.aws.chaos.ASGChaosCrawler$Types",
"com.netflix.simianarmy.basic.chaos.BasicInstanceGroup",
"com.netflix.simianarmy.aws.SimpleDBRecorder$Keys$1",
"com.netflix.simianarmy.aws.SimpleDBRecorder$Keys",
"com.amazonaws.services.simpledb.model.transform.PutAttributesRequestMarshaller",
"com.netflix.simianarmy.basic.LocalDbRecorder$MapDbRecorderEvent",
"com.amazonaws.services.ec2.model.DescribeSnapshotsRequest",
"com.amazonaws.services.ec2.model.transform.DescribeSnapshotsRequestMarshaller",
"com.amazonaws.services.ec2.model.transform.DescribeSnapshotsResultStaxUnmarshaller",
"com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClient",
"com.amazonaws.auth.AnonymousAWSCredentials",
"com.amazonaws.internal.StaticCredentialsProvider",
"com.amazonaws.services.securitytoken.model.transform.ExpiredTokenExceptionUnmarshaller",
"com.amazonaws.services.securitytoken.model.transform.IDPCommunicationErrorExceptionUnmarshaller",
"com.amazonaws.services.securitytoken.model.transform.MalformedPolicyDocumentExceptionUnmarshaller",
"com.amazonaws.services.securitytoken.model.transform.PackedPolicyTooLargeExceptionUnmarshaller",
"com.amazonaws.services.securitytoken.model.transform.IDPRejectedClaimExceptionUnmarshaller",
"com.amazonaws.services.securitytoken.model.transform.InvalidAuthorizationMessageExceptionUnmarshaller",
"com.amazonaws.services.securitytoken.model.transform.InvalidIdentityTokenExceptionUnmarshaller",
"com.netflix.simianarmy.aws.janitor.VolumeTaggingMonkey",
"com.vmware.vim25.HostSnmpConfigSpec",
"com.amazonaws.services.opsworks.model.UpdateAppRequest",
"com.netflix.simianarmy.conformity.ConformityMonkey$Type",
"com.amazonaws.services.opsworks.model.CreateLayerRequest",
"com.amazonaws.services.ec2.model.DescribeInstancesRequest",
"com.amazonaws.services.ec2.model.transform.DescribeInstancesRequestMarshaller",
"com.amazonaws.services.ec2.model.transform.DescribeInstancesResultStaxUnmarshaller",
"com.amazonaws.services.opsworks.model.CreateAppRequest",
"com.amazonaws.auth.STSAssumeRoleSessionCredentialsProvider",
"com.netflix.simianarmy.aws.janitor.rule.volume.DeleteOnTerminationRule",
"com.amazonaws.auth.STSSessionCredentialsProvider",
"com.amazonaws.services.autoscaling.model.DescribeAutoScalingGroupsRequest",
"com.amazonaws.services.autoscaling.model.transform.DescribeAutoScalingGroupsRequestMarshaller",
"com.amazonaws.services.autoscaling.model.transform.DescribeAutoScalingGroupsResultStaxUnmarshaller",
"com.amazonaws.services.securitytoken.model.transform.AssumeRoleRequestMarshaller",
"com.amazonaws.services.securitytoken.model.transform.AssumeRoleResultStaxUnmarshaller",
"com.amazonaws.auth.PropertiesFileCredentialsProvider",
"org.mapdb.DBMaker",
"org.mapdb.DB",
"org.mapdb.Volume",
"org.mapdb.Volume$1",
"org.mapdb.Store",
"org.mapdb.StoreDirect",
"org.mapdb.StoreWAL",
"org.mapdb.Utils$1",
"org.mapdb.Utils$2",
"org.mapdb.Utils",
"org.mapdb.Volume$ByteBufferVol",
"org.mapdb.Volume$MappedFileVol",
"org.mapdb.LongMap",
"org.mapdb.LongConcurrentHashMap",
"org.mapdb.LongConcurrentHashMap$Segment",
"org.mapdb.LongConcurrentHashMap$HashEntry",
"org.mapdb.LongHashMap",
"org.mapdb.EngineWrapper",
"org.mapdb.AsyncWriteEngine",
"org.mapdb.AsyncWriteEngine$WriterRunnable",
"org.mapdb.Caches$HashTable",
"org.mapdb.SnapshotEngine",
"org.mapdb.DBMaker$1",
"org.mapdb.Serializer$1",
"org.mapdb.Serializer$2",
"org.mapdb.Serializer$3",
"org.mapdb.Serializer$4",
"org.mapdb.Serializer$5",
"org.mapdb.SerializerBase",
"org.mapdb.Serializer$6",
"org.mapdb.Serializer$7",
"org.mapdb.Serializer",
"org.mapdb.DataInput2",
"org.mapdb.Fun$1",
"org.mapdb.Fun",
"org.mapdb.Fun$Tuple2",
"org.mapdb.Caches$HashTable$HashItem",
"org.mapdb.SerializerPojo$1",
"org.mapdb.SerializerPojo",
"com.amazonaws.services.ec2.model.Tag",
"com.amazonaws.services.ec2.model.CreateTagsRequest",
"com.amazonaws.services.ec2.model.transform.CreateTagsRequestMarshaller",
"com.netflix.simianarmy.conformity.ConformityMonkey",
"com.netflix.simianarmy.basic.conformity.BasicConformityMonkey",
"org.jclouds.compute.options.RunScriptOptions$ImmutableRunScriptOptions",
"org.jclouds.compute.options.RunScriptOptions",
"com.google.common.collect.ImmutableCollection",
"com.google.common.collect.ImmutableSet",
"com.google.common.collect.SingletonImmutableSet",
"org.jclouds.compute.options.TemplateOptions$ImmutableTemplateOptions",
"com.google.common.collect.EmptyImmutableSet",
"org.jclouds.compute.options.TemplateOptions",
"com.amazonaws.services.sqs.model.SetQueueAttributesRequest",
"com.netflix.servo.tag.SortedTagList$Builder",
"com.google.common.collect.ImmutableMap",
"com.google.common.collect.ImmutableSortedMapFauxverideShim",
"com.google.common.collect.Ordering",
"com.google.common.collect.NaturalOrdering",
"com.google.common.collect.EmptyImmutableSortedMap",
"com.google.common.collect.ImmutableSortedSetFauxverideShim",
"com.google.common.collect.EmptyImmutableSortedSet",
"com.google.common.collect.ImmutableSortedSet",
"com.google.common.collect.ImmutableSortedMap",
"com.google.common.collect.Maps$EntryFunction",
"com.google.common.collect.ByFunctionOrdering",
"com.netflix.servo.tag.SortedTagList",
"com.google.common.collect.UnmodifiableIterator",
"com.google.common.collect.UnmodifiableListIterator",
"com.google.common.collect.Iterators$1",
"com.google.common.collect.Iterators$2",
"com.google.common.collect.Iterators",
"com.netflix.servo.tag.BasicTagList",
"com.google.common.collect.Interners",
"com.google.common.collect.Interners$WeakInterner",
"com.google.common.collect.GenericMapMaker",
"com.google.common.collect.MapMaker",
"com.google.common.collect.MapMakerInternalMap$Strength",
"com.google.common.base.Equivalence",
"com.google.common.base.Equivalence$Equals",
"com.google.common.collect.MapMakerInternalMap$1",
"com.google.common.collect.MapMakerInternalMap$2",
"com.google.common.collect.MapMakerInternalMap",
"com.google.common.base.MoreObjects",
"com.google.common.base.Equivalence$Identity",
"com.google.common.collect.MapMakerInternalMap$EntryFactory",
"com.google.common.base.Ticker$1",
"com.google.common.base.Ticker",
"com.google.common.collect.GenericMapMaker$NullListener",
"com.google.common.collect.MapMakerInternalMap$Segment",
"com.netflix.servo.tag.Tags",
"com.amazonaws.services.ec2.model.DetachVolumeRequest",
"com.amazonaws.services.ec2.model.transform.DetachVolumeRequestMarshaller",
"com.amazonaws.services.ec2.model.transform.DetachVolumeResultStaxUnmarshaller",
"com.amazonaws.auth.PropertiesCredentials",
"com.amazonaws.services.sns.model.SetPlatformApplicationAttributesRequest",
"com.amazonaws.services.s3.model.ObjectMetadata",
"com.vmware.vim25.PerformanceManagerCounterLevelMapping",
"com.amazonaws.services.ec2.model.DeleteSnapshotRequest",
"com.amazonaws.services.ec2.model.transform.DeleteSnapshotRequestMarshaller",
"com.amazonaws.services.cognitoidentity.model.UnlinkIdentityRequest",
"com.amazonaws.event.ProgressListener$ExceptionReporter",
"com.amazonaws.auth.profile.internal.AbstractProfilesConfigFileScanner",
"com.amazonaws.auth.profile.internal.ProfilesConfigFileLoader$ProfilesConfigFileLoaderHelper",
"com.amazonaws.services.sns.model.CreatePlatformEndpointRequest",
"com.amazonaws.services.sqs.model.CreateQueueRequest",
"com.amazonaws.services.s3.model.S3Object",
"com.google.common.collect.RegularImmutableList",
"com.google.common.collect.ObjectArrays",
"com.google.common.collect.ImmutableList",
"com.amazonaws.services.securitytoken.model.AssumeRoleWithWebIdentityRequest",
"com.amazonaws.services.securitytoken.model.transform.AssumeRoleWithWebIdentityRequestMarshaller",
"com.amazonaws.services.securitytoken.model.transform.AssumeRoleWithWebIdentityResultStaxUnmarshaller",
"com.amazonaws.services.ec2.model.DeregisterImageRequest",
"com.amazonaws.services.ec2.model.transform.DeregisterImageRequestMarshaller",
"com.amazonaws.services.autoscaling.model.DeleteAutoScalingGroupRequest",
"com.amazonaws.services.autoscaling.model.transform.DeleteAutoScalingGroupRequestMarshaller",
"com.netflix.simianarmy.chaos.ChaosInstance",
"com.amazonaws.services.elasticloadbalancing.model.DescribeTagsRequest",
"com.amazonaws.services.autoscaling.model.DescribeAutoScalingInstancesRequest",
"com.amazonaws.services.autoscaling.model.transform.DescribeAutoScalingInstancesRequestMarshaller",
"com.amazonaws.services.autoscaling.model.transform.DescribeAutoScalingInstancesResultStaxUnmarshaller",
"com.amazonaws.services.elasticloadbalancing.model.transform.DescribeLoadBalancersRequestMarshaller",
"com.amazonaws.services.elasticloadbalancing.model.transform.DescribeLoadBalancersResultStaxUnmarshaller",
"com.vmware.vim25.ImportSpec",
"com.vmware.vim25.VirtualMachineConfigSpec",
"com.amazonaws.services.elasticloadbalancing.model.DescribeLoadBalancerAttributesRequest",
"com.amazonaws.services.elasticloadbalancing.model.transform.DescribeLoadBalancerAttributesRequestMarshaller",
"com.amazonaws.services.elasticloadbalancing.model.transform.DescribeLoadBalancerAttributesResultStaxUnmarshaller",
"org.jclouds.config.ValueOfConfigurationKeyOrNull",
"org.jclouds.compute.config.GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull",
"org.apache.http.client.methods.HttpTrace",
"com.amazonaws.http.HttpResponse",
"com.amazonaws.Response",
"com.netflix.simianarmy.Monkey$1",
"com.amazonaws.services.simpledb.model.SelectResult",
"com.amazonaws.services.ec2.model.DescribeVolumesRequest",
"com.amazonaws.services.ec2.model.transform.DescribeVolumesRequestMarshaller",
"com.amazonaws.services.ec2.model.transform.DescribeVolumesResultStaxUnmarshaller",
"com.amazonaws.services.sns.model.CreatePlatformApplicationRequest",
"com.amazonaws.services.cognitoidentity.model.GetIdRequest",
"com.fasterxml.jackson.core.json.ReaderBasedJsonParser",
"com.fasterxml.jackson.core.JsonProcessingException",
"com.fasterxml.jackson.databind.JsonMappingException",
"com.fasterxml.jackson.core.JsonLocation",
"com.amazonaws.services.opsworks.model.Source",
"com.amazonaws.services.s3.model.InitiateMultipartUploadRequest",
"com.amazonaws.services.s3.model.EncryptedInitiateMultipartUploadRequest",
"com.amazonaws.services.s3.model.PutObjectRequest",
"com.amazonaws.services.s3.model.EncryptedPutObjectRequest",
"com.amazonaws.services.cognitoidentity.model.CreateIdentityPoolRequest",
"com.amazonaws.event.SyncProgressListener",
"com.amazonaws.event.ProgressTracker$1",
"com.amazonaws.event.request.Progress",
"com.amazonaws.event.request.ProgressSupport",
"com.amazonaws.event.ProgressTracker",
"com.amazonaws.services.securitytoken.model.GetSessionTokenRequest",
"com.amazonaws.services.securitytoken.model.transform.GetSessionTokenRequestMarshaller",
"com.amazonaws.services.securitytoken.model.transform.GetSessionTokenResultStaxUnmarshaller",
"com.amazonaws.services.sns.model.SetEndpointAttributesRequest",
"com.amazonaws.services.s3.model.BucketTaggingConfiguration",
"com.amazonaws.services.s3.model.EncryptionMaterials",
"com.netflix.simianarmy.chaos.SshConfig",
"org.jclouds.domain.Credentials",
"org.jclouds.domain.LoginCredentials",
"org.jclouds.domain.Credentials$Builder",
"org.jclouds.domain.LoginCredentials$Builder",
"com.google.common.base.Optional",
"com.google.common.base.Absent"
);
}
}
|
3e0c2e9bc205a1e0e626296bd4cb2d74b65da75c | 502 | java | Java | serenity-core/src/test/java/net/thucydides/core/model/samples/MyBaseStepLibrary.java | ricardorlg-aval/serenity-core | 97ee446aa544545a642a21c36090015d1bc733c1 | [
"Apache-2.0"
] | 649 | 2015-01-14T13:07:04.000Z | 2022-03-27T15:06:48.000Z | serenity-core/src/test/java/net/thucydides/core/model/samples/MyBaseStepLibrary.java | timai89/serenity-core | f561ab70fa8d651fb171e332543d727701269dbd | [
"Apache-2.0"
] | 2,344 | 2015-01-06T16:21:46.000Z | 2022-03-31T13:44:14.000Z | serenity-core/src/test/java/net/thucydides/core/model/samples/MyBaseStepLibrary.java | timai89/serenity-core | f561ab70fa8d651fb171e332543d727701269dbd | [
"Apache-2.0"
] | 571 | 2015-01-19T02:25:31.000Z | 2022-03-29T15:46:13.000Z | 22.818182 | 61 | 0.673307 | 5,170 | package net.thucydides.core.model.samples;
import net.thucydides.core.annotations.Step;
import net.thucydides.core.pages.Pages;
import net.thucydides.core.steps.ScenarioSteps;
public class MyBaseStepLibrary extends ScenarioSteps {
MyBaseStepLibrary(Pages pages) {
super(pages);
}
@Step
public void aStep() {}
@Step
protected boolean aProtectedStep() { return true; }
protected boolean aProtectedMethod() { return true; }
}
|
3e0c2f5e4c37467fa50fe09900fa48b6a35b3993 | 1,206 | java | Java | src/main/java/org/thinkit/generator/common/catalog/Modifier.java | myConsciousness/generator-commons | 3d0484dedfee2f260116f28ac5b7c7480f8e1aad | [
"Apache-2.0"
] | 1 | 2020-08-24T01:59:50.000Z | 2020-08-24T01:59:50.000Z | src/main/java/org/thinkit/generator/common/catalog/Modifier.java | myConsciousness/generator-commons | 3d0484dedfee2f260116f28ac5b7c7480f8e1aad | [
"Apache-2.0"
] | 12 | 2020-07-29T03:00:02.000Z | 2020-12-24T03:27:15.000Z | src/main/java/org/thinkit/generator/common/catalog/Modifier.java | myConsciousness/generator-commons | 3d0484dedfee2f260116f28ac5b7c7480f8e1aad | [
"Apache-2.0"
] | null | null | null | 19.451613 | 100 | 0.645937 | 5,171 | /*
* Copyright 2020 Kato Shinya.
*
* 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.thinkit.generator.common.catalog;
import org.thinkit.api.catalog.Catalog;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
* アクセス修飾子を管理するカタログです。
*
* @author Kato Shinya
* @since 1.0.0
*/
@RequiredArgsConstructor
public enum Modifier implements Catalog<Modifier> {
/**
* 指定なし
*/
NONE(0),
/**
* public
*/
PUBLIC(1),
/**
* protected
*/
PROTECTED(2),
/**
* private
*/
PRIVATE(3),
/**
* package private
*/
PACKAGE(4);
/**
* コード値
*/
@Getter
private final int code;
}
|
3e0c304f3b0f8e58d942aa42494a21830917e93d | 1,485 | java | Java | src/main/java/gchat/lastseen/LastSeenService.java | sandeep0402/chat-application-system-design | a608a4f81a7fbf33826aa0605d1944ae97859133 | [
"MIT"
] | null | null | null | src/main/java/gchat/lastseen/LastSeenService.java | sandeep0402/chat-application-system-design | a608a4f81a7fbf33826aa0605d1944ae97859133 | [
"MIT"
] | null | null | null | src/main/java/gchat/lastseen/LastSeenService.java | sandeep0402/chat-application-system-design | a608a4f81a7fbf33826aa0605d1944ae97859133 | [
"MIT"
] | null | null | null | 33 | 80 | 0.695623 | 5,172 | package gchat.lastseen;
import gchat.user.User;
import gchat.user.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.Optional;
@Service
@RequiredArgsConstructor
@Slf4j
public class LastSeenService {
private final LastSeenRepository lastSeenRepository;
private final UserService userService;
@Async()
public void recordLastSeenDateTime(Authentication auth){
String username = (((org.springframework.security.core.userdetails.User)
auth.getPrincipal()).getUsername());
User currentUser = userService.findByUsername(username);
if(currentUser == null || currentUser.getId()==null){
return;
}
String userId = currentUser.getId().toString();
Optional<LastSeen> lastSeenObject = lastSeenRepository.findById(userId);
LastSeen lastSeen;
if(lastSeenObject.isPresent()){
lastSeen = lastSeenObject.get();
lastSeen.setLastSeenAt(LocalDateTime.now());
}else{
lastSeen = LastSeen.builder()
.userId(userId).lastSeenAt(LocalDateTime.now()).build();
}
log.info("user id: "+ userId +", Last seen record updated.");
lastSeenRepository.save(lastSeen);
}
}
|
3e0c30c2c4874c2e16eb7d8a5e848c2faedbcd4e | 44,043 | java | Java | fdb-record-layer-core/src/test/java/com/apple/foundationdb/record/provider/foundationdb/keyspace/LocatableResolverTest.java | 0xflotus/fdb-record-layer | 7e49ce31c0f9fc15652e2003f7d63801e4ec4be1 | [
"Apache-2.0"
] | 1 | 2019-06-27T01:12:11.000Z | 2019-06-27T01:12:11.000Z | fdb-record-layer-core/src/test/java/com/apple/foundationdb/record/provider/foundationdb/keyspace/LocatableResolverTest.java | 0xflotus/fdb-record-layer | 7e49ce31c0f9fc15652e2003f7d63801e4ec4be1 | [
"Apache-2.0"
] | null | null | null | fdb-record-layer-core/src/test/java/com/apple/foundationdb/record/provider/foundationdb/keyspace/LocatableResolverTest.java | 0xflotus/fdb-record-layer | 7e49ce31c0f9fc15652e2003f7d63801e4ec4be1 | [
"Apache-2.0"
] | null | null | null | 48.029444 | 154 | 0.645097 | 5,173 | /*
* LocatableResolverTest.java
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2015-2018 Apple Inc. and the FoundationDB project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.apple.foundationdb.record.provider.foundationdb.keyspace;
import com.apple.foundationdb.Range;
import com.apple.foundationdb.async.AsyncUtil;
import com.apple.foundationdb.async.MoreAsyncUtil;
import com.apple.foundationdb.record.RecordCoreException;
import com.apple.foundationdb.record.provider.foundationdb.FDBDatabase;
import com.apple.foundationdb.record.provider.foundationdb.FDBDatabaseFactory;
import com.apple.foundationdb.record.provider.foundationdb.FDBRecordContext;
import com.apple.foundationdb.record.provider.foundationdb.FDBStoreTimer;
import com.apple.foundationdb.record.provider.foundationdb.keyspace.LocatableResolver.LocatableResolverLockedException;
import com.apple.foundationdb.record.provider.foundationdb.keyspace.ResolverCreateHooks.MetadataHook;
import com.apple.foundationdb.record.provider.foundationdb.keyspace.ResolverCreateHooks.PreWriteCheck;
import com.apple.foundationdb.tuple.Tuple;
import com.apple.test.Tags;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheStats;
import com.google.common.collect.ImmutableList;
import org.apache.commons.lang3.tuple.Pair;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static com.apple.foundationdb.record.TestHelpers.ExceptionMessageMatcher.hasMessageContaining;
import static com.apple.foundationdb.record.TestHelpers.consistently;
import static com.apple.foundationdb.record.TestHelpers.eventually;
import static com.apple.foundationdb.record.provider.foundationdb.keyspace.KeySpaceDirectory.KeyType;
import static com.apple.foundationdb.record.provider.foundationdb.keyspace.ResolverCreateHooks.DEFAULT_CHECK;
import static com.apple.foundationdb.record.provider.foundationdb.keyspace.ResolverCreateHooks.DEFAULT_HOOK;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.core.Is.is;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.fail;
/**
* Tests for {@link LocatableResolver}.
*/
@Tag(Tags.WipesFDB)
@Tag(Tags.RequiresFDB)
public abstract class LocatableResolverTest {
protected FDBDatabase database;
protected LocatableResolver globalScope;
protected BiFunction<FDBRecordContext, KeySpacePath, LocatableResolver> scopedDirectoryGenerator;
protected Function<FDBDatabase, LocatableResolver> globalScopeGenerator;
protected Random random;
@BeforeEach
public void setup() {
FDBDatabaseFactory factory = FDBDatabaseFactory.instance();
factory.setDirectoryCacheSize(100);
long seed = System.currentTimeMillis();
System.out.println("Seed " + seed);
random = new Random(seed);
database = factory.getDatabase();
// clear all state in the db
database.close();
// resets the lock cache
database.setResolverStateRefreshTimeMillis(30000);
globalScope = globalScopeGenerator.apply(database);
wipeFDB();
}
@Test
public void testLookupCaching() {
KeySpace keySpace = new KeySpace(new KeySpaceDirectory("path", KeyType.STRING, "path"));
FDBRecordContext context = database.openContext();
KeySpacePath path1 = keySpace.pathFromKey(context, Tuple.from("path"));
LocatableResolver resolver = scopedDirectoryGenerator.apply(context, path1);
Long value = resolver.resolve(context.getTimer(), "foo").join();
context = database.openContext();
for (int i = 0; i < 5; i++) {
Long fetched = resolver.resolve(context.getTimer(), "foo").join();
assertThat("we should always get the original value", fetched, is(value));
}
CacheStats stats = context.getDatabase().getDirectoryCacheStats();
assertThat("subsequent lookups should hit the cache", stats.hitCount(), is(5L));
}
@Test
public void testDirectoryIsolation() {
KeySpace keySpace = new KeySpace(
new KeySpaceDirectory("path", KeyType.STRING, "path")
.addSubdirectory(new KeySpaceDirectory("to", KeyType.STRING, "to")
.addSubdirectory(new KeySpaceDirectory("dirLayer1", KeyType.STRING, "dirLayer1"))
.addSubdirectory(new KeySpaceDirectory("dirLayer2", KeyType.STRING, "dirLayer2"))
)
);
try (FDBRecordContext context = database.openContext()) {
KeySpacePath path1 = keySpace.pathFromKey(context, Tuple.from("path", "to", "dirLayer1"));
KeySpacePath path2 = keySpace.pathFromKey(context, Tuple.from("path", "to", "dirLayer2"));
LocatableResolver resolver = scopedDirectoryGenerator.apply(context, path1);
LocatableResolver sameResolver = scopedDirectoryGenerator.apply(context, path1);
LocatableResolver differentResolver = scopedDirectoryGenerator.apply(context, path2);
List<String> names = ImmutableList.of("a", "set", "of", "names", "to", "resolve");
List<Long> resolved = new ArrayList<>();
List<Long> same = new ArrayList<>();
List<Long> different = new ArrayList<>();
for (String name : names) {
resolved.add(resolver.resolve(context.getTimer(), name).join());
same.add(sameResolver.resolve(context.getTimer(), name).join());
different.add(differentResolver.resolve(context.getTimer(), name).join());
}
assertThat("same resolvers produce identical results", resolved, contains(same.toArray()));
assertThat("different resolvers are independent", resolved, not(contains(different.toArray())));
}
}
@Test
public void testScopedCaching() {
KeySpace keySpace = new KeySpace(
new KeySpaceDirectory("path1", KeyType.STRING, "path1"),
new KeySpaceDirectory("path2", KeyType.STRING, "path2")
);
FDBRecordContext context = database.openContext();
final KeySpacePath path1 = keySpace.pathFromKey(context, Tuple.from("path1"));
final LocatableResolver resolver1 = scopedDirectoryGenerator.apply(context, path1);
Cache<ScopedValue<String>, Long> cache = CacheBuilder.newBuilder().build();
cache.put(resolver1.wrap("stuff"), 1L);
assertThat("values can be read from the cache by scoped string",
cache.getIfPresent(resolver1.wrap("stuff")), is(1L));
assertThat("cache misses when looking for unknown name in scope",
cache.getIfPresent(resolver1.wrap("missing")), equalTo(null));
final KeySpacePath path2 = keySpace.pathFromKey(context, Tuple.from("path2"));
final LocatableResolver resolver2 = scopedDirectoryGenerator.apply(context, path2);
assertThat("cache misses when string is not in this scope",
cache.getIfPresent(resolver2.wrap("stuff")), equalTo(null));
final LocatableResolver newResolver = scopedDirectoryGenerator.apply(context, path1);
assertThat("scoping is determined by value of scope directory, not a reference to it",
cache.getIfPresent(newResolver.wrap("stuff")), is(1L));
}
@Test
public void testDirectoryCache() {
FDBDatabaseFactory factory = FDBDatabaseFactory.instance();
factory.setDirectoryCacheSize(10);
FDBStoreTimer timer = new FDBStoreTimer();
FDBDatabase fdb = factory.getDatabase();
fdb.close(); // Make sure cache is fresh.
String key = "world";
Long value;
try (FDBRecordContext context = fdb.openContext()) {
context.setTimer(timer);
value = context.asyncToSync(FDBStoreTimer.Waits.WAIT_DIRECTORY_RESOLVE, globalScope.resolve(context.getTimer(), key));
}
int initialReads = timer.getCount(FDBStoreTimer.Events.DIRECTORY_READ);
assertThat(initialReads, is(greaterThanOrEqualTo(1)));
for (int i = 0; i < 10; i++) {
try (FDBRecordContext context = fdb.openContext()) {
context.setTimer(timer);
assertThat("we continue to resolve the same value",
context.asyncToSync(FDBStoreTimer.Waits.WAIT_DIRECTORY_RESOLVE, globalScope.resolve(context.getTimer(), key)),
is(value));
}
}
assertEquals(timer.getCount(FDBStoreTimer.Events.DIRECTORY_READ), initialReads);
}
@Test
public void testResolveUseCacheCommits() {
FDBDatabaseFactory factory = FDBDatabaseFactory.instance();
factory.setDirectoryCacheSize(10);
FDBStoreTimer timer = new FDBStoreTimer();
String key = "hello " + UUID.randomUUID();
FDBDatabase fdb = factory.getDatabase();
assertEquals(0, timer.getCount(FDBStoreTimer.Events.COMMIT));
try (FDBRecordContext context = fdb.openContext()) {
context.setTimer(timer);
context.asyncToSync(FDBStoreTimer.Waits.WAIT_DIRECTORY_RESOLVE, globalScope.resolve(context.getTimer(), key));
}
// initial resolve may commit twice, once for the key and once to initialize the reverse directory cache
assertThat(timer.getCount(FDBStoreTimer.Events.COMMIT), is(greaterThanOrEqualTo(1)));
timer.reset();
try (FDBRecordContext context = fdb.openContext()) {
context.setTimer(timer);
context.asyncToSync(FDBStoreTimer.Waits.WAIT_DIRECTORY_RESOLVE, globalScope.resolve(context.getTimer(), "a-new-key"));
}
assertEquals(1, timer.getCount(FDBStoreTimer.Events.COMMIT));
timer.reset();
assertEquals(0, timer.getCount(FDBStoreTimer.Events.COMMIT));
try (FDBRecordContext context = fdb.openContext()) {
context.setTimer(timer);
context.asyncToSync(FDBStoreTimer.Waits.WAIT_DIRECTORY_RESOLVE, globalScope.resolve(context.getTimer(), key));
}
assertEquals(0, timer.getCount(FDBStoreTimer.Events.COMMIT));
}
@Test
public void testResolveCommitsWhenCacheEnabled() {
Map<String, Long> mappings = new HashMap<>();
try (FDBRecordContext context = database.openContext()) {
for (int i = 0; i < 10; i++) {
String key = "string-" + i;
Long value = globalScope.resolve(context.getTimer(), key).join();
mappings.put(key, value);
}
}
Long baseline = database.getDirectoryCacheStats().hitCount();
Long reverseCacheBaseline = database.getReverseDirectoryInMemoryCache().stats().hitCount();
database.close();
database = FDBDatabaseFactory.instance().getDatabase();
try (FDBRecordContext context = database.openContext()) {
for (Map.Entry<String, Long> entry : mappings.entrySet()) {
Long value = globalScope.resolve(context.getTimer(), entry.getKey()).join();
String name = globalScope.reverseLookup(null, value).join();
assertEquals(value, entry.getValue(), "mapping is persisted even though context in arg was not committed");
assertEquals(name, entry.getKey(), "reverse mapping is persisted even though context in arg was not committed");
}
assertEquals(database.getDirectoryCacheStats().hitCount() - baseline, 0L, "values are persisted, not in cache");
assertEquals(database.getReverseDirectoryInMemoryCache().stats().hitCount() - reverseCacheBaseline, 0L, "values are persisted, not in cache");
}
}
@Test
public void testResolveWithNoMetadata() {
Long value;
ResolverResult noHookResult;
value = globalScope.resolve(null, "resolve-string").join();
noHookResult = globalScope.resolveWithMetadata(null, "resolve-string", ResolverCreateHooks.getDefault()).join();
assertThat("the value is the same", noHookResult.getValue(), is(value));
assertThat("entry was created without metadata", noHookResult.getMetadata(), is(nullValue()));
}
@Test
public void testReverseLookup() {
Long value;
try (FDBRecordContext context = database.openContext()) {
value = globalScope.resolve(context.getTimer(), "something").join();
context.commit();
}
String lookupString = globalScope.reverseLookup(null, value).join();
assertThat("reverse lookup works in a new context", lookupString, is("something"));
}
@Test
public void testReverseLookupNotFound() {
try {
globalScope.reverseLookup(null, -1L).join();
fail("should throw CompletionException");
} catch (CompletionException ex) {
assertThat(ex.getCause(), is(instanceOf(NoSuchElementException.class)));
}
}
@Test
public void testReverseLookupCaching() {
Long value;
try (FDBRecordContext context = database.openContext()) {
value = globalScope.resolve(context.getTimer(), "something").join();
context.commit();
}
database.clearForwardDirectoryCache();
long baseHitCount = database.getReverseDirectoryInMemoryCache().stats().hitCount();
long baseMissCount = database.getReverseDirectoryInMemoryCache().stats().missCount();
String name = globalScope.reverseLookup(null, value).join();
assertThat("reverse lookup gives previous result", name, is("something"));
long hitCount = database.getReverseDirectoryInMemoryCache().stats().hitCount();
long missCount = database.getReverseDirectoryInMemoryCache().stats().missCount();
assertEquals(0L, hitCount - baseHitCount);
assertEquals(1L, missCount - baseMissCount);
// repeated lookups use the in-memory cache
for (int i = 0; i < 10; i++) {
name = globalScope.reverseLookup(null, value).join();
assertThat("reverse lookup gives the same result", name, is("something"));
}
hitCount = database.getReverseDirectoryInMemoryCache().stats().hitCount();
missCount = database.getReverseDirectoryInMemoryCache().stats().missCount();
assertEquals(10L, hitCount - baseHitCount);
assertEquals(1L, missCount - baseMissCount);
}
@Test
public void testCacheConsistency() {
final AtomicBoolean keepRunning = new AtomicBoolean(true);
final List<Pair<String, ResolverResult>> cacheHits = new ArrayList<>();
final List<Pair<Long, String>> reverseCacheHits = new ArrayList<>();
CompletableFuture<Void> loopOperation = AsyncUtil.whileTrue(() ->
MoreAsyncUtil.delayedFuture(1, TimeUnit.MILLISECONDS)
.thenRun(() -> gatherCacheHits(database.getDirectoryCache(/* always return current version */ 0), cacheHits))
.thenRun(() -> gatherCacheHits(database.getReverseDirectoryInMemoryCache(), reverseCacheHits))
.thenApply(ignored2 -> keepRunning.get())
);
List<CompletableFuture<Pair<String, ResolverResult>>> allocationOperations = IntStream.range(0, 50)
.mapToObj(i -> "string-" + i)
.map(name -> database.run(ctx -> globalScope.resolveWithMetadata(ctx.getTimer(), name, ResolverCreateHooks.getDefault()))
.thenApply(result -> Pair.of(name, result))
)
.collect(Collectors.toList());
List<Pair<String, ResolverResult>> allocations = AsyncUtil.getAll(allocationOperations).thenApply(list -> {
keepRunning.set(false);
return list;
}).join();
loopOperation.join();
List<Pair<Long, String>> reverseAllocations = allocations.stream()
.map(e -> Pair.of(e.getValue().getValue(), e.getKey()))
.collect(Collectors.toList());
validateCacheHits(cacheHits, allocations,
(context, name) -> globalScope.resolveWithMetadata(context.getTimer(), name, ResolverCreateHooks.getDefault()));
validateCacheHits(reverseCacheHits, reverseAllocations,
(context, value) -> globalScope.reverseLookup(null, value));
}
private <K, V> void validateCacheHits(List<Pair<K, V>> cacheHits,
List<Pair<K, V>> allocations,
BiFunction<FDBRecordContext, K, CompletableFuture<V>> persistedMappingSupplier) {
for (Pair<K, V> pair : cacheHits) {
V persistedMapping;
try (FDBRecordContext context = database.openContext()) {
persistedMapping = persistedMappingSupplier.apply(context, pair.getKey()).join();
}
assertThat("every cache hit corresponds to an allocation", allocations, hasItem(equalTo(pair)));
assertEquals(persistedMapping, pair.getValue(), "all cache hits correspond to a persisted mapping");
}
}
private <K, V> void gatherCacheHits(Cache<ScopedValue<K>, V> cache, List<Pair<K, V>> cacheHits) {
cacheHits.addAll(
cache.asMap().entrySet().stream().map(e -> Pair.of(e.getKey().getData(), e.getValue())).collect(Collectors.toList())
);
}
@Test
public void testParallelSet() {
String key = "some-random-key-" + random.nextLong();
List<CompletableFuture<Long>> allocations = new ArrayList<>();
for (int i = 0; i < 20; i++) {
allocations.add(allocateInNewContext(key, globalScope));
}
Set<Long> allocationSet = new HashSet<>(AsyncUtil.getAll(allocations).join());
assertThat("only one value is allocated", allocationSet, hasSize(1));
}
private CompletableFuture<Long> allocateInNewContext(String key, LocatableResolver resolver) {
FDBRecordContext context = database.openContext();
return resolver.resolve(context.getTimer(), key).whenComplete((ignore1, ignore2) -> context.close());
}
@Test
public void testWriteLockCaching() {
FDBStoreTimer timer = new FDBStoreTimer();
try (FDBRecordContext context = database.openContext()) {
context.setTimer(timer);
globalScope.resolve(context.getTimer(), "something").join();
int initialCount = timer.getCount(FDBStoreTimer.DetailEvents.RESOLVER_STATE_READ);
assertThat("first read must check the lock in the database", initialCount, greaterThanOrEqualTo(1));
timer.reset();
int oldCount = timer.getCount(FDBStoreTimer.DetailEvents.RESOLVER_STATE_READ);
for (int i = 0; i < 10; i++) {
globalScope.resolve(context.getTimer(), "something-" + i).join();
// depending on the nature of the write safety check we may need to read the key multiple times
// so assert that we do at least one read on each resolve
int currentCount = timer.getCount(FDBStoreTimer.DetailEvents.RESOLVER_STATE_READ);
assertThat("subsequent writes must also check the key",
currentCount, is(greaterThan(oldCount)));
oldCount = currentCount;
}
timer.reset();
for (int i = 0; i < 10; i++) {
globalScope.resolve(context.getTimer(), "something-" + i).join();
}
assertThat("reads do not need to check the key",
timer.getCount(FDBStoreTimer.DetailEvents.RESOLVER_STATE_READ), is(0));
}
FDBDatabaseFactory.instance().clear();
FDBDatabase newDatabase = FDBDatabaseFactory.instance().getDatabase();
FDBStoreTimer timer2 = new FDBStoreTimer();
try (FDBRecordContext context = newDatabase.openContext()) {
context.setTimer(timer2);
globalScope.resolve(context.getTimer(), "something").join();
assertThat("state is loaded from the new database",
timer2.getCount(FDBStoreTimer.DetailEvents.RESOLVER_STATE_READ), is(1));
}
}
@Test
public void testCachingPerDbPerResolver() {
KeySpace keySpace = new KeySpace(
new KeySpaceDirectory("resolver1", KeyType.STRING, "resolver1"),
new KeySpaceDirectory("resolver2", KeyType.STRING, "resolver2"));
LocatableResolver resolver1;
LocatableResolver resolver2;
FDBStoreTimer timer = new FDBStoreTimer();
try (FDBRecordContext context = database.openContext()) {
resolver1 = scopedDirectoryGenerator.apply(context, keySpace.path("resolver1"));
resolver2 = scopedDirectoryGenerator.apply(context, keySpace.path("resolver2"));
context.setTimer(timer);
for (int i = 0; i < 10; i++) {
resolver1.getVersion(context.getTimer()).join();
}
assertThat("We only read the value once", timer.getCount(FDBStoreTimer.DetailEvents.RESOLVER_STATE_READ), is(1));
timer = new FDBStoreTimer();
assertThat("count is reset", timer.getCount(FDBStoreTimer.DetailEvents.RESOLVER_STATE_READ), is(0));
context.setTimer(timer);
resolver2.getVersion(context.getTimer()).join();
assertThat("We have to read the value for the new resolver", timer.getCount(FDBStoreTimer.DetailEvents.RESOLVER_STATE_READ), is(1));
LocatableResolver newResolver1 = scopedDirectoryGenerator.apply(context, keySpace.path("resolver1"));
timer = new FDBStoreTimer();
assertThat("count is reset", timer.getCount(FDBStoreTimer.DetailEvents.RESOLVER_STATE_READ), is(0));
context.setTimer(timer);
for (int i = 0; i < 10; i++) {
newResolver1.getVersion(context.getTimer()).join();
}
assertThat("we still hit the cache", timer.getCount(FDBStoreTimer.DetailEvents.RESOLVER_STATE_READ), is(0));
}
}
@Test
public void testEnableDisableWriteLock() {
database.setResolverStateRefreshTimeMillis(100);
final Long value;
try (FDBRecordContext context = database.openContext()) {
// resolver starts in unlocked state
value = globalScope.resolve(context.getTimer(), "some-string").join();
}
globalScope.enableWriteLock().join();
assertLocked(database, globalScope);
try (FDBRecordContext context = database.openContext()) {
consistently("we should still be able to read the old value", () ->
globalScope.resolve(context.getTimer(), "some-string").join(), is(value), 100, 10);
}
globalScope.disableWriteLock().join();
try (FDBRecordContext context = database.openContext()) {
eventually("writes should succeed", () -> {
try {
globalScope.resolve(context.getTimer(), "random-value-" + random.nextLong()).join();
} catch (CompletionException exception) {
return exception.getCause();
}
return null;
}, is(nullValue()), 120, 10);
consistently("writes should continue to succeed", () -> {
try {
globalScope.resolve(context.getTimer(), "random-value-" + random.nextLong()).join();
} catch (CompletionException exception) {
return exception.getCause();
}
return null;
}, is(nullValue()), 100, 10);
}
}
@Test
public void testExclusiveLock() {
// version is cached for 30 seconds by default
database.setResolverStateRefreshTimeMillis(100);
globalScope.exclusiveLock().join();
assertLocked(database, globalScope);
try {
globalScope.exclusiveLock().join();
fail("lock already enabled, should fail");
} catch (CompletionException ex) {
assertThat("we get the correct cause", ex.getCause(), allOf(
instanceOf(LocatableResolverLockedException.class),
hasMessageContaining("resolver must be unlocked to get exclusive lock")
));
}
}
@Test
public void testExclusiveLockParallel() {
// test that when parallel threads/instances attempt to get the exclusive lock only one will win.
List<CompletableFuture<Void>> parallelGets = new ArrayList<>();
AtomicInteger lockGetCount = new AtomicInteger();
for (int i = 0; i < 20; i++) {
parallelGets.add(globalScope.exclusiveLock().handle((ignore, ex) -> {
if (ex == null) {
lockGetCount.incrementAndGet();
return null;
} else if (ex instanceof LocatableResolverLockedException ||
(ex instanceof CompletionException && ex.getCause() instanceof LocatableResolverLockedException)) {
return null;
}
throw new AssertionError("unexpected error", ex);
}));
}
CompletableFuture.allOf(parallelGets.toArray(new CompletableFuture<?>[0])).join();
assertThat("only one exclusiveLock succeeds", lockGetCount.get(), is(1));
assertLocked(database, globalScope);
}
private void assertLocked(@Nonnull final FDBDatabase database, @Nonnull final LocatableResolver resolver) {
try (FDBRecordContext context = database.openContext()) {
eventually("write lock is enabled", () -> {
try {
resolver.resolve(context.getTimer(), "random-value-" + random.nextLong()).join();
} catch (CompletionException exception) {
return exception.getCause();
}
return null;
}, allOf(instanceOf(LocatableResolverLockedException.class),
hasMessageContaining("locatable resolver is not writable")), 120, 10);
consistently("write lock remains enabled", () -> {
try {
resolver.resolve(context.getTimer(), "random-value-" + random.nextLong()).join();
} catch (CompletionException exception) {
return exception.getCause();
}
return null;
}, allOf(instanceOf(LocatableResolverLockedException.class),
hasMessageContaining("locatable resolver is not writable")), 120, 10);
}
}
@Test
public void testGetVersion() {
// version is cached for 30 seconds by default
database.setResolverStateRefreshTimeMillis(100);
consistently("uninitialized version is 0", () -> {
try (FDBRecordContext context = database.openContext()) {
return globalScope.getVersion(context.getTimer()).join();
}
}, is(0), 200, 10);
globalScope.incrementVersion().join();
eventually("version changes to 1", () -> {
try (FDBRecordContext context = database.openContext()) {
return globalScope.getVersion(context.getTimer()).join();
}
}, is(1), 120, 10);
globalScope.incrementVersion().join();
eventually("version changes to 2", () -> {
try (FDBRecordContext context = database.openContext()) {
return globalScope.getVersion(context.getTimer()).join();
}
}, is(2), 120, 10);
}
@Test
public void testParallelDbAndScopeGetVersion() {
// version is cached for 30 seconds by default
database.setResolverStateRefreshTimeMillis(100);
// sets the timeout for all the db instances we create
final FDBDatabaseFactory parallelFactory = new FDBDatabaseFactory();
parallelFactory.setStateRefreshTimeMillis(100);
Supplier<FDBDatabase> databaseSupplier = () -> new FDBDatabase(parallelFactory, null);
consistently("uninitialized version is 0", () -> {
try (FDBRecordContext context = database.openContext()) {
return globalScope.getVersion(context.getTimer()).join();
}
}, is(0), 200, 10);
List<Pair<FDBDatabase, LocatableResolver>> simulatedInstances = IntStream.range(0, 20)
.mapToObj(i -> {
FDBDatabase db = databaseSupplier.get();
return Pair.of(db, globalScopeGenerator.apply(db));
})
.collect(Collectors.toList());
Supplier<CompletableFuture<Set<Integer>>> supplier = () -> {
List<CompletableFuture<Integer>> parallelOperations = simulatedInstances.stream()
.map(pair -> {
FDBDatabase db = pair.getKey();
LocatableResolver resolver = pair.getValue();
FDBRecordContext context = db.openContext();
return resolver.getVersion(context.getTimer()).whenComplete((ignore, e) -> context.close());
}).collect(Collectors.toList());
return AsyncUtil.getAll(parallelOperations).thenApply(HashSet::new);
};
consistently("all instances report the version as 0", () -> supplier.get().join(),
is(Collections.singleton(0)), 200, 10);
globalScope.incrementVersion().join();
eventually("all instances report the new version once the caches have refreshed", () -> supplier.get().join(),
is(Collections.singleton(1)), 120, 10);
}
@Test
public void testVersionIncrementInvalidatesCache() {
FDBDatabaseFactory factory = FDBDatabaseFactory.instance();
factory.setDirectoryCacheSize(10);
FDBStoreTimer timer = new FDBStoreTimer();
FDBDatabase fdb = factory.getDatabase();
fdb.close(); // Make sure cache is fresh, and resets version
fdb.setResolverStateRefreshTimeMillis(100);
String key = "some-key";
Long value;
try (FDBRecordContext context = fdb.openContext()) {
context.setTimer(timer);
value = context.asyncToSync(FDBStoreTimer.Waits.WAIT_DIRECTORY_RESOLVE, globalScope.resolve(context.getTimer(), key));
}
assertThat(timer.getCount(FDBStoreTimer.Events.DIRECTORY_READ), is(greaterThanOrEqualTo(1)));
timer.reset();
consistently("we hit the cached value", () -> {
try (FDBRecordContext context = fdb.openContext()) {
context.setTimer(timer);
assertThat("the resolved value is still the same", globalScope.resolve(context.getTimer(), key).join(), is(value));
}
return timer.getCount(FDBStoreTimer.Events.DIRECTORY_READ);
}, is(0), 200, 10);
globalScope.incrementVersion().join();
timer.reset();
eventually("we see the version change and invalidate the cache", () -> {
try (FDBRecordContext context = fdb.openContext()) {
context.setTimer(timer);
assertThat("the resolved value is still the same", globalScope.resolve(context.getTimer(), key).join(), is(value));
}
return timer.getCount(FDBStoreTimer.Events.DIRECTORY_READ);
}, is(1), 120, 10);
timer.reset();
consistently("the value is cached while the version is not changed", () -> {
try (FDBRecordContext context = fdb.openContext()) {
context.setTimer(timer);
assertThat("the resolved value is still the same", globalScope.resolve(context.getTimer(), key).join(), is(value));
}
return timer.getCount(FDBStoreTimer.Events.DIRECTORY_READ);
}, is(0), 200, 10);
}
@Test
public void testWriteSafetyCheck() {
KeySpace keySpace = new KeySpace(
new KeySpaceDirectory("path1", KeyType.STRING, "path1"),
new KeySpaceDirectory("path2", KeyType.STRING, "path2")
);
final LocatableResolver path1Resolver;
final LocatableResolver path2Resolver;
try (FDBRecordContext context = database.openContext()) {
KeySpacePath path1 = keySpace.path("path1");
KeySpacePath path2 = keySpace.path("path2");
path1Resolver = scopedDirectoryGenerator.apply(context, path1);
path2Resolver = scopedDirectoryGenerator.apply(context, path2);
}
PreWriteCheck validCheck = (context, resolver) ->
CompletableFuture.completedFuture(Objects.equals(path1Resolver, resolver));
PreWriteCheck invalidCheck = (context, resolver) ->
CompletableFuture.completedFuture(Objects.equals(path2Resolver, resolver));
ResolverCreateHooks validHooks = new ResolverCreateHooks(validCheck, DEFAULT_HOOK);
ResolverCreateHooks invalidHooks = new ResolverCreateHooks(invalidCheck, DEFAULT_HOOK);
Long value = path1Resolver.resolve(null, "some-key", validHooks).join();
try (FDBRecordContext context = database.openContext()) {
assertThat("it succeeds and writes the value", path1Resolver.mustResolve(context, "some-key").join(), is(value));
}
assertThat("when reading the same key it doesn't perform the check", path1Resolver.resolve(null, "some-key", invalidHooks).join(), is(value));
try {
path1Resolver.resolve(null, "another-key", invalidHooks).join();
fail("should throw CompletionException");
} catch (CompletionException ex) {
assertThat("it has the correct cause", ex.getCause(), is(instanceOf(LocatableResolverLockedException.class)));
assertThat(ex, hasMessageContaining("prewrite check failed"));
}
}
@Test
public void testResolveWithMetadata() {
byte[] metadata = Tuple.from("some-metadata").pack();
MetadataHook hook = ignore -> metadata;
final ResolverResult result;
final ResolverCreateHooks hooks = new ResolverCreateHooks(DEFAULT_CHECK, hook);
result = globalScope.resolveWithMetadata(null, "a-key", hooks).join();
assertArrayEquals(metadata, result.getMetadata());
// check that the result with metadata is persisted to the database
ResolverResult expected = new ResolverResult(result.getValue(), metadata);
try (FDBRecordContext context = database.openContext()) {
ResolverResult resultFromDB = globalScope.mustResolveWithMetadata(context, "a-key").join();
assertEquals(expected.getValue(), resultFromDB.getValue());
assertArrayEquals(expected.getMetadata(), resultFromDB.getMetadata());
}
assertEquals(expected, globalScope.resolveWithMetadata(null, "a-key", hooks).join());
byte[] newMetadata = Tuple.from("some-different-metadata").pack();
MetadataHook newHook = ignore -> newMetadata;
final ResolverCreateHooks newHooks = new ResolverCreateHooks(DEFAULT_CHECK, newHook);
// make sure we don't just read the cached value
database.clearCaches();
assertArrayEquals(metadata, globalScope.resolveWithMetadata(null, "a-key", newHooks).join().getMetadata(),
"hook is only run on create, does not update metadata");
}
@Test
public void testUpdateMetadata() {
database.setResolverStateRefreshTimeMillis(100);
final byte[] oldMetadata = Tuple.from("old").pack();
final byte[] newMetadata = Tuple.from("new").pack();
final ResolverCreateHooks hooks = new ResolverCreateHooks(DEFAULT_CHECK, ignore -> oldMetadata);
ResolverResult initialResult;
try (FDBRecordContext context = database.openContext()) {
initialResult = globalScope.resolveWithMetadata(context.getTimer(), "some-key", hooks).join();
assertArrayEquals(initialResult.getMetadata(), oldMetadata);
}
globalScope.updateMetadataAndVersion("some-key", newMetadata).join();
ResolverResult expected = new ResolverResult(initialResult.getValue(), newMetadata);
eventually("we see the new metadata", () ->
globalScope.resolveWithMetadata(null, "some-key", hooks).join(),
is(expected), 120, 10);
}
@Test
public void testSetMapping() {
Long value;
try (FDBRecordContext context = database.openContext()) {
value = globalScope.resolve(context.getTimer(), "an-existing-mapping").join();
}
try (FDBRecordContext context = database.openContext()) {
globalScope.setMapping(context, "a-new-mapping", 99L).join();
globalScope.setMapping(context, "an-existing-mapping", value).join();
// need to commit before we will be able to see the mapping with resolve
// since resolve always uses a separate transaction
context.commit();
}
try (FDBRecordContext context = database.openContext()) {
assertThat("we can see the new mapping", globalScope.resolve(context.getTimer(), "a-new-mapping").join(), is(99L));
assertThat("we can see the new reverse mapping", globalScope.reverseLookup(null, 99L).join(), is("a-new-mapping"));
assertThat("we can see the existing mapping", globalScope.resolve(context.getTimer(), "an-existing-mapping").join(), is(value));
assertThat("we can see the existing reverse mapping", globalScope.reverseLookup(null, value).join(), is("an-existing-mapping"));
}
}
@Test
public void testSetMappingWithConflicts() {
Long value;
try (FDBRecordContext context = database.openContext()) {
value = globalScope.resolve(context.getTimer(), "an-existing-mapping").join();
}
try (FDBRecordContext context = database.openContext()) {
globalScope.setMapping(context, "an-existing-mapping", value + 1).join();
fail("should throw an exception");
} catch (CompletionException ex) {
assertThat("cause is a record core exception", ex.getCause(), is(instanceOf(RecordCoreException.class)));
assertThat("it has a helpful message", ex.getCause(),
hasMessageContaining("mapping already exists with different value"));
}
try (FDBRecordContext context = database.openContext()) {
assertThat("will still only see the original mapping",
globalScope.mustResolve(context, "an-existing-mapping").join(), is(value));
assertThat("will still only see the original reverse mapping",
globalScope.reverseLookup(null, value).join(), is("an-existing-mapping"));
assertThrows(CompletionException.class, () -> globalScope.reverseLookup(null, value + 1).join(),
"nothing was added for the wrong value");
}
try (FDBRecordContext context = database.openContext()) {
globalScope.setMapping(context, "a-different-key", value).join();
fail("should throw an exception");
} catch (CompletionException ex) {
assertThat("cause is a record core exception", ex.getCause(), is(instanceOf(RecordCoreException.class)));
assertThat("it has a helpful message", ex.getCause(),
hasMessageContaining("reverse mapping already exists with different key"));
}
try (FDBRecordContext context = database.openContext()) {
assertThrows(CompletionException.class, () -> globalScope.mustResolve(context, "a-different-key").join(),
"nothing is added for that key");
}
}
@Test
public void testSetWindow() {
Map<String, Long> oldMappings = new HashMap<>();
try (FDBRecordContext context = database.openContext()) {
for (int i = 0; i < 20; i++) {
String key = "old-resolved-" + i;
Long value = globalScope.resolve(context.getTimer(), key).join();
oldMappings.put(key, value);
}
}
globalScope.setWindow(10000L).join();
try (FDBRecordContext context = database.openContext()) {
for (int i = 0; i < 20; i++) {
Long value = globalScope.resolve(context.getTimer(), "new-resolved-" + i).join();
assertThat("resolved value is larger than the set window", value, greaterThanOrEqualTo(10000L));
}
for (Map.Entry<String, Long> entry : oldMappings.entrySet()) {
Long value = globalScope.resolve(context.getTimer(), entry.getKey()).join();
assertThat("we can still read the old mappings", value, is(entry.getValue()));
}
}
}
// Protected methods
@Test
public void testReadCreateExists() {
ResolverResult value;
try (FDBRecordContext context = database.openContext()) {
value = globalScope.create(context, "a-string").join();
assertThat("we see the value exists", globalScope.read(context, "a-string").join().isPresent(), is(true));
assertThat("we see other values don't exist", globalScope.read(context, "something-else").join().isPresent(), is(false));
assertThat("we can read the value", globalScope.read(context, "a-string").join(), is(Optional.of(value)));
assertThat("we get nothing for other values", globalScope.read(context, "something-else").join(), is(Optional.empty()));
}
}
protected void wipeFDB() {
database.run((context -> {
context.ensureActive().clear(new Range(new byte[] {(byte)0x00}, new byte[] {(byte)0xFF}));
return null;
}));
database.clearCaches();
}
}
|
3e0c316c2f23d39ba150be85fb9cbc2a90dbf458 | 4,509 | java | Java | src/test/java/org/onehippo/forge/jcrshell/console/completers/FileNameCompleterTest.java | onehippo-forge/jcr-shell | 84fa8a52648222fded3b5456f92deb08d3158efb | [
"Apache-2.0"
] | null | null | null | src/test/java/org/onehippo/forge/jcrshell/console/completers/FileNameCompleterTest.java | onehippo-forge/jcr-shell | 84fa8a52648222fded3b5456f92deb08d3158efb | [
"Apache-2.0"
] | null | null | null | src/test/java/org/onehippo/forge/jcrshell/console/completers/FileNameCompleterTest.java | onehippo-forge/jcr-shell | 84fa8a52648222fded3b5456f92deb08d3158efb | [
"Apache-2.0"
] | 1 | 2019-10-16T22:04:47.000Z | 2019-10-16T22:04:47.000Z | 36.658537 | 89 | 0.622089 | 5,174 | /*
* Copyright 2010-2018 Hippo.
*
* 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.onehippo.forge.jcrshell.console.completers;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class FileNameCompleterTest {
private static final String FILE_NAME = "fnc-completer-test-file";
private static final String FILE_NAME_START = "fnc-c";
private static final String DIR_NAME = "fnc-completer-test-directory";
private static final String DIR_NAME_START = "fnc-c";
private static final String SUBDIR_NAME = "fnc-completer-test-subdir";
private static final String SUBDIR_NAME_START = "fnc-c";
@Test
public void testFileNameCompletion() throws IOException {
File file = new File(FILE_NAME);
file.createNewFile();
try {
FileNameCompleter fnc = new FileNameCompleter();
List<CharSequence> candidates = new LinkedList<CharSequence>();
int result = fnc.complete(FILE_NAME_START, 1, candidates);
assertEquals(0, result);
assertEquals(1, candidates.size());
assertEquals(FILE_NAME + " ", candidates.get(0).toString());
} finally {
file.delete();
}
}
@Test
public void testFileInSubdirCompletion() throws IOException {
File dir = new File(DIR_NAME);
dir.mkdir();
File file = new File(dir, FILE_NAME);
file.createNewFile();
try {
FileNameCompleter fnc = new FileNameCompleter();
List<CharSequence> candidates = new LinkedList<CharSequence>();
int result = fnc.complete(DIR_NAME + "/" + FILE_NAME_START, 1, candidates);
assertEquals(DIR_NAME.length() + 1, result);
assertEquals(1, candidates.size());
assertEquals(FILE_NAME + " ", candidates.get(0).toString());
} finally {
file.delete();
dir.delete();
}
}
@Test
public void testDirNameCompletion() throws IOException {
File file = new File(DIR_NAME);
file.mkdir();
try {
DirNameCompleter fnc = new DirNameCompleter();
List<CharSequence> candidates = new LinkedList<CharSequence>();
int result = fnc.complete(DIR_NAME_START, 1, candidates);
assertEquals(0, result);
assertEquals(1, candidates.size());
assertEquals(DIR_NAME + "/", candidates.get(0).toString());
} finally {
file.delete();
}
}
@Test
public void testDirInSubdirCompletion() throws IOException {
File dir = new File(DIR_NAME);
dir.mkdir();
File file = new File(dir, SUBDIR_NAME);
file.mkdir();
try {
DirNameCompleter fnc = new DirNameCompleter();
List<CharSequence> candidates = new LinkedList<CharSequence>();
int result = fnc.complete(DIR_NAME + "/" + SUBDIR_NAME_START, 1, candidates);
assertEquals(DIR_NAME.length() + 1, result);
assertEquals(1, candidates.size());
assertEquals(SUBDIR_NAME + "/", candidates.get(0).toString());
} finally {
file.delete();
dir.delete();
}
}
@Test
public void testHomeFileNameCompletion() throws IOException {
File file = new File(new File(System.getProperty("user.home")), FILE_NAME);
file.createNewFile();
try {
FileNameCompleter fnc = new FileNameCompleter();
List<CharSequence> candidates = new LinkedList<CharSequence>();
int result = fnc.complete("~/" + FILE_NAME_START, 1, candidates);
assertEquals(2, result);
assertEquals(1, candidates.size());
assertEquals(FILE_NAME + " ", candidates.get(0).toString());
} finally {
file.delete();
}
}
}
|
3e0c317fe41095f399029d7e73bbe58419f2e070 | 6,191 | java | Java | module-manager/src/main/java/com/nu/art/modular/core/ModuleManagerBuilder.java | intuition-robotics/cyborg | fa6c8f399f910aadb8d4a85ec042c3e35d11fbea | [
"Apache-2.0"
] | 15 | 2019-09-24T07:45:43.000Z | 2019-09-29T06:45:44.000Z | module-manager/src/main/java/com/nu/art/modular/core/ModuleManagerBuilder.java | intuition-robotics/cyborg | fa6c8f399f910aadb8d4a85ec042c3e35d11fbea | [
"Apache-2.0"
] | null | null | null | module-manager/src/main/java/com/nu/art/modular/core/ModuleManagerBuilder.java | intuition-robotics/cyborg | fa6c8f399f910aadb8d4a85ec042c3e35d11fbea | [
"Apache-2.0"
] | 1 | 2021-03-04T12:01:02.000Z | 2021-03-04T12:01:02.000Z | 41 | 191 | 0.646422 | 5,175 | /*
* The module-manager project, is THE infrastructure that all my frameworks
* are based on, it allows encapsulation of logic where needed, and allow
* modules to converse without other design patterns limitations.
*
* Copyright (C) 2018 Adam van der Kruk aka TacB0sS
*
* 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.nu.art.modular.core;
import com.nu.art.belog.Logger;
import com.nu.art.modular.core.ModuleManager.ModuleCreatedListener;
import com.nu.art.modular.core.ModuleManager.ModuleInitializedListener;
import com.nu.art.modular.interfaces.OnApplicationStartingListener;
import com.nu.art.reflection.tools.ReflectiveTools;
import java.util.ArrayList;
import java.util.Arrays;
public class ModuleManagerBuilder
extends Logger
implements OnApplicationStartingListener {
private ArrayList<ModulesPack> modulePacks = new ArrayList<>();
private ModuleInitializedListener moduleInitializedListener = (this instanceof ModuleInitializedListener ? (ModuleInitializedListener) this : null);
private ModuleCreatedListener moduleCreatedListener = (this instanceof ModuleCreatedListener ? (ModuleCreatedListener) this : null);
protected final ModuleManager manager = new ModuleManager();
private OnApplicationStartingListener listener = this;
public ModuleManagerBuilder() {
}
public ModuleManagerBuilder setOnApplicationStartingListener(OnApplicationStartingListener listener) {
if (listener != null)
this.listener = listener;
return this;
}
public ModuleManagerBuilder setModuleInitializedListener(ModuleInitializedListener moduleInitializedListener) {
this.moduleInitializedListener = moduleInitializedListener;
return this;
}
public ModuleManagerBuilder setModuleCreatedListener(ModuleCreatedListener moduleCreatedListener) {
this.moduleCreatedListener = moduleCreatedListener;
return this;
}
@SuppressWarnings("unchecked")
public final ModuleManagerBuilder addModulePacks(Class<? extends ModulesPack>... modulePacks) {
for (Class<? extends ModulesPack> packType : modulePacks) {
ModulesPack pack = ReflectiveTools.newInstance(packType);
this.modulePacks.add(pack);
}
return this;
}
public final ModuleManagerBuilder addModulePacks(ModulesPack... modulePacks) {
this.modulePacks.addAll(Arrays.asList(modulePacks));
return this;
}
@SuppressWarnings("unchecked")
public final ModuleManagerBuilder addModules(Class<? extends Module>... modules) {
this.modulePacks.add(new ModulesPack(modules));
return this;
}
public final ModuleManager build() {
manager.setModuleCreatedListener(this.moduleCreatedListener);
manager.setModuleInitializedListener(this.moduleInitializedListener);
ArrayList<Class<? extends Module>> modulesTypes = new ArrayList<>();
for (ModulesPack pack : modulePacks) {
pack.setManager(manager);
for (Class<? extends Module> moduleType : pack.moduleTypes) {
if (modulesTypes.contains(moduleType))
continue;
modulesTypes.add(moduleType);
manager.registerModule(moduleType);
}
}
for (ModulesPack pack : modulePacks) {
pack.init();
}
Module[] registeredModules = manager.getOrderedModules();
validateModules(registeredModules);
for (Module registeredModule : registeredModules) {
manager.getInjector().injectToInstance(registeredModule);
}
logVerbose(" Application Starting...");
logVerbose(" ");
listener.onApplicationStarting();
manager.init();
for (Module module : registeredModules) {
logInfo("----------- " + module.getClass().getSimpleName() + " ------------");
module.printDetails();
logInfo("-------- End of " + module.getClass().getSimpleName() + " --------");
}
manager.onBuildCompleted();
return manager;
}
private void validateModules(Module[] allRegisteredModuleInstances) {
ValidationResult result = new ValidationResult();
for (Module module : allRegisteredModuleInstances)
module.validateModule(result);
if (!result.isEmpty())
throw new com.nu.art.modular.exceptions.ModuleNotSupportedException("\n" + result.getErrorData());
}
protected void postInit(Module[] allRegisteredModuleInstances) {
}
public void onApplicationStarting() {
logVerbose(" _______ _______ _______ _ _________ _______ _______ __________________ _______ _ _______ _________ _______ _______ _________ _______ ______ ");
logVerbose("( ___ )( ____ )( ____ )( \\ \\__ __/( ____ \\( ___ )\\__ __/\\__ __/( ___ )( ( /| ( ____ \\\\__ __/( ___ )( ____ )\\__ __/( ____ \\( __ \\ ");
logVerbose("| ( ) || ( )|| ( )|| ( ) ( | ( \\/| ( ) | ) ( ) ( | ( ) || \\ ( | | ( \\/ ) ( | ( ) || ( )| ) ( | ( \\/| ( \\ )");
logVerbose("| (___) || (____)|| (____)|| | | | | | | (___) | | | | | | | | || \\ | | | (_____ | | | (___) || (____)| | | | (__ | | ) |");
logVerbose("| ___ || _____)| _____)| | | | | | | ___ | | | | | | | | || (\\ \\) | (_____ ) | | | ___ || __) | | | __) | | | |");
logVerbose("| ( ) || ( | ( | | | | | | | ( ) | | | | | | | | || | \\ | ) | | | | ( ) || (\\ ( | | | ( | | ) |");
logVerbose("| ) ( || ) | ) | (____/\\___) (___| (____/\\| ) ( | | | ___) (___| (___) || ) \\ | /\\____) | | | | ) ( || ) \\ \\__ | | | (____/\\| (__/ )");
logVerbose("|/ \\||/ |/ (_______/\\_______/(_______/|/ \\| )_( \\_______/(_______)|/ )_) \\_______) )_( |/ \\||/ \\__/ )_( (_______/(______/ ");
logVerbose(" ");
}
}
|
3e0c31d7c3fb4299a45b3eaba398fc8827cf0c2b | 10,518 | java | Java | apps/jreleaser/src/main/java/org/jreleaser/cli/Release.java | mthmulders/jreleaser | 495d8697fd03c7ec34cc5035264b5b412cbb65b6 | [
"Apache-2.0"
] | null | null | null | apps/jreleaser/src/main/java/org/jreleaser/cli/Release.java | mthmulders/jreleaser | 495d8697fd03c7ec34cc5035264b5b412cbb65b6 | [
"Apache-2.0"
] | null | null | null | apps/jreleaser/src/main/java/org/jreleaser/cli/Release.java | mthmulders/jreleaser | 495d8697fd03c7ec34cc5035264b5b412cbb65b6 | [
"Apache-2.0"
] | null | null | null | 34.827815 | 108 | 0.640521 | 5,176 | /*
* SPDX-License-Identifier: Apache-2.0
*
* Copyright 2020-2022 The JReleaser authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jreleaser.cli;
import org.jreleaser.engine.context.ModelAutoConfigurer;
import org.jreleaser.model.JReleaserContext;
import org.jreleaser.model.UpdateSection;
import org.jreleaser.workflow.Workflows;
import picocli.CommandLine;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* @author Andres Almiray
* @since 0.1.0
*/
@CommandLine.Command(name = "release")
public class Release extends AbstractPlatformAwareModelCommand {
@CommandLine.Option(names = {"--dry-run"})
boolean dryrun;
@CommandLine.ArgGroup
Composite composite;
static class Composite {
@CommandLine.ArgGroup(exclusive = false, order = 1,
headingKey = "include.filter.header")
Include include;
@CommandLine.ArgGroup(exclusive = false, order = 2,
headingKey = "exclude.filter.header")
Exclude exclude;
@CommandLine.ArgGroup(exclusive = false, order = 3,
headingKey = "auto-config.header")
AutoConfigGroup autoConfig;
String[] includedDistributions() {
return include != null ? include.includedDistributions : null;
}
String[] excludedDistributions() {
return exclude != null ? exclude.excludedDistributions : null;
}
String[] includedUploaderTypes() {
return include != null ? include.includedUploaderTypes : null;
}
String[] includedUploaderNames() {
return include != null ? include.includedUploaderNames : null;
}
String[] excludedUploaderTypes() {
return exclude != null ? exclude.excludedUploaderTypes : null;
}
String[] excludedUploaderNames() {
return exclude != null ? exclude.excludedUploaderNames : null;
}
boolean autoConfig() {
return autoConfig != null && autoConfig.autoConfig;
}
}
static class Include {
@CommandLine.Option(names = {"-d", "--distribution"},
paramLabel = "<distribution>")
String[] includedDistributions;
@CommandLine.Option(names = {"-u", "--uploader"},
paramLabel = "<uploader>")
String[] includedUploaderTypes;
@CommandLine.Option(names = {"-un", "--uploader-name"},
paramLabel = "<name>")
String[] includedUploaderNames;
}
static class Exclude {
@CommandLine.Option(names = {"-xd", "--exclude-distribution"},
paramLabel = "<distribution>")
String[] excludedDistributions;
@CommandLine.Option(names = {"-xu", "--exclude-uploader"},
paramLabel = "<uploader>")
String[] excludedUploaderTypes;
@CommandLine.Option(names = {"-xun", "--exclude-uploader-name"},
paramLabel = "<name>")
String[] excludedUploaderNames;
}
static class AutoConfigGroup {
@CommandLine.Option(names = {"--auto-config"})
boolean autoConfig;
@CommandLine.Option(names = {"--project-name"})
String projectName;
@CommandLine.Option(names = {"--project-version"})
String projectVersion;
@CommandLine.Option(names = {"--project-version-pattern"})
String projectVersionPattern;
@CommandLine.Option(names = {"--project-snapshot-pattern"})
String projectSnapshotPattern;
@CommandLine.Option(names = {"--project-snapshot-label"})
String projectSnapshotLabel;
@CommandLine.Option(names = {"--project-snapshot-full-changelog"})
boolean projectSnapshotFullChangelog;
@CommandLine.Option(names = {"--tag-name"})
String tagName;
@CommandLine.Option(names = {"--previous-tag-name"})
String previousTagName;
@CommandLine.Option(names = {"--release-name"})
String releaseName;
@CommandLine.Option(names = {"--milestone-name"})
String milestoneName;
@CommandLine.Option(names = {"--prerelease"})
boolean prerelease;
@CommandLine.Option(names = {"--prerelease-pattern"})
String prereleasePattern;
@CommandLine.Option(names = {"--draft"})
boolean draft;
@CommandLine.Option(names = {"--overwrite"})
boolean overwrite;
@CommandLine.Option(names = {"--update"})
boolean update;
@CommandLine.Option(names = {"--update-section"},
paramLabel = "<section>")
String[] updateSections;
@CommandLine.Option(names = {"--skip-tag"})
boolean skipTag;
@CommandLine.Option(names = {"--skip-release"})
boolean skipRelease;
@CommandLine.Option(names = {"--branch"})
String branch;
@CommandLine.Option(names = {"--changelog"})
String changelog;
@CommandLine.Option(names = {"--changelog-formatted"})
boolean changelogFormatted;
@CommandLine.Option(names = {"--username"})
String username;
@CommandLine.Option(names = {"--commit-author-name"})
String commitAuthorName;
@CommandLine.Option(names = {"--commit-author-email"})
String commitAuthorEmail;
@CommandLine.Option(names = {"--signing-enabled"})
boolean signing;
@CommandLine.Option(names = {"--signing-armored"})
boolean armored;
@CommandLine.Option(names = {"--file"},
paramLabel = "<file>")
String[] files;
@CommandLine.Option(names = {"--glob"},
paramLabel = "<glob>")
String[] globs;
}
@Override
protected JReleaserContext createContext() {
JReleaserContext context = super.createContext();
if (null != composite) {
context.setIncludedDistributions(collectEntries(composite.includedDistributions()));
context.setIncludedUploaderTypes(collectEntries(composite.includedUploaderTypes(), true));
context.setIncludedUploaderNames(collectEntries(composite.includedUploaderNames()));
context.setExcludedDistributions(collectEntries(composite.excludedDistributions()));
context.setExcludedUploaderTypes(collectEntries(composite.excludedUploaderTypes(), true));
context.setExcludedUploaderNames(collectEntries(composite.excludedUploaderNames()));
}
return context;
}
protected void execute() {
if (composite == null || !composite.autoConfig()) {
super.execute();
return;
}
basedir();
initLogger();
JReleaserContext context = ModelAutoConfigurer.builder()
.logger(logger)
.basedir(actualBasedir)
.outputDirectory(getOutputDirectory())
.dryrun(dryrun())
.gitRootSearch(gitRootSearch)
.projectName(composite.autoConfig.projectName)
.projectVersion(composite.autoConfig.projectVersion)
.projectVersionPattern(composite.autoConfig.projectVersionPattern)
.projectSnapshotPattern(composite.autoConfig.projectSnapshotPattern)
.projectSnapshotLabel(composite.autoConfig.projectSnapshotLabel)
.projectSnapshotFullChangelog(composite.autoConfig.projectSnapshotFullChangelog)
.tagName(composite.autoConfig.tagName)
.previousTagName(composite.autoConfig.previousTagName)
.releaseName(composite.autoConfig.releaseName)
.milestoneName(composite.autoConfig.milestoneName)
.branch(composite.autoConfig.branch)
.prerelease(composite.autoConfig.prerelease)
.prereleasePattern(composite.autoConfig.prereleasePattern)
.draft(composite.autoConfig.draft)
.overwrite(composite.autoConfig.overwrite)
.update(composite.autoConfig.update)
.updateSections(collectUpdateSections())
.skipTag(composite.autoConfig.skipTag)
.skipRelease(composite.autoConfig.skipRelease)
.changelog(composite.autoConfig.changelog)
.changelogFormatted(composite.autoConfig.changelogFormatted)
.username(composite.autoConfig.username)
.commitAuthorName(composite.autoConfig.commitAuthorName)
.commitAuthorEmail(composite.autoConfig.commitAuthorEmail)
.signing(composite.autoConfig.signing)
.armored(composite.autoConfig.armored)
.files(collectEntries(composite.autoConfig.files))
.globs(collectEntries(composite.autoConfig.globs))
.selectedPlatforms(collectSelectedPlatforms())
.autoConfigure();
doExecute(context);
}
private Set<UpdateSection> collectUpdateSections() {
Set<UpdateSection> set = new LinkedHashSet<>();
if (composite.autoConfig.updateSections != null && composite.autoConfig.updateSections.length > 0) {
for (String updateSection : composite.autoConfig.updateSections) {
set.add(UpdateSection.of(updateSection.trim()));
}
}
return set;
}
private void basedir() {
actualBasedir = null != basedir ? basedir : Paths.get(".").normalize();
if (!Files.exists(actualBasedir)) {
throw halt($("ERROR_missing_required_option", "--basedir=<basedir>"));
}
}
@Override
protected void doExecute(JReleaserContext context) {
Workflows.release(context).execute();
}
@Override
protected boolean dryrun() {
return dryrun;
}
private HaltExecutionException halt(String message) throws HaltExecutionException {
spec.commandLine().getErr()
.println(spec.commandLine().getColorScheme().errorText(message));
spec.commandLine().usage(parent.out);
throw new HaltExecutionException();
}
}
|
3e0c32ce37053c2402b4c92e892b07290f757dec | 2,995 | java | Java | riverock-forum/src/main/java/org/riverock/forum/dao/ForumIntegrityDao.java | sergmain/webmill | 9280f62ddfef4b3ed5a8628a912c260984040ebf | [
"Apache-2.0"
] | null | null | null | riverock-forum/src/main/java/org/riverock/forum/dao/ForumIntegrityDao.java | sergmain/webmill | 9280f62ddfef4b3ed5a8628a912c260984040ebf | [
"Apache-2.0"
] | 2 | 2022-01-27T16:20:03.000Z | 2022-01-27T16:20:08.000Z | riverock-forum/src/main/java/org/riverock/forum/dao/ForumIntegrityDao.java | sergmain/webmill | 9280f62ddfef4b3ed5a8628a912c260984040ebf | [
"Apache-2.0"
] | null | null | null | 31.197917 | 82 | 0.615025 | 5,177 | /*
* org.riverock.forum - Forum portlet
*
* Copyright (C) 2006, Riverock Software, All Rights Reserved.
*
* Riverock - The Open-source Java Development Community
* http://www.riverock.org
*
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.riverock.forum.dao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.riverock.common.tools.RsetTools;
import org.riverock.forum.bean.ForumIntegrityBean;
import org.riverock.generic.db.Database;
import org.riverock.generic.db.DatabaseManager;
/**
* @author Sergei Maslyukov
* Date: 29.05.2006
* Time: 14:17:52
*/
@SuppressWarnings({"UnusedAssignment"})
public class ForumIntegrityDao {
private final static Logger log = Logger.getLogger(ForumListManagerDAO.class);
private static final String sql =
"" +
"select a.* " +
"from ( " +
"select f_u_id user_id " +
"from WM_FORUM_concrete " +
"union " +
"select f_u_id2 " +
"from WM_FORUM_concrete " +
") a " +
"where a.user_id not in " +
"(select id_user from wm_list_user)";
public ForumIntegrityBean getIntegrityStatus(Long siteId) {
Database adapter = null;
PreparedStatement ps = null;
ResultSet rs = null;
ForumIntegrityBean bean = new ForumIntegrityBean();
try {
adapter = Database.getInstance();
ps = adapter.prepareStatement( sql );
rs = ps.executeQuery();
List<Long> list = new ArrayList<Long>();
while(rs.next()) {
list.add(RsetTools.getLong(rs, "USER_ID"));
}
bean.setLostUserId(list);
if (!list.isEmpty()) {
bean.setCountLostUser(list.size());
bean.setValid(false);
}
return bean;
}
catch (Exception e) {
String es = "Error execute homeDAO";
log.error(es, e);
throw new IllegalStateException(es, e);
}
finally {
DatabaseManager.close(adapter, rs, ps);
adapter = null;
rs = null;
ps = null;
}
}
}
|
3e0c33f12b449d4d853a2aceef8ebefd26a75054 | 2,494 | java | Java | modules/dashboard-providers/dashboard-provider-api/src/main/java/org/jboss/dashboard/provider/DataFormatterRegistry.java | jeroenvds/dashboard-builder | bfc701ffe904c1226ee14807b72bed5f188aed20 | [
"Apache-2.0"
] | 1 | 2019-06-27T11:52:03.000Z | 2019-06-27T11:52:03.000Z | modules/dashboard-providers/dashboard-provider-api/src/main/java/org/jboss/dashboard/provider/DataFormatterRegistry.java | jeroenvds/dashboard-builder | bfc701ffe904c1226ee14807b72bed5f188aed20 | [
"Apache-2.0"
] | null | null | null | modules/dashboard-providers/dashboard-provider-api/src/main/java/org/jboss/dashboard/provider/DataFormatterRegistry.java | jeroenvds/dashboard-builder | bfc701ffe904c1226ee14807b72bed5f188aed20 | [
"Apache-2.0"
] | null | null | null | 33.702703 | 93 | 0.701283 | 5,178 | /**
* Copyright (C) 2012 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.dashboard.provider;
import org.jboss.dashboard.annotation.Install;
import org.jboss.dashboard.commons.cdi.CDIBeanLocator;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import javax.inject.Named;
import java.util.HashMap;
import java.util.Map;
/**
* Registry of data property formatters.
*/
@ApplicationScoped
@Named("dataFormatterRegistry")
public class DataFormatterRegistry {
/**
* GoF singleton pattern.
*/
public static DataFormatterRegistry lookup() {
return (DataFormatterRegistry) CDIBeanLocator.getBeanByName("dataFormatterRegistry");
}
/** The default general-purpose property formatter */
protected DataPropertyFormatter defaultPropertyFormatter;
/** The registry of custom property formatters */
Map<String,DataPropertyFormatter> customFormatterMap;
@Inject @Install
protected Instance<DataPropertyFormatter> dataPropertyFormatters;
@PostConstruct
protected void init() {
customFormatterMap = new HashMap<String, DataPropertyFormatter>();
for (DataPropertyFormatter formatter : dataPropertyFormatters) {
String[] propIds = formatter.getSupportedPropertyIds();
if (propIds == null) {
defaultPropertyFormatter = formatter;
} else {
for (int i = 0; i < propIds.length; i++) {
String propId = propIds[i];
customFormatterMap.put(propId, formatter);
}
}
}
}
public DataPropertyFormatter getPropertyFormatter(String propId) {
DataPropertyFormatter propFormatter = customFormatterMap.get(propId);
if (propFormatter != null) return propFormatter;
return defaultPropertyFormatter;
}
}
|
3e0c34433b1bcf6b0b084431e4e844fca290828f | 463 | java | Java | java/limax/src/limax/edb/Allocator.java | zhangtongrui/limax_5.16 | cb243c50bbce5720da733ba913a271a5452fec04 | [
"MIT"
] | null | null | null | java/limax/src/limax/edb/Allocator.java | zhangtongrui/limax_5.16 | cb243c50bbce5720da733ba913a271a5452fec04 | [
"MIT"
] | null | null | null | java/limax/src/limax/edb/Allocator.java | zhangtongrui/limax_5.16 | cb243c50bbce5720da733ba913a271a5452fec04 | [
"MIT"
] | null | null | null | 24.368421 | 102 | 0.721382 | 5,179 | package limax.edb;
import java.nio.ByteBuffer;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
class Allocator {
private final static Queue<ByteBuffer> pool = new ConcurrentLinkedQueue<>();
static ByteBuffer alloc() {
ByteBuffer bb = pool.poll();
return bb != null ? bb : ByteBuffer.allocateDirect(Configure.PAGESIZE).order(Configure.BYTE_ORDER);
}
static void free(ByteBuffer bb) {
pool.offer(bb);
}
}
|
3e0c350da8da044eb536db4df5adcdae3ba84222 | 2,911 | java | Java | Variant Programs/2-2/7/analogue/ProceduresMoot.java | hjc851/Dataset2-HowToDetectAdvancedSourceCodePlagiarism | a42ced1d5a92963207e3565860cac0946312e1b3 | [
"MIT"
] | null | null | null | Variant Programs/2-2/7/analogue/ProceduresMoot.java | hjc851/Dataset2-HowToDetectAdvancedSourceCodePlagiarism | a42ced1d5a92963207e3565860cac0946312e1b3 | [
"MIT"
] | null | null | null | Variant Programs/2-2/7/analogue/ProceduresMoot.java | hjc851/Dataset2-HowToDetectAdvancedSourceCodePlagiarism | a42ced1d5a92963207e3565860cac0946312e1b3 | [
"MIT"
] | null | null | null | 38.302632 | 140 | 0.674339 | 5,180 | package analogue;
import salesperson.Mailer;
import timer.Proceeding;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.LinkedList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ProceduresMoot {
private java.util.LinkedList<Proceeding> systemDocket;
private salesperson.Mailer regulator;
private static java.lang.String RepresentationsInitiate;
public static java.io.BufferedWriter SupplyDocumentation;
public void operate(java.lang.String tenants) {
this.RepresentationsInitiate = tenants;
regulator = new salesperson.Mailer();
systemDocket = new java.util.LinkedList<>();
System.out.println("Reading in input file...");
try {
java.lang.String unclothedList =
RepresentationsInitiate.substring(0, RepresentationsInitiate.lastIndexOf("."));
SupplyDocumentation =
new java.io.BufferedWriter(
new java.io.FileWriter(
"./out/production/c3063467A1/" + unclothedList + "_output.txt"));
} catch (java.io.IOException abe) {
System.out.println("Unable to generate output file.");
}
RepresentationsInitiate = "./out/production/c3063467A1/" + RepresentationsInitiate;
try {
java.lang.String stimulation =
perusedArchives(RepresentationsInitiate, StandardCharsets.UTF_8);
java.lang.String equiv = "DISP:[\\s]+(?<DISP>[\\d]+)";
java.util.regex.Pattern writes = java.util.regex.Pattern.compile(equiv);
java.util.regex.Matcher sm = writes.matcher(stimulation);
java.lang.String exp2 =
"ID:[\\s]+(?<ID>[\\w]*)[\\s][\\r\\n]+Arrive:[\\s]+(?<Arrive>[\\d]+)[\\s][\\r\\n]+ExecSize:[\\s]+(?<SIZE>[\\d]+)[\\s][\\r\\n]+END";
java.util.regex.Pattern a3 = java.util.regex.Pattern.compile(exp2);
java.util.regex.Matcher f2 = a3.matcher(stimulation);
while (sm.find()) {
regulator.fixedDeployingOpportunity(java.lang.Integer.parseInt(sm.group("DISP")));
}
while (f2.find()) {
systemDocket.add(
new timer.Proceeding(
f2.group("ID"),
java.lang.Integer.parseInt(f2.group("Arrive")),
java.lang.Integer.parseInt(f2.group("SIZE"))));
}
System.out.println("Finished reading input file...");
} catch (java.lang.Exception eden) {
System.out.println(eden.toString());
}
regulator.placedSue(systemDocket);
regulator.leanExporter();
}
private static java.lang.String perusedArchives(
java.lang.String pattern, java.nio.charset.Charset coding) throws IOException {
byte[] ciphered = java.nio.file.Files.readAllBytes(java.nio.file.Paths.get(pattern));
return new java.lang.String(ciphered, coding);
}
}
|
3e0c3601b0a66794d92fa29f3fbec3d0d02711e3 | 1,141 | java | Java | agent/src/main/java/com/thoughtworks/go/agent/statusapi/IsConnectedToServerV1.java | java-app-scans/gocd | 9477487e74f86c4b54563d8ee7786a8205ebfc97 | [
"Apache-2.0"
] | 5,865 | 2015-01-02T04:24:52.000Z | 2022-03-31T11:00:46.000Z | agent/src/main/java/com/thoughtworks/go/agent/statusapi/IsConnectedToServerV1.java | java-app-scans/gocd | 9477487e74f86c4b54563d8ee7786a8205ebfc97 | [
"Apache-2.0"
] | 5,972 | 2015-01-02T10:20:42.000Z | 2022-03-31T20:17:09.000Z | agent/src/main/java/com/thoughtworks/go/agent/statusapi/IsConnectedToServerV1.java | java-app-scans/gocd | 9477487e74f86c4b54563d8ee7786a8205ebfc97 | [
"Apache-2.0"
] | 998 | 2015-01-01T18:02:09.000Z | 2022-03-28T21:20:50.000Z | 31.694444 | 75 | 0.755478 | 5,181 | /*
* Copyright 2021 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.agent.statusapi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class IsConnectedToServerV1 extends HttpHandler {
private final AgentHealthHolder agentHealthHolder;
@Autowired
public IsConnectedToServerV1(AgentHealthHolder agentHealthHolder) {
this.agentHealthHolder = agentHealthHolder;
}
@Override
protected boolean isPassed() {
return !agentHealthHolder.hasLostContact();
}
}
|
3e0c361fbb8b2ab079f7a2788d6d5b6b4a5024c4 | 1,845 | java | Java | ArrayList/myArrayList/src/myArrayList/util/Results.java | Munjal511/Design-Patterns | 3381f6d061f0339b52fa2ea8f4b9f882a5ee3f97 | [
"MIT"
] | null | null | null | ArrayList/myArrayList/src/myArrayList/util/Results.java | Munjal511/Design-Patterns | 3381f6d061f0339b52fa2ea8f4b9f882a5ee3f97 | [
"MIT"
] | null | null | null | ArrayList/myArrayList/src/myArrayList/util/Results.java | Munjal511/Design-Patterns | 3381f6d061f0339b52fa2ea8f4b9f882a5ee3f97 | [
"MIT"
] | null | null | null | 23.0625 | 79 | 0.489431 | 5,182 | package myArrayList.util;
import java.io.BufferedWriter;
import java.io.FileWriter;
/*
* @author Munjal Shah
*/
public class Results implements FileDisplayInterface, StdoutDisplayInterface {
public FileWriter fw = null;
public String output = null;
public StdoutDisplayInterface sdi;
public FileDisplayInterface fdi;
public int tests = 0;
private String testCases[] = new String[50];
/**
* This method writes to file
* @param s
*/
@Override
public void writeToFile(String s) {
try {
fw = new FileWriter(output);
fw.write(s);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fw != null) {
fw.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* This method gives output on console
* @param s
*/
@Override
public void writeToStdout(String s) {
System.out.println(s);
}
/**
* This method is used to initialize objects
*/
public void initialize() {
sdi = new Results();
fdi = new Results();
}
/**
* This method is used to store result in an array
* @param str
*/
public void storeNewResult(String str) {
testCases[tests] = str;
tests++;
}
/**
* This method is used to get all the result in string
* @param index
* @return
*/
public String getResults(int index) {
String r = null;
for (int i = 0; i <= tests; i++) {
if (i == index) {
r = testCases[i];
}
}
return r;
}
} |
3e0c36ecaa071030cab485c13db39189458ea2e0 | 583 | java | Java | src/main/java/io/github/foundationgames/automobility/automobile/BasicWheelBase.java | OakBricks/Automobility | 9173f860bc2a94390d5091de8f13c24fa30db083 | [
"MIT"
] | 15 | 2021-06-22T18:10:11.000Z | 2022-03-09T02:32:05.000Z | src/main/java/io/github/foundationgames/automobility/automobile/BasicWheelBase.java | OakBricks/Automobility | 9173f860bc2a94390d5091de8f13c24fa30db083 | [
"MIT"
] | 3 | 2021-06-26T08:24:37.000Z | 2022-02-21T02:39:57.000Z | src/main/java/io/github/foundationgames/automobility/automobile/BasicWheelBase.java | OakBricks/Automobility | 9173f860bc2a94390d5091de8f13c24fa30db083 | [
"MIT"
] | 5 | 2021-07-15T03:29:32.000Z | 2022-03-04T18:39:37.000Z | 44.846154 | 96 | 0.627787 | 5,183 | package io.github.foundationgames.automobility.automobile;
public class BasicWheelBase extends WheelBase {
public BasicWheelBase(float sepLong, float sepWide) {
super(
new WheelPos(sepLong / 2, sepWide / -2, 1, 0, WheelEnd.FRONT, WheelSide.LEFT),
new WheelPos(sepLong / -2, sepWide / -2, 1, 0, WheelEnd.BACK, WheelSide.LEFT),
new WheelPos(sepLong / 2, sepWide / 2, 1, 180, WheelEnd.FRONT, WheelSide.RIGHT),
new WheelPos(sepLong / -2, sepWide / 2, 1, 180, WheelEnd.BACK, WheelSide.RIGHT)
);
}
}
|
3e0c37ee96efab6d837c4efd3bcdb41e57e5add9 | 413 | java | Java | jeebiz-admin-extras/jeebiz-admin-extras-inform/src/main/java/net/jeebiz/admin/extras/inform/setup/provider/InformOutputProvider.java | Jeebiz/jeebiz-admin | 964cb27b6949cf422eaab14b41667ff1186caa6d | [
"Apache-2.0"
] | 2 | 2020-12-21T10:38:02.000Z | 2021-12-18T05:00:40.000Z | jeebiz-admin-extras/jeebiz-admin-extras-inform/src/main/java/net/jeebiz/admin/extras/inform/setup/provider/InformOutputProvider.java | Jeebiz/jeebiz-admin | 964cb27b6949cf422eaab14b41667ff1186caa6d | [
"Apache-2.0"
] | 1 | 2019-11-02T15:34:30.000Z | 2019-11-02T15:34:30.000Z | jeebiz-admin-extras/jeebiz-admin-extras-inform/src/main/java/net/jeebiz/admin/extras/inform/setup/provider/InformOutputProvider.java | Jeebiz/jeebiz-admin | 964cb27b6949cf422eaab14b41667ff1186caa6d | [
"Apache-2.0"
] | 5 | 2019-05-17T08:40:15.000Z | 2021-12-18T05:00:42.000Z | 16.52 | 59 | 0.680387 | 5,184 | /**
* Copyright (C) 2018 Jeebiz (http://jeebiz.net).
* All Rights Reserved.
*/
package net.jeebiz.admin.extras.inform.setup.provider;
import net.jeebiz.admin.extras.inform.setup.InformProvider;
public interface InformOutputProvider<T> {
/**
* Inform Provider
* @return
*/
InformProvider getProvider();
/**
*消息发送
* @param inform 消息通知对象
* @return 发送成功识别
*/
boolean output(T inform);
}
|
3e0c384c3e8244202723c51bd0da29b2c583cfc4 | 3,236 | java | Java | src/main/java/fr/lirmm/aren/service/BroadcasterService.java | harifidyilay/aren | e0db6dac3fac8ec762f38bba772fe2dddd2987e3 | [
"MIT"
] | 6 | 2020-09-25T08:15:33.000Z | 2022-02-06T17:19:38.000Z | src/main/java/fr/lirmm/aren/service/BroadcasterService.java | harifidyilay/aren | e0db6dac3fac8ec762f38bba772fe2dddd2987e3 | [
"MIT"
] | 1 | 2021-07-12T17:31:03.000Z | 2021-07-12T17:31:03.000Z | src/main/java/fr/lirmm/aren/service/BroadcasterService.java | harifidyilay/aren | e0db6dac3fac8ec762f38bba772fe2dddd2987e3 | [
"MIT"
] | 6 | 2020-11-05T11:51:14.000Z | 2021-05-15T08:59:48.000Z | 27.5 | 179 | 0.627735 | 5,185 | package fr.lirmm.aren.service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.enterprise.context.ApplicationScoped;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import fr.lirmm.aren.model.AbstractEntity;
import fr.lirmm.aren.model.Comment;
import fr.lirmm.aren.model.Debate;
import fr.lirmm.aren.model.Notification;
import fr.lirmm.aren.security.AuthenticatedUserDetails;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.sse.OutboundSseEvent;
import javax.ws.rs.sse.Sse;
import javax.ws.rs.sse.SseBroadcaster;
import javax.ws.rs.sse.SseEventSink;
/**
*
* @author Florent Descroix {@literal <ychag@example.com>}
*/
@ApplicationScoped
public class BroadcasterService {
@Context
private Sse sse;
/**
*
*/
@Context
protected SecurityContext securityContext;
private OutboundSseEvent.Builder eventBuilder;
private final Map<Class<? extends AbstractEntity>, HashMap<Long, SseBroadcaster>> broadcasters = new HashMap<Class<? extends AbstractEntity>, HashMap<Long, SseBroadcaster>>();
/**
*
* @param sse
*/
@Context
public void setSse(Sse sse) {
this.sse = sse;
this.eventBuilder = sse.newEventBuilder();
}
private void broadcast(Long id, AbstractEntity object, Class<? extends AbstractEntity> which) {
if (broadcasters.containsKey(which)) {
OutboundSseEvent sseEvent = this.eventBuilder
.comment(((AuthenticatedUserDetails) securityContext.getUserPrincipal()).getUser().getId() + "")
.name("message")
.mediaType(MediaType.APPLICATION_JSON_TYPE)
.data(which, object)
.reconnectDelay(5000)
.build();
if (broadcasters.get(which).containsKey(id)) {
broadcasters.get(which).get(id).broadcast(sseEvent);
}
if (broadcasters.get(which).containsKey(-1L)) {
broadcasters.get(which).get(-1L).broadcast(sseEvent);
}
}
}
/**
*
* @param id
* @param which
* @param sink
*/
public void openListener(Long id, Class<? extends AbstractEntity> which, SseEventSink sink) {
if (!broadcasters.containsKey(which)) {
broadcasters.put(which, new HashMap<Long, SseBroadcaster>());
}
if (!broadcasters.get(which).containsKey(id)) {
broadcasters.get(which).put(id, sse.newBroadcaster());
}
broadcasters.get(which).get(id).register(sink);
sink.send(sse.newEvent("registered", "true"));
}
/**
*
* @param comment
*/
public void broadcastComment(Comment comment) {
broadcast(comment.getDebate().getId(), comment, Debate.class);
}
/**
*
* @param notif
*/
public void broadcastNotification(Notification notif) {
broadcast(notif.getOwner().getId(), notif, Notification.class);
}
/**
*
* @param notifs
*/
public void broadcastNotification(List<Notification> notifs) {
notifs.forEach(notif -> {
broadcastNotification(notif);
});
}
}
|
3e0c38a65373c80c9f5c09ec39c0ea1487ab9889 | 872 | java | Java | src/main/java/geex/grule/console/repository/ClientConfig.java | gyqw/grule-console | 034ef78defdb494799d801bee059ce7c297381a3 | [
"Apache-2.0"
] | null | null | null | src/main/java/geex/grule/console/repository/ClientConfig.java | gyqw/grule-console | 034ef78defdb494799d801bee059ce7c297381a3 | [
"Apache-2.0"
] | null | null | null | src/main/java/geex/grule/console/repository/ClientConfig.java | gyqw/grule-console | 034ef78defdb494799d801bee059ce7c297381a3 | [
"Apache-2.0"
] | null | null | null | 18.956522 | 48 | 0.527523 | 5,186 | package geex.grule.console.repository;
/**
* @author Jacky.gao
* @author fred
* 2016年8月11日
*/
public class ClientConfig {
private String name;
private String client;
private String project;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClient() {
return client;
}
public void setClient(String client) {
this.client = client;
}
public String getProject() {
return project;
}
public void setProject(String project) {
this.project = project;
}
@Override
public String toString() {
return "ClientConfig{" +
"name='" + name + '\'' +
", client='" + client + '\'' +
", project='" + project + '\'' +
'}';
}
}
|
3e0c38ebe89a1ce293697eb99525d3752d466875 | 1,183 | java | Java | modulo_3_3/pessoaapi/src/main/java/com/dbc/pessoaapi/repository/EnderecoRepository.java | joaovjc/vemser-backend | d3889319fcac5a34126a5b1fa8d07faf7a1ca484 | [
"MIT"
] | null | null | null | modulo_3_3/pessoaapi/src/main/java/com/dbc/pessoaapi/repository/EnderecoRepository.java | joaovjc/vemser-backend | d3889319fcac5a34126a5b1fa8d07faf7a1ca484 | [
"MIT"
] | null | null | null | modulo_3_3/pessoaapi/src/main/java/com/dbc/pessoaapi/repository/EnderecoRepository.java | joaovjc/vemser-backend | d3889319fcac5a34126a5b1fa8d07faf7a1ca484 | [
"MIT"
] | null | null | null | 36.96875 | 100 | 0.796281 | 5,187 | package com.dbc.pessoaapi.repository;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.dbc.pessoaapi.entity.EnderecoEntity;
@Repository
public interface EnderecoRepository extends JpaRepository<EnderecoEntity, Integer>{
// List<EnderecoEntity> findAllByIdPessoa(Integer idPessoa);
@Query("select e from ENDERECO_PESSOA e where e.pais = :nome")
List<EnderecoEntity> listPorPais(String nome);
Page<EnderecoEntity> findAllByPais(String pais, Pageable pageable);
@Query("select e from ENDERECO_PESSOA e JOIN FETCH e.pessoas p where p.idPessoa = :id")
List<EnderecoEntity> listPorIdPessoa(Integer id);
@Query(nativeQuery = true, value = "SELECT * FROM ENDERECO_PESSOA ep WHERE ep.COMPLEMENTO IS NULL")
List<EnderecoEntity> listPorSemComplemento();
@Query(nativeQuery = true, value = "SELECT * FROM ENDERECO_PESSOA ep WHERE ep.CIDADE = 1? OR 2?")
List<EnderecoEntity> listPorCidadeOuPais(String cidade, String Pais);
}
|
3e0c399cca99f136a13d5af9f099a21cd89ca536 | 6,497 | java | Java | gsyVideoPlayer-java/src/main/java/com/shuyu/gsyvideoplayer/player/IJKPlayerManager.java | pjcchinaren/GSYVideoPlayer | 7f198432bb7a2bf542029768a8952dffc33a6497 | [
"Apache-2.0"
] | 3 | 2021-06-01T09:24:49.000Z | 2021-06-25T12:09:05.000Z | gsyVideoPlayer-java/src/main/java/com/shuyu/gsyvideoplayer/player/IJKPlayerManager.java | willShuhuan/GSYVideoPlayer | 059f287423e20bd4f544456def8e02e3a6f75d34 | [
"Apache-2.0"
] | null | null | null | gsyVideoPlayer-java/src/main/java/com/shuyu/gsyvideoplayer/player/IJKPlayerManager.java | willShuhuan/GSYVideoPlayer | 059f287423e20bd4f544456def8e02e3a6f75d34 | [
"Apache-2.0"
] | 1 | 2018-06-04T06:58:54.000Z | 2018-06-04T06:58:54.000Z | 33.489691 | 116 | 0.606126 | 5,188 | package com.shuyu.gsyvideoplayer.player;
import android.content.ContentResolver;
import android.content.Context;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.Surface;
import com.shuyu.gsyvideoplayer.model.GSYModel;
import com.shuyu.gsyvideoplayer.model.VideoOptionModel;
import com.shuyu.gsyvideoplayer.utils.Debuger;
import com.shuyu.gsyvideoplayer.utils.GSYVideoType;
import com.shuyu.gsyvideoplayer.utils.RawDataSourceProvider;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IjkLibLoader;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;
/**
* IJKPLayer
* Created by guoshuyu on 2018/1/11.
*/
public class IJKPlayerManager implements IPlayerManager {
//log level
private static int logLevel = IjkMediaPlayer.IJK_LOG_DEFAULT;
private static IjkLibLoader ijkLibLoader;
private IjkMediaPlayer mediaPlayer;
private List<VideoOptionModel> optionModelList;
private Surface surface;
@Override
public IMediaPlayer getMediaPlayer() {
return mediaPlayer;
}
@Override
public void initVideoPlayer(Context context, Message msg, List<VideoOptionModel> optionModelList) {
mediaPlayer = (ijkLibLoader == null) ? new IjkMediaPlayer() : new IjkMediaPlayer(ijkLibLoader);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnNativeInvokeListener(new IjkMediaPlayer.OnNativeInvokeListener() {
@Override
public boolean onNativeInvoke(int i, Bundle bundle) {
return true;
}
});
try {
//开启硬解码
if (GSYVideoType.isMediaCodec()) {
Debuger.printfLog("enable mediaCodec");
mediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", 1);
mediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-auto-rotate", 1);
mediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-handle-resolution-change", 1);
}
String url = ((GSYModel) msg.obj).getUrl();
if(!TextUtils.isEmpty(url)) {
Uri uri = Uri.parse(url);
if(uri.getScheme().equals(ContentResolver.SCHEME_ANDROID_RESOURCE)){
RawDataSourceProvider rawDataSourceProvider = RawDataSourceProvider.create(context, uri);
mediaPlayer.setDataSource(rawDataSourceProvider);
} else {
mediaPlayer.setDataSource(url, ((GSYModel) msg.obj).getMapHeadData());
}
} else {
mediaPlayer.setDataSource(url, ((GSYModel) msg.obj).getMapHeadData());
}
mediaPlayer.setLooping(((GSYModel) msg.obj).isLooping());
if (((GSYModel) msg.obj).getSpeed() != 1 && ((GSYModel) msg.obj).getSpeed() > 0) {
mediaPlayer.setSpeed(((GSYModel) msg.obj).getSpeed());
}
mediaPlayer.native_setLogLevel(logLevel);
initIJKOption(mediaPlayer, optionModelList);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void showDisplay(Message msg) {
if (msg.obj == null && mediaPlayer != null) {
mediaPlayer.setSurface(null);
} else {
Surface holder = (Surface) msg.obj;
surface = holder;
if (mediaPlayer != null && holder.isValid()) {
mediaPlayer.setSurface(holder);
}
}
}
@Override
public void setSpeed(float speed, boolean soundTouch) {
if (speed > 0) {
try {
if(mediaPlayer != null) {
mediaPlayer.setSpeed(speed);
}
} catch (Exception e) {
e.printStackTrace();
}
if (soundTouch) {
VideoOptionModel videoOptionModel =
new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", 1);
List<VideoOptionModel> list = getOptionModelList();
if (list != null) {
list.add(videoOptionModel);
} else {
list = new ArrayList<>();
list.add(videoOptionModel);
}
setOptionModelList(list);
}
}
}
@Override
public void setNeedMute(boolean needMute) {
if(mediaPlayer != null) {
if (needMute) {
mediaPlayer.setVolume(0, 0);
} else {
mediaPlayer.setVolume(1, 1);
}
}
}
@Override
public void releaseSurface() {
if (surface != null) {
surface.release();
surface = null;
}
}
@Override
public void release() {
if(mediaPlayer != null) {
mediaPlayer.release();
}
}
private void initIJKOption(IjkMediaPlayer ijkMediaPlayer, List<VideoOptionModel> optionModelList) {
if (optionModelList != null && optionModelList.size() > 0) {
for (VideoOptionModel videoOptionModel : optionModelList) {
if (videoOptionModel.getValueType() == VideoOptionModel.VALUE_TYPE_INT) {
ijkMediaPlayer.setOption(videoOptionModel.getCategory(),
videoOptionModel.getName(), videoOptionModel.getValueInt());
} else {
ijkMediaPlayer.setOption(videoOptionModel.getCategory(),
videoOptionModel.getName(), videoOptionModel.getValueString());
}
}
}
}
public List<VideoOptionModel> getOptionModelList() {
return optionModelList;
}
public void setOptionModelList(List<VideoOptionModel> optionModelList) {
this.optionModelList = optionModelList;
}
public static IjkLibLoader getIjkLibLoader() {
return ijkLibLoader;
}
public static void setIjkLibLoader(IjkLibLoader ijkLibLoader) {
IJKPlayerManager.ijkLibLoader = ijkLibLoader;
}
public static int getLogLevel() {
return logLevel;
}
public static void setLogLevel(int logLevel) {
IJKPlayerManager.logLevel = logLevel;
}
} |
3e0c39b91a1c9e8f49f4f52767c5f7f871d9497b | 991 | java | Java | gapi-gateway/src/main/java/io/github/conanchen/gobject/graphql/api/Resolvers.java | conanchen/netifi-kgmovies | 77da1f463fb52a52fe91396e86840af84635fcb2 | [
"Apache-2.0"
] | 1 | 2020-08-18T14:55:27.000Z | 2020-08-18T14:55:27.000Z | gapi-gateway/src/main/java/io/github/conanchen/gobject/graphql/api/Resolvers.java | conanchen/netifi-kgmovies | 77da1f463fb52a52fe91396e86840af84635fcb2 | [
"Apache-2.0"
] | null | null | null | gapi-gateway/src/main/java/io/github/conanchen/gobject/graphql/api/Resolvers.java | conanchen/netifi-kgmovies | 77da1f463fb52a52fe91396e86840af84635fcb2 | [
"Apache-2.0"
] | 1 | 2020-02-10T06:31:29.000Z | 2020-02-10T06:31:29.000Z | 22.522727 | 56 | 0.676085 | 5,189 | package io.github.conanchen.gobject.graphql.api;
import java.util.*;
import io.github.conanchen.person.graphql.model.*;
import io.github.conanchen.organization.graphql.model.*;
import io.github.conanchen.place.graphql.model.*;
import io.github.conanchen.gobject.graphql.model.*;
import io.github.conanchen.zommon.graphql.model.*;
import io.github.conanchen.shoppingdoor.graphql.model.*;
import graphql.schema.DataFetchingEnvironment;
import graphql.relay.Connection;
public class Resolvers{
public interface GeneralObject {
// KK
}
public interface ImageObject {
// KK
}
public interface AudioObject {
// KK
}
public interface VideoObject {
// KK
}
public interface GxcelObject {
// KK
}
public interface Gxsheet {
// KK
}
public interface AggregateGxrow {
// KK
}
public interface Gxrow {
// KK
}
public interface Gxcell {
// KK
}
public interface GxcolDef {
// KK
}
} |
3e0c3a2a29547dc55d33c39d04c793e46cbaf7f8 | 77 | java | Java | Hw7/src/MyList.java | asheemchhetri/ECE30862 | 7a452ba4bcbac8643f9176eab6bd01fe48fd44e8 | [
"MIT"
] | null | null | null | Hw7/src/MyList.java | asheemchhetri/ECE30862 | 7a452ba4bcbac8643f9176eab6bd01fe48fd44e8 | [
"MIT"
] | null | null | null | Hw7/src/MyList.java | asheemchhetri/ECE30862 | 7a452ba4bcbac8643f9176eab6bd01fe48fd44e8 | [
"MIT"
] | null | null | null | 15.4 | 25 | 0.727273 | 5,190 | public interface MyList {
public MyList next();
public void printNode();
}
|
3e0c3aa75f9a467f8408b133deb670ae314c3110 | 5,904 | java | Java | yoo-master-dc2492330d5d46b48f1ceca891e0f9f7e1593fee/module/yoomath/ym-mobile/src/main/java/com/lanking/uxb/service/nationalDayActivity01/resource/ZyMTeaNationalDayActivity01Controller.java | wangsikai/learn | af85f7c7db5c38b5009ebdfb8c8985032eca565c | [
"Apache-2.0"
] | 1 | 2019-01-20T06:19:53.000Z | 2019-01-20T06:19:53.000Z | yoo-master-dc2492330d5d46b48f1ceca891e0f9f7e1593fee/module/yoomath/ym-mobile/src/main/java/com/lanking/uxb/service/nationalDayActivity01/resource/ZyMTeaNationalDayActivity01Controller.java | wangsikai/learn | af85f7c7db5c38b5009ebdfb8c8985032eca565c | [
"Apache-2.0"
] | null | null | null | yoo-master-dc2492330d5d46b48f1ceca891e0f9f7e1593fee/module/yoomath/ym-mobile/src/main/java/com/lanking/uxb/service/nationalDayActivity01/resource/ZyMTeaNationalDayActivity01Controller.java | wangsikai/learn | af85f7c7db5c38b5009ebdfb8c8985032eca565c | [
"Apache-2.0"
] | 2 | 2019-01-20T06:19:54.000Z | 2021-07-21T14:13:44.000Z | 33.389831 | 103 | 0.727242 | 5,191 | package com.lanking.uxb.service.nationalDayActivity01.resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.lanking.cloud.component.db.masterslave.MasterSlaveDataSource;
import com.lanking.cloud.domain.yoo.activity.nationalDay01.NationalDayActivity01;
import com.lanking.cloud.domain.yoo.activity.nationalDay01.NationalDayActivity01Tea;
import com.lanking.cloud.domain.yoo.activity.nationalDay01.NationalDayActivity01TeaAward;
import com.lanking.cloud.sdk.value.Value;
import com.lanking.uxb.core.annotation.RolesAllowed;
import com.lanking.uxb.service.nationalDayActivity01.api.NationalDayActivity01Service;
import com.lanking.uxb.service.nationalDayActivity01.api.NationalDayActivity01TeaAwardService;
import com.lanking.uxb.service.nationalDayActivity01.api.NationalDayActivity01TeaService;
import com.lanking.uxb.service.nationalDayActivity01.convert.NationalDayActivity01TeaAwardConvert;
import com.lanking.uxb.service.nationalDayActivity01.convert.NationalDayActivity01TeaConvert;
import com.lanking.uxb.service.nationalDayActivity01.value.VNationalDayActivity01Rank;
import com.lanking.uxb.service.session.api.impl.Security;
import httl.util.CollectionUtils;
/**
* 国庆节活动老师相关接口
*
* @author <a href="mailto:ychag@example.com">sikai.wang</a>
* @version 2017年9月21日
*/
@RestController
@RequestMapping("zy/m/t/nda01")
public class ZyMTeaNationalDayActivity01Controller {
@Autowired
private NationalDayActivity01Service nationalDayActivity01Service;
@Autowired
private NationalDayActivity01TeaService nationalDayActivity01TeaService;
@Autowired
private NationalDayActivity01TeaConvert nationalDayActivity01TeaConvert;
@Autowired
private NationalDayActivity01TeaAwardService nationalDayActivity01TeaAwardService;
@Autowired
private NationalDayActivity01TeaAwardConvert nationalDayActivity01TeaAwardConvert;
/**
* 介绍页接口
*
* @since yoomath(mobile) V1.4.7
* @return {@link Value}
*/
@MasterSlaveDataSource(type = "MS")
@RolesAllowed(userTypes = { "TEACHER" })
@RequestMapping(value = "index", method = { RequestMethod.POST, RequestMethod.GET })
public Value index() {
Map<String, Object> data = new HashMap<String, Object>();
NationalDayActivity01 activity = nationalDayActivity01Service.getActivity();
if (activity != null) {
data.put("startTime", activity.getStartTime().getTime());
data.put("endTime", activity.getEndTime().getTime());
}
return new Value(data);
}
/**
* 排行榜接口
*
* @since yoomath(mobile) V1.4.7
* @return {@link Value}
*/
@MasterSlaveDataSource(type = "MS")
@RolesAllowed(userTypes = { "TEACHER" })
@RequestMapping(value = "rankingList", method = { RequestMethod.POST, RequestMethod.GET })
public Value rankingList() {
Map<String, Object> data = new HashMap<String, Object>();
List<NationalDayActivity01Tea> teas = nationalDayActivity01TeaService.getTopN(10);
if (CollectionUtils.isEmpty(teas)) {
data.put("items", Collections.EMPTY_LIST);
} else {
data.put("items", getRanks(teas));
}
// 该用户自己的排行
NationalDayActivity01Tea meTeaRank = null;
int meRank = 0;
for (int i = 0; i < teas.size(); i++) {
if (teas.get(i).getUserId() == Security.getUserId()) {
meTeaRank = teas.get(i);
meRank = i + 1;
break;
}
}
VNationalDayActivity01Rank vMeRank = null;
if (meTeaRank == null) {
Map<String, Object> meRankMap = nationalDayActivity01TeaService.getTeaByUser(Security.getUserId());
if (meRankMap != null && !meRankMap.isEmpty()) {
meTeaRank = (NationalDayActivity01Tea) meRankMap.get("activityTea");
vMeRank = nationalDayActivity01TeaConvert.to(meTeaRank);
vMeRank.setRank((int) meRankMap.get("rownum"));
} else {
meTeaRank = new NationalDayActivity01Tea();
meTeaRank.setUserId(Security.getUserId());
vMeRank = nationalDayActivity01TeaConvert.to(meTeaRank);
vMeRank.setRank(0);
}
} else {
vMeRank = nationalDayActivity01TeaConvert.to(meTeaRank);
vMeRank.setRank(meRank);
}
vMeRank.getUser().setName(formatTeacherName(vMeRank.getUser().getName()));
data.put("meRank", vMeRank);
return new Value(data);
}
/**
* 设置排行榜排名
*
* @param teas
* @return
*/
private List<VNationalDayActivity01Rank> getRanks(List<NationalDayActivity01Tea> teas) {
List<VNationalDayActivity01Rank> vRanks = nationalDayActivity01TeaConvert.to(teas);
for (int i = 0; i < vRanks.size(); i++) {
vRanks.get(i).setRank(i + 1);
vRanks.get(i).getUser().setName(formatTeacherName(vRanks.get(i).getUser().getName()));
}
return vRanks;
}
/**
* 截取老师名称
*
* @param teacherName
* @return
*/
private String formatTeacherName(String teacherName) {
if (teacherName != null && teacherName.length() > 0) {
return teacherName.substring(0, 1) + "老师";
} else {
return "老师";
}
}
/**
* 获奖榜单接口
*
* @since yoomath(mobile) V1.4.7
* @return {@link Value}
*/
@MasterSlaveDataSource(type = "MS")
@RolesAllowed(userTypes = { "TEACHER" })
@RequestMapping(value = "awardList", method = { RequestMethod.POST, RequestMethod.GET })
public Value awardList() {
Map<String, Object> data = new HashMap<String, Object>();
List<NationalDayActivity01TeaAward> awards = nationalDayActivity01TeaAwardService.getTeaAward();
if (CollectionUtils.isEmpty(awards)) {
data.put("items", Collections.EMPTY_LIST);
}
data.put("items", nationalDayActivity01TeaAwardConvert.to(awards));
return new Value(data);
}
}
|
3e0c3b324637eb20d03aa9655c223722cf9fe57e | 2,259 | java | Java | src/com/wyq/hf/po/Menu.java | ErinMeQiao/car-maintaince | 50d69b8e4b7bbd9989b698c475a4c19a3a58ffa5 | [
"MIT"
] | null | null | null | src/com/wyq/hf/po/Menu.java | ErinMeQiao/car-maintaince | 50d69b8e4b7bbd9989b698c475a4c19a3a58ffa5 | [
"MIT"
] | null | null | null | src/com/wyq/hf/po/Menu.java | ErinMeQiao/car-maintaince | 50d69b8e4b7bbd9989b698c475a4c19a3a58ffa5 | [
"MIT"
] | null | null | null | 20.724771 | 67 | 0.711819 | 5,192 | package com.wyq.hf.po;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Menu entity.
*
* @author MyEclipse Persistence Tools
*/
@Entity
@Table(name = "menu", catalog = "homefinance")
public class Menu implements java.io.Serializable {
// Fields
private Integer menuid;
private String menuname;
private String menuurl;
private Integer parentmenuid;
private String remark;
private String state;
// Constructors
/** default constructor */
public Menu() {
}
/** minimal constructor */
public Menu(String menuname, String menuurl, Integer parentmenuid,
String state) {
this.menuname = menuname;
this.menuurl = menuurl;
this.parentmenuid = parentmenuid;
this.state = state;
}
/** full constructor */
public Menu(String menuname, String menuurl, Integer parentmenuid,
String remark, String state) {
this.menuname = menuname;
this.menuurl = menuurl;
this.parentmenuid = parentmenuid;
this.remark = remark;
this.state = state;
}
// Property accessors
@Id
@GeneratedValue
@Column(name = "menuid", unique = true, nullable = false)
public Integer getMenuid() {
return this.menuid;
}
public void setMenuid(Integer menuid) {
this.menuid = menuid;
}
@Column(name = "menuname", nullable = false, length = 100)
public String getMenuname() {
return this.menuname;
}
public void setMenuname(String menuname) {
this.menuname = menuname;
}
@Column(name = "menuurl", nullable = false, length = 100)
public String getMenuurl() {
return this.menuurl;
}
public void setMenuurl(String menuurl) {
this.menuurl = menuurl;
}
@Column(name = "parentmenuid", nullable = false)
public Integer getParentmenuid() {
return this.parentmenuid;
}
public void setParentmenuid(Integer parentmenuid) {
this.parentmenuid = parentmenuid;
}
@Column(name = "remark", length = 256)
public String getRemark() {
return this.remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
@Column(name = "state", nullable = false, length = 1)
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
} |
3e0c3b4b92dbea7a377759a30aca8e1609dade3c | 1,632 | java | Java | persistence-api/src/main/java/io/stargate/db/schema/TableName.java | polandll/stargate | e2f0ac1b86fea1cb27fcf67dc544753afccecbee | [
"Apache-2.0"
] | 602 | 2020-09-03T16:19:59.000Z | 2022-03-31T12:44:20.000Z | persistence-api/src/main/java/io/stargate/db/schema/TableName.java | polandll/stargate | e2f0ac1b86fea1cb27fcf67dc544753afccecbee | [
"Apache-2.0"
] | 1,174 | 2020-08-29T20:55:24.000Z | 2022-03-31T15:26:22.000Z | persistence-api/src/main/java/io/stargate/db/schema/TableName.java | polandll/stargate | e2f0ac1b86fea1cb27fcf67dc544753afccecbee | [
"Apache-2.0"
] | 86 | 2020-09-10T13:23:52.000Z | 2022-03-28T16:36:05.000Z | 32 | 86 | 0.668505 | 5,193 | /*
* Copyright The Stargate Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.stargate.db.schema;
import java.util.Collection;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import org.immutables.value.Value;
/** Represents a qualified table name. */
@Value.Immutable
public interface TableName extends QualifiedSchemaEntity {
static TableName of(Collection<Column> columns) {
Set<TableName> tables =
columns.stream()
.map(
column ->
ImmutableTableName.builder()
.keyspace(Objects.requireNonNull(column.keyspace()))
.name(Objects.requireNonNull(column.table()))
.build())
.collect(Collectors.toSet());
if (tables.isEmpty()) {
throw new IllegalArgumentException(
"Missing table information in the provided set of columns.");
}
if (tables.size() > 1) {
throw new IllegalArgumentException("Too many tables are referenced: " + tables);
}
return tables.iterator().next();
}
}
|
3e0c3c5ddc31a1a3c6872319188e3dd638e3d662 | 1,710 | java | Java | DrDisease-prog/DoctorDisease/src/doctordisease/PlayerListener.java | DragonRox/Java | ff72e4105c4375b00ce99c86c28d4ff12e1952b5 | [
"Apache-2.0"
] | null | null | null | DrDisease-prog/DoctorDisease/src/doctordisease/PlayerListener.java | DragonRox/Java | ff72e4105c4375b00ce99c86c28d4ff12e1952b5 | [
"Apache-2.0"
] | null | null | null | DrDisease-prog/DoctorDisease/src/doctordisease/PlayerListener.java | DragonRox/Java | ff72e4105c4375b00ce99c86c28d4ff12e1952b5 | [
"Apache-2.0"
] | null | null | null | 38.863636 | 180 | 0.481287 | 5,194 | /*
* 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 doctordisease;
/**
*
* @author verratti.gfv
*/
public class PlayerListener {
}
/**
if (type == "state"){
button = new MouseOverArea(gc, buttonImg[0], x - (buttonImg[0].getWidth()/2), y, buttonImg[0].getWidth(), buttonImg[0].getHeight(), new ComponentListener() {
@Override
public void componentActivated(AbstractComponent arg0) {
Menu.estadosMenu[0] = var;
}
});
button.setMouseOverImage(buttonImg[1]);
}
if (type == "controle"){
button = new MouseOverArea(gc, imgButton, x - (buttonImg[0].getWidth()/2), y, buttonImg[0].getWidth(), buttonImg[0].getHeight(), new ComponentListener() {
@Override
public void componentActivated(AbstractComponent arg0) {
Menu.estadosMenu[var] += 1;
if (Menu.estadosMenu[var] > 1) Menu.estadosMenu[var] = 0;
if (Menu.estadosMenu[var] == 0) {
button.setNormalImage(buttonImg[0]);
button.setMouseOverImage(buttonImg[0]);
}
else {
button.setNormalImage(buttonImg[1]);
button.setMouseOverImage(buttonImg[1]);
}
}
});
}
*/ |
3e0c3d0be8f5d80d298441a466778e9587f29e9e | 615 | java | Java | core-services/src/main/java/it/uniroma2/art/semanticturkey/services/core/resourceview/consumers/DenotationsStatementConsumer.java | tocororo/semantic-turkey | 2ade3e27cb5123cbc9e0b866ee05f4d5c68a9519 | [
"BSD-3-Clause"
] | null | null | null | core-services/src/main/java/it/uniroma2/art/semanticturkey/services/core/resourceview/consumers/DenotationsStatementConsumer.java | tocororo/semantic-turkey | 2ade3e27cb5123cbc9e0b866ee05f4d5c68a9519 | [
"BSD-3-Clause"
] | 2 | 2021-01-21T01:31:30.000Z | 2021-12-09T22:35:18.000Z | core-services/src/main/java/it/uniroma2/art/semanticturkey/services/core/resourceview/consumers/DenotationsStatementConsumer.java | tocororo/semantic-turkey | 2ade3e27cb5123cbc9e0b866ee05f4d5c68a9519 | [
"BSD-3-Clause"
] | null | null | null | 38.4375 | 108 | 0.84065 | 5,195 | package it.uniroma2.art.semanticturkey.services.core.resourceview.consumers;
import java.util.Collections;
import it.uniroma2.art.lime.model.vocabulary.ONTOLEX;
import it.uniroma2.art.semanticturkey.customform.CustomFormManager;
import it.uniroma2.art.semanticturkey.services.core.resourceview.AbstractPropertyMatchingStatementConsumer;
public class DenotationsStatementConsumer extends AbstractPropertyMatchingStatementConsumer {
public DenotationsStatementConsumer(CustomFormManager customFormManager) {
super(customFormManager, "denotations", Collections.singleton(ONTOLEX.DENOTES));
}
}
|
3e0c3d421f93c57265db7839307cfea920658936 | 1,834 | java | Java | src/main/java/io/github/oliviercailloux/y2018/Master.java | saraTag/Java_EE_Personel | 9495b94f6720d70ebf113606fa4cfedd62bfe22a | [
"MIT"
] | null | null | null | src/main/java/io/github/oliviercailloux/y2018/Master.java | saraTag/Java_EE_Personel | 9495b94f6720d70ebf113606fa4cfedd62bfe22a | [
"MIT"
] | null | null | null | src/main/java/io/github/oliviercailloux/y2018/Master.java | saraTag/Java_EE_Personel | 9495b94f6720d70ebf113606fa4cfedd62bfe22a | [
"MIT"
] | null | null | null | 19.510638 | 72 | 0.717012 | 5,196 | package io.github.oliviercailloux.y2018;
import java.util.Optional;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.json.bind.annotation.JsonbPropertyOrder;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import com.google.common.base.Strings;
@Entity
@JsonbPropertyOrder({ "id", "name", "description" })
@XmlRootElement
public class Master {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@XmlAttribute
private int id;
private String name;
private Optional<String> description;
private static Jsonb jsonb = JsonbBuilder.create();
public Master() {
super();
this.name = "";
}
public Master(int id, String nom, String description) {
super();
this.id = id;
this.name = Strings.nullToEmpty(nom);
this.description = Optional.of(description);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
/**
* @return not null.
*/
@XmlAttribute(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = Strings.nullToEmpty(name);
}
/**
* @return not null.
*/
@XmlAttribute(name = "description")
public Optional<String> getDescription() {
return description;
}
public void setDescription(String description) {
this.description = Optional.of(description);
}
/**
* @return Master : json
*
*/
public String toJson() {
return jsonb.toJson(this);
}
/**
* @param jsonMaster : String
* @return Object : Master not null
*/
public static Master fromJson(String jsonbMaster) {
return jsonb.fromJson(Strings.nullToEmpty(jsonbMaster), Master.class);
}
}
|
3e0c3d8312dbddddb32fdde2423ff93d01237641 | 1,441 | java | Java | Crypto/PKCS12/PKCS12WP/src/cn/xiaolus/hxctf/crypto/pkcs12/GenMain.java | xiaolulwr/HXCTF-4th-Official | 5c76316f4e9d118bffbe025fde7bab53bbebed94 | [
"Apache-2.0"
] | 11 | 2019-04-10T16:29:27.000Z | 2021-01-14T20:34:32.000Z | Crypto/PKCS12/PKCS12WP/src/cn/xiaolus/hxctf/crypto/pkcs12/GenMain.java | xiaolulwr/HXCTF-4th-Official | 5c76316f4e9d118bffbe025fde7bab53bbebed94 | [
"Apache-2.0"
] | null | null | null | Crypto/PKCS12/PKCS12WP/src/cn/xiaolus/hxctf/crypto/pkcs12/GenMain.java | xiaolulwr/HXCTF-4th-Official | 5c76316f4e9d118bffbe025fde7bab53bbebed94 | [
"Apache-2.0"
] | 5 | 2020-09-30T09:41:29.000Z | 2021-06-30T09:53:54.000Z | 35.146341 | 101 | 0.760583 | 5,197 | package cn.xiaolus.hxctf.crypto.pkcs12;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.KeyStore.SecretKeyEntry;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
public class GenMain {
public static void main(String[] args) throws Exception {
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(new FileInputStream("PKCS12.keystore"), "admin123".toCharArray());
KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection("admin123".toCharArray());
KeyStore.SecretKeyEntry keyEntry = (SecretKeyEntry)ks.getEntry("key", protParam);
SecretKey key = keyEntry.getSecretKey();
FileOutputStream encFos = new FileOutputStream("flag.enc");
SecureRandom random = new SecureRandom();
byte[] bytes = new byte[16];
random.nextBytes(bytes);
IvParameterSpec iv = new IvParameterSpec(bytes);
Cipher cipher = Cipher.getInstance("AES/OFB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
byte[] enc = cipher.doFinal("HXCTF{Weak_PWD_Make_Key_Unsecure}".getBytes());
encFos.write("Mode=AES/OFB/PKCS5Padding\r\nIV=".getBytes());
encFos.write(Base64.getEncoder().encode(bytes));
encFos.write("\r\nCiphertext=".getBytes());
encFos.write(Base64.getEncoder().encode(enc));
encFos.flush();
encFos.close();
}
}
|
3e0c3ee1f0800c1fd6dc03bfc2b8f6adabbcb952 | 685 | java | Java | src/main/java/com/avispl/dal/communicator/cisco/controller/type/AudioConfigurationCommandType.java | AVISPL/dal-codecs-singlecodecs-cisco | 3bf9e672f93cbf3ffa2d1db38e84b3304e74a43f | [
"MIT"
] | null | null | null | src/main/java/com/avispl/dal/communicator/cisco/controller/type/AudioConfigurationCommandType.java | AVISPL/dal-codecs-singlecodecs-cisco | 3bf9e672f93cbf3ffa2d1db38e84b3304e74a43f | [
"MIT"
] | null | null | null | src/main/java/com/avispl/dal/communicator/cisco/controller/type/AudioConfigurationCommandType.java | AVISPL/dal-codecs-singlecodecs-cisco | 3bf9e672f93cbf3ffa2d1db38e84b3304e74a43f | [
"MIT"
] | null | null | null | 32.619048 | 98 | 0.728467 | 5,198 | /*
* Copyright (c) 2021 AVI-SPL Inc. All Rights Reserved.
*/
package com.avispl.dal.communicator.cisco.controller.type;
/**
* Audio configuration command type class.
* Serves the purpose of distinguishing between the audio config command types, to have the right
* instance of the payload built for a specific control command.
*
* @author Maksym.Rossiitsev / Symphony Dev Team<br>
* Created on Apr 26, 2021
* @since 1.0
*/
public enum AudioConfigurationCommandType {
/**MicrophoneMode for microphome mode commands*/
MicrophoneMode,
/**MaxUltrasoundVolume for maximum ultrasound volume for people presence detector*/
MaxUltrasoundVolume
}
|
3e0c3f403b516176f43cf9ebb8b0f4ab6e52a3ee | 431 | java | Java | ITA-JAVA-SPECIALIZATION/DESENVOLVIMENTO_AGIL_DESIGN_PATTERNS/WEEK04/projeto/src/week04/exemplo01/GeradorNome.java | iratuan/coursera | 3a0519787852dd15215b43f65e586f43366d835e | [
"Apache-2.0"
] | null | null | null | ITA-JAVA-SPECIALIZATION/DESENVOLVIMENTO_AGIL_DESIGN_PATTERNS/WEEK04/projeto/src/week04/exemplo01/GeradorNome.java | iratuan/coursera | 3a0519787852dd15215b43f65e586f43366d835e | [
"Apache-2.0"
] | 3 | 2022-02-13T07:47:43.000Z | 2022-02-27T00:50:37.000Z | ITA-JAVA-SPECIALIZATION/DESENVOLVIMENTO_AGIL_DESIGN_PATTERNS/WEEK04/projeto/src/week04/exemplo01/GeradorNome.java | iratuan/coursera | 3a0519787852dd15215b43f65e586f43366d835e | [
"Apache-2.0"
] | null | null | null | 15.392857 | 54 | 0.723898 | 5,199 | package week04.exemplo01;
public class GeradorNome {
private Tratamento tratamento = new NullTratamento();
public void setTratamento(Tratamento tratamento) {
this.tratamento = tratamento;
}
public String gerarNome(String nome) {
return tratamento.tratar() + getTratamento() + nome;
}
public Tratamento getTratamentoStrategy() {
return tratamento;
}
protected String getTratamento() {
return "";
}
}
|
3e0c40b5cf2d431d1741eb7ba510820ed8420ca7 | 1,481 | java | Java | java8/src/test/java/com/shekhargulati/leetcode/algorithms/Problem05Test.java | chitranjanB/99-problems | 0fcbc97ce8a5c59be123d67e361c5ddab218d348 | [
"MIT"
] | 3,734 | 2016-05-23T10:54:47.000Z | 2022-03-29T02:27:27.000Z | java8/src/test/java/com/shekhargulati/leetcode/algorithms/Problem05Test.java | chitranjanB/99-problems | 0fcbc97ce8a5c59be123d67e361c5ddab218d348 | [
"MIT"
] | 11 | 2016-05-24T05:23:59.000Z | 2020-10-28T17:44:20.000Z | java8/src/test/java/com/shekhargulati/leetcode/algorithms/Problem05Test.java | chitranjanB/99-problems | 0fcbc97ce8a5c59be123d67e361c5ddab218d348 | [
"MIT"
] | 1,203 | 2016-05-23T11:28:32.000Z | 2022-03-28T08:48:21.000Z | 32.195652 | 168 | 0.712357 | 5,200 | package com.shekhargulati.leetcode.algorithms;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
public class Problem05Test {
@Test
public void shouldDetectLongestPalindrome() throws Exception {
final String input = "saasdcjkbkjnjnnknvjfknjnfjkvnjkfdnvjknfdkvjnkjfdnvkjnvjknjkgnbjkngkjvnjkgnbvkjngfreyh67ujrtyhytju789oijtnuk789oikmtul0oymmmmmmmmmmmmmmmm";
String l = Problem05.longestPalindrome(input);
assertThat(l, equalTo("mmmmmmmmmmmmmmmm"));
}
@Test
public void shouldFindLongestPalindromeString() throws Exception {
final String input = "racecar";
String s = Problem05.longestPalindrome1(input);
assertThat(s, equalTo("racecar"));
}
@Test
public void shouldFindLongestPalindromeString_2() throws Exception {
final String input = "saas";
String s = Problem05.longestPalindrome1(input);
assertThat(s, equalTo("saas"));
}
@Test
public void shouldFindLongestPalindromeString_3() throws Exception {
final String input = "forgeeksskeegfor";
String s = Problem05.longestPalindrome1(input);
assertThat(s, equalTo("geeksskeeg"));
}
@Test
public void shouldFindLongestPalindromeString_4() throws Exception {
final String input = "abaccddccefe";
String s = Problem05.longestPalindrome1(input);
assertThat(s, equalTo("ccddcc"));
}
}
|
3e0c40d38a8b5b035f13d43aa4c5fec8b8b5cae5 | 753 | java | Java | waterdrop-core/src/main/java/io/github/interestinglab/waterdrop/config/ExposeSparkConf.java | kindred77/waterdrop | bba2d8d54fb3cab39558828289fd9795b7e85360 | [
"Apache-2.0"
] | 2 | 2019-05-27T07:22:36.000Z | 2019-07-04T06:00:32.000Z | waterdrop-core/src/main/java/io/github/interestinglab/waterdrop/config/ExposeSparkConf.java | kindred77/waterdrop | bba2d8d54fb3cab39558828289fd9795b7e85360 | [
"Apache-2.0"
] | null | null | null | waterdrop-core/src/main/java/io/github/interestinglab/waterdrop/config/ExposeSparkConf.java | kindred77/waterdrop | bba2d8d54fb3cab39558828289fd9795b7e85360 | [
"Apache-2.0"
] | null | null | null | 31.375 | 108 | 0.691899 | 5,201 | package io.github.interestinglab.waterdrop.config;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import com.typesafe.config.ConfigValue;
import java.io.File;
import java.util.Map;
public class ExposeSparkConf {
public static void main(String[] args) throws Exception {
Config appConfig = ConfigFactory.parseFile(new File(args[0]));
StringBuilder stringBuilder = new StringBuilder();
for (Map.Entry<String, ConfigValue> entry: appConfig.getConfig("spark").entrySet()) {
String conf = String.format(" --conf \"%s=%s\" ", entry.getKey(), entry.getValue().unwrapped());
stringBuilder.append(conf);
}
System.out.print(stringBuilder.toString());
}
}
|
3e0c415c523c1952c8d1d09a5e1afd8f06b8961a | 1,638 | java | Java | app/src/main/java/whot/what/hot/api/ApiServices.java | quickey123/AndroidMvpSample | fc8dde7256e50ca62b5e8207b3e9ae27daa680c5 | [
"Unlicense"
] | 2 | 2018-02-27T11:11:57.000Z | 2019-03-25T10:05:48.000Z | app/src/main/java/whot/what/hot/api/ApiServices.java | quickey123/AndroidMvpSample | fc8dde7256e50ca62b5e8207b3e9ae27daa680c5 | [
"Unlicense"
] | 1 | 2018-07-03T03:58:39.000Z | 2018-07-03T10:01:39.000Z | app/src/main/java/whot/what/hot/api/ApiServices.java | quickey123/AndroidMvpSample | fc8dde7256e50ca62b5e8207b3e9ae27daa680c5 | [
"Unlicense"
] | null | null | null | 28.736842 | 114 | 0.738706 | 5,202 | package whot.what.hot.api;
import java.util.HashMap;
import java.util.Map;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;
import retrofit2.http.Query;
import retrofit2.http.QueryMap;
import retrofit2.http.Url;
import rx.Observable;
import whot.what.hot.data.AntModel;
import whot.what.hot.data.GankModel;
import whot.what.hot.data.InstagramTagModel;
import whot.what.hot.data.MainModel;
import whot.what.hot.data.WeatherDataModel;
/**
* Created by sapido on 21/09/2017.
*/
public interface ApiServices {
@GET("api/data/Android/10/1")
Call<ResponseBody> getAndroidInfo();
@GET("api/data/Android/10/1")
Call<GankModel> getAndroidInfoWithGson();
@GET("{fullUrl}")
Observable<AntModel> getAntInfoWithGson(@Path(value = "fullUrl", encoded = true) String fullUrl);
@GET
Observable<InstagramTagModel> getInstagramGson(@Url String URL);
@GET("onebox/weather/query?cityname=深圳")
Call<WeatherDataModel> getWeather(@Query("key") String key);
@GET("{fullUrl}")
Observable<GankModel> getAndroidInfoWithParameters(@Path(value = "fullUrl", encoded = true) String fullUrl);
/*轉換URL把括號內刪除 並給入完整的URL即可*/
@GET
Observable<WeatherDataModel> getWeatherWithParameters(@Url String URL , @QueryMap Map<String, String> params);
@POST("{page}")
Call<MainModel> getNotificationCount(@Path("page") String page, @Body HashMap hashMap);
@POST("{page}")
Observable<MainModel> getNotificationCountWithRxJava(@Path("page") String page, @Body HashMap hashMap);
}
|
3e0c41ba140c4c6097d350041edfd7c63c1090bd | 382 | java | Java | cmn/src/test/java/core/aws/util/RandomsTest.java | caine-lea/cmn-project | e71dfd49243533288628525c80b6fd81d300e1fd | [
"Apache-2.0"
] | null | null | null | cmn/src/test/java/core/aws/util/RandomsTest.java | caine-lea/cmn-project | e71dfd49243533288628525c80b6fd81d300e1fd | [
"Apache-2.0"
] | 1 | 2020-04-27T03:39:56.000Z | 2020-04-27T03:39:56.000Z | cmn/src/test/java/core/aws/util/RandomsTest.java | caine-lea/cmn-project | e71dfd49243533288628525c80b6fd81d300e1fd | [
"Apache-2.0"
] | null | null | null | 21.222222 | 57 | 0.685864 | 5,203 | package core.aws.util;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author neo
*/
class RandomsTest {
@Test
void randomAlphaNumeric() {
assertThat(Randoms.alphaNumeric(3)).hasSize(3);
assertThat(Randoms.alphaNumeric(5)).hasSize(5);
assertThat(Randoms.alphaNumeric(10)).hasSize(10);
}
}
|
3e0c4201547d933a8cfb33ab77023934d32781aa | 215 | java | Java | src/com/company/TestaLacoFor.java | gabizinha12/treinamento-rchlo | 5642f7abf6c4de515cc14df2e94787523ba6f6e5 | [
"MIT"
] | 2 | 2021-08-23T00:43:28.000Z | 2021-11-08T08:56:35.000Z | src/com/company/TestaLacoFor.java | gabizinha12/treinamento-rchlo1 | 5642f7abf6c4de515cc14df2e94787523ba6f6e5 | [
"MIT"
] | null | null | null | src/com/company/TestaLacoFor.java | gabizinha12/treinamento-rchlo1 | 5642f7abf6c4de515cc14df2e94787523ba6f6e5 | [
"MIT"
] | null | null | null | 21.5 | 59 | 0.590698 | 5,204 | package com.company;
public class TestaLacoFor {
public static void main(String[] args) {
for(int contador = 0; contador <= 10; contador++) {
System.out.println(contador);
}
}
}
|
3e0c431d07e109007aca94fccc532726f94cae9b | 1,649 | java | Java | src/main/java/tech/jhipster/controlcenter/security/jwt/JWTRelayGatewayFilterFactory.java | vmartowicz/jhipster-control-center | 50687902a8fc3550511120012ebddabd3a21584d | [
"Apache-2.0"
] | 54 | 2020-02-09T18:18:36.000Z | 2022-03-11T18:58:19.000Z | src/main/java/tech/jhipster/controlcenter/security/jwt/JWTRelayGatewayFilterFactory.java | vmartowicz/jhipster-control-center | 50687902a8fc3550511120012ebddabd3a21584d | [
"Apache-2.0"
] | 107 | 2020-03-26T17:36:42.000Z | 2022-03-19T17:27:57.000Z | src/main/java/tech/jhipster/controlcenter/security/jwt/JWTRelayGatewayFilterFactory.java | vmartowicz/jhipster-control-center | 50687902a8fc3550511120012ebddabd3a21584d | [
"Apache-2.0"
] | 44 | 2020-02-10T15:33:20.000Z | 2022-03-30T07:43:18.000Z | 41.225 | 131 | 0.733778 | 5,205 | package tech.jhipster.controlcenter.security.jwt;
import static tech.jhipster.controlcenter.security.jwt.JWTFilter.AUTHORIZATION_HEADER;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
@Component
public class JWTRelayGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> {
private final TokenProvider tokenProvider;
public JWTRelayGatewayFilterFactory(TokenProvider tokenProvider) {
this.tokenProvider = tokenProvider;
}
@Override
public GatewayFilter apply(Object config) {
return (exchange, chain) -> {
String token = this.extractJWTToken(exchange.getRequest());
if (StringUtils.hasText(token) && this.tokenProvider.validateToken(token)) {
ServerHttpRequest request = exchange.getRequest().mutate().header(AUTHORIZATION_HEADER, "Bearer " + token).build();
return chain.filter(exchange.mutate().request(request).build());
}
return chain.filter(exchange);
};
}
private String extractJWTToken(ServerHttpRequest request) {
String bearerToken = request.getHeaders().getFirst(AUTHORIZATION_HEADER);
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
return bearerToken.substring(7);
}
throw new IllegalArgumentException("Invalid token in Authorization header");
}
}
|
3e0c43a857e01a5967759de94ef434d8dc90bfbd | 526 | java | Java | hanyi-demo/src/main/java/com/hanyi/demo/common/design/adapter/ElectricCooker.java | Dearker/middleground | 6c8241d32483fcc685a76305c6cb9b9dae7af53f | [
"Apache-2.0"
] | 4 | 2020-05-11T12:10:30.000Z | 2021-11-11T04:02:12.000Z | hanyi-demo/src/main/java/com/hanyi/demo/common/design/adapter/ElectricCooker.java | Dearker/middleground | 6c8241d32483fcc685a76305c6cb9b9dae7af53f | [
"Apache-2.0"
] | 2 | 2020-11-21T09:12:29.000Z | 2020-11-21T09:12:43.000Z | hanyi-demo/src/main/java/com/hanyi/demo/common/design/adapter/ElectricCooker.java | Dearker/middleground | 6c8241d32483fcc685a76305c6cb9b9dae7af53f | [
"Apache-2.0"
] | 3 | 2020-01-14T01:38:08.000Z | 2020-08-14T06:27:34.000Z | 21.916667 | 79 | 0.701521 | 5,206 | package com.hanyi.demo.common.design.adapter;
/**
* @ClassName: middleground com.hanyi.demo.common.design.adapter ElectricCooker
* @Author: weiwenchang
* @Description: java类作用描述
* @CreateDate: 2020-01-23 15:37
* @Version: 1.0
*/
public class ElectricCooker {
private JP110VInterface jp110VInterface;
ElectricCooker(JP110VInterface jp110VInterface){
this.jp110VInterface=jp110VInterface;
}
public void cook(){
jp110VInterface.connect();
System.out.println("开始做饭了..");
}
}
|
3e0c43da1ce7f35044c84b62a36e164b65e84786 | 1,549 | java | Java | common/protocol/src/test/java/org/sdo/iotplatformsdk/common/protocol/security/PemPrivateKeySupplierTest.java | bprashan/iot-platform-sdk | 839fba8004a6d575a1e55fb91d6a720d70de07fa | [
"Apache-2.0"
] | null | null | null | common/protocol/src/test/java/org/sdo/iotplatformsdk/common/protocol/security/PemPrivateKeySupplierTest.java | bprashan/iot-platform-sdk | 839fba8004a6d575a1e55fb91d6a720d70de07fa | [
"Apache-2.0"
] | null | null | null | common/protocol/src/test/java/org/sdo/iotplatformsdk/common/protocol/security/PemPrivateKeySupplierTest.java | bprashan/iot-platform-sdk | 839fba8004a6d575a1e55fb91d6a720d70de07fa | [
"Apache-2.0"
] | null | null | null | 31.612245 | 85 | 0.695933 | 5,207 | /*******************************************************************************
* Copyright 2020 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package org.sdo.iotplatformsdk.common.protocol.security;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.sdo.iotplatformsdk.common.protocol.security.PemPrivateKeySupplier;
class PemPrivateKeySupplierTest {
PemPrivateKeySupplier pemPrivateKeySupplier;
URL url;
@BeforeEach
void beforeEach() throws MalformedURLException {
url = new URL("http://www.intel.com");
pemPrivateKeySupplier = new PemPrivateKeySupplier(url);
}
@Test
void test_Get() throws IOException, InvalidKeyException, NoSuchAlgorithmException {
pemPrivateKeySupplier.get();
}
}
|
3e0c44f36f3b31432e07f18f49af4cb11630e515 | 282 | java | Java | BinaryTree/src/com/datastructure/tree/TreeNode.java | joydsilva/Tree | 034958b86bf676120e47e4baf2776c69cb451363 | [
"MIT"
] | null | null | null | BinaryTree/src/com/datastructure/tree/TreeNode.java | joydsilva/Tree | 034958b86bf676120e47e4baf2776c69cb451363 | [
"MIT"
] | null | null | null | BinaryTree/src/com/datastructure/tree/TreeNode.java | joydsilva/Tree | 034958b86bf676120e47e4baf2776c69cb451363 | [
"MIT"
] | null | null | null | 12.818182 | 31 | 0.652482 | 5,208 | package com.datastructure.tree;
/**
* Binary Tree class
*
* @author joydsilva
*
*/
public class TreeNode {
String data;
TreeNode left = null;
TreeNode right = null;;
TreeNode(String data) {
this.data = data;
}
public void debug() {
System.out.println(data);
}
}
|
3e0c4628de90524a2a72575307d7c6dcbeda4af2 | 945 | java | Java | chess/src/main/java/ru/job4j/chess/firuges/black/PawnBlack.java | Darmandi/Java_intern | 94d7445b5356a6ffab10aaffc85ab6114f366c12 | [
"Apache-2.0"
] | 1 | 2018-12-07T15:50:34.000Z | 2018-12-07T15:50:34.000Z | chess/src/main/java/ru/job4j/chess/firuges/black/PawnBlack.java | Darmandi/dsaraev | 94d7445b5356a6ffab10aaffc85ab6114f366c12 | [
"Apache-2.0"
] | null | null | null | chess/src/main/java/ru/job4j/chess/firuges/black/PawnBlack.java | Darmandi/dsaraev | 94d7445b5356a6ffab10aaffc85ab6114f366c12 | [
"Apache-2.0"
] | 1 | 2020-10-27T09:52:18.000Z | 2020-10-27T09:52:18.000Z | 22.547619 | 74 | 0.631468 | 5,209 | package ru.job4j.chess.firuges.black;
import ru.job4j.chess.ImpossibleMoveException;
import ru.job4j.chess.firuges.Cell;
import ru.job4j.chess.firuges.Figure;
import ru.job4j.chess.firuges.Movement;
/**
*
* @author Petr Arsentev (dycjh@example.com)
* @version $Id$
* @since 0.1
*/
public class PawnBlack implements Figure {
private final Cell position;
public PawnBlack(final Cell position) {
this.position = position;
}
@Override
public Cell position() {
return this.position;
}
@Override
public Cell[] way(Cell source, Cell dest) {
Cell[] steps = new Cell[0];
if (Movement.pawnBlackMove(source, dest)) {
steps = new Cell[] {dest };
} else {
throw new ImpossibleMoveException("Невозможно сделать ход 1");
}
return steps;
}
@Override
public Figure copy(Cell dest) {
return new PawnBlack(dest);
}
}
|
3e0c47e6958e9417829e6d325a36714566ebfb6c | 32,405 | java | Java | api/pacman-api-compliance/src/main/java/com/tmobile/pacman/api/compliance/controller/ComplianceController.java | lifer84/pacbot | 997c240c123d81cf3f55ff5093127c5fda6119c3 | [
"Apache-2.0"
] | 1,165 | 2018-10-05T19:07:34.000Z | 2022-03-28T19:34:27.000Z | api/pacman-api-compliance/src/main/java/com/tmobile/pacman/api/compliance/controller/ComplianceController.java | lifer84/pacbot | 997c240c123d81cf3f55ff5093127c5fda6119c3 | [
"Apache-2.0"
] | 334 | 2018-10-10T14:00:41.000Z | 2022-03-19T16:32:08.000Z | api/pacman-api-compliance/src/main/java/com/tmobile/pacman/api/compliance/controller/ComplianceController.java | lifer84/pacbot | 997c240c123d81cf3f55ff5093127c5fda6119c3 | [
"Apache-2.0"
] | 268 | 2018-10-05T19:53:25.000Z | 2022-03-31T07:39:47.000Z | 45.25838 | 147 | 0.670082 | 5,210 | /*******************************************************************************
* Copyright 2018 T Mobile, Inc. or its affiliates. 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.tmobile.pacman.api.compliance.controller;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.google.common.base.Strings;
import com.tmobile.pacman.api.commons.Constants;
import com.tmobile.pacman.api.commons.exception.ServiceException;
import com.tmobile.pacman.api.commons.utils.ResponseUtils;
import com.tmobile.pacman.api.compliance.domain.DitributionDTO;
import com.tmobile.pacman.api.compliance.domain.IssueAuditLogRequest;
import com.tmobile.pacman.api.compliance.domain.IssueResponse;
import com.tmobile.pacman.api.compliance.domain.IssuesException;
import com.tmobile.pacman.api.compliance.domain.KernelVersion;
import com.tmobile.pacman.api.compliance.domain.OutputDTO;
import com.tmobile.pacman.api.compliance.domain.PolicyDescription;
import com.tmobile.pacman.api.compliance.domain.PolicyViolationDetails;
import com.tmobile.pacman.api.compliance.domain.Request;
import com.tmobile.pacman.api.compliance.domain.ResourceTypeResponse;
import com.tmobile.pacman.api.compliance.domain.ResponseData;
import com.tmobile.pacman.api.compliance.domain.ResponseWithOrder;
import com.tmobile.pacman.api.compliance.domain.RevokeIssuesException;
import com.tmobile.pacman.api.compliance.domain.RuleDetails;
import com.tmobile.pacman.api.compliance.service.ComplianceService;
/**
* The Class ComplianceController.
*/
@RestController
@PreAuthorize("@securityService.hasPermission(authentication, 'ROLE_USER')")
public class ComplianceController implements Constants {
/** The compliance service. */
@Autowired
private ComplianceService complianceService;
/**
* Gets the issues details.Request expects asssetGroup and domain as
* mandatory, ruleId as optional.If API receives assetGroup and domain as
* request parameter, it gives details of all open issues for all the rules
* associated to that domain. If API receives assetGroup, domain and ruleId
* as request parameter,it gives only open issues of that rule associated to
* that domain. SearchText is used to match any text you are looking
* for.From and size are for the pagination
*
* @param request request body
* @return issues
*/
@RequestMapping(path = "/v1/issues", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Object> getIssues(@RequestBody(required = false) Request request) {
String assetGroup = request.getAg();
Map<String, String> filters = request.getFilter();
if (Strings.isNullOrEmpty(assetGroup) || MapUtils.isEmpty(filters)
|| Strings.isNullOrEmpty(filters.get(DOMAIN))) {
return ResponseUtils.buildFailureResponse(new Exception(ASSET_GROUP_DOMAIN));
}
ResponseWithOrder response = null;
try {
response = complianceService.getIssues(request);
} catch (ServiceException e) {
return complianceService.formatException(e);
}
return ResponseUtils.buildSucessResponse(response);
}
/**
* Gets the issues count. asssetGroup and domain are mandatory & ruleId is
* optional parameter, it gives issues count of all open issues for all the rules
* associated to that domain. If API receives assetGroup,domain and ruleId
* as request parameter,it gives issues count of all open issues for that
* rule associated to that domain.
*
* @param assetGroup name of the asset group
* @param domain the domain
* @param ruleId the rule id
* @return the issues count
*/
@RequestMapping(path = "/v1/issues/count", method = RequestMethod.GET)
public ResponseEntity<Object> getIssuesCount(@RequestParam("ag") String assetGroup,
@RequestParam("domain") String domain, @RequestParam(name = "ruleId", required = false) String ruleId) {
if (Strings.isNullOrEmpty(assetGroup) || Strings.isNullOrEmpty(domain)) {
return ResponseUtils.buildFailureResponse(new Exception(ASSET_GROUP_DOMAIN));
}
Map<String, Long> response = new HashMap<>();
try {
response.put("total_issues", complianceService.getIssuesCount(assetGroup, ruleId, domain));
} catch (ServiceException e) {
return ResponseUtils.buildFailureResponse(e);
}
return ResponseUtils.buildSucessResponse(response);
}
/**
* Gets the issue distribution by ruleCategory and severity.asssetGroup
* is mandatory, domain is optional. API return issue distribution rule
* severity & rule Category for given asset group
*
* @param assetGroup name of the asset group
* @param domain the domain
* @return ResponseEntity
*/
@RequestMapping(path = "/v1/issues/distribution", method = RequestMethod.GET)
public ResponseEntity<Object> getDistribution(@RequestParam("ag") String assetGroup,
@RequestParam(name = "domain", required = false) String domain) {
if (Strings.isNullOrEmpty(assetGroup)) {
return ResponseUtils.buildFailureResponse(new Exception(ASSET_MANDATORY));
}
DitributionDTO distribution = null;
try {
distribution = new DitributionDTO(complianceService.getDistribution(assetGroup, domain));
} catch (ServiceException e) {
return complianceService.formatException(e);
}
return ResponseUtils.buildSucessResponse(distribution);
}
/**
* Gets the tagging compliance summary.asssetGroup is mandatory and
* targetType is optional If API receives assetGroup as request parameter,
* api returns tagged/un-tagged/asset count of all the target types for that
* asset group. If API receives both assetGroup and targetType as request
* parameter,api returns tagged/un-tagged/asset count of specified target
* type.
*
* @param assetGroup name of the asset group
* @param targetType the target type
* @return ResponseEntity
*/
@RequestMapping(path = "/v1/tagging", method = RequestMethod.GET)
public ResponseEntity<Object> getTagging(@RequestParam("ag") String assetGroup,
@RequestParam(name = "targettype", required = false) String targetType) {
if (Strings.isNullOrEmpty(assetGroup)) {
return ResponseUtils.buildFailureResponse(new Exception(ASSET_MANDATORY));
}
OutputDTO output = null;
try {
output = new OutputDTO(complianceService.getTagging(assetGroup, targetType));
} catch (ServiceException e) {
return complianceService.formatException(e);
}
return ResponseUtils.buildSucessResponse(output);
}
/**
* Gets the certificates compliance details.asssetGroup is mandatory. API
* returns count of expiredCertificates with in 60days and totalCertificates
* for given assetGroup
*
* @param assetGroup name of the asset group
* @return ResponseEntity
*/
@RequestMapping(path = "/v1/certificates", method = RequestMethod.GET)
public ResponseEntity<Object> getCertificates(@RequestParam("ag") String assetGroup) {
if (Strings.isNullOrEmpty(assetGroup)) {
return ResponseUtils.buildFailureResponse(new Exception(ASSET_MANDATORY));
}
OutputDTO output = null;
try {
output = new OutputDTO(complianceService.getCertificates(assetGroup));
} catch (ServiceException e) {
return complianceService.formatException(e);
}
return ResponseUtils.buildSucessResponse(output);
}
/**
* Gets the patching compliance details.AssetGroup is mandatory. API returns
* count of totalPached/toalUnpatched/TotalInstances for given assetGroup
*
* @param assetGroup name of the asset group
* @return ResponseEntity
*/
@RequestMapping(path = "/v1/patching", method = RequestMethod.GET)
public ResponseEntity<Object> getPatching(@RequestParam("ag") String assetGroup) {
if (Strings.isNullOrEmpty(assetGroup)) {
return ResponseUtils.buildFailureResponse(new Exception("Asset group is mandatory"));
}
OutputDTO output = null;
try {
output = new OutputDTO(complianceService.getPatching(assetGroup, null,null));
} catch (ServiceException e) {
return complianceService.formatException(e);
}
return ResponseUtils.buildSucessResponse(output);
}
/**
* Gets the recommendations details by policy.asssetGroup is mandatory and
* targetType is optional. If API receives assetGroup as request parameter,
* API returns list of all the issue counts which are related to
* recommendations rules from the ES for the given assetGroup with all the
* targetTypes.If API receives both assetGroup and targetType as request
* parameter,API returns list of all the issue counts which are related to
* recommendations rules from the ES for the given targetType & assetGroup.
*
* @param assetGroup name of the asset group
* @param targetType the target type
* @return ResponseEntity
*/
@RequestMapping(path = "/v1/recommendations", method = RequestMethod.GET)
public ResponseEntity<Object> getRecommendations(@RequestParam("ag") String assetGroup,
@RequestParam(name = "targettype", required = false) String targetType) {
if (Strings.isNullOrEmpty(assetGroup)) {
return ResponseUtils.buildFailureResponse(new Exception(ASSET_MANDATORY));
}
ResponseData response = null;
try {
response = new ResponseData(complianceService.getRecommendations(assetGroup, targetType));
} catch (ServiceException e) {
return complianceService.formatException(e);
}
return ResponseUtils.buildSucessResponse(response);
}
/**
* Gets the issue audit details.This request accepts
* annotationId,targetType,size as mandatory. If API receives
* annotationId,targetType,size as request parameter, API returns list of
* data source, audit date and status of that annotationId. searchText is used
* to match any text you are looking for. from and size are for pagination.
*
* @param request the request
* @return the issue audit
*/
@RequestMapping(path = "/v1/issueauditlog", method = RequestMethod.POST)
public ResponseEntity<Object> getIssueAudit(@RequestBody IssueAuditLogRequest request) {
String issueId = request.getIssueId();
String targetType = request.getTargetType();
int from = request.getFrom();
int size = request.getSize();
String searchText = request.getSearchText();
if (Strings.isNullOrEmpty(issueId) || Strings.isNullOrEmpty(targetType) || from < 0 || size <= 0) {
return ResponseUtils.buildFailureResponse(new Exception("IssueId/Targettype/from/size is Mandatory"));
}
ResponseWithOrder response = null;
try {
response = complianceService.getIssueAuditLog(issueId, targetType, from, size, searchText);
} catch (ServiceException e) {
return complianceService.formatException(e);
}
return ResponseUtils.buildSucessResponse(response);
}
/**
* Gets the resource details.assetGroup and resourceId are mandatory. API
* returns map details for given resourceId
*
* @param assetGroup name of the asset group
* @param resourceId the resource id
* @return ResponseEntity
*/
@RequestMapping(path = "/v1/resourcedetails", method = RequestMethod.GET)
public ResponseEntity<Object> getResourceDetails(@RequestParam("ag") String assetGroup,
@RequestParam("resourceId") String resourceId) {
if (Strings.isNullOrEmpty(resourceId)) {
return ResponseUtils.buildFailureResponse(new Exception("assetGroup/resourceId is mandatory"));
}
ResponseData response = null;
try {
response = new ResponseData(complianceService.getResourceDetails(assetGroup, resourceId));
} catch (ServiceException e) {
return complianceService.formatException(e);
}
return ResponseUtils.buildSucessResponse(response);
}
/**
* Close issues.ruleDetails expects ruleId,reason and userId, Api returns
* true if its successfully closes all issues in ES for that ruleId else
* false
*
* @param ruleDetails the rule details
* @return ResponseEntity
*/
@ApiOperation(httpMethod = "PUT", value = "Close Issues by Rule Details")
@RequestMapping(path = "/v1/issues/close-by-rule-id", method = RequestMethod.PUT)
@ResponseBody
public ResponseEntity<Object> closeIssues(
@ApiParam(value = "Provide valid Rule Details ", required = true) @RequestBody(required = true) RuleDetails ruleDetails) {
Map<String, Object> response = complianceService.closeIssuesByRule(ruleDetails);
if (Integer.parseInt(response.get("status").toString()) == TWO_HUNDRED) {
return new ResponseEntity<>(response, HttpStatus.OK);
} else {
return new ResponseEntity<>(response, HttpStatus.FORBIDDEN);
}
}
/**
* Adds the issue exception.issueException expects
* issueId,exceptionGrantedDate,exceptionEndDate and exceptionReason, API is
* for adding issue exception to the corresponding target type.
*
* @param issueException the issue exception
* @return ResponseEntity
*/
@ApiOperation(httpMethod = "POST", value = "Adding issue exception to the corresponding target type")
@RequestMapping(path = "/v1/issues/add-exception", method = RequestMethod.POST)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Successfully Added Issue Exception"),
@ApiResponse(code = 401, message = "You are not authorized to Add Issue Exception"),
@ApiResponse(code = 403, message = "Add Issue Exception is forbidden") })
@ResponseBody
public ResponseEntity<Object> addIssueException(
@ApiParam(value = "Provide Issue Exception Details", required = true) @RequestBody(required = true) IssueResponse issueException) {
try {
Boolean isExempted = complianceService.addIssueException(issueException);
if (isExempted) {
return ResponseUtils.buildSucessResponse("Successfully Added Issue Exception");
} else {
return ResponseUtils.buildFailureResponse(new Exception("Failed in Adding Issue Exception"));
}
} catch (ServiceException exception) {
return ResponseUtils.buildFailureResponse(exception);
}
}
/**
* Revoke issue exception.
*
* @param issueId the issue id
* @return ResponseEntity
*/
@ApiOperation(httpMethod = "POST", value = "Revoking issue exception to the corresponding target type")
@RequestMapping(path = "/v1/issues/revoke-exception", method = RequestMethod.POST)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Successfully Revoked Issue Exception"),
@ApiResponse(code = 401, message = "You are not authorized to Revoke Issue Exception"),
@ApiResponse(code = 403, message = "Revoke IssueException is forbidden") })
@ResponseBody
public ResponseEntity<Object> revokeIssueException(
@ApiParam(value = "Provide Issue Id", required = true) @RequestParam(required = true) String issueId) {
try {
Boolean isIssueExceptionRevoked = complianceService.revokeIssueException(issueId);
if (isIssueExceptionRevoked) {
return ResponseUtils.buildSucessResponse("Successfully Revoked Issue Exception");
} else {
return ResponseUtils.buildFailureResponse(new Exception("Failed in Revoking Issue Exception"));
}
} catch (ServiceException exception) {
return ResponseUtils.buildFailureResponse(exception);
}
}
/**
* Gets the non compliance policy by rule.request expects asset group and
* domain as mandatory.Api returns list of all the rules associated to that
* domain with compliance percentage/severity/ruleCategory etc fields.
*
* @param request the request
* @return ResponseEntity
*/
@RequestMapping(path = "/v1/noncompliancepolicy", method = RequestMethod.POST)
// @Cacheable(cacheNames="compliance",unless="#result.status==200")
// commenting to performance after refacoting
// @Cacheable(cacheNames="compliance",key="#request.key")
public ResponseEntity<Object> getNonCompliancePolicyByRule(@RequestBody(required = false) Request request) {
String assetGroup = request.getAg();
Map<String, String> filters = request.getFilter();
if (Strings.isNullOrEmpty(assetGroup) || MapUtils.isEmpty(filters)
|| Strings.isNullOrEmpty(filters.get(DOMAIN))) {
return ResponseUtils.buildFailureResponse(new Exception(ASSET_GROUP_DOMAIN));
}
ResponseWithOrder response = null;
try {
response = (complianceService.getRulecompliance(request));
} catch (ServiceException e) {
return complianceService.formatException(e);
}
return ResponseUtils.buildSucessResponse(response);
}
/**
* Gets the policy details by application.asssetGroup and ruleId are
* mandatory. API returns total/application/compliant/compliantPercentage of
* the ruleId for given assetGroup. SearchText is used to match any text you
* are looking for
*
* @param assetGroup name of the asset group
* @param ruleId the rule id
* @param searchText the search text
* @return ResponseEntity
*/
@RequestMapping(path = "/v1/policydetailsbyapplication", method = RequestMethod.GET)
// @Cacheable(cacheNames="compliance",unless="#result.status==200")
public ResponseEntity<Object> getPolicydetailsbyApplication(@RequestParam("ag") String assetGroup,
@RequestParam("ruleId") String ruleId,
@RequestParam(name = "searchText", required = false) String searchText) {
if (Strings.isNullOrEmpty(assetGroup) || Strings.isNullOrEmpty(ruleId)) {
return ResponseUtils.buildFailureResponse(new Exception("Assetgroup/ruleId is mandatory"));
}
ResponseData response = null;
try {
response = new ResponseData(complianceService.getRuleDetailsbyApplication(assetGroup, ruleId, searchText));
} catch (ServiceException e) {
return complianceService.formatException(e);
}
return ResponseUtils.buildSucessResponse(response);
}
/**
* Gets the policy details by environment.asssetGroup,application and ruleId
* are mandatory. API returns
* total/environment/compliant/compliantPercentage of the ruleId for given
* assetGroup and application. SearchText is used to match any text you are
* looking for
*
* @param assetGroup name of the asset group
* @param application name of the application
* @param ruleId the rule id
* @param searchText the search text
* @return ResponseEntity
*/
@RequestMapping(path = "/v1/policydetailsbyenvironment", method = RequestMethod.GET)
public ResponseEntity<Object> getpolicydetailsbyEnvironment(@RequestParam("ag") String assetGroup,
@RequestParam("application") String application, @RequestParam("ruleId") String ruleId,
@RequestParam(name = "searchText", required = false) String searchText) {
if (Strings.isNullOrEmpty(assetGroup) || Strings.isNullOrEmpty(application) || Strings.isNullOrEmpty(ruleId)) {
return ResponseUtils.buildFailureResponse(new Exception("assetgroup/application/ruleId is mandatory"));
}
ResponseData response = null;
try {
response = new ResponseData(complianceService.getRuleDetailsbyEnvironment(assetGroup, ruleId, application,
searchText));
} catch (ServiceException e) {
return complianceService.formatException(e);
}
return ResponseUtils.buildSucessResponse(response);
}
/**
* API returns details of the given ruleId.
*
* @param ruleId the rule id
* @return ResponseEntity<Object>
*/
@RequestMapping(path = "/v1/policydescription", method = RequestMethod.GET)
public ResponseEntity<Object> getPolicyDescription(@RequestParam("ruleId") String ruleId) {
if (Strings.isNullOrEmpty(ruleId)) {
return ResponseUtils.buildFailureResponse(new Exception("ruleId Mandatory"));
}
PolicyDescription response = null;
try {
response = new PolicyDescription(complianceService.getRuleDescription(ruleId));
} catch (ServiceException e) {
return complianceService.formatException(e);
}
return ResponseUtils.buildSucessResponse(response);
}
/**
* API returns the kernel version of the given instanceId if it is
* from web service.
*
* @param instanceId the instance id
* @return ResponseEntity<Object>
*/
@RequestMapping(path = "/v1/kernelcompliancebyinstanceid", method = RequestMethod.GET)
public ResponseEntity<Object> getKernelComplianceByInstanceId(@RequestParam("instanceId") String instanceId) {
if (Strings.isNullOrEmpty(instanceId)) {
return ResponseUtils.buildFailureResponse(new Exception("instanceId is mandatory"));
}
PolicyDescription output = null;
try {
output = new PolicyDescription(complianceService.getKernelComplianceByInstanceIdFromDb(instanceId));
} catch (ServiceException e) {
return complianceService.formatException(e);
}
return ResponseUtils.buildSucessResponse(output);
}
/**
* API returns true if it updates the kernel version for the given
* instanceId successfully.
*
* @param kernelVersion the kernel version
* @return ResponseEntity<Object>
*/
@ApiOperation(httpMethod = "PUT", value = "Update Kernel Version by InstanceId")
@RequestMapping(path = "/v1/update-kernel-version", method = RequestMethod.PUT)
@ResponseBody
public ResponseEntity<Object> updateKernelVersion(
@ApiParam(value = "Provide valid Rule Details ", required = true) @RequestBody(required = true) KernelVersion kernelVersion) {
Map<String, Object> response = complianceService.updateKernelVersion(kernelVersion);
return new ResponseEntity<>(response, HttpStatus.OK);
}
/**
* API returns overall compliance based on rule category and severity weightages
* for given asset group and domain.
*
* @param assetGroup - String
* @param domain - String
* @return ResponseEntity<Object> .
*/
@RequestMapping(path = "/v1/overallcompliance", method = RequestMethod.GET)
public ResponseEntity<Object> getOverallCompliance(@RequestParam("ag") String assetGroup,
@RequestParam(name = "domain") String domain) {
if (Strings.isNullOrEmpty(assetGroup) || Strings.isNullOrEmpty(domain)) {
return ResponseUtils.buildFailureResponse(new Exception(ASSET_GROUP_DOMAIN));
}
DitributionDTO distribution = null;
try {
distribution = new DitributionDTO(complianceService.getOverallComplianceByDomain(assetGroup, domain));
} catch (ServiceException e) {
return complianceService.formatException(e);
}
return ResponseUtils.buildSucessResponse(distribution);
}
/**
* API returns targetTypes for given asset group and domain based on
* project target types configurations.
*
* @param assetgroup the assetgroup
* @param domain the domain
* @return ResponseEntity<Object>
*/
@RequestMapping(path = "/v1/targetType", method = RequestMethod.GET)
public ResponseEntity<Object> getTargetType(@RequestParam("ag") String assetgroup,
@RequestParam(name = "domain", required = false) String domain) {
if (Strings.isNullOrEmpty(assetgroup)) {
return ResponseUtils.buildFailureResponse(new Exception(ASSET_MANDATORY));
}
ResourceTypeResponse response;
try {
response = new ResourceTypeResponse(complianceService.getResourceType(assetgroup, domain));
} catch (Exception e) {
return ResponseUtils.buildFailureResponse(e);
}
return ResponseUtils.buildSucessResponse(response);
}
/**
* API returns reason for violation along with other details for the
* given asset group and issueId.
*
* @param assetgroup the assetgroup
* @param issueId the issue id
* @return ResponseEntity<Object>
*/
@RequestMapping(path = "/v1/policyViolationReason", method = RequestMethod.GET)
public ResponseEntity<Object> policyViolationReason(@RequestParam("ag") String assetgroup,
@RequestParam(name = "issueId") String issueId) {
if (Strings.isNullOrEmpty(assetgroup) && Strings.isNullOrEmpty(issueId)) {
return ResponseUtils.buildFailureResponse(new Exception("AssetGroup/IssueId is Mandatory"));
}
PolicyViolationDetails response = null;
try {
response = complianceService.getPolicyViolationDetailsByIssueId(assetgroup, issueId);
} catch (ServiceException e) {
return complianceService.formatException(e);
}
return ResponseUtils.buildSucessResponse(response);
}
/**
* API returns current kernel versions.
*
* @return ResponseEntity<Object>
*/
@RequestMapping(path = "/v1/get-current-kernel-versions", method = RequestMethod.GET)
public ResponseEntity<Object> getCurrentKernelVersions() {
return ResponseUtils.buildSucessResponse(complianceService.getCurrentKernelVersions());
}
/**
* Adds the issues exception.
*
* @param issuesException the issues exception
* @return the response entity
*/
@ApiOperation(httpMethod = "POST", value = "Adding issue exception to the corresponding target type")
@RequestMapping(path = "/v2/issue/add-exception", method = RequestMethod.POST)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Successfully Added Issue Exception"),
@ApiResponse(code = 401, message = "You are not authorized to Add Issue Exception"),
@ApiResponse(code = 403, message = "Add Issue Exception is forbidden") })
@ResponseBody
public ResponseEntity<Object> addIssuesException(
@ApiParam(value = "Provide Issue Exception Details", required = true) @RequestBody(required = true) IssuesException issuesException) {
try {
if (issuesException.getExceptionGrantedDate() == null) {
return ResponseUtils.buildFailureResponse(new Exception("Exception Granted Date is mandatory"));
}
if (issuesException.getExceptionEndDate() == null) {
return ResponseUtils.buildFailureResponse(new Exception("Exception End Date is mandatory"));
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
if(sdf.parse(sdf.format(issuesException.getExceptionGrantedDate())).before(sdf.parse(sdf.format(cal.getTime())))) {
return ResponseUtils.buildFailureResponse(new Exception("Exception Granted Date cannot be earlier date than today"));
}
if(sdf.parse(sdf.format(issuesException.getExceptionEndDate())).before(sdf.parse(sdf.format(cal.getTime())))) {
return ResponseUtils.buildFailureResponse(new Exception("Exception End Date cannot be earlier date than today"));
}
if(issuesException.getIssueIds().isEmpty()) {
return ResponseUtils.buildFailureResponse(new Exception("Atleast one issue id is required"));
}
return ResponseUtils.buildSucessResponse(complianceService.addMultipleIssueException(issuesException));
} catch (ServiceException | ParseException exception) {
return ResponseUtils.buildFailureResponse(exception);
}
}
/**
* Revoke issue exception.
*
* @param issueIds the issue ids
* @return ResponseEntity
*/
@ApiOperation(httpMethod = "POST", value = "Revoking issue exception to the corresponding target type")
@RequestMapping(path = "/v2/issue/revoke-exception", method = RequestMethod.POST)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Successfully Revoked Issue Exception"),
@ApiResponse(code = 401, message = "You are not authorized to Revoke Issue Exception"),
@ApiResponse(code = 403, message = "Revoke IssueException is forbidden") })
@ResponseBody
public ResponseEntity<Object> revokeIssuesException(
@ApiParam(value = "Provide Issue Id", required = true) @RequestBody(required = true) RevokeIssuesException revokeIssuesException) {
try {
if(revokeIssuesException.getIssueIds().isEmpty()) {
return ResponseUtils.buildFailureResponse(new Exception("Atleast one issue id is required"));
}
return ResponseUtils.buildSucessResponse(complianceService.revokeMultipleIssueException(revokeIssuesException.getIssueIds()));
} catch (ServiceException exception) {
return ResponseUtils.buildFailureResponse(exception);
}
}
}
|
3e0c47f7934266658042e9727719e07c30e63c57 | 94 | java | Java | libraries-http-2/src/test/java/com/baeldung/okhttp/Consts.java | jsardan/tutorials | d7cca3ffe36a65f84a0f16107ec4888aa33fc6ae | [
"MIT"
] | 32,544 | 2015-01-02T16:59:22.000Z | 2022-03-31T21:04:05.000Z | libraries-http-2/src/test/java/com/baeldung/okhttp/Consts.java | jsardan/tutorials | d7cca3ffe36a65f84a0f16107ec4888aa33fc6ae | [
"MIT"
] | 1,577 | 2015-02-21T17:47:03.000Z | 2022-03-31T14:25:58.000Z | libraries-http-2/src/test/java/com/baeldung/okhttp/Consts.java | jsardan/tutorials | d7cca3ffe36a65f84a0f16107ec4888aa33fc6ae | [
"MIT"
] | 55,853 | 2015-01-01T07:52:09.000Z | 2022-03-31T21:08:15.000Z | 18.8 | 36 | 0.765957 | 5,211 | package com.baeldung.okhttp;
public interface Consts {
int SSL_APPLICATION_PORT = 8443;
} |
3e0c48794752e24a083afae4cde7df3492a296ba | 93 | java | Java | src/main/java/com/baislsl/decompiler/instruction/FNEG.java | baislsl/java-class-decompiler | 23de04348aea7b31746699c2724077e1fc4c37a8 | [
"MIT"
] | null | null | null | src/main/java/com/baislsl/decompiler/instruction/FNEG.java | baislsl/java-class-decompiler | 23de04348aea7b31746699c2724077e1fc4c37a8 | [
"MIT"
] | null | null | null | src/main/java/com/baislsl/decompiler/instruction/FNEG.java | baislsl/java-class-decompiler | 23de04348aea7b31746699c2724077e1fc4c37a8 | [
"MIT"
] | null | null | null | 18.6 | 45 | 0.827957 | 5,212 | package com.baislsl.decompiler.instruction;
public class FNEG extends NegateInstruction {
}
|
3e0c48bfe429fac52d2265d911bc64d4e9c00d7e | 9,039 | java | Java | SOURCECODES/tomcat_module_source_code/WEB-INF/classes/src/src_servlet/imgmarkservlet.java | jmGithub2021/iMediXcare | d6fa9ddd27134f0d216f783a193a28e35e784d0f | [
"Apache-2.0"
] | 5 | 2021-03-01T08:05:49.000Z | 2022-01-06T07:27:52.000Z | SOURCECODES/tomcat_module_source_code/WEB-INF/classes/src/src_servlet/imgmarkservlet.java | jmGithub2021/iMediXcare | d6fa9ddd27134f0d216f783a193a28e35e784d0f | [
"Apache-2.0"
] | null | null | null | SOURCECODES/tomcat_module_source_code/WEB-INF/classes/src/src_servlet/imgmarkservlet.java | jmGithub2021/iMediXcare | d6fa9ddd27134f0d216f783a193a28e35e784d0f | [
"Apache-2.0"
] | null | null | null | 29.733553 | 937 | 0.608696 | 5,213 | package imedixservlets;
import imedix.dataobj;
import imedix.cook;
import imedix.rcDataEntryFrm;
import imedix.myDate;
import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.imageio.*;
import javax.swing.*;
public class imgmarkservlet extends HttpServlet {
JFrame f = null;
FileOutputStream fout;
String para="";
public void init(ServletConfig config) throws ServletException {
super.init(config);
f = new JFrame();
f.addNotify();
}
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
//res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("Error: this servlet does not support the GET method!");
out.close();
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
StringBuffer msgBuf = new StringBuffer();
BufferedReader fromApplet = req.getReader();
String line;
String ans="Saved";
while ((line=fromApplet.readLine())!=null) {
if (msgBuf.length()>0) msgBuf.append('\n');
msgBuf.append(line);
}
fromApplet.close();
para=msgBuf.toString();
String pin[]=para.split("&");
res.setContentType("text/plain");
String pid="",type="",isl="",dt="",ccode="",uid="",lin="",circle="",rect="",fhand="",txt="";
try{
pid=pin[0].substring(pin[0].indexOf("=")+1);
type=pin[1].substring(pin[1].indexOf("=")+1);
isl=pin[2].substring(pin[2].indexOf("=")+1);
dt=pin[3].substring(pin[3].indexOf("=")+1); //dd-mm-yyyyy
ccode=pin[4].substring(pin[4].indexOf("=")+1);
uid=pin[5].substring(pin[5].indexOf("=")+1);
lin=pin[6].substring(pin[6].indexOf("=")+1).trim();
circle=pin[7].substring(pin[7].indexOf("=")+1).trim();
rect=pin[8].substring(pin[8].indexOf("=")+1).trim();
fhand=pin[9].substring(pin[9].indexOf("=")+1).trim();
txt=pin[10].substring(pin[10].indexOf("=")+1).trim();
}catch (Exception e){
System.out.println(e.toString());
ans="Error";
}
String imgdirname=req.getRealPath("//")+"/temp/"+uid+"/images/"+pid+"/";
String fdt =dt.replaceAll("/","");
String fname=pid+fdt+type+isl+".jpg";
fname=fname.toLowerCase();
String imgpath = imgdirname+fname;
//id=NRSH1811070000&type=BLD&ser=1&dt=11/12/2007&ccode=NRSH&uid=doc&line= &circle= &rect= &fhand= -65536,180,217,179,217,178,217,176,216,174,213,168,207,160,199,154,190,146,179,140,166,135,155,134,147,133,139,133,132,135,124,139,117,145,112,153,107,163,104,175,104,192,106,211,111,234,120,261,130,286,136,307,141,326,141,343,135,358,126,366,116,373,103,376,94,377,88,377,85,375,83,373,81,371,81,368,80,366,80,363,82,361,84,359,86,358,87,356,89,355,91,354,95,353,97,353,99,352,100,351,101,351,102,350,103,350,105,350,108,350,111,350,114,350,117,350,120,350,124,350,128,350,132,350,136,350,143,351,147,351,150,351,153,351,157,351,159,351,163,351,167,351,171,352,176,352,180,352,184,352,188,352,192,352,196,351,202,350,206,349,209,348,214,347,216,347,219,345,221,344,223,342,226,340,229,336,231,334,234,330,236,327,238,323,240,319,241,315,242,311,242,307,242,304,242,300,242,296,242,292,242,287,242,283,242,281,242,280,242,279,242#&txt=
/*
Image img = imgicon.getImage();
BufferedImage bi = (BufferedImage)f.createImage(img.getWidth(f),img.getHeight(f));
Graphics g = bi.createGraphics(); // Get a Graphics object
g.drawImage(img,0,0,img.getWidth(f),img.getHeight(f),null);
Graphics2D g2D = (Graphics2D) g;
Stroke stroke = new BasicStroke((float)1.5);
g2D.setStroke(stroke);
*/
ImageIcon imgicon=null;
int imgw=0;
int imgh=0;
try {
imgicon =new ImageIcon(imgpath);
imgw=imgicon.getIconWidth();
imgh=imgicon.getIconHeight();
}catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, e.toString());
}
BufferedImage bi = new BufferedImage(imgw, imgh, BufferedImage.TYPE_USHORT_555_RGB);
Graphics2D g = bi.createGraphics();
g.drawImage(imgicon.getImage(),0,0,imgw,imgh,null);
Stroke stroke = new BasicStroke((float)1.5);
g.setStroke(stroke);
/// draw Line
try{
if(lin!=""){
StringTokenizer li = new StringTokenizer(lin, "#");
while (li.hasMoreTokens())
{
String pts = li.nextToken();
// System.out.println(pts);
StringTokenizer minili = new StringTokenizer(pts, ",");
g.setColor(Color.decode(minili.nextToken()));
int x=Integer.parseInt(minili.nextToken());
int y=Integer.parseInt(minili.nextToken());
int x1=Integer.parseInt(minili.nextToken());
int y1=Integer.parseInt(minili.nextToken());
g.drawLine(x,y,x1,y1);
}
}
}catch (Exception e){
System.out.println(e.toString());
ans="Error";
}
/// draw rec
try{
if(rect!=""){
StringTokenizer li = new StringTokenizer(rect, "#");
while (li.hasMoreTokens())
{
String pts = li.nextToken();
// System.out.println(pts);
StringTokenizer minili = new StringTokenizer(pts, ",");
g.setColor(Color.decode(minili.nextToken()));
int x=Integer.parseInt(minili.nextToken());
int y=Integer.parseInt(minili.nextToken());
int w=Integer.parseInt(minili.nextToken());
int h=Integer.parseInt(minili.nextToken());
g.drawRect(x,y,w,h);
}
}
}catch (Exception e){
System.out.println(e.toString());
ans="Error";
}
/// draw circle
try{
if(circle!=""){
StringTokenizer li = new StringTokenizer(circle, "#");
while (li.hasMoreTokens())
{
String pts = li.nextToken();
// System.out.println(pts);
StringTokenizer minili = new StringTokenizer(pts, ",");
g.setColor(Color.decode(minili.nextToken()));
int x=Integer.parseInt(minili.nextToken());
int y=Integer.parseInt(minili.nextToken());
int w=Integer.parseInt(minili.nextToken());
int h=Integer.parseInt(minili.nextToken());
g.drawOval(x,y,w,h);
}
}
}catch (Exception e){
System.out.println(e.toString());
ans="Error";
}
/// draw TXT
try{
if(txt!=""){
StringTokenizer li = new StringTokenizer(txt,"#");
while (li.hasMoreTokens())
{
String pts = li.nextToken();
// System.out.println(pts);
StringTokenizer minili = new StringTokenizer(pts, ",");
g.setColor(Color.decode(minili.nextToken()));
String txtval=minili.nextToken();
int x=Integer.parseInt(minili.nextToken());
int y=Integer.parseInt(minili.nextToken());
g.drawString(txtval,x,y);
}
}
}catch (Exception e){
System.out.println(e.toString());
ans="Error";
}
/// draw freehand
try{
if(fhand!=""){
StringTokenizer li = new StringTokenizer(fhand,"#");
while (li.hasMoreTokens())
{
String pts = li.nextToken();
// System.out.println(pts);
String[] strpts = pts.split(",");
g.setColor(Color.decode(strpts[0]));
int x =Integer.parseInt(strpts[1]);
int y =Integer.parseInt(strpts[2]);
for(int i=3;i<strpts.length-1;){
int x1=Integer.parseInt(strpts[i++]);
int y1=Integer.parseInt(strpts[i++]);
g.drawLine(x,y,x1,y1);
x=x1;
y=y1;
}
}
}
}catch (Exception e){
System.out.println(e.toString());
}
try{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(baos);
ImageIO.write(bi,"jpg",bos);
byte[] _byte = baos.toByteArray();
int size = baos.size();
if (g != null) g.dispose();
cook cookx = new cook();
dataobj obj = new dataobj();
rcDataEntryFrm rcdef = new rcDataEntryFrm(req.getRealPath("/"));
String edt=myDate.getCurrentDate("dmy",false);
obj.add("pat_id",pid);
obj.add("ext","jpg");
obj.add("type",type);
obj.add("imgdesc","Ref Images");
obj.add("ref_code",ccode);
obj.add("lab_name",cookx.getCookieValue("centername", req.getCookies ()));
obj.add("doc_name",cookx.getCookieValue("username", req.getCookies ()));
obj.add("testdate",edt);
obj.add("entrydate",edt);
obj.add("img_serno",isl);
obj.add("size",Integer.toString(size));
obj.add("con_type","image/pjpeg");
ans=rcdef.SaveMarkImg(obj,_byte);
}catch (Exception e){
System.out.println(e.toString());
ans="Error";
}
PrintWriter printwriter = res.getWriter();
printwriter.println(ans);
printwriter.close();
}
public void destroy() {
if (f != null) f.removeNotify();
}
}
|
3e0c49a4147f80b64eb50ee6d625375400ccb4f6 | 26,985 | java | Java | Java/Loon-Lite(PureJava)/Loon-Lite-Core/src/loon/geom/Affine2f.java | cping/LGame | 6ee0daf43841cbafc9638f73e35cbb1c30bf69ad | [
"Apache-2.0"
] | 428 | 2015-01-02T17:25:20.000Z | 2022-03-26T20:38:48.000Z | Java/Loon-Lite(PureJava)/Loon-Lite-Core/src/loon/geom/Affine2f.java | lhn500382/LGame | a9b6c0044369f1f5e1dfadbb6e858f8a012cdf01 | [
"Apache-2.0"
] | 26 | 2015-01-19T15:05:48.000Z | 2021-06-13T14:22:29.000Z | Java/Loon-Lite(PureJava)/Loon-Lite-Core/src/loon/geom/Affine2f.java | lhn500382/LGame | a9b6c0044369f1f5e1dfadbb6e858f8a012cdf01 | [
"Apache-2.0"
] | 153 | 2015-01-07T08:40:09.000Z | 2022-02-28T01:47:07.000Z | 24.858195 | 114 | 0.619721 | 5,214 | /**
* Copyright 2008 - 2015 The Loon Game Engine Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
* @project loon
* @author cping
* @nnheo@example.com
* @version 0.5
*/
package loon.geom;
import loon.LSysException;
import loon.LSystem;
import loon.LTrans;
import loon.utils.MathUtils;
import loon.utils.NumberUtils;
import loon.utils.StringKeyValue;
/**
* 以对象存储,而非数组的方式实现一个3x2(标准矩阵应为3x3)的2D仿射矩阵类,
* 也就是保留了线的“直线性”和“平行性”,但缺少了长宽高的3D矩阵延展能力。 所以,此类仅适合2D应用中使用.
*
* 对应的3x3矩阵关系如下所示:
*
* <pre>
* {@code
* [ m00, m10, tx ]
* [ m01, m11, ty ]
* [ 0, 0, 1 ]
* }
* </pre>
*/
public class Affine2f implements LTrans, XY {
public final static Affine2f multiply(Affine2f a, Affine2f b, Affine2f into) {
return multiply(a.m00, a.m01, a.m10, a.m11, a.tx, a.ty, b.m00, b.m01, b.m10, b.m11, b.tx, b.ty, into);
}
public final static Affine2f multiply(Affine2f a, float m00, float m01, float m10, float m11, float tx, float ty,
Affine2f into) {
return multiply(a.m00, a.m01, a.m10, a.m11, a.tx, a.ty, m00, m01, m10, m11, tx, ty, into);
}
public final static Affine2f multiply(float m00, float m01, float m10, float m11, float tx, float ty, Affine2f b,
Affine2f into) {
return multiply(m00, m01, m10, m11, tx, ty, b.m00, b.m01, b.m10, b.m11, b.tx, b.ty, into);
}
public final static Affine2f multiply(float am00, float am01, float am10, float am11, float atx, float aty,
float bm00, float bm01, float bm10, float bm11, float btx, float bty, Affine2f into) {
into.setTransform(am00 * bm00 + am10 * bm01, am01 * bm00 + am11 * bm01, am00 * bm10 + am10 * bm11,
am01 * bm10 + am11 * bm11, am00 * btx + am10 * bty + atx, am01 * btx + am11 * bty + aty);
return into;
}
private static Matrix4 projectionMatrix = null;
protected Affine2f(Affine2f other) {
this(other.scaleX(), other.scaleY(), other.rotation(), other.tx(), other.ty());
}
public static Affine2f transform(Affine2f tx, float x, float y, int transform) {
switch (transform) {
case TRANS_ROT90: {
tx.translate(x, y);
tx.rotate(ANGLE_90);
tx.translate(-x, -y);
break;
}
case TRANS_ROT180: {
tx.translate(x, y);
tx.rotate(MathUtils.PI);
tx.translate(-x, -y);
break;
}
case TRANS_ROT270: {
tx.translate(x, y);
tx.rotate(ANGLE_270);
tx.translate(-x, -y);
break;
}
case TRANS_MIRROR: {
tx.translate(x, y);
tx.scale(-1, 1);
tx.translate(-x, -y);
break;
}
case TRANS_MIRROR_ROT90: {
tx.translate(x, y);
tx.rotate(ANGLE_90);
tx.translate(-x, -y);
tx.scale(-1, 1);
break;
}
case TRANS_MIRROR_ROT180: {
tx.translate(x, y);
tx.scale(-1, 1);
tx.translate(-x, -y);
tx.translate(x, y);
tx.rotate(MathUtils.PI);
tx.translate(-x, -y);
break;
}
case TRANS_MIRROR_ROT270: {
tx.translate(x, y);
tx.rotate(ANGLE_270);
tx.translate(-x, -y);
tx.scale(-1, 1);
break;
}
}
return tx;
}
public static Affine2f transform(Affine2f tx, float x, float y, int transform, float width, float height) {
switch (transform) {
case TRANS_ROT90: {
float w = x + width / 2;
float h = y + height / 2;
tx.translate(w, h);
tx.rotate(ANGLE_90);
tx.translate(-w, -h);
break;
}
case TRANS_ROT180: {
float w = x + width / 2;
float h = y + height / 2;
tx.translate(w, h);
tx.rotate(MathUtils.PI);
tx.translate(-w, -h);
break;
}
case TRANS_ROT270: {
float w = x + width / 2;
float h = y + height / 2;
tx.translate(w, h);
tx.rotate(ANGLE_270);
tx.translate(-w, -h);
break;
}
case TRANS_MIRROR: {
float w = x + width / 2;
float h = y + height / 2;
tx.translate(w, h);
tx.scale(-1, 1);
tx.translate(-w, -h);
break;
}
case TRANS_MIRROR_ROT90: {
float w = x + width / 2;
float h = y + height / 2;
tx.translate(w, h);
tx.rotate(ANGLE_90);
tx.translate(-w, -h);
tx.scale(-1, 1);
break;
}
case TRANS_MIRROR_ROT180: {
float w = x + width / 2;
float h = y + height / 2;
tx.translate(w, h);
tx.scale(-1, 1);
tx.translate(-w, -h);
w = x + width / 2;
h = y + height / 2;
tx.translate(w, h);
tx.rotate(MathUtils.PI);
tx.translate(-w, -h);
break;
}
case TRANS_MIRROR_ROT270: {
float w = x + width / 2;
float h = y + height / 2;
tx.translate(w, h);
tx.rotate(ANGLE_270);
tx.translate(-w, -h);
tx.scale(-1, 1);
break;
}
}
return tx;
}
public static Affine2f transformRegion(Affine2f tx, float x, float y, int transform, float width, float height) {
switch (transform) {
case TRANS_ROT90: {
float w = height;
float h = y;
tx.translate(w, h);
tx.rotate(ANGLE_90);
tx.translate(-w, -h);
break;
}
case TRANS_ROT180: {
float w = x + width;
float h = y + height;
tx.translate(w, h);
tx.rotate(MathUtils.PI);
tx.translate(-w, -h);
break;
}
case TRANS_ROT270: {
float w = x;
float h = y + width;
tx.translate(w, h);
tx.rotate(ANGLE_270);
tx.translate(-w, -h);
break;
}
case TRANS_MIRROR: {
float w = x + width;
float h = y;
tx.translate(w, h);
tx.scale(-1, 1);
tx.translate(-w, -h);
break;
}
case TRANS_MIRROR_ROT90: {
float w = x + height;
float h = y;
tx.translate(w, h);
tx.rotate(ANGLE_90);
tx.translate(-w, -h);
tx.scale(-1, 1);
break;
}
case TRANS_MIRROR_ROT180: {
float w = x + width;
float h = y;
tx.translate(w, h);
tx.scale(-1, 1);
tx.translate(-w, -h);
w = x + width;
h = y + height;
tx.translate(w, h);
tx.rotate(MathUtils.PI);
tx.translate(-w, -h);
break;
}
case TRANS_MIRROR_ROT270: {
tx.rotate(ANGLE_270);
tx.scale(-1, 1);
break;
}
}
return tx;
}
public Affine2f combined(Matrix4 mat) {
float[] m = mat.val;
float m00 = m[Matrix4.M00] * this.m00 + m[Matrix4.M01] * this.m10;
float m01 = m[Matrix4.M00] * this.m11 + m[Matrix4.M11] * this.m10;
float tx = m[Matrix4.M00] * this.m01 + m[Matrix4.M01] * this.m11;
float m10 = m[Matrix4.M00] * this.tx + m[Matrix4.M01] * this.ty + m[Matrix4.M02];
float m11 = m[Matrix4.M10] * this.tx + m[Matrix4.M11] * this.ty + m[Matrix4.M12];
m[Matrix4.M00] = m00;
m[Matrix4.M01] = m01;
m[Matrix4.M03] = tx;
m[Matrix4.M10] = m10;
m[Matrix4.M11] = m11;
m[Matrix4.M13] = ty;
return this;
}
public Affine2f combined4x4(float[] vals) {
float[] m = vals;
float m00 = m[Matrix4.M00] * this.m00 + m[Matrix4.M01] * this.m10;
float m01 = m[Matrix4.M00] * this.m11 + m[Matrix4.M11] * this.m10;
float tx = m[Matrix4.M00] * this.m01 + m[Matrix4.M01] * this.m11;
float m10 = m[Matrix4.M00] * this.tx + m[Matrix4.M01] * this.ty + m[Matrix4.M02];
float m11 = m[Matrix4.M10] * this.tx + m[Matrix4.M11] * this.ty + m[Matrix4.M12];
m[Matrix4.M00] = m00;
m[Matrix4.M01] = m01;
m[Matrix4.M03] = tx;
m[Matrix4.M10] = m10;
m[Matrix4.M11] = m11;
m[Matrix4.M13] = ty;
return this;
}
public static final int GENERALITY = 4;
/* x scale */
public float m00 = 1.0f;
/* y skew */
public float m01 = 0.0f;
/* x skew */
public float m10 = 0.0f;
/* y scale */
public float m11 = 1.0f;
/* x translation */
public float tx = 0.0f;
/* y translation */
public float ty = 0.0f;
public Affine2f() {
this(1, 0, 0, 1, 0, 0);
}
public Affine2f idt() {
this.m00 = 1;
this.m01 = 0;
this.tx = 0;
this.m10 = 0;
this.m11 = 1;
this.ty = 0;
return this;
}
public final Affine2f reset() {
return this.idt();
}
public boolean equals(Object o) {
if (null == o) {
return false;
}
if (o == this) {
return true;
}
if (o instanceof Affine2f) {
Affine2f a2f = (Affine2f) o;
if (a2f.m00 == m00 && a2f.m01 == m01 && a2f.tx == tx && a2f.ty == ty && a2f.m10 == m10 && a2f.m11 == m11) {
return true;
}
}
return false;
}
public boolean equals(Affine2f a2f) {
if (a2f == null) {
return false;
}
return a2f.m00 == m00 && a2f.m01 == m01 && a2f.tx == tx && a2f.ty == ty && a2f.m10 == m10 && a2f.m11 == m11;
}
public Affine2f set(Matrix3 matrix) {
float[] other = matrix.val;
m00 = other[Matrix3.M00];
m01 = other[Matrix3.M01];
tx = other[Matrix3.M02];
m10 = other[Matrix3.M10];
m11 = other[Matrix3.M11];
ty = other[Matrix3.M12];
return this;
}
public Affine2f setValue3x3(float[] vals) {
m00 = vals[Matrix3.M00];
m01 = vals[Matrix3.M01];
tx = vals[Matrix3.M02];
m10 = vals[Matrix3.M10];
m11 = vals[Matrix3.M11];
ty = vals[Matrix3.M12];
return this;
}
public Affine2f set(Matrix4 matrix) {
float[] other = matrix.val;
m00 = other[Matrix4.M00];
m01 = other[Matrix4.M01];
tx = other[Matrix4.M03];
m10 = other[Matrix4.M10];
m11 = other[Matrix4.M11];
ty = other[Matrix4.M13];
return this;
}
public Affine2f setValue4x4(float[] vals) {
m00 = vals[Matrix4.M00];
m01 = vals[Matrix4.M01];
tx = vals[Matrix4.M03];
m10 = vals[Matrix4.M10];
m11 = vals[Matrix4.M11];
ty = vals[Matrix4.M13];
return this;
}
public final void setThis(final Affine2f aff) {
this.m00 = aff.m00;
this.m11 = aff.m11;
this.m01 = aff.m01;
this.m10 = aff.m10;
this.tx = aff.tx;
this.ty = aff.ty;
}
public Affine2f(float scale, float angle, float tx, float ty) {
this(scale, scale, angle, tx, ty);
}
public Affine2f(float scaleX, float scaleY, float angle, float tx, float ty) {
float sina = MathUtils.sin(angle), cosa = MathUtils.cos(angle);
this.m00 = cosa * scaleX;
this.m01 = sina * scaleY;
this.m10 = -sina * scaleX;
this.m11 = cosa * scaleY;
this.tx = tx;
this.ty = ty;
}
public Affine2f(float m00, float m01, float m10, float m11, float tx, float ty) {
this.m00 = m00;
this.m01 = m01;
this.m10 = m10;
this.m11 = m11;
this.tx = tx;
this.ty = ty;
}
public Affine2f set(Affine2f other) {
return setTransform(other.m00, other.m01, other.m10, other.m11, other.tx, other.ty);
}
public float uniformScale() {
float cp = m00 * m11 - m01 * m10;
return (cp < 0f) ? -MathUtils.sqrt(-cp) : MathUtils.sqrt(cp);
}
public float scaleX() {
return MathUtils.sqrt(m00 * m00 + m01 * m01);
}
public float scaleY() {
return MathUtils.sqrt(m10 * m10 + m11 * m11);
}
public float skewX() {
if (this.m11 < 0) {
return MathUtils.atan2(this.m11, this.m01) + (MathUtils.PI / 2);
} else {
return MathUtils.atan2(this.m11, this.m01) - (MathUtils.PI / 2);
}
}
public float skewY() {
if (this.m00 < 0) {
return MathUtils.atan2(this.m10, this.m00) - MathUtils.PI;
} else {
return MathUtils.atan2(this.m10, this.m00);
}
}
public float rotation() {
float n00 = m00, n10 = m10;
float n01 = m01, n11 = m11;
for (int ii = 0; ii < 10; ii++) {
float o00 = n00, o10 = n10;
float o01 = n01, o11 = n11;
float det = o00 * o11 - o10 * o01;
if (MathUtils.abs(det) == 0f) {
throw new LSysException("Affine2f exception " + this.toString());
}
float hrdet = 0.5f / det;
n00 = +o11 * hrdet + o00 * 0.5f;
n10 = -o01 * hrdet + o10 * 0.5f;
n01 = -o10 * hrdet + o01 * 0.5f;
n11 = +o00 * hrdet + o11 * 0.5f;
float d00 = n00 - o00, d10 = n10 - o10;
float d01 = n01 - o01, d11 = n11 - o11;
if (d00 * d00 + d10 * d10 + d01 * d01 + d11 * d11 < MathUtils.EPSILON) {
break;
}
}
return MathUtils.atan2(n01, n00);
}
public float getAngle() {
return MathUtils.toRadians(rotation());
}
public float tx() {
return this.tx;
}
public float ty() {
return this.ty;
}
public void get(float[] matrix) {
matrix[0] = m00;
matrix[1] = m01;
matrix[2] = m10;
matrix[3] = m11;
matrix[4] = tx;
matrix[5] = ty;
}
public Affine2f setUniformScale(float scale) {
return (Affine2f) setScale(scale, scale);
}
public Affine2f setScaleX(float scaleX) {
// 计算新的X轴缩放
float mult = scaleX / scaleX();
m00 *= mult;
m01 *= mult;
return this;
}
public Affine2f setScaleY(float scaleY) {
// 计算新的Y轴缩放
float mult = scaleY / scaleY();
m10 *= mult;
m11 *= mult;
return this;
}
public Affine2f setRotation(float angle) {
// 提取比例,然后重新应用旋转和缩放在一起
float sx = scaleX(), sy = scaleY();
float sina = MathUtils.sin(angle), cosa = MathUtils.cos(angle);
m00 = cosa * sx;
m01 = sina * sx;
m10 = -sina * sy;
m11 = cosa * sy;
return this;
}
public Affine2f rotate(float angle) {
float sina = MathUtils.sin(angle), cosa = MathUtils.cos(angle);
return multiply(this, cosa, sina, -sina, cosa, 0, 0, this);
}
public Affine2f rotate(float angle, float x, float y) {
float sina = MathUtils.sin(angle), cosa = MathUtils.cos(angle);
return multiply(this, cosa, sina, -sina, cosa, x, y, this);
}
public final Affine2f preRotate(final float angle) {
final float angleRad = MathUtils.DEG_TO_RAD * angle;
final float sin = MathUtils.sin(angleRad);
final float cos = MathUtils.cos(angleRad);
final float m00 = this.m00;
final float m01 = this.m01;
final float m10 = this.m10;
final float m11 = this.m11;
this.m00 = cos * m00 + sin * m10;
this.m01 = cos * m01 + sin * m11;
this.m10 = cos * m10 - sin * m00;
this.m11 = cos * m11 - sin * m01;
return this;
}
public final Affine2f postRotate(final float angle) {
final float angleRad = MathUtils.DEG_TO_RAD * angle;
final float sin = MathUtils.sin(angleRad);
final float cos = MathUtils.cos(angleRad);
final float m00 = this.m00;
final float m01 = this.m01;
final float m10 = this.m10;
final float m11 = this.m11;
final float tx = this.tx;
final float ty = this.ty;
this.m00 = m00 * cos - m01 * sin;
this.m01 = m00 * sin + m01 * cos;
this.m10 = m10 * cos - m11 * sin;
this.m11 = m10 * sin + m11 * cos;
this.tx = tx * cos - ty * sin;
this.ty = tx * sin + ty * cos;
return this;
}
public final Affine2f setToRotate(final float angle) {
final float angleRad = MathUtils.DEG_TO_RAD * angle;
final float sin = MathUtils.sin(angleRad);
final float cos = MathUtils.cos(angleRad);
this.m00 = cos;
this.m01 = sin;
this.m10 = -sin;
this.m11 = cos;
this.tx = 0.0f;
this.ty = 0.0f;
return this;
}
public Affine2f setTranslation(float tx, float ty) {
this.tx = tx;
this.ty = ty;
return this;
}
public Affine2f setTx(float tx) {
this.tx = tx;
return this;
}
public Affine2f setTy(float ty) {
this.ty = ty;
return this;
}
public Affine2f setTo(float m00, float m01, float m10, float m11, float tx, float ty) {
return setTransform(m00, m01, m10, m11, tx, ty);
}
public Affine2f setTransform(float m00, float m01, float m10, float m11, float tx, float ty) {
this.m00 = m00;
this.m01 = m01;
this.m10 = m10;
this.m11 = m11;
this.tx = tx;
this.ty = ty;
return this;
}
public Affine2f uniformScale(float scale) {
return scale(scale, scale);
}
public Affine2f scale(float scaleX, float scaleY) {
m00 *= scaleX;
m01 *= scaleX;
m10 *= scaleY;
m11 *= scaleY;
return this;
}
public final Affine2f preScale(final float sx, final float sy) {
return scale(sx, sy);
}
public final Affine2f postScale(final float sx, final float sy) {
this.m00 = this.m00 * sx;
this.m01 = this.m01 * sy;
this.m10 = this.m10 * sx;
this.m11 = this.m11 * sy;
this.tx = this.tx * sx;
this.ty = this.ty * sy;
return this;
}
public final Affine2f setToScale(final float sx, final float sy) {
this.m00 = sx;
this.m01 = 0.0f;
this.m10 = 0.0f;
this.m11 = sy;
this.tx = 0.0f;
this.ty = 0.0f;
return this;
}
public Affine2f scaleX(float scaleX) {
return multiply(this, scaleX, 0, 0, 1, 0, 0, this);
}
public Affine2f scaleY(float scaleY) {
return multiply(this, 1, 0, 0, scaleY, 0, 0, this);
}
public Affine2f translate(float tx, float ty) {
this.tx += m00 * tx + m10 * ty;
this.ty += m11 * ty + m01 * tx;
return this;
}
public final Affine2f preTranslate(final float tx, final float ty) {
return translate(tx, ty);
}
public final Affine2f postTranslate(final float tx, final float ty) {
this.tx += tx;
this.ty += ty;
return this;
}
public final Affine2f setToTranslate(final float tx, final float ty) {
this.m00 = 1.0f;
this.m01 = 0.0f;
this.m10 = 0.0f;
this.m11 = 1.0f;
this.tx = tx;
this.ty = ty;
return this;
}
public Affine2f translateX(float tx) {
return multiply(this, 1, 0, 0, 1, tx, 0, this);
}
public Affine2f translateY(float ty) {
return multiply(this, 1, 0, 0, 1, 0, ty, this);
}
public Affine2f shear(float sx, float sy) {
return multiply(this, 1, sy, sx, 1, 0, 0, this);
}
public Affine2f shearX(float sx) {
return multiply(this, 1, 0, sx, 1, 0, 0, this);
}
public Affine2f shearY(float sy) {
return multiply(this, 1, sy, 0, 1, 0, 0, this);
}
public final Affine2f preShear(final float sx, final float sy) {
final float tanX = MathUtils.tan(-MathUtils.DEG_TO_RAD * sx);
final float tanY = MathUtils.tan(-MathUtils.DEG_TO_RAD * sy);
final float m00 = this.m00;
final float m01 = this.m01;
final float m10 = this.m10;
final float m11 = this.m11;
final float tx = this.tx;
final float ty = this.ty;
this.m00 = m00 + tanY * m10;
this.m01 = m01 + tanY * m11;
this.m10 = tanX * m00 + m10;
this.m11 = tanX * m01 + m11;
this.tx = tx;
this.ty = ty;
return this;
}
public final void postShear(final float sx, final float sy) {
final float tanX = MathUtils.tan(-MathUtils.DEG_TO_RAD * sx);
final float tanY = MathUtils.tan(-MathUtils.DEG_TO_RAD * sy);
final float m00 = this.m00;
final float m01 = this.m01;
final float m10 = this.m10;
final float m11 = this.m11;
final float tx = this.tx;
final float ty = this.ty;
this.m00 = m00 + m01 * tanX;
this.m01 = m00 * tanY + m01;
this.m10 = m10 + m11 * tanX;
this.m11 = m10 * tanY + m11;
this.tx = tx + ty * tanX;
this.ty = tx * tanY + ty;
}
public final Affine2f setToShear(final float sx, final float sy) {
this.m00 = 1.0f;
this.m01 = MathUtils.tan(-MathUtils.DEG_TO_RAD * sy);
this.m10 = MathUtils.tan(-MathUtils.DEG_TO_RAD * sx);
this.m11 = 1.0f;
this.tx = 0.0f;
this.ty = 0.0f;
return this;
}
public Affine2f invert() {
// 计算行列式,并临时存储数值
float det = m00 * m11 - m10 * m01;
if (MathUtils.abs(det) == 0f) {
// 行列式为零时,矩阵将不可逆,无法还原所以报错
throw new LSysException(this.toString());
}
float rdet = 1f / det;
return new Affine2f(+m11 * rdet, -m10 * rdet, -m01 * rdet, +m00 * rdet, (m10 * ty - m11 * tx) * rdet,
(m01 * tx - m00 * ty) * rdet);
}
public Affine2f concat(Affine2f other) {
float a = this.m00 * other.m00;
float b = 0f;
float c = 0f;
float d = this.m11 * other.m11;
float tx = this.tx * other.m00 + other.tx;
float ty = this.ty * other.m11 + other.ty;
if (this.m10 != 0f || this.m01 != 0f || other.m10 != 0f || other.m01 != 0f) {
a += this.m10 * other.m01;
d += this.m01 * other.m10;
b += this.m00 * other.m10 + this.m10 * other.m11;
c += this.m01 * other.m00 + this.m11 * other.m01;
tx += this.ty * other.m01;
ty += this.tx * other.m10;
}
this.m00 = a;
this.m01 = b;
this.m10 = c;
this.m11 = d;
this.tx = tx;
this.ty = ty;
return this;
}
public Affine2f concatenate(Affine2f other) {
if (generality() < other.generality()) {
return other.preConcatenate(this);
}
if (other instanceof Affine2f) {
return multiply(this, (Affine2f) other, new Affine2f());
} else {
Affine2f oaff = new Affine2f(other);
return multiply(this, oaff, oaff);
}
}
public Affine2f preConcatenate(Affine2f other) {
if (generality() < other.generality()) {
return other.concatenate(this);
}
if (other instanceof Affine2f) {
return multiply((Affine2f) other, this, new Affine2f());
} else {
Affine2f oaff = new Affine2f(other);
return multiply(oaff, this, oaff);
}
}
public final Affine2f postConcatenate(final Affine2f t) {
return postConcatenate(t.m00, t.m01, t.m10, t.m11, t.tx, t.ty);
}
public Affine2f postConcatenate(final float ma, final float mb, final float mc, final float md, final float mx,
final float my) {
final float m00 = this.m00;
final float m01 = this.m01;
final float m10 = this.m10;
final float m11 = this.m11;
final float tx = this.tx;
final float ty = this.ty;
this.m00 = m00 * ma + m01 * mc;
this.m01 = m00 * mb + m01 * md;
this.m10 = m10 * ma + m11 * mc;
this.m11 = m10 * mb + m11 * md;
this.tx = tx * ma + ty * mc + mx;
this.ty = tx * mb + ty * md + my;
return this;
}
/**
* 让矩阵前置一组新矩阵数据
*
* @param a
* @param b
* @param c
* @param d
* @param tx
* @param ty
* @return
*/
public Affine2f prepend(float a, float b, float c, float d, float tx, float ty) {
float tx1 = this.tx;
if (this.m00 != 1 || b != 0 || c != 0 || d != 1) {
float a1 = this.m00;
float c1 = this.m01;
this.m00 = a1 * a + this.m10 * c;
this.m10 = a1 * b + this.m10 * d;
this.m01 = c1 * a + this.m11 * c;
this.m11 = c1 * b + this.m11 * d;
}
this.tx = tx1 * a + this.ty * c + tx;
this.ty = tx1 * b + this.ty * d + ty;
return this;
}
/**
* 让矩阵后置一组新矩阵数据
*
* @param other
* @return
*/
public Affine2f prepend(Affine2f other) {
return prepend(other.m00, other.m10, other.m01, other.m11, other.tx, other.ty);
}
/**
* 让矩阵后置一组新矩阵数据
*
* @param a
* @param b
* @param c
* @param d
* @param tx
* @param ty
* @return
*/
public Affine2f append(float a, float b, float c, float d, float tx, float ty) {
float a1 = this.m00;
float b1 = this.m10;
float c1 = this.m01;
float d1 = this.m11;
if (a != 1 || b != 0 || c != 0 || d != 1) {
this.m00 = a * a1 + b * c1;
this.m10 = a * b1 + b * d1;
this.m01 = c * a1 + d * c1;
this.m11 = c * b1 + d * d1;
}
this.tx = tx * a1 + ty * c1 + this.tx;
this.ty = tx * b1 + ty * d1 + this.ty;
return this;
}
/**
* 让矩阵后置一组新矩阵数据
*
* @param other
* @return
*/
public Affine2f append(Affine2f other) {
return append(other.m00, other.m10, other.m01, other.m11, other.tx, other.ty);
}
public Affine2f lerp(Affine2f other, float t) {
if (generality() < other.generality()) {
return other.lerp(this, -t);
}
Affine2f ot = (other instanceof Affine2f) ? (Affine2f) other : new Affine2f(other);
return new Affine2f(m00 + t * (ot.m00 - m00), m01 + t * (ot.m01 - m01), m10 + t * (ot.m10 - m10),
m11 + t * (ot.m11 - m11), tx + t * (ot.tx - tx), ty + t * (ot.ty - ty));
}
public void transform(Vector2f[] src, int srcOff, Vector2f[] dst, int dstOff, int count) {
for (int ii = 0; ii < count; ii++) {
transform(src[srcOff++], dst[dstOff++]);
}
}
public void transform(float[] src, int srcOff, float[] dst, int dstOff, int count) {
for (int ii = 0; ii < count; ii++) {
float x = src[srcOff++], y = src[srcOff++];
dst[dstOff++] = m00 * x + m10 * y + tx;
dst[dstOff++] = m01 * x + m11 * y + ty;
}
}
public void transform(final float[] vertices) {
int count = vertices.length >> 1;
int i = 0;
int j = 0;
while (--count >= 0) {
final float x = vertices[i++];
final float y = vertices[i++];
vertices[j++] = x * this.m00 + y * this.m10 + this.tx;
vertices[j++] = x * this.m01 + y * this.m11 + this.ty;
}
}
public PointI transformPoint(int pointX, int pointY, PointI resultPoint) {
int x = (int) (this.m00 * pointX + this.m01 * pointY + this.tx);
int y = (int) (this.m10 * pointX + this.m11 * pointY + this.ty);
if (resultPoint != null) {
resultPoint.set(x, y);
return resultPoint;
}
return new PointI(x, y);
}
public PointF transformPoint(float pointX, float pointY, PointF resultPoint) {
float x = this.m00 * pointX + this.m01 * pointY + this.tx;
float y = this.m10 * pointX + this.m11 * pointY + this.ty;
if (resultPoint != null) {
resultPoint.set(x, y);
return resultPoint;
}
return new PointF(x, y);
}
public Vector2f transformPoint(float pointX, float pointY, Vector2f resultPoint) {
float x = this.m00 * pointX + this.m01 * pointY + this.tx;
float y = this.m10 * pointX + this.m11 * pointY + this.ty;
if (resultPoint != null) {
resultPoint.set(x, y);
return resultPoint;
}
return new Vector2f(x, y);
}
public Vector2f transformPoint(Vector2f v, Vector2f into) {
float x = v.x(), y = v.y();
return into.set(m00 * x + m10 * y + tx, m01 * x + m11 * y + ty);
}
public Vector2f transform(Vector2f v, Vector2f into) {
float x = v.x(), y = v.y();
return into.set(m00 * x + m10 * y, m01 * x + m11 * y);
}
public Vector2f inverseTransform(Vector2f v, Vector2f into) {
float x = v.x(), y = v.y();
float det = m00 * m11 - m01 * m10;
if (MathUtils.abs(det) == 0f) {
// 行列式为零时,矩阵将不可逆,无法还原所以报错
throw new LSysException("Affine2f exception " + this.toString());
}
float rdet = 1 / det;
return into.set((x * m11 - y * m10) * rdet, (y * m00 - x * m01) * rdet);
}
public Matrix4 toViewMatrix4() {
Dimension dim = LSystem.viewSize;
if (projectionMatrix == null) {
projectionMatrix = new Matrix4();
}
projectionMatrix.setToOrtho2D(0, 0, dim.width * LSystem.getScaleWidth(), dim.height * LSystem.getScaleHeight());
projectionMatrix.thisCombine(this);
return projectionMatrix;
}
public Affine2f cpy() {
return new Affine2f(m00, m01, m10, m11, tx, ty);
}
public int generality() {
return GENERALITY;
}
public Object tag;
public Vector2f scale() {
return new Vector2f(scaleX(), scaleY());
}
public Vector2f translation() {
return new Vector2f(tx(), ty());
}
public Affine2f setScale(float scaleX, float scaleY) {
setScaleX(scaleX);
setScaleY(scaleY);
return this;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 17;
result = prime * result + NumberUtils.floatToIntBits(m00);
result = prime * result + NumberUtils.floatToIntBits(m11);
result = prime * result + NumberUtils.floatToIntBits(m01);
result = prime * result + NumberUtils.floatToIntBits(m10);
result = prime * result + NumberUtils.floatToIntBits(tx);
result = prime * result + NumberUtils.floatToIntBits(ty);
return result;
}
@Override
public float getX() {
return tx();
}
@Override
public float getY() {
return ty();
}
/** 显示结果上补足了不存在的长高宽坐标,充当完整3x3矩阵…… **/
@Override
public String toString() {
StringKeyValue builder = new StringKeyValue("Affine");
builder.newLine().pushBracket().addValue(MathUtils.toString((m00))).comma().addValue(MathUtils.toString(m10))
.comma().addValue(MathUtils.toString(tx)).popBracket().newLine().pushBracket()
.addValue(MathUtils.toString(m01)).comma().addValue(MathUtils.toString(m11)).comma()
.addValue(MathUtils.toString(ty)).popBracket().newLine().addValue("[0.0,0.0,1.0]").newLine();
return builder.toString();
}
}
|
3e0c4a32c969ce71c6c95c42b5525c9be7fe5346 | 959 | java | Java | dragome-js-jre/src/main/java/java/lang/RuntimeException.java | nosix/dragome-sdk | 60b577738fab90cc42b1357a9e8f01b9b228929c | [
"Apache-2.0"
] | 73 | 2015-02-05T15:33:53.000Z | 2022-01-26T18:43:47.000Z | dragome-js-jre/src/main/java/java/lang/RuntimeException.java | nosix/dragome-sdk | 60b577738fab90cc42b1357a9e8f01b9b228929c | [
"Apache-2.0"
] | 130 | 2015-01-31T18:14:07.000Z | 2021-06-14T00:57:47.000Z | dragome-js-jre/src/main/java/java/lang/RuntimeException.java | nosix/dragome-sdk | 60b577738fab90cc42b1357a9e8f01b9b228929c | [
"Apache-2.0"
] | 25 | 2015-02-13T17:59:45.000Z | 2021-01-04T18:44:50.000Z | 23.975 | 75 | 0.735141 | 5,215 | /*
* Copyright (c) 2011-2014 Fernando Petrola
*
* 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 java.lang;
public class RuntimeException extends Exception
{
public RuntimeException()
{
super();
}
public RuntimeException(String message)
{
super(message);
}
public RuntimeException(Throwable cause)
{
super(cause);
}
public RuntimeException(String aMessage, Throwable aThrowable)
{
super(aMessage, aThrowable);
}
}
|
3e0c4b40a29d9cd3885cd4598437edec6e4bf359 | 1,833 | java | Java | src/com/apkscanner/gui/action/SaveResFileAction.java | sunggyu-kam/apk-scanner | 8df2816e1c483f7fd498616870c6f5bd416362fc | [
"Apache-2.0"
] | 9 | 2019-01-02T08:15:53.000Z | 2022-03-14T15:37:57.000Z | src/com/apkscanner/gui/action/SaveResFileAction.java | sunggyu-kam/apk-scanner | 8df2816e1c483f7fd498616870c6f5bd416362fc | [
"Apache-2.0"
] | 1 | 2019-04-26T18:02:16.000Z | 2019-05-07T18:45:47.000Z | src/com/apkscanner/gui/action/SaveResFileAction.java | sunggyu-kam/apk-scanner | 8df2816e1c483f7fd498616870c6f5bd416362fc | [
"Apache-2.0"
] | 4 | 2019-01-11T03:17:09.000Z | 2022-01-09T16:30:11.000Z | 33.327273 | 139 | 0.770322 | 5,216 | package com.apkscanner.gui.action;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.io.File;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import com.apkscanner.gui.tabpanels.DefaultNodeData;
import com.apkscanner.gui.tabpanels.TreeNodeData;
import com.apkscanner.resource.RProp;
import com.apkspectrum.swing.ApkFileChooser;
import com.apkspectrum.util.FileUtil;
@SuppressWarnings("serial")
public class SaveResFileAction extends AbstractApkScannerAction
{
public static final String ACTION_COMMAND = "ACT_CMD_SAVE_RESOURCE_FILE";
public SaveResFileAction(ActionEventHandler h) { super(h); }
@Override
public void actionPerformed(ActionEvent e) {
final JComponent comp = (JComponent) e.getSource();
final DefaultNodeData resObj = (DefaultNodeData) comp.getClientProperty(TreeNodeData.class);
if(resObj.isFolder() || resObj.getLoadingState()) return;
File destFile = getSaveFile(null, resObj.getPath().replace("/", File.separator));
if(destFile == null) return;
String destPath = destFile.getAbsolutePath();
if(resObj.getURI() != null
&& "file".equals(resObj.getURI().getScheme())) {
FileUtil.copy(resObj.getPath(), destPath);
} else {
destPath = uncompressRes(resObj, destPath);
}
}
public File getSaveFile(Component component, String defaultFilePath) {
JFileChooser jfc = ApkFileChooser.getFileChooser(RProp.S.LAST_FILE_SAVE_PATH.get(), JFileChooser.SAVE_DIALOG, new File(defaultFilePath));
//jfc.setFileFilter(new javax.swing.filechooser.FileNameExtensionFilter(RStr.LABEL_APK_FILE_DESC.get(),"apk"));
if(jfc.showSaveDialog(component) != JFileChooser.APPROVE_OPTION)
return null;
File dir = jfc.getSelectedFile();
if(dir != null) {
RProp.S.LAST_FILE_SAVE_PATH.set(dir.getParentFile().getAbsolutePath());
}
return dir;
}
}
|
3e0c4b74b23fa7242d96bbf08697ab4689d718dc | 4,521 | java | Java | src/main/java/vg/civcraft/mc/civmodcore/itemHandling/itemExpression/misc/ItemAttributeMatcher.java | CivWizardry/CivModCore | 77f4b65f262f21b7e472a1a5bb2edab11e02a562 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/vg/civcraft/mc/civmodcore/itemHandling/itemExpression/misc/ItemAttributeMatcher.java | CivWizardry/CivModCore | 77f4b65f262f21b7e472a1a5bb2edab11e02a562 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/vg/civcraft/mc/civmodcore/itemHandling/itemExpression/misc/ItemAttributeMatcher.java | CivWizardry/CivModCore | 77f4b65f262f21b7e472a1a5bb2edab11e02a562 | [
"BSD-3-Clause"
] | null | null | null | 36.168 | 131 | 0.765539 | 5,217 | package vg.civcraft.mc.civmodcore.itemHandling.itemExpression.misc;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import org.bukkit.Bukkit;
import org.bukkit.attribute.Attribute;
import org.bukkit.attribute.AttributeModifier;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import vg.civcraft.mc.civmodcore.itemHandling.itemExpression.ItemMatcher;
import vg.civcraft.mc.civmodcore.itemHandling.itemExpression.Matcher;
import vg.civcraft.mc.civmodcore.itemHandling.itemExpression.amount.AmountMatcher;
import vg.civcraft.mc.civmodcore.itemHandling.itemExpression.enummatcher.EnumMatcher;
import vg.civcraft.mc.civmodcore.itemHandling.itemExpression.name.NameMatcher;
import vg.civcraft.mc.civmodcore.itemHandling.itemExpression.uuid.UUIDMatcher;
import java.util.AbstractMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* Matches over the attributes of an item that apply for a given slot.
*
* @author Ameliorate
*/
public class ItemAttributeMatcher implements ItemMatcher {
/**
* @param slot May be null, for an item that applies no matter what slot it is in.
*/
public ItemAttributeMatcher(List<AttributeMatcher> matchers, EquipmentSlot slot, ListMatchingMode mode) {
this.matchers = matchers;
this.slot = slot;
this.mode = mode;
matchers.forEach((m) -> m.slot = slot);
}
public List<AttributeMatcher> matchers;
public EquipmentSlot slot;
public ListMatchingMode mode;
@Override
public boolean matches(ItemStack item) {
if (!item.hasItemMeta() || !item.getItemMeta().hasAttributeModifiers())
return false;
return mode.matches(matchers, item.getItemMeta().getAttributeModifiers(slot).entries());
}
@Override
public ItemStack solve(ItemStack item) throws NotSolvableException {
ItemMeta meta = item.hasItemMeta() ? item.getItemMeta() : Bukkit.getItemFactory().getItemMeta(item.getType());
List<Map.Entry<Attribute, AttributeModifier>> attributes = mode.solve(matchers,
() -> new AbstractMap.SimpleEntry<>(Attribute.GENERIC_ARMOR,
new AttributeModifier("a", 1, AttributeModifier.Operation.ADD_NUMBER)));
Multimap<Attribute, AttributeModifier> attributesMap = HashMultimap.create();
for (Map.Entry<Attribute, AttributeModifier> entry : attributes) {
attributesMap.put(entry.getKey(), entry.getValue());
}
meta.setAttributeModifiers(attributesMap);
item.setItemMeta(meta);
return item;
}
public static class AttributeMatcher implements Matcher<Map.Entry<Attribute, AttributeModifier>> {
public AttributeMatcher(EnumMatcher<Attribute> attribute,
NameMatcher name, EnumMatcher<AttributeModifier.Operation> operation,
UUIDMatcher uuid, AmountMatcher amount) {
this.attribute = attribute;
this.name = name;
this.operation = operation;
this.uuid = uuid;
this.amount = amount;
}
public EnumMatcher<Attribute> attribute;
public EnumMatcher<AttributeModifier.Operation> operation;
public NameMatcher name;
public UUIDMatcher uuid;
public AmountMatcher amount;
private EquipmentSlot slot;
public boolean matches(Attribute attribute, AttributeModifier modifier) {
if (this.attribute != null && !this.attribute.matches(attribute))
return false;
else if (name != null && !name.matches(modifier.getName()))
return false;
else if (operation != null && !operation.matches(modifier.getOperation()))
return false;
else if (uuid != null && !uuid.matches(modifier.getUniqueId()))
return false;
else if (amount != null && !amount.matches(modifier.getAmount()))
return false;
else
return true;
}
@Override
public boolean matches(Map.Entry<Attribute, AttributeModifier> matched) {
return matches(matched.getKey(), matched.getValue());
}
@Override
public Map.Entry<Attribute, AttributeModifier> solve(Map.Entry<Attribute, AttributeModifier> entry) throws NotSolvableException {
Attribute attribute = this.attribute.solve(entry.getKey());
AttributeModifier defaultModifier = entry.getValue();
AttributeModifier.Operation operation = this.operation.solve(defaultModifier.getOperation());
String name = this.name.solve(defaultModifier.getName());
UUID uuid = this.uuid.solve(defaultModifier.getUniqueId());
double amount = this.amount.solve(defaultModifier.getAmount());
return new AbstractMap.SimpleEntry<>(attribute, new AttributeModifier(uuid, name, amount, operation, slot));
}
}
}
|
3e0c4b7ffccd5aba57ed63d1d1b22eb362ae3eee | 1,753 | java | Java | inception-ui-kb/src/main/java/de/tudarmstadt/ukp/inception/ui/kb/IriInfoBadge.java | pranavibitra/inception | f9a2ad523829c3fa1af800466f1e32b2656bd959 | [
"Apache-2.0"
] | 2 | 2019-10-05T17:44:41.000Z | 2019-10-10T16:07:37.000Z | inception-ui-kb/src/main/java/de/tudarmstadt/ukp/inception/ui/kb/IriInfoBadge.java | pranavibitra/inception | f9a2ad523829c3fa1af800466f1e32b2656bd959 | [
"Apache-2.0"
] | 53 | 2019-09-30T12:19:40.000Z | 2020-03-15T19:13:51.000Z | inception-ui-kb/src/main/java/de/tudarmstadt/ukp/inception/ui/kb/IriInfoBadge.java | pranavibitra/inception | f9a2ad523829c3fa1af800466f1e32b2656bd959 | [
"Apache-2.0"
] | 44 | 2019-09-04T22:11:19.000Z | 2021-06-01T12:51:48.000Z | 29.216667 | 75 | 0.691386 | 5,218 | /*
* Copyright 2019
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.tudarmstadt.ukp.inception.ui.kb;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import com.googlecode.wicket.jquery.core.Options;
import com.googlecode.wicket.kendo.ui.widget.tooltip.TooltipBehavior;
public class IriInfoBadge extends Panel
{
private static final long serialVersionUID = 1L;
private TooltipBehavior tip;
public IriInfoBadge(String aId, IModel<String> aModel)
{
super(aId, aModel);
WebMarkupContainer iri = new WebMarkupContainer("iri");
tip = new TooltipBehavior();
tip.setOption("autoHide", false);
tip.setOption("showOn", Options.asString("click"));
iri.add(tip);
add(iri);
}
@Override
protected void onConfigure()
{
super.onConfigure();
tip.setOption("content", Options.asString(getModelObject()));
}
public String getModelObject()
{
return (String) getDefaultModelObject();
}
}
|
3e0c4cc9ca6b2605d4206591cd2819d1cb5ea89f | 289 | java | Java | rx/src/main/java/com/duyp/androidutils/rx/functions/PlainAction.java | duyp/Android-Utils | 29378df5cb0de76d06380b521018e0b0b5aabd11 | [
"Apache-2.0"
] | null | null | null | rx/src/main/java/com/duyp/androidutils/rx/functions/PlainAction.java | duyp/Android-Utils | 29378df5cb0de76d06380b521018e0b0b5aabd11 | [
"Apache-2.0"
] | null | null | null | rx/src/main/java/com/duyp/androidutils/rx/functions/PlainAction.java | duyp/Android-Utils | 29378df5cb0de76d06380b521018e0b0b5aabd11 | [
"Apache-2.0"
] | null | null | null | 16.055556 | 45 | 0.6609 | 5,219 | package com.duyp.androidutils.rx.functions;
import io.reactivex.functions.Action;
/**
* Created by duypham on 7/26/17.
* Like {@link Action} but without Exception
*/
public interface PlainAction extends Action {
/**
* Run the action
*/
@Override
void run();
}
|
3e0c4d4c202b2609b06f05bb4ccd7728a12b7d59 | 4,536 | java | Java | model-seev-types/src/generated/java/com/prowidesoftware/swift/model/mx/dic/InstructionCancellationRequestStatus9Choice.java | luongnvUIT/prowide-iso20022 | 59210a4b67cd38759df2d0dd82ad19acf93ffe75 | [
"Apache-2.0"
] | 40 | 2020-10-13T13:44:59.000Z | 2022-03-30T13:58:32.000Z | model-seev-types/src/generated/java/com/prowidesoftware/swift/model/mx/dic/InstructionCancellationRequestStatus9Choice.java | luongnvUIT/prowide-iso20022 | 59210a4b67cd38759df2d0dd82ad19acf93ffe75 | [
"Apache-2.0"
] | 25 | 2020-10-04T23:46:22.000Z | 2022-03-30T12:31:03.000Z | model-seev-types/src/generated/java/com/prowidesoftware/swift/model/mx/dic/InstructionCancellationRequestStatus9Choice.java | luongnvUIT/prowide-iso20022 | 59210a4b67cd38759df2d0dd82ad19acf93ffe75 | [
"Apache-2.0"
] | 22 | 2020-12-22T14:50:22.000Z | 2022-03-30T13:19:10.000Z | 24.923077 | 106 | 0.630071 | 5,220 |
package com.prowidesoftware.swift.model.mx.dic;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
/**
* Choice between different instruction cancellation request statuses.
*
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "InstructionCancellationRequestStatus9Choice", propOrder = {
"cxlCmpltd",
"accptd",
"rjctd",
"pdgCxl",
"prtrySts"
})
public class InstructionCancellationRequestStatus9Choice {
@XmlElement(name = "CxlCmpltd")
protected CancelledStatus11Choice cxlCmpltd;
@XmlElement(name = "Accptd")
protected NoSpecifiedReason1 accptd;
@XmlElement(name = "Rjctd")
protected RejectedStatus18Choice rjctd;
@XmlElement(name = "PdgCxl")
protected PendingCancellationStatus5Choice pdgCxl;
@XmlElement(name = "PrtrySts")
protected ProprietaryStatusAndReason6 prtrySts;
/**
* Gets the value of the cxlCmpltd property.
*
* @return
* possible object is
* {@link CancelledStatus11Choice }
*
*/
public CancelledStatus11Choice getCxlCmpltd() {
return cxlCmpltd;
}
/**
* Sets the value of the cxlCmpltd property.
*
* @param value
* allowed object is
* {@link CancelledStatus11Choice }
*
*/
public InstructionCancellationRequestStatus9Choice setCxlCmpltd(CancelledStatus11Choice value) {
this.cxlCmpltd = value;
return this;
}
/**
* Gets the value of the accptd property.
*
* @return
* possible object is
* {@link NoSpecifiedReason1 }
*
*/
public NoSpecifiedReason1 getAccptd() {
return accptd;
}
/**
* Sets the value of the accptd property.
*
* @param value
* allowed object is
* {@link NoSpecifiedReason1 }
*
*/
public InstructionCancellationRequestStatus9Choice setAccptd(NoSpecifiedReason1 value) {
this.accptd = value;
return this;
}
/**
* Gets the value of the rjctd property.
*
* @return
* possible object is
* {@link RejectedStatus18Choice }
*
*/
public RejectedStatus18Choice getRjctd() {
return rjctd;
}
/**
* Sets the value of the rjctd property.
*
* @param value
* allowed object is
* {@link RejectedStatus18Choice }
*
*/
public InstructionCancellationRequestStatus9Choice setRjctd(RejectedStatus18Choice value) {
this.rjctd = value;
return this;
}
/**
* Gets the value of the pdgCxl property.
*
* @return
* possible object is
* {@link PendingCancellationStatus5Choice }
*
*/
public PendingCancellationStatus5Choice getPdgCxl() {
return pdgCxl;
}
/**
* Sets the value of the pdgCxl property.
*
* @param value
* allowed object is
* {@link PendingCancellationStatus5Choice }
*
*/
public InstructionCancellationRequestStatus9Choice setPdgCxl(PendingCancellationStatus5Choice value) {
this.pdgCxl = value;
return this;
}
/**
* Gets the value of the prtrySts property.
*
* @return
* possible object is
* {@link ProprietaryStatusAndReason6 }
*
*/
public ProprietaryStatusAndReason6 getPrtrySts() {
return prtrySts;
}
/**
* Sets the value of the prtrySts property.
*
* @param value
* allowed object is
* {@link ProprietaryStatusAndReason6 }
*
*/
public InstructionCancellationRequestStatus9Choice setPrtrySts(ProprietaryStatusAndReason6 value) {
this.prtrySts = value;
return this;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
@Override
public boolean equals(Object that) {
return EqualsBuilder.reflectionEquals(this, that);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}
|
3e0c4dfe3542c87a9a85957528a21434fd2852dc | 656 | java | Java | app/src/main/java/com/sprotte/geolocator/demo/java/GeofenceIntentService.java | dandycheung/Geolocator | b0e2e184f7ec50ebeb4dec44f2df0610a2673059 | [
"MIT"
] | 78 | 2019-09-06T14:15:23.000Z | 2022-03-20T20:06:29.000Z | app/src/main/java/com/sprotte/geolocator/demo/java/GeofenceIntentService.java | dandycheung/Geolocator | b0e2e184f7ec50ebeb4dec44f2df0610a2673059 | [
"MIT"
] | 17 | 2019-09-14T10:02:53.000Z | 2021-04-27T08:11:08.000Z | app/src/main/java/com/sprotte/geolocator/demo/java/GeofenceIntentService.java | dandycheung/Geolocator | b0e2e184f7ec50ebeb4dec44f2df0610a2673059 | [
"MIT"
] | 18 | 2019-09-23T06:29:24.000Z | 2021-08-25T05:42:51.000Z | 27.333333 | 107 | 0.71189 | 5,221 | package com.sprotte.geolocator.demo.java;
import android.util.Log;
import com.sprotte.geolocator.demo.misc.UtilsKt;
import com.sprotte.geolocator.geofencer.models.Geofence;
import org.jetbrains.annotations.NotNull;
public class GeofenceIntentService extends com.sprotte.geolocator.geofencer.service.GeofenceIntentService {
@Override
public void onGeofence(@NotNull Geofence geofence) {
Log.v(GeofenceIntentService.class.getSimpleName(), "onGeofence " + geofence);
UtilsKt.sendNotification(
getApplicationContext(),
geofence.getTitle(),
geofence.getMessage()
);
}
}
|
3e0c4e012ebfad45430013d2e3ea1375f811fe04 | 1,806 | java | Java | mobius-rx/src/main/java/com/spotify/mobius/rx/MergedTransformer.java | btoo/mobius | 1cae5f1e78c898bb4a158b27526343b43bc66ea0 | [
"Apache-2.0"
] | 1,073 | 2018-01-26T16:00:37.000Z | 2022-03-31T20:16:27.000Z | mobius-rx/src/main/java/com/spotify/mobius/rx/MergedTransformer.java | btoo/mobius | 1cae5f1e78c898bb4a158b27526343b43bc66ea0 | [
"Apache-2.0"
] | 127 | 2018-01-30T19:01:26.000Z | 2022-03-17T23:58:59.000Z | mobius-rx/src/main/java/com/spotify/mobius/rx/MergedTransformer.java | btoo/mobius | 1cae5f1e78c898bb4a158b27526343b43bc66ea0 | [
"Apache-2.0"
] | 81 | 2018-01-30T08:55:15.000Z | 2022-03-14T04:21:03.000Z | 31.684211 | 97 | 0.684939 | 5,222 | /*
* -\-\-
* Mobius
* --
* Copyright (c) 2017-2020 Spotify AB
* --
* 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.spotify.mobius.rx;
import java.util.ArrayList;
import java.util.List;
import rx.Observable;
import rx.functions.Func1;
/**
* Utility that dispatches each item emitted from a source observable of type T to multiple other
* Observable.Transformers, and merges the results to a stream of type R.
*
* @param <T> input type
* @param <R> output type
*/
class MergedTransformer<T, R> implements Observable.Transformer<T, R> {
private final Iterable<Observable.Transformer<T, R>> transformers;
public MergedTransformer(Iterable<Observable.Transformer<T, R>> transformers) {
this.transformers = transformers;
}
@Override
public Observable<R> call(Observable<T> input) {
return input.publish(
new Func1<Observable<T>, Observable<R>>() {
@Override
public Observable<R> call(Observable<T> innerInput) {
final List<Observable<R>> transformed = new ArrayList<>();
for (Observable.Transformer<T, R> transformer : transformers) {
transformed.add(innerInput.compose(transformer));
}
return Observable.merge(transformed);
}
});
}
}
|
3e0c4e36498260c5ea4fe0d7478726cc94cad791 | 15,135 | java | Java | src/com/cdd/bao/editor/LookupPanel.java | cdd/bioassay-template | 02358931c31747e4ce525ff93fca4c12cba7ba21 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 6 | 2017-02-16T17:25:14.000Z | 2021-09-25T03:02:16.000Z | src/com/cdd/bao/editor/LookupPanel.java | cdd/bioassay-template | 02358931c31747e4ce525ff93fca4c12cba7ba21 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 70 | 2016-12-28T00:58:16.000Z | 2020-07-21T16:39:47.000Z | src/com/cdd/bao/editor/LookupPanel.java | cdd/bioassay-template | 02358931c31747e4ce525ff93fca4c12cba7ba21 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 2 | 2018-01-03T19:27:04.000Z | 2018-05-14T17:40:32.000Z | 32.270789 | 135 | 0.70109 | 5,223 | /*
* BioAssay Ontology Annotator Tools
*
* (c) 2014-2018 Collaborative Drug Discovery Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License 2.0
* as published by the Free Software Foundation:
*
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.cdd.bao.editor;
import com.cdd.bao.*;
import com.cdd.bao.template.*;
import com.cdd.bao.util.Lineup;
import com.cdd.bao.util.RowLine;
import java.io.*;
import java.util.*;
import org.apache.commons.lang3.StringUtils;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.control.cell.*;
import javafx.scene.input.*;
import javafx.scene.layout.*;
import javafx.scene.paint.*;
import javafx.application.*;
import javafx.beans.property.*;
import javafx.beans.value.*;
import javafx.collections.*;
import javafx.event.ActionEvent;
import javafx.geometry.*;
import javafx.util.*;
/*
Lookup panel: takes a partially specified schema value and opens up the vocabulary list, to make it easy to pick URI/label/description
combinations.
*/
public class LookupPanel extends Dialog<LookupPanel.Resource[]>
{
private Vocabulary vocab = null;
private Vocabulary.Hierarchy hier = null;
private boolean isProperty; // false = value lookup, true = property lookup
private Set<String> usedURI, exclURI;
private boolean multi;
public static final class Resource
{
public String uri, label, descr;
public String[] altLabels;
public boolean beingUsed;
public Resource(String uri, String label, String[] altLabels, String descr)
{
this.uri = uri;
this.label = label == null ? "" : label;
this.altLabels = altLabels == null ? new String[0] : altLabels;
this.descr = descr == null ? "" : descr;
}
};
private List<Resource> resources = new ArrayList<>();
private TabPane tabber = new TabPane();
private Tab tabList = new Tab("List"), tabTree = new Tab("Hierarchy");
private TextField fieldSearch = new TextField();
private CheckBox includeAltLabels = new CheckBox();
private TableView<Resource> tableList = new TableView<>();
private TreeItem<Vocabulary.Branch> treeRoot = new TreeItem<>(new Vocabulary.Branch(null, null));
private TreeView<Vocabulary.Branch> treeView = new TreeView<>(treeRoot);
private final class HierarchyTreeCell extends TreeCell<Vocabulary.Branch>
{
public void updateItem(Vocabulary.Branch branch, boolean empty)
{
super.updateItem(branch, empty);
if (branch != null)
{
String text = "URI <" + branch.uri + ">";
String descr = vocab.getDescr(branch.uri);
if (descr != null && descr.length() > 0) text += "\n\n" + descr;
Tooltip tip = new Tooltip(text);
tip.setWrapText(true);
tip.setMaxWidth(400);
Tooltip.install(this, tip);
}
if (empty)
{
setText(null);
setGraphic(null);
}
else
{
String label = branch.label;
String style = "-fx-font-family: arial; -fx-text-fill: black; -fx-font-weight: normal;";
if (usedURI.contains(branch.uri)) style = "-fx-text-fill: #000080; -fx-font-weight: bold;";
else if (exclURI.contains(branch.uri)) style = "-fx-text-fill: #800080; -fx-font-weight: bold;";
if (branch.uri.startsWith(ModelSchema.PFX_BAO) || branch.uri.startsWith(ModelSchema.PFX_BAT))
{
style += " -fx-font-style: normal;";
}
else
{
style += " -fx-font-style: italic;";
label += " *";
}
setText(label);
setStyle(style);
setGraphic(getTreeItem().getGraphic());
}
}
}
private static final int PADDING = 2;
// ------------ public methods ------------
public LookupPanel(boolean isProperty, String searchText, Set<String> usedURI, Set<String> exclURI, boolean multi)
{
super();
this.isProperty = isProperty;
this.usedURI = usedURI;
this.exclURI = exclURI;
this.multi = multi;
loadResources();
setTitle("Lookup " + (isProperty ? "Property" : multi ? "Values" : "Value"));
setResizable(true);
for (Tab tab : new Tab[]{tabList, tabTree}) {tab.setClosable(false);}
setupList(searchText);
setupTree(searchText);
tabber.getTabs().addAll(tabList, tabTree);
getDialogPane().setContent(tabber);
getDialogPane().getButtonTypes().add(new ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE));
// setup the buttons
ButtonType btnTypeUse = new ButtonType("Use", ButtonBar.ButtonData.OK_DONE);
getDialogPane().getButtonTypes().add(btnTypeUse);
setResultConverter(buttonType ->
{
if (buttonType == btnTypeUse) return composeCurrentValue();
return null;
});
Button btnUse = (Button)getDialogPane().lookupButton(btnTypeUse);
btnUse.addEventFilter(ActionEvent.ACTION, event ->
{
if (tableList.getSelectionModel().getSelectedIndex() < 0 &&
treeView.getSelectionModel().getSelectedIndex() < 0) event.consume();
});
tableList.setOnMousePressed(event ->
{
if (event.isPrimaryButtonDown() && event.getClickCount() == 2) btnUse.fire();
});
tableList.setOnKeyPressed(event ->
{
if (event.getCode() == KeyCode.ENTER) btnUse.fire();
});
tableList.getSelectionModel().setSelectionMode(multi ? SelectionMode.MULTIPLE : SelectionMode.SINGLE);
treeView.getSelectionModel().setSelectionMode(multi ? SelectionMode.MULTIPLE : SelectionMode.SINGLE);
tabber.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) ->
{
if (oldValue == tabList && newValue == tabTree) syncSelectionListToTree();
else if (oldValue == tabTree && newValue == tabList) syncSelectionTreeToList();
});
Platform.runLater(() -> fieldSearch.requestFocus());
}
// if there's a starting value, set it in the list
public void setInitialURI(String uri)
{
if (uri == null || uri.length() == 0) return;
List<Resource> resList = tableList.getItems();
for (int n = 0; n < resList.size(); n++) if (resList.get(n).uri.equals(uri))
{
tableList.getSelectionModel().clearAndSelect(n);
return;
}
}
// ------------ private methods ------------
private void loadResources()
{
vocab = Vocabulary.globalInstance();
hier = isProperty ? vocab.getPropertyHierarchy() : vocab.getValueHierarchy();
String[] source = isProperty ? vocab.getPropertyURIs() : vocab.getValueURIs();
for (String uri : source)
{
Resource res = new Resource(uri, vocab.getLabel(uri), vocab.getAltLabels(uri), vocab.getDescr(uri));
res.beingUsed = usedURI.contains(uri);
resources.add(res);
}
}
private void setupList(String searchText)
{
RowLine searchRow = new RowLine(PADDING + 3);
Label searchTitle = new Label("Search:");
searchRow.add(searchTitle, 0);
searchRow.add(fieldSearch, 1);
includeAltLabels.setText("Include other labels in search");
includeAltLabels.setSelected(true);
searchRow.add(includeAltLabels, 0);
tableList.setEditable(false);
TableColumn<Resource, String> colUsed = new TableColumn<>("U");
colUsed.setMinWidth(20);
colUsed.setPrefWidth(20);
colUsed.setCellValueFactory(resource -> new SimpleStringProperty(resource.getValue().beingUsed ? "\u2713" : ""));
TableColumn<Resource, String> colURI = new TableColumn<>("URI");
colURI.setMinWidth(150);
colURI.setCellValueFactory(resource -> new SimpleStringProperty(ModelSchema.collapsePrefix(resource.getValue().uri)));
TableColumn<Resource, String> colLabel = new TableColumn<>("Label");
colLabel.setMinWidth(200);
colLabel.setCellValueFactory(resource -> new SimpleStringProperty(resource.getValue().label));
TableColumn<Resource, String> colDescr = new TableColumn<>("Description");
colDescr.setMinWidth(400);
colDescr.setCellValueFactory(resource -> new SimpleStringProperty(cleanupDescription(resource.getValue().descr)));
TableColumn<Resource, String> colAltLabels = new TableColumn<>("Other Labels");
colAltLabels.setMinWidth(200);
colAltLabels.setCellValueFactory(resource -> new SimpleStringProperty(StringUtils.join(resource.getValue().altLabels, ",")));
tableList.setMinHeight(450);
tableList.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
tableList.getColumns().add(colUsed);
tableList.getColumns().add(colURI);
tableList.getColumns().add(colLabel);
tableList.getColumns().add(colDescr);
tableList.getColumns().add(colAltLabels);
tableList.setItems(FXCollections.observableArrayList(searchedSubset(searchText)));
BorderPane pane = new BorderPane();
pane.setPrefSize(800, 500);
pane.setMaxHeight(Double.MAX_VALUE);
pane.setPadding(new Insets(PADDING, PADDING, PADDING, PADDING));
BorderPane.setMargin(searchRow, new Insets(0, 0, PADDING, 0));
pane.setTop(searchRow);
pane.setCenter(tableList);
tabList.setContent(pane);
fieldSearch.setText(searchText);
fieldSearch.textProperty().addListener((observable, oldValue, newValue) ->
{
updateTableList(newValue);
});
// coerce update to results list whenever checkbox for alternate labels is toggled
includeAltLabels.selectedProperty().addListener((observable, oldValue, newValue) ->
{
updateTableList(fieldSearch.getText());
});
}
private void updateTableList(String searchText)
{
tableList.setItems(FXCollections.observableArrayList(searchedSubset(searchText)));
}
private void setupTree(String searchText)
{
for (Vocabulary.Branch branch : hier.rootBranches)
{
TreeItem<Vocabulary.Branch> item = populateTreeBranch(treeRoot, branch);
item.setExpanded(true); // open up just the first level
}
treeView.setShowRoot(false);
treeView.setCellFactory(p -> new HierarchyTreeCell());
BorderPane pane = new BorderPane();
pane.setPrefSize(800, 500);
pane.setMaxHeight(Double.MAX_VALUE);
pane.setPadding(new Insets(PADDING, PADDING, PADDING, PADDING));
pane.setCenter(treeView);
tabTree.setContent(pane);
}
// recursively add a new branch into the tree
private TreeItem<Vocabulary.Branch> populateTreeBranch(TreeItem<Vocabulary.Branch> parent, Vocabulary.Branch branch)
{
TreeItem<Vocabulary.Branch> item = new TreeItem<>(branch);
parent.getChildren().add(item);
if (usedURI.contains(branch.uri))
{
TreeItem<Vocabulary.Branch> look = item.getParent();
while (look != null)
{
look.setExpanded(true);
look = look.getParent();
}
}
for (Vocabulary.Branch child : branch.children) populateTreeBranch(item, child);
return item;
}
// manufactures a value from the selected items
private LookupPanel.Resource[] composeCurrentValue()
{
if (tabber.getSelectionModel().getSelectedItem() == tabList)
{
List<LookupPanel.Resource> list = tableList.getSelectionModel().getSelectedItems();
return list.toArray(new LookupPanel.Resource[list.size()]);
}
else if (tabber.getSelectionModel().getSelectedItem() == tabTree)
{
List<TreeItem<Vocabulary.Branch>> list = treeView.getSelectionModel().getSelectedItems();
List<LookupPanel.Resource> ret = new ArrayList<>();
for (int n = 0; n < list.size(); n++)
{
Vocabulary.Branch branch = list.get(n).getValue();
if (multi && usedURI.contains(branch.uri)) continue;
ret.add(new Resource(branch.uri, branch.label, vocab.getAltLabels(branch.uri), vocab.getDescr(branch.uri)));
}
return ret.toArray(new LookupPanel.Resource[ret.size()]);
}
return null;
}
// returns a subset of the resources which matches the search text (or all if blank)
private List<Resource> searchedSubset(String searchText)
{
if (searchText.length() == 0) return resources;
String searchLC = searchText.toLowerCase();
List<Resource> subset = new ArrayList<>();
for (Resource res : resources)
{
if (res.label.toLowerCase().indexOf(searchLC) >= 0 || res.uri.toLowerCase().indexOf(searchLC) >= 0 ||
res.descr.toLowerCase().indexOf(searchLC) >= 0) subset.add(res);
else if (includeAltLabels.isSelected())
{
for (int k = 0; k < res.altLabels.length; k++) if (res.altLabels[k].toLowerCase().indexOf(searchLC) >= 0)
{
subset.add(res);
break;
}
}
}
return subset;
}
// when switching tabs: update selection to match
private void syncSelectionListToTree()
{
if (tableList.getSelectionModel().getSelectedIndex() < 0) return; // nothing selected: do not disturb
Set<String> selected = new HashSet<>();
for (Resource res : tableList.getSelectionModel().getSelectedItems()) selected.add(res.uri);
treeView.getSelectionModel().clearSelection();
List<TreeItem<Vocabulary.Branch>> stack = new ArrayList<>();
stack.add(treeRoot);
List<TreeItem<Vocabulary.Branch>> toSelect = new ArrayList<>();
while (stack.size() > 0)
{
TreeItem<Vocabulary.Branch> item = stack.remove(0);
if (selected.contains(item.getValue().uri))
{
toSelect.add(item);
for (TreeItem<Vocabulary.Branch> look = item.getParent(); look != null; look = look.getParent()) look.setExpanded(true);
if (!multi) break; // since a URI can appear twice in the tree due to multiple inheritance, this check is necessary
}
for (TreeItem<Vocabulary.Branch> child : item.getChildren()) stack.add(child);
}
for (int n = 0; n < toSelect.size(); n++)
{
TreeItem<Vocabulary.Branch> item = toSelect.get(n);
int row = treeView.getRow(item);
treeView.getSelectionModel().select(row);
if (n == 0) treeView.scrollTo(row);
}
}
private void syncSelectionTreeToList()
{
if (treeView.getSelectionModel().getSelectedIndex() < 0) return; // nothing selected: do not disturb
Map<String, Integer> uriToIndex = new HashMap<>();
List<Resource> resList = tableList.getItems();
for (int n = 0; n < resList.size(); n++) uriToIndex.put(resList.get(n).uri, n);
tableList.getSelectionModel().clearSelection();
int scrollTo = -1;
for (TreeItem<Vocabulary.Branch> item : treeView.getSelectionModel().getSelectedItems())
{
Integer idx = uriToIndex.get(item.getValue().uri);
if (idx != null)
{
tableList.getSelectionModel().select(idx);
if (scrollTo < 0) scrollTo = idx;
}
}
if (scrollTo >= 0) tableList.scrollTo(scrollTo);
}
// switches shorter prefixes for display convenience
/*private final String[] SUBST =
{
"obo:", "http://purl.obolibrary.org/obo/",
"bao:", "http://www.bioassayontology.org/bao#",
"bat:", "http://www.bioassayontology.org/bat#",
"uo:", "http://purl.org/obo/owl/UO#"
};
private String substitutePrefix(String uri)
{
for (int n = 0; n < SUBST.length; n += 2)
{
if (uri.startsWith(SUBST[n + 1])) return SUBST[n] + uri.substring(SUBST[n + 1].length());
}
return uri;
}*/
private String cleanupDescription(String descr)
{
return descr.replaceAll("\n", " ");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.